
    !ge                         d dl Zd dlZd dlmZ d dlmZmZm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZmZmZ  G d d	e      Z G d
 de      Z eee       y)    N)
inv_boxcox)boxcoxrv_continuousrv_discrete)	rv_frozen)
PandasData)Results)ResultsWrapperpopulate_wrapperunion_dictsc                       e Zd ZdZ	 d fd	Zed        Zed        Zed        Zed        Z	ed        Z
e
j                  d        Z
ed	        Zed
        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zej                  d        ZddZddZd Z	 	 	 	 	 ddZ xZS )HoltWintersResultsa  
    Results from fitting Exponential Smoothing models.

    Parameters
    ----------
    model : ExponentialSmoothing instance
        The fitted model instance.
    params : dict
        All the parameters for the Exponential Smoothing model.
    sse : float
        The sum of squared errors.
    aic : float
        The Akaike information criterion.
    aicc : float
        AIC with a correction for finite sample sizes.
    bic : float
        The Bayesian information criterion.
    optimized : bool
        Flag indicating whether the model parameters were optimized to fit
        the data.
    level : ndarray
        An array of the levels values that make up the fitted values.
    trend : ndarray
        An array of the trend values that make up the fitted values.
    season : ndarray
        An array of the seasonal values that make up the fitted values.
    params_formatted : pd.DataFrame
        DataFrame containing all parameters, their short names and a flag
        indicating whether the parameter's value was optimized to fit the data.
    resid : ndarray
        An array of the residuals of the fittedvalues and actual values.
    k : int
        The k parameter used to remove the bias in AIC, BIC etc.
    fittedvalues : ndarray
        An array of the fitted values. Fitted by the Exponential Smoothing
        model.
    fittedfcast : ndarray
        An array of both the fitted values and forecast values.
    fcastvalues : ndarray
        An array of the forecast values forecast by the Exponential Smoothing
        model.
    mle_retvals : {None, scipy.optimize.optimize.OptimizeResult}
        Optimization results if the parameters were optimized to fit the data.
    c                 (   |j                   | _         t        | 	  ||       || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        || _        || _        || _        || _        || _        || _        y N)datasuper__init___model_sse_aic_aicc_bic
_optimized_level_trend_season_params_formatted_fittedvalues_fittedfcast_fcastvalues_resid_k_mle_retvals)selfmodelparamssseaicaiccbic	optimizedleveltrendseasonparams_formattedresidkfittedvaluesfittedfcastfcastvaluesmle_retvals	__class__s                     `/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/holtwinters/results.pyr   zHoltWintersResults.__init__B   s    ( JJ	'		
	#!1)'''    c                     | j                   S )z3
        The Akaike information criterion.
        )r   r$   s    r7   r(   zHoltWintersResults.aici       
 yyr8   c                     | j                   S )z@
        AIC with a correction for finite sample sizes.
        )r   r:   s    r7   r)   zHoltWintersResults.aiccp   s    
 zzr8   c                     | j                   S )z5
        The Bayesian information criterion.
        )r   r:   s    r7   r*   zHoltWintersResults.bicw   r;   r8   c                     | j                   S )zS
        The sum of squared errors between the data and the fittted value.
        )r   r:   s    r7   r'   zHoltWintersResults.sse~   r;   r8   c                     | j                   S )zA
        The model used to produce the results instance.
        r   r:   s    r7   r%   zHoltWintersResults.model       
 {{r8   c                     || _         y r   r@   r$   values     r7   r%   zHoltWintersResults.model   s	    r8   c                     | j                   S )zO
        An array of the levels values that make up the fitted values.
        )r   r:   s    r7   r,   zHoltWintersResults.level   rA   r8   c                     | j                   S )zU
        Flag indicating if model parameters were optimized to fit the data.
        )r   r:   s    r7   r+   zHoltWintersResults.optimized   s    
 r8   c                     | j                   S )zN
        An array of the trend values that make up the fitted values.
        )r   r:   s    r7   r-   zHoltWintersResults.trend   rA   r8   c                     | j                   S )zQ
        An array of the seasonal values that make up the fitted values.
        )r   r:   s    r7   r.   zHoltWintersResults.season   s    
 ||r8   c                     | j                   S )z
        DataFrame containing all parameters

        Contains short names and a flag indicating whether the parameter's
        value was optimized to fit the data.
        )r   r:   s    r7   r/   z#HoltWintersResults.params_formatted   s     %%%r8   c                     | j                   S )z/
        An array of the fitted values
        )r   r:   s    r7   r2   zHoltWintersResults.fittedvalues   s    
 !!!r8   c                     | j                   S )zI
        An array of both the fitted values and forecast values.
        )r   r:   s    r7   r3   zHoltWintersResults.fittedfcast       
    r8   c                     | j                   S )z1
        An array of the forecast values
        )r    r:   s    r7   r4   zHoltWintersResults.fcastvalues   rL   r8   c                     | j                   S )zR
        An array of the residuals of the fittedvalues and actual values.
        )r!   r:   s    r7   r0   zHoltWintersResults.resid   rA   r8   c                     | j                   S )zJ
        The k parameter used to remove the bias in AIC, BIC etc.
        )r"   r:   s    r7   r1   zHoltWintersResults.k   s    
 wwr8   c                     | j                   S )zX
        Optimization results if the parameters were optimized to fit the data.
        r#   r:   s    r7   r5   zHoltWintersResults.mle_retvals   rL   r8   c                     || _         y r   rQ   rC   s     r7   r5   zHoltWintersResults.mle_retvals   s
    !r8   c                 P    | j                   j                  | j                  ||      S )a  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.

        Returns
        -------
        forecast : ndarray
            Array of out of sample forecasts.
        )r%   predictr&   )r$   startends      r7   rT   zHoltWintersResults.predict   s!    . zz!!$++uc::r8   c                    	 t        | j                  j                  dd      }t        |t              szt        | j                  j                  t
        j                  t
        j                  f      r<| j                  j                  d   |z   }| j                  j                  d   ||z  z   }n+| j                  j                  j                  d   }||z   dz
  }| j                  j                  | j                  ||      S # t        $ r5  | j                  j                  dd|i| j                  j                  cY S w xY w)a'  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int
            The number of out of sample forecasts from the end of the
            sample.

        Returns
        -------
        forecast : ndarray
            Array of out of sample forecasts
        freq   r   )rU   rV   h )getattrr%   _index
isinstanceintpdDatetimeIndexPeriodIndexshaperT   r&   AttributeError_predictr4   )r$   stepsrX   rU   rV   s        r7   forecastzHoltWintersResults.forecast   s	   	K4::,,fa8DdC(Z

!!B$4$4bnn#E. 

))"-4jj''+edl:

))//2ema'::%%dkkC%HH 	K&4::&&>>$++>JJJ	Ks   C=D   ;D>=D>c                 "   ddl m} ddlm} | j                  }|j
                  j                  dz   }d}| j                  j                  j                  }t        |t        j                        r|j                  d   }n&t        |t        j                        r|j                  }| j                  j                  dn| j                  j                   }ddddd	d
}| j"                  d   }	|	rdnd}
t        |	t$              r|	n| j"                  d   }t        |t&              r|d}d|gfd|j
                  j                  gfdt%        t)        j*                  | j,                              gfd|| j                  j.                     gfd|| j                  j                     gfdt%        |      gfdt%        |
      gfdt%        |      gfg}dt%        t1        | j                  j2                              gfd| j4                  dgfd| j6                  dgfd| j8                  dgfd| j:                  dgfddg} |       }|j=                  | |||        | j>                  }d! }g }|jA                         D ]\  \  }}|jC                   ||jD                  d"         |jD                  d   d#t%        tG        |jD                  d$               d#g       ^  ||g d%d&tI        |jJ                        '      }|jL                  jC                  |       |S )(a6  
        Summarize the fitted Model

        Returns
        -------
        smry : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        r   )Summary)SimpleTablez Model ResultsendogNAdditiveMultiplicativeNone)addadditivemulmultiplicativeN
use_boxcoxTFlamdaz>10.5fzDep. Variable:zModel:z
Optimized:zTrend:z	Seasonal:zSeasonal Periods:zBox-Cox:zBox-Cox Coeff.:zNo. Observations:SSEz5.3fAICBICAICC)zDate:N)zTime:N)gleftgrighttitlec                 "   t        j                  |       }d}t        j                  |       rt        |       dS |dk7  rt	        t        j
                  |            }|dkD  s|dk  r| dS t        d|z
  d      }d| d	}|j                  |       S )
NrY   >20r      z>20.5g   z{:>20.zf})npabsisnanstrr`   log10minformat)xabs_xscaledecfmts        r7   _fmtz(HoltWintersResults.summary.<locals>._fmtc  s    FF1IEExx{a&&zBHHUO,qyEBJF$a%i#CC5$C::a= r8   rY   r~      )coeffcoder+    )headersr|   stubs)'statsmodels.iolib.summaryrj   statsmodels.iolib.tablerk   r%   r6   __name__r   
orig_endogr_   ra   	DataFramecolumnsSeriesnameseasonalseasonal_periodsr&   r   floatr   anyr+   r-   lenrl   r'   r(   r*   r)   add_table_2colsr/   iterrowsappendilocboollistindextables)r$   rj   rk   r%   r|   dep_variabler   r   lookup	transformbox_cox_transformbox_cox_coefftop_left	top_rightsmry	formattedr   tab_valsparams_tables                        r7   summaryzHoltWintersResults.summary  s    	67

((+;;ZZ__//
j",,/%--a0L
BII.%??L zz""* ,, 	 "#.
 KK-	$-D5#Is3IW9M 	 mU+,V4M~.0012Ct~~ 6789tzz//0126$**"5"5678 3'7#8"9:#/012]!3 45	
 !3s4::+;+;'<#=">?()()()4(*+
	 y% 	 	
 ))		!  ))+ 	GAtJJ1&yy|C(4		!-.s3	 #2y'	
 	<(r8   c                    |dv rddd|   }|dvrt        d      ||dk(  r| j                  j                  }nC|dk(  rd	}n;| j                  j                  |      \  }}}t	        |t
              r|j                  }|d	k  r|| j                  j                  z  }|| j                  j                  kD  rt        d
      | j                  j                  }	| j                  j                  }
| j                  j                  }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }t        | j                  j                  d      }dd| j                  j                  z  z   |dz   | j                  j                  z  z   |
z   }|dk(  }|	dk(  }|dk(  }|r#t        j                   }t        j"                  }d}n"t        j$                  }t        j                   }d	}|rt        j                   }d}nt        j$                  }d	}| j&                  }| j                  }| j(                  }t        j*                  ||f      }t        j*                  |dz   |f      } t        j*                  |dz   |f      }!t        j*                  ||z   |f      }"|d	k(  r-| j                  d   | dddf<   | j                  d   |!dddf<   n||dz
     | dddf<   ||dz
     |!dddf<   d	|k  r^||k  rY| j                  d   }#t        j,                  |#|d |d| f      }$t        j.                  |$|df      j0                  |"| dddf<   n2t        j.                  |||z
  | |df      j0                  |"| dddf<   |	||!ddddf<   d}d	}|||"ddddf<   d	}|
sd}|rt3        | j4                  |      }%n| j4                  }%|dk(  r| j                  j6                  |%z
  }&n| j                  j6                  |%z
  |%z  }&t        j8                  t        j:                  |&dz        t=        |&      |z
  z        }'t	        |t        j>                        r |j@                  ||fk7  rt        d      |}(nI|dk(  r&t        jB                  jE                  |&||fd      }(n||$t        jB                  jG                  ||      |'z  }(nt	        |tH              r5t        jB                  jK                  |      })|)jG                  ||      |'z  }(nt	        |t        jB                  jJ                        r|jG                  ||      |'z  }(nwt        d      t	        |tL        tN        f      r&|jQ                  |&      }* |jR                  |*d||fi}(n0t	        |tT              r|jS                  ||f      }(nt        d      tW        |      D ]  }+ ||!|+dz
  ddf   |      }, || |+dz
  ddf   |,      }-|"|+|z
  ddf   }. ||-|.      }/|dk(  r(d}0|rd|.z  nd}1|r|1| |+dz
  ddf   z  n|1}2|rd|-z  nd}3n.|/}0|rd	n|.}1|r|1| |+dz
  ddf   z  n|1| |+dz
  ddf   z   }2|rd	n|-}3|/|0|(|+ddf   z  z   ||+ddf<   |-|||-z  |1z   z  |(|+ddf   z  z   | |+ddf<   |,|||,z  |2z   z  |(|+ddf   z  z   |!|+ddf<   |.|||.z  |3z   z  |(|+ddf   z  z   |"|+ddf<    |rtY        ||      }t        jZ                  t        j\                  |            }4|j@                  d	   dk(  r|j^                  dkD  r	|4dddf   }4t	        | j                  j`                  tb              s|4S | j                  je                  |||z   dz
        \  }}}}5|dk(  r.tg        jh                  |4|5| j                  jj                        }4|4S tg        jl                  |4|5       }4|4S )!a  
        Random simulations using the state space formulation.

        Parameters
        ----------
        nsimulations : int
            The number of simulation steps.
        anchor : int, str, or datetime, optional
            First period for simulation. The simulation will be conditional on
            all existing datapoints prior to the `anchor`.  Type depends on the
            index of the given `endog` in the model. Two special cases are the
            strings 'start' and 'end'. `start` refers to beginning the
            simulation at the first period of the sample, and `end` refers to
            beginning the simulation at the first period after the sample.
            Integer values can run from 0 to `nobs`, or can be negative to
            apply negative indexing. Finally, if a date/time index was provided
            to the model, then this argument can be a date string to parse or a
            datetime type. Default is 'end'.
        repetitions : int, optional
            Number of simulated paths to generate. Default is 1 simulated path.
        error : {"add", "mul", "additive", "multiplicative"}, optional
            Error model for state space formulation. Default is ``"add"``.
        random_errors : optional
            Specifies how the random errors should be obtained. Can be one of
            the following:

            * ``None``: Random normally distributed values with variance
              estimated from the fit errors drawn from numpy's standard
              RNG (can be seeded with the `random_state` argument). This is the
              default option.
            * A distribution function from ``scipy.stats``, e.g.
              ``scipy.stats.norm``: Fits the distribution function to the fit
              errors and draws from the fitted distribution.
              Note the difference between ``scipy.stats.norm`` and
              ``scipy.stats.norm()``, the latter one is a frozen distribution
              function.
            * A frozen distribution function from ``scipy.stats``, e.g.
              ``scipy.stats.norm(scale=2)``: Draws from the frozen distribution
              function.
            * A ``np.ndarray`` with shape (`nsimulations`, `repetitions`): Uses
              the given values as random errors.
            * ``"bootstrap"``: Samples the random errors from the fit errors.

        random_state : int or np.random.RandomState, optional
            A seed for the random number generator or a
            ``np.random.RandomState`` object. Only used if `random_errors` is
            ``None``. Default is ``None``.

        Returns
        -------
        sim : pd.Series, pd.DataFrame or np.ndarray
            An ``np.ndarray``, ``pd.Series``, or ``pd.DataFrame`` of simulated
            values.
            If the original data was a ``pd.Series`` or ``pd.DataFrame``, `sim`
            will be a ``pd.Series`` if `repetitions` is 1, and a
            ``pd.DataFrame`` of shape (`nsimulations`, `repetitions`) else.
            Otherwise, if `repetitions` is 1, a ``np.ndarray`` of shape
            (`nsimulations`,) is returned, and if `repetitions` is not 1 a
            ``np.ndarray`` of shape (`nsimulations`, `repetitions`) is
            returned.

        Notes
        -----
        The simulation is based on the state space model of the Holt-Winter's
        methods. The state space model assumes that the true value at time
        :math:`t` is randomly distributed around the prediction value.
        If using the additive error model, this means:

        .. math::

            y_t &= \hat{y}_{t|t-1} + e_t\\
            e_t &\sim \mathcal{N}(0, \sigma^2)

        Using the multiplicative error model:

        .. math::

            y_t &= \hat{y}_{t|t-1} \cdot (1 + e_t)\\
            e_t &\sim \mathcal{N}(0, \sigma^2)

        Inserting these equations into the smoothing equation formulation leads
        to the state space equations. The notation used here follows
        [1]_.

        Additionally,

        .. math::

           B_t &= b_{t-1} \circ_d \phi\\
           L_t &= l_{t-1} \circ_b B_t\\
           S_t &= s_{t-m}\\
           Y_t &= L_t \circ_s S_t,

        where :math:`\circ_d` is the operation linking trend and damping
        parameter (multiplication if the trend is additive, power if the trend
        is multiplicative), :math:`\circ_b` is the operation linking level and
        trend (addition if the trend is additive, multiplication if the trend
        is multiplicative), and :math:`\circ_s` is the operation linking
        seasonality to the rest.

        The state space equations can then be formulated as

        .. math::

           y_t &= Y_t + \eta \cdot e_t\\
           l_t &= L_t + \alpha \cdot (M_e \cdot L_t + \kappa_l) \cdot e_t\\
           b_t &= B_t + \beta \cdot (M_e \cdot B_t + \kappa_b) \cdot e_t\\
           s_t &= S_t + \gamma \cdot (M_e \cdot S_t + \kappa_s) \cdot e_t\\

        with

        .. math::

           \eta &= \begin{cases}
                       Y_t\quad\text{if error is multiplicative}\\
                       1\quad\text{else}
                   \end{cases}\\
           M_e &= \begin{cases}
                       1\quad\text{if error is multiplicative}\\
                       0\quad\text{else}
                   \end{cases}\\

        and, when using the additive error model,

        .. math::

           \kappa_l &= \begin{cases}
                       \frac{1}{S_t}\quad
                       \text{if seasonality is multiplicative}\\
                       1\quad\text{else}
                   \end{cases}\\
           \kappa_b &= \begin{cases}
                       \frac{\kappa_l}{l_{t-1}}\quad
                       \text{if trend is multiplicative}\\
                       \kappa_l\quad\text{else}
                   \end{cases}\\
           \kappa_s &= \begin{cases}
                       \frac{1}{L_t}\quad\text{if seasonality is
                                               multiplicative}\\
                       1\quad\text{else}
                   \end{cases}

        When using the multiplicative error model

        .. math::

           \kappa_l &= \begin{cases}
                       0\quad
                       \text{if seasonality is multiplicative}\\
                       S_t\quad\text{else}
                   \end{cases}\\
           \kappa_b &= \begin{cases}
                       \frac{\kappa_l}{l_{t-1}}\quad
                       \text{if trend is multiplicative}\\
                       \kappa_l + l_{t-1}\quad\text{else}
                   \end{cases}\\
           \kappa_s &= \begin{cases}
                       0\quad\text{if seasonality is multiplicative}\\
                       L_t\quad\text{else}
                   \end{cases}

        References
        ----------
        .. [1] Hyndman, R.J., & Athanasopoulos, G. (2018) *Forecasting:
           principles and practice*, 2nd edition, OTexts: Melbourne,
           Australia. OTexts.com/fpp2. Accessed on February 28th 2020.
        )rq   rs   rp   rr   )rp   rr   zerror must be 'add' or 'mul'!NrV   rU   r   z/Cannot anchor simulation outside of the sample.rt   ru   smoothing_levelsmoothing_trendsmoothing_seasonaldamping_trendrY   r   initial_levelrZ   initial_trendinitial_seasonszNIf random_errors is an ndarray, it must have shape (nsimulations, repetitions)	bootstrapT)sizereplacezWArgument random_state must be None, an integer, or an instance of np.random.RandomStater   )r   z,Argument random_errors has unexpected value!)r   r   )r   )7
ValueErrorr%   nobs_get_index_locr_   slicerU   r-   damped_trendr   r&   maxr   	has_trendhas_seasonalr   multiplypowerrp   r,   r.   emptyconcatenatetileTr   r2   _ysqrtsumr   ndarrayrd   randomchoicerandnr`   RandomStater   r   fitrvsr   ranger   
atleast_1dsqueezer   r   r   _get_prediction_indexra   r   endog_namesr   )6r$   nsimulationsanchorrepetitionserrorrandom_errorsrandom_state	start_idxr   r-   dampedr   rt   ru   alphabetagammaphimn_paramsmul_seasonal	mul_trend	mul_errorop_bop_d	neutral_bop_s	neutral_sr,   r   r.   ylvlbsr   _sfittedr0   sigmaepsrngr&   tb0l0s0y0etakappa_lkappa_bkappa_ssimr   s6                                                         r7   simulatezHoltWintersResults.simulate  s   d 22!&%@GE&<== >Vu_

IwI"jj77?OIq!)U+%OO	q=(Itzz&NOO 

  ((::&&[[.
G$-.{{,-01kk/*

++Q/$**&&&'1u

///0  	  5(UN	UN	 ;;D88DI66D;;DI;;DI66DI 

HHlK01hhq(+67HHlQ&45HHlQ&45>_5CAJ{{?3Ab!eHy1}-CAJi!m,Ab!eH	>i1n"kk*;<O ,fZi.@AB [!$4577Aqbc1fIy1}y1K3Ca qbc1fI
 =AadGCDAadGEC D--u5F&&FE>JJMMF*EZZ]]V+v5Euax(CJ,ABC mRZZ0""|[&AA 2   Ck)))""\;7 # C "#iioolK@5HL#.ii++L9iik:UBL"))*?*?@"(({CeK >  {'CD"&&u-F#-##VN<2MNCy1##,)D#ECKLL|$ 	JAaAqk3'Bc!a%(mR(B1q5!8Bb"B~$0!b&a5>'CAqM1G$0!b&a+! ! c!a%(m+ 3q1uax=0 
  ,!3QT?*AadGUi"nw&>?#ad)KKC1I49r>G#;<s1a4yHHAadG5INW$<=AqD	IIAadG/	J2 1e$AmmBJJqM*771:?qvvzdAg,C$**//:6J99y</!3
1a !))Cu4::3I3IJC 
 ,,s%0C
r8   r   )NN)rY   )NrY   rp   NN)r   
__module____qualname____doc__r   propertyr(   r)   r*   r'   r%   setterr,   r+   r-   r.   r/   r2   r3   r4   r0   r1   r5   rT   rh   r   r	  __classcell__)r6   s   @r7   r   r      s   +~ %%(N           \\          & & " " ! ! ! !     ! ! " ";2K<gX ir8   r   c                   t    e Zd ZdddddddZ eej                  e      ZdddZ eej                  e      Zy)HoltWintersResultsWrapperrows)r2   r,   r0   r.   r-   slopedates)rT   rh   N)	r   r
  r  _attrsr   r
   _wrap_attrs_methods_wrap_methodsr\   r8   r7   r  r    sK    F n88&AK"8H < <hGMr8   r  )numpyr   pandasra   scipy.specialr   scipy.statsr   r   r   scipy.stats.distributionsr   statsmodels.base.datar   statsmodels.base.modelr	   statsmodels.base.wrapperr
   r   r   r   r  r\   r8   r7   <module>r!     sX      $ 
 0 , * Y YxH H *,> ?r8   