
    M/Ph\Z                       d Z ddlmZ ddlZddlZddlZddlZ	ddl
mZmZmZ ddlmZ ddlmZ ddlmc mZ ddlmZ ddl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#m$Z$ ddl%m&c mc m'Z( ddl)mZ ddl*m&c m+c m,Z- ddl.m/Z/m0Z0 ddl1m2Z2  G d dej3                  Z4 G d dej5                  Z6 G d dej7                  Z8 ej9        e8e6            G d d          Z: G d dej7                  Z; ej9        e;e:           dS )a  
ETS models for time series analysis.

The ETS models are a family of time series models. They can be seen as a
generalization of simple exponential smoothing to time series that contain
trends and seasonalities. Additionally, they have an underlying state space
model.

An ETS model is specified by an error type (E; additive or multiplicative), a
trend type (T; additive or multiplicative, both damped or undamped, or none),
and a seasonality type (S; additive or multiplicative or none).
The following gives a very short summary, a more thorough introduction can be
found in [1]_.

Denote with :math:`\circ_b` the trend operation (addition or
multiplication), with :math:`\circ_d` the operation linking trend and dampening
factor :math:`\phi` (multiplication if trend is additive, power if trend is
multiplicative), and with :math:`\circ_s` the seasonality operation (addition
or multiplication).
Furthermore, let :math:`\ominus` be the respective inverse operation
(subtraction or division).

With this, it is possible to formulate the ETS models as a forecast equation
and 3 smoothing equations. The former is used to forecast observations, the
latter are used to update the internal state.

.. math::

    \hat{y}_{t|t-1} &= (l_{t-1} \circ_b (b_{t-1}\circ_d \phi))\circ_s s_{t-m}\\
    l_{t} &= \alpha (y_{t} \ominus_s s_{t-m})
             + (1 - \alpha) (l_{t-1} \circ_b (b_{t-1} \circ_d \phi))\\
    b_{t} &= \beta/\alpha (l_{t} \ominus_b l_{t-1})
             + (1 - \beta/\alpha) b_{t-1}\\
    s_{t} &= \gamma (y_t \ominus_s (l_{t-1} \circ_b (b_{t-1}\circ_d\phi))
             + (1 - \gamma) s_{t-m}

The notation here follows [1]_; :math:`l_t` denotes the level at time
:math:`t`, `b_t` the trend, and `s_t` the seasonal component. :math:`m` is the
number of seasonal periods, and :math:`\phi` a trend damping factor.
The parameters :math:`\alpha, \beta, \gamma` are the smoothing parameters,
which are called ``smoothing_level``, ``smoothing_trend``, and
``smoothing_seasonal``, respectively.

Note that the formulation above as forecast and smoothing equation does not
distinguish different error models -- it is the same for additive and
multiplicative errors. But the different error models lead to different
likelihood models, and therefore will lead to different fit results.

The error models specify how the true values :math:`y_t` are updated. In the
additive error model,

.. math::

    y_t = \hat{y}_{t|t-1} + e_t,

in the multiplicative error model,

.. math::

    y_t = \hat{y}_{t|t-1}\cdot (1 + e_t).

Using these error models, it is possible to formulate state space equations for
the ETS models:

.. 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::

   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,

and

.. 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}

When fitting an ETS model, the parameters :math:`\alpha, \beta`, \gamma,
\phi` and the initial states `l_{-1}, b_{-1}, s_{-1}, \ldots, s_{-m}` are
selected as maximizers of log likelihood.

References
----------
.. [1] Hyndman, R.J., & Athanasopoulos, G. (2019) *Forecasting:
   principles and practice*, 3rd edition, OTexts: Melbourne,
   Australia. OTexts.com/fpp3. Accessed on April 19th 2020.
    )OrderedDictN)normrv_continuousrv_discrete)	rv_frozen)descriptionsforg)SimpleTable)
fmt_params)cache_readonly)Bunch)
array_like	bool_likeint_likestring_like)base)_initialization_simple_initialization_heuristic)freq_to_periodc                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 d0 fd	Z	 	 	 d1dZ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	d             Ze	d             Ze	d             Ze	d             Ze	d             Zd Zd Ze	d             Zd Zd Ze	d             Ze	d              Zd! Z d" Z!	 	 	 	 	 	 d2 fd%	Z"	 	 	 	 d3d&Z#e$j%        d'             Z&d( Z'd4d)Z(d* Z)d5d+Z*e	d,             Z+	 d6d-Z,	 d6d.Z-d/ Z. xZ/S )7ETSModela>  
    ETS models.

    Parameters
    ----------
    endog : array_like
        The observed time-series process :math:`y`
    error : str, optional
        The error model. "add" (default) or "mul".
    trend : str or None, optional
        The trend component model. "add", "mul", or None (default).
    damped_trend : bool, optional
        Whether or not an included trend component is damped. Default is
        False.
    seasonal : str, optional
        The seasonality model. "add", "mul", or None (default).
    seasonal_periods : int, optional
        The number of periods in a complete seasonal cycle for seasonal
        (Holt-Winters) models. For example, 4 for quarterly data with an
        annual cycle or 7 for daily data with a weekly cycle. Required if
        `seasonal` is not None.
    initialization_method : str, optional
        Method for initialization of the state space model. One of:

        * 'estimated' (default)
        * 'heuristic'
        * 'known'

        If 'known' initialization is used, then `initial_level` must be
        passed, as well as `initial_trend` and `initial_seasonal` if
        applicable.
        'heuristic' uses a heuristic based on the data to estimate initial
        level, trend, and seasonal state. 'estimated' uses the same heuristic
        as initial guesses, but then estimates the initial states as part of
        the fitting process.  Default is 'estimated'.
    initial_level : float, optional
        The initial level component. Only used if initialization is 'known'.
    initial_trend : float, optional
        The initial trend component. Only used if initialization is 'known'.
    initial_seasonal : array_like, optional
        The initial seasonal component. An array of length `seasonal_periods`.
        Only used if initialization is 'known'.
    bounds : dict or None, optional
        A dictionary with parameter names as keys and the respective bounds
        intervals as values (lists/tuples/arrays).
        The available parameter names are, depending on the model and
        initialization method:

        * "smoothing_level"
        * "smoothing_trend"
        * "smoothing_seasonal"
        * "damping_trend"
        * "initial_level"
        * "initial_trend"
        * "initial_seasonal.0", ..., "initial_seasonal.<m-1>"

        The default option is ``None``, in which case the traditional
        (nonlinear) bounds as described in [1]_ are used.

    Notes
    -----
    The ETS models are a family of time series models. They can be seen as a
    generalization of simple exponential smoothing to time series that contain
    trends and seasonalities. Additionally, they have an underlying state
    space model.

    An ETS model is specified by an error type (E; additive or multiplicative),
    a trend type (T; additive or multiplicative, both damped or undamped, or
    none), and a seasonality type (S; additive or multiplicative or none).
    The following gives a very short summary, a more thorough introduction can
    be found in [1]_.

    Denote with :math:`\circ_b` the trend operation (addition or
    multiplication), with :math:`\circ_d` the operation linking trend and
    dampening factor :math:`\phi` (multiplication if trend is additive, power
    if trend is multiplicative), and with :math:`\circ_s` the seasonality
    operation (addition or multiplication). Furthermore, let :math:`\ominus`
    be the respective inverse operation (subtraction or division).

    With this, it is possible to formulate the ETS models as a forecast
    equation and 3 smoothing equations. The former is used to forecast
    observations, the latter are used to update the internal state.

    .. math::

        \hat{y}_{t|t-1} &= (l_{t-1} \circ_b (b_{t-1}\circ_d \phi))
                           \circ_s s_{t-m}\\
        l_{t} &= \alpha (y_{t} \ominus_s s_{t-m})
                 + (1 - \alpha) (l_{t-1} \circ_b (b_{t-1} \circ_d \phi))\\
        b_{t} &= \beta/\alpha (l_{t} \ominus_b l_{t-1})
                 + (1 - \beta/\alpha) b_{t-1}\\
        s_{t} &= \gamma (y_t \ominus_s (l_{t-1} \circ_b (b_{t-1}\circ_d\phi))
                 + (1 - \gamma) s_{t-m}

    The notation here follows [1]_; :math:`l_t` denotes the level at time
    :math:`t`, `b_t` the trend, and `s_t` the seasonal component. :math:`m`
    is the number of seasonal periods, and :math:`\phi` a trend damping
    factor. The parameters :math:`\alpha, \beta, \gamma` are the smoothing
    parameters, which are called ``smoothing_level``, ``smoothing_trend``, and
    ``smoothing_seasonal``, respectively.

    Note that the formulation above as forecast and smoothing equation does
    not distinguish different error models -- it is the same for additive and
    multiplicative errors. But the different error models lead to different
    likelihood models, and therefore will lead to different fit results.

    The error models specify how the true values :math:`y_t` are
    updated. In the additive error model,

    .. math::

        y_t = \hat{y}_{t|t-1} + e_t,

    in the multiplicative error model,

    .. math::

        y_t = \hat{y}_{t|t-1}\cdot (1 + e_t).

    Using these error models, it is possible to formulate state space
    equations for the ETS models:

    .. 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::

       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,

    and

    .. 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}

    When fitting an ETS model, the parameters :math:`\alpha, \beta`, \gamma,
    \phi` and the initial states `l_{-1}, b_{-1}, s_{-1}, \ldots, s_{-m}` are
    selected as maximizers of log likelihood.

    References
    ----------
    .. [1] Hyndman, R.J., & Athanasopoulos, G. (2019) *Forecasting:
       principles and practice*, 3rd edition, OTexts: Melbourne,
       Australia. OTexts.com/fpp3. Accessed on April 19th 2020.
    addNF	estimatednonec                    t                                          |d |||           d}t          |d|          d d         | _        t          |d|d          | _        | j        | j        d d         | _        t          |d	          | _        t          |d
|d          | _        | j        | j        d d         | _        | j        d u| _        | j        d u| _	        | j	        rMt          |dd          | _        |t          | j                  | _        | j        dk    rt          d          nd| _        t          j        | j        dk              r0| j        dk    s| j        dk    s| j        dk    rt          d          | j        r| j        st          d          |                     |||	|
           |                     |           | j        dk    s| j        8| j        dk    s| j        t(          j        | _        d S t(          j        | _        d S | j        dk    s| j        t(          j        | _        d S t(          j        | _        d S )N)exogdatesfreqmissing)r   muladditivemultiplicativeerroroptions   trendT)r&   optionaldamped_trendseasonalseasonal_periods)r)      z'seasonal_periods must be larger than 1.r   r!   z^endog must be strictly positive when using multiplicative error, trend or seasonal components.z#Can only dampen the trend componentr   )super__init__r   r$   r(   r   r*   r+   	has_trendhas_seasonalr   r,   r   _index_freq
ValueErrornpanyendogset_initialization_method
set_boundssmooth_ets_smooth_add_add_smoothing_func_ets_smooth_add_mul_ets_smooth_mul_add_ets_smooth_mul_mul)selfr6   r$   r(   r*   r+   r,   initialization_methodinitial_levelinitial_trendinitial_seasonalboundsr   r   r    r&   	__class__s                   i/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/exponential_smoothing/ets.pyr/   zETSModel.__init__  s   $ 	Eg 	 	
 	
 	
 ? AAA"1"E
 7Gd
 
 

 :!BQBDJ%lNCC#j'D
 
 
 =$ M"1"-DM4/ M5 	&$, "4t% % %D!  '(6t7G(H(H%$)) !JKKK * %&D! 6$*/"" 	J%zU""}%%F    	DT^ 	DBCCC 	&&!		
 	
 	
 	 :$*"4}%%)>'-'A$$$'-'A$$$}%%)>'-'A$$$'-'A$$$    c                 x   t          |dd          | _        | j        dk    rB|t          d          | j        r|t          d          | j        r|t          d          n| j        d	k    r,t          | j        | j        | j        | j	        
          \  }}}n{| j        dk    rp| j
        dd| j	        dz  z  z   k     r,t          | j        | j        | j        | j	        
          \  }}}n+t          | j        | j        | j        | j	        
          \  }}}| j        sd}| j        sd}|| _        || _        || _        t          t!          | j        t%          j        | j                                      | _        t          t!          | j        t%          j        | j                                      | _        dS )a  
        Sets a new initialization method for the state space model.

        Parameters
        ----------
        initialization_method : str, optional
            Method for initialization of the state space model. One of:

            * 'estimated' (default)
            * 'heuristic'
            * 'known'

            If 'known' initialization is used, then `initial_level` must be
            passed, as well as `initial_trend` and `initial_seasonal` if
            applicable.
            'heuristic' uses a heuristic based on the data to estimate initial
            level, trend, and seasonal state. 'estimated' uses the same
            heuristic as initial guesses, but then estimates the initial states
            as part of the fitting process. Default is 'estimated'.
        initial_level : float, optional
            The initial level component. Only used if initialization is
            'known'.
        initial_trend : float, optional
            The initial trend component. Only used if initialization is
            'known'.
        initial_seasonal : array_like, optional
            The initial seasonal component. An array of length
            `seasonal_periods`. Only used if initialization is 'known'.
        r@   )r   known	heuristicr%   rI   NzW`initial_level` argument must be provided when initialization method is set to "known".zy`initial_trend` argument must be provided for models with a trend component when initialization method is set to "known".z`initial_seasonal` argument must be provided for models with a seasonal component when initialization method is set to "known".rJ   )r(   r+   r,   r   
      r   )r   r@   r3   r0   r1   r   r6   r(   r+   r,   nobsr   rA   rB   rC   r   zip_internal_param_namesr4   arange_k_params_internal_internal_params_indexparam_namesk_params_params_index)r?   r@   rA   rB   rC   s        rF   r7   z"ETSModel.set_initialization_method  s3   H &1!#7&
 &
 &
"
 %00$ E   ~ -"7 @  
   %5%= @  
 ';66
 *
j!%!6	  	   ';66y2T%:a%? @@@@
 +J*!]%)%:	  	!!$$ .J*!]%)%:	  	!!$ ~ 	M  	! ** 0 '2*BId6M,N,NOO'
 '
# ) ")DM":":;;
 
rG   c                     |	i | _         dS t          |t          t          f          st	          d          |D ]=}|| j        vrt	          d| d          t          ||         d| dd          ||<   >|| _         dS )	a  
        Set bounds for parameter estimation.

        Parameters
        ----------
        bounds : dict or None, optional
            A dictionary with parameter names as keys and the respective bounds
            intervals as values (lists/tuples/arrays).
            The available parameter names are in ``self.param_names``.
            The default option is ``None``, in which case the traditional
            (nonlinear) bounds as described in [1]_ are used.

        References
        ----------
        .. [1] Hyndman, R.J., & Athanasopoulos, G. (2019) *Forecasting:
           principles and practice*, 3rd edition, OTexts: Melbourne,
           Australia. OTexts.com/fpp3. Accessed on April 19th 2020.
        Nzbounds must be a dictionaryzInvalid key: z in bounds dictionaryzbounds[])rL   )shape)rD   
isinstancedictr   r3   rS   r   )r?   rD   keys      rF   r8   zETSModel.set_boundsh  s    & >DKKKft[&9:: @ !>???  d...$BBBB   )3K!13!1!1!1  s !DKKKrG   c                     t          j        | j        d          }|j        dk    rt	          d          |j        t           j        k    r!t          j        | j        dt                    }|dfS )zH
        Prepare data for use in the state space representation
        WC)requirementsr-   zendog must be 1-dimensional)r^   dtypeN)r4   require
orig_endogndimr3   r_   doublefloat)datar6   s     rF   prepare_datazETSModel.prepare_data  sn    
 
4?>>>:??:;;;;")##Jd%  E d{rG   c                     | j         S NrM   r?   s    rF   nobs_effectivezETSModel.nobs_effective  
    yrG   c                     dS Nr-    rj   s    rF   k_endogzETSModel.k_endog  s    qrG   c                     d                     d | j        | j        | j        fD                       }| j        r|dd         dz   |d         z   }|S )N c                 \    g | ])}t          |          d                                          *S )r   )strupper).0ss     rF   
<listcomp>z'ETSModel.short_name.<locals>.<listcomp>  s<        Aq	!!  rG   r   rL   d)joinr$   r(   r+   r*   )r?   names     rF   
short_namezETSModel.short_name  sj    ww *dj$-@  
 
  	-!9s?T!W,DrG   c                     dg}| j         r|dgz  }| j        r|dgz  }| j        r|dgz  }| j        dk    r;|dgz  }| j         r|dgz  }| j        r!|d t	          | j                  D             z  }|S )	Nsmoothing_levelsmoothing_trendsmoothing_seasonaldamping_trendr   rA   rB   c                     g | ]}d | S zinitial_seasonal.ro   rv   is     rF   rx   z)ETSModel._param_names.<locals>.<listcomp>  s0           ,++     rG   )r0   r1   r*   r@   ranger,   r?   rS   s     rF   _param_nameszETSModel._param_names  s    ()> 	/-..K 	2011K 	-O,,K %44O,,K~ 100      "4#899       rG   c                 @    dg}| j         r|dgz  }| j        r|dgz  }|S )Nlevelr(   r+   )r0   r1   r?   namess     rF   state_nameszETSModel.state_names  s;    	> 	gYE 	"j\!ErG   c                 v    dg}| j         r|dgz  }| j        r!|d t          | j                  D             z  }|S )NrA   rB   c                     g | ]}d | S r   ro   r   s     rF   rx   z0ETSModel.initial_state_names.<locals>.<listcomp>  s.       ,-'A''  rG   )r0   r1   r   r,   r   s     rF   initial_state_nameszETSModel.initial_state_names  sd     !> 	'o&&E 	  16t7L1M1M   E rG   c                 
    g dS )Nr~   r   r   r   ro   rj   s    rF   _smoothing_param_nameszETSModel._smoothing_param_names  s    
 
 
 	
rG   c                 P    ddg}|d t          | j                  D             z  }|S )NrA   rB   c                     g | ]}d | S r   ro   r   s     rF   rx   z:ETSModel._internal_initial_state_names.<locals>.<listcomp>  s.     
 
 
()###
 
 
rG   )r   r,   r   s     rF   _internal_initial_state_namesz&ETSModel._internal_initial_state_names  sL     
 	 
 
-243H-I-I
 
 
 	
 rG   c                      | j         | j        z   S rh   )r   r   rj   s    rF   rO   zETSModel._internal_param_names  s    *T-OOOrG   c                 Z    dt          | j                  z   t          | j                  z   S rn   )intr0   r1   rj   s    rF   	_k_stateszETSModel._k_states  s'    3t~&&&T->)?)???rG   c                     d| j         z   S )NrL   r,   rj   s    rF   _k_states_internalzETSModel._k_states_internal  s    4(((rG   c                 :    | j         t          | j                  z   S rh   )r   r   r*   rj   s    rF   _k_smoothing_paramszETSModel._k_smoothing_params  s    ~D$5 6 666rG   c                 l    dt          | j                  z   t          | j                  
 | j        z  z   S rn   )r   r0   r1   r,   rj   s    rF   _k_initial_stateszETSModel._k_initial_states  s<     $.!!"4$%%%(==>	
rG   c                 >    | j         }| j        dk    r
|| j        z  }|S )Nr   )r   r@   r   )r?   ks     rF   rT   zETSModel.k_params  s*    $%44''ArG   c                     d| j         z   S )N   r   rj   s    rF   rQ   zETSModel._k_params_internal	  s    t,,,rG   c                 v   t          j        | j        |j                  }t	          | j                  D ]\  }}| j        |         }||         ||<   | j        sd|d<   | j        dk    rO| j	        |d<   | j
        |d<   t          j        | j                  r| j        |dd<   n| j        ddd	         |dd<   |S )
zu
        Converts a parameter array passed from outside to the internally used
        full parameter array.
        r_   r-   r'   r         r   N)r4   zerosrQ   r_   	enumeraterS   rR   r*   r@   rA   rB   isscalarrC   )r?   paramsinternalr   r{   internal_idxs         rF   _internal_paramszETSModel._internal_params  s     8D36<HHH !122 	/ 	/GAt6t<L%+AYH\""  	HQK%44,HQK,HQK{4011 ;#4  $4TTrT:rG   c                     t          j        | j                  }t          | j                  D ]\  }}| j        |         }||         ||<   |S )zB
        Converts internal parameters to model parameters
        )r4   emptyrT   r   rS   rR   )r?   r   r   r   r{   r   s         rF   _model_paramszETSModel._model_params$  sU     $-(( !122 	/ 	/GAt6t<L .F1IIrG   c                 0    dt          | j                  z   S rn   )r   r0   rj   s    rF   _seasonal_indexzETSModel._seasonal_index.  s    3t~&&&&rG   c                     t          j        | j        | j        f          }g d}t	          | j                  D ]-\  }}|                    |          }|d d |f         |d d |f<   .|S )N)r   r(   r+   )r4   r   rM   r   r   r   index)r?   xhatstates	all_namesr   r{   idxs          rF   _get_stateszETSModel._get_states2  sx    49dn566222	 !122 	( 	(GAt//$''C3<F111a4LLrG   c                    |                      |          }t          |t          j        t          j        f          r|j        }t          j        | j        d| j	        z   f          }|dddf         |dddf<   | j
        r|dddf         |dddf<   | j        rZt          | j	                  D ]E}|d| j        |z
  | j        f         ||dd|z   f<   |dd|z            ddd         |d|d|z   f<   F|S )ze
        Converts a state matrix/dataframe to the (nobs, 2+m) matrix used
        internally
        rL   Nr   r-   r   r   )r   rY   pdSeries	DataFramevaluesr4   r   rM   r,   r0   r1   r   r   )r?   r   r   internal_paramsinternal_statesjs         rF   _get_internal_stateszETSModel._get_internal_states:  s/   
 //77fry",788 	#]F(DIq43H/H#IJJ &qqq!t1> 	1$*111a4LOAAAqD! 	O4011 O O-3	A%t';;.AE	* />a!a%i.H2.N!QU
++rG   c                     dddddS )Ng?g{Gz?\(\?r   ro   rj   s    rF   _default_start_paramszETSModel._default_start_paramsN  s      ##"&!	
 
 	
rG   c                    g }| j         D ]+}|| j        v r |                    | j        |                    ,| j        dk    rt          |          }|| j        gz  }| j        r|| j        gz  }| j	        rl| j
        }| j        dk    r"||xx         |d         z  cc<   ||d         z  }n!||xx         |d         z  cc<   ||d         z  }||                                z  }t          j        |          S )z
        Default start params in the format of external parameters.
        This should not be called directly, but by calling
        ``self.start_params``.
        r   r!   r   )r   rS   appendr   r@   lenrA   r0   rB   r1   rC   r+   tolistr4   array)r?   r   plvl_idxrC   s        rF   _start_paramszETSModel._start_paramsW  s.    , 	= 	=AD$$$d8;<<<%44&kkGt)**F~ /4-..  
4 $(#8 =E))7OOO'7';;OOO$(8(<<$$7OOO'7';;OOO$(8(<<$*11333xrG   c                 P   |                      |          }| j        D ]}| j        |         }|| j        vr||         gdz  | j        |<   n)| j        r"|| j        v r| j        |         gdz  | j        |<   || j        v r)t          j        ||         dz   g| j        |         R  ||<   |S )z
        This converts start params to internal params, sets internal-only
        parameters as bounded, sets bounds for fixed parameters, and then makes
        sure that all start parameters are within the specified bounds.
        rL   gMbP?)	r   rO   rR   rS   rD   _has_fixed_params_fixed_paramsr4   clip)r?   r   r   r   r   s        rF   _convert_and_bound_start_paramsz(ETSModel._convert_and_bound_start_paramsv  s     //77+ 	 	A-a0C((( #2#"6!7!!;A' =A1C,C,C"&"4Q"7!81!<ADK')w#C(( [^( ( ($
 rG   c                    t          j        | j                  dz   t          j        | j                  dz
  d\  d<   d<   | j        dk    rEt           j         dd<   t           j        dd<   | j        dk    rd\  d<   d<   nd	\  d<   d<   | j        D ].}| j        |         }|| j	        v r| j	        |         \  |<   |<   /fd
t          | j                  D             S )Ng-C6?)g?r   r'   r   r   r   r!   )r-   r-   r   r   c                 0    g | ]}|         |         fS ro   ro   )rv   r   lbubs     rF   rx   z*ETSModel._setup_bounds.<locals>.<listcomp>  s%    GGG1A1GGGrG   )r4   r   rQ   onesr@   infr+   rO   rR   rD   r   )r?   r   r   r   r   s      @@rF   _setup_boundszETSModel._setup_bounds  s    Xd-..5WT,--4 !1r!u%44wBqtHvBqtH }%%!%22!%22 + 	2 	2A-a0CDK#';q> 3CGGGGGd.E(F(FGGGGrG     Tc                 ~   || j         }nt          j        |          }| j        rdt	          | j                  dk    rLt          j        t          | j                                                            }t          |dd          }	nz| 
                    |          }
|                                 }d| j        v}|r|
dxx         |
d         z  cc<   d| j        v}|r|
dxx         d|
d         z
  z  cc<   t          j        | j        t          j                  }t          j        |
          }g }g |d	<   t#          | j                  D ]s}||         d         ||         d         k    rd
||<   ||         d         ||<   7|                    |
|                    |d	                             ||                    tt          j        |          }t          j        | j                  }t          j        | j        | j        f          }d
|d<   |                                 5   t-                      j        |f||||||fd||||d
d|}	ddd           n# 1 swxY w Y   t          j        |
          }d}t#          | j                  D ]+}||         r||         ||<   |	j        |         ||<   |dz  },|r|dxx         |d         z  cc<   |r|dxx         d|d         z
  z  cc<   |                     |          }|r|S |                     |          }|	|_        |	j        |_        |	j        |_        |S )a		  
        Fit an ETS model by maximizing log-likelihood.

        Log-likelihood is a function of the model parameters :math:`\alpha,
        \beta, \gamma, \phi` (depending on the chosen model), and, if
        `initialization_method` was set to `'estimated'` in the constructor,
        also the initial states :math:`l_{-1}, b_{-1}, s_{-1}, \ldots, s_{-m}`.

        The fit is performed using the L-BFGS algorithm.

        Parameters
        ----------
        start_params : array_like, optional
            Initial values for parameters that will be optimized. If this is
            ``None``, default values will be used.
            The length of this depends on the chosen model. This should contain
            the parameters in the following order, skipping parameters that do
            not exist in the chosen model.

            * `smoothing_level` (:math:`\alpha`)
            * `smoothing_trend` (:math:`\beta`)
            * `smoothing_seasonal` (:math:`\gamma`)
            * `damping_trend` (:math:`\phi`)

            If ``initialization_method`` was set to ``'estimated'`` (the
            default), additionally, the parameters

            * `initial_level` (:math:`l_{-1}`)
            * `initial_trend` (:math:`l_{-1}`)
            * `initial_seasonal.0` (:math:`s_{-1}`)
            * ...
            * `initial_seasonal.<m-1>` (:math:`s_{-m}`)

            also have to be specified.
        maxiter : int, optional
            The maximum number of iterations to perform.
        full_output : bool, optional
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
        disp : bool, optional
            Set to True to print convergence messages.
        callback : callable callback(xk), optional
            Called after each iteration, as callback(xk), where xk is the
            current parameter vector.
        return_params : bool, optional
            Whether or not to return only the array of maximizing parameters.
            Default is False.
        **kwargs
            Additional keyword arguments to pass to the optimizer.

        Returns
        -------
        results : ETSResults
        Nr   )r   mle_retvalsmle_settingsr   r-   r   rL   r   rD   Tapprox_gradlbfgs)fargsmethodmaxiterfull_outputdispcallbackskip_hessian)start_paramsr4   asarrayr   r   _free_params_indexlistr   r   r   r   r   rD   r   rQ   int64
empty_liker   r   rM   r   use_internal_logliker.   fitr   r   r9   mlefitr   r   )r?   r   r   r   r   r   return_paramskwargsfinal_paramsr   internal_start_paramsrD   use_beta_staruse_gamma_staris_fixedfixed_valuesparams_without_fixedr   yhatr   fitted_paramsidx_without_fixedresultrE   s                          rF   r   zETSModel.fit  s   D ,LL:l33L! I	=c$*A&B&Ba&G&G:d4+=+D+D+F+F&G&GHHL#D  FF %)$H$H% %! ''))F .T[@M E%a(((,A!,DD(((1DN I%a(((A0Ea0H,HH((( x 7rxHHHH=)>??L#% !F84233 7 7!9Q<6!9Q<//"&HQK&,QilLOO(//0Ea0HIII8$++F1I6666#%:.B#C#C  8DI&&D8TY(?@AAD$(F=!**,,  $(  $%& ## +%!%   !               * M*?@@M !4233 + +A; +'3AM!$$'-}5F'GM!$%*%% 5a   M!$44    9a   Aa(8$88   --m<<L 	[[..F"FM!'!3F"("5FMs   ')II #I c           
         t          j        |          r!t          j        | j        t                    }n| j        }|Ft          j        | j        t           j                  }t          j        | j        |j	                  }n t          j
        |t           j                  }|                     ||||||||           |                     ||          }	| j         dz  t          j        dt           j        z  t          j        |	dz            z            dz   z  }
| j        dk    rWdddt          j        ||dk                       z   z  z  ||dk    <   |
t          j        t          j        |                    z  }
|
S )	a  
        Log-likelihood function to be called from fit to avoid reallocation of
        memory.

        Parameters
        ----------
        params : np.ndarray of np.float
            Model parameters: (alpha, beta, gamma, phi, l[-1],
            b[-1], s[-1], ..., s[-m]). If there are no fixed values this must
            be in the format of internal parameters. Otherwise the fixed values
            are skipped.
        yhat : np.ndarray
            Array of size (n,) where fitted values will be written to.
        xhat : np.ndarray
            Array of size (n, _k_states_internal) where fitted states will be
            written to.
        is_fixed : np.ndarray or None
            Boolean array indicating values which are fixed during fitting.
            This must have the full length of internal parameters.
        fixed_values : np.ndarray or None
            Array of fixed values (arbitrary values for non-fixed parameters)
            This must have the full length of internal parameters.
        use_beta_star : boolean
            Whether to internally use beta_star as parameter
        use_gamma_star : boolean
            Whether to internally use gamma_star as parameter
        r   Nre   rL   r-   r!   g:0yE>r   )r4   iscomplexobjr   r6   complexr   rQ   r   r   r_   ascontiguousarrayr;   
_residualsrM   logpimeanr$   abssum)r?   r   r   r   r   r   r   r   re   reslogLs              rF   _loglike_internalzETSModel._loglike_internalP  so   J ?6"" 	:dj888DD:Dx 7rxHHHH8'v|  LL +HBHEEEH		
 		
 		
 oodo..	zA~BE	BGC1H4E4E(E!F!F!JK:  41rvd419o/F/F+F#GHDOBF26$<<(((DrG   c              #   `   K   | j         }| j        | _         	 d V  || _         d S # || _         w xY wrh   )logliker  )r?   external_loglikes     rF   r   zETSModel.use_internal_loglike  sE      <-	,EEE+DLLL+DL++++s   $ 	-c                 0   |                      t          j        |                    }t          j        | j        |j                  }t          j        | j        | j        f|j                  }|                     t          j        |          ||          S )a  
        Log-likelihood of model.

        Parameters
        ----------
        params : np.ndarray of np.float
            Model parameters: (alpha, beta, gamma, phi, l[-1],
            b[-1], s[-1], ..., s[-m])

        Notes
        -----
        The log-likelihood of a exponential smoothing model is [1]_:

        .. math::

           l(\theta, x_0|y) = - \frac{n}{2}(\log(2\pi s^2) + 1)
                              - \sum\limits_{t=1}^n \log(k_t)

        with

        .. math::

           s^2 = \frac{1}{n}\sum\limits_{t=1}^n \frac{(\hat{y}_t - y_t)^2}{k_t}

        where :math:`k_t = 1` for the additive error model and :math:`k_t =
        y_t` for the multiplicative error model.

        References
        ----------
        .. [1] J. K. Ord, A. B. Koehler R. D. and Snyder (1997). Estimation and
           Prediction for a Class of Dynamic Nonlinear Statistical Models.
           *Journal of the American Statistical Association*, 92(440),
           1621-1629
        r   )r   r4   r   r   rM   r_   r   r  )r?   r   r   r   r   s        rF   r  zETSModel.loglike  s    F &&rz&'9'9::x	666xY/0
 
 
 %%bj&8&8$EEErG   c                 D    || j         }| j        dk    r||z
  |z  S ||z
  S )z$Calculates residuals of a predictionNr!   )r6   r$   )r?   r   re   s      rF   r  zETSModel._residuals  s4    <:D:4K4''$;rG   c                    |                      |          }t          j        | j                  }t          j        | j        | j        f          }t          j        | j        t          j                  }t          j        | j        |j                  }| 	                    || j
        ||||           |                     |          }| j        rm|                     d| j        dz
            \  }}}}	t          j        ||	          }dg}
| j        r|
dgz  }
| j        r|
dgz  }
t          j        ||	|
          }||fS )	aE  
        Exponential smoothing with given parameters

        Parameters
        ----------
        params : array_like
            Model parameters

        Returns
        -------
        yhat : pd.Series or np.ndarray
            Predicted values from exponential smoothing. If original data was a
            ``pd.Series``, returns a ``pd.Series``, else a ``np.ndarray``.
        xhat : pd.DataFrame or np.ndarray
            Internal states of exponential smoothing. If original data was a
            ``pd.Series``, returns a ``pd.DataFrame``, else a ``np.ndarray``.
        r   r   r-   r   r   r(   r+   r   columns)r   r4   r   rM   r   rQ   r   r   r_   r;   r6   r   
use_pandas_get_prediction_indexr   r   r0   r1   r   )r?   r   r   r   r   r   r   r   _r   
statenamess              rF   _smoothzETSModel._smooth  sE   $ //77x	""xD$;<==8D328DDDx 7v|LLLTZtX|	
 	
 	

 !!$''? 	K!7749q=IINAq!U9T///D!J~ (wi'
  +zl*
\&zJJJFV|rG   c                     t          j        |          }|                     |          }|                     |||          S )aB  
        Exponential smoothing with given parameters

        Parameters
        ----------
        params : array_like
            Model parameters
        return_raw : bool, optional
            Whether to return only the state space results or the full results
            object. Default is ``False``.

        Returns
        -------
        result : ETSResultsWrapper or tuple
            If ``return_raw=False``, returns a ETSResultsWrapper
            object. Otherwise a tuple of arrays or pandas objects, depending on
            the format of the endog data.
        )r4   r   r  _wrap_results)r?   r   
return_rawresultss       rF   r9   zETSModel.smooth  s<    & F##,,v&&!!&':>>>rG   c                 "    dt           t          fiS )Nr   )
ETSResultsETSResultsWrapperrj   s    rF   _res_classeszETSModel._res_classes  s    
$5677rG   c                     |                     dd          }|dk    r"|r | j        |fi |}n  | j        |fd|i|}nt          d          |S )a  
        Hessian matrix of the likelihood function, evaluated at the given
        parameters

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the hessian.
        approx_centered : bool
            Whether to use a centered scheme for finite difference
            approximation
        approx_complex_step : bool
            Whether to use complex step differentiation for approximation

        Returns
        -------
        hessian : ndarray
            Hessian matrix evaluated at `params`

        Notes
        -----
        This is a numerical approximation.
        r   approxapprox_centeredz#Invalid Hessian calculation method.)get_hessian_complex_step_hessian_finite_differenceNotImplementedError)r?   r   r(  approx_complex_stepr   r   hessians          rF   r.  zETSModel.hessian  s    4 Hh//X" 4$4VFFvFF9$9 ,;?E  &&KLLLrG   c                     |                     dd          }|dk    r"|r | j        |fi |}n  | j        |fd|i|}nt          d          |S )Nr   r'  r(  zInvalid score method.)r)  _score_complex_step_score_finite_differencer,  )r?   r   r(  r-  r   r   scores          rF   r2  zETSModel.score@  s     Hh//X" 00BB6BB55 ,;?E  &&=>>>rG   c                     d S rh   ro   )r   argsr   s      rF   updatezETSModel.updateQ  s    rG   )r   NFNNr   NNNNNNr   )NNN)Nr   TTNF)NNFFrh   )F)FT)0__name__
__module____qualname____doc__r/   r7   r8   staticmethodrf   propertyrk   rp   r|   r   r   r   r   r   rO   r   r   r   r   rT   rQ   r   r   r   r   r   r   r   r   r   r   r  
contextlibcontextmanagerr   r  r  r  r9   r%  r.  r2  r5  __classcell__rE   s   @rF   r   r      sD       F FV )^B ^B ^B ^B ^B ^BF k
 k
 k
 k
Z !  !  !D   \   X   X 	 	 X	   X*   X   X 
 
 X
   X P P XP @ @ X@ ) ) X) 7 7 X7 
 
 X
   X - - X-  .   ' ' X'    ( 
 
 X
     X <  2$H $H $HP Y Y Y Y Y Y@ F F F FP , , ,(F (F (FT   ' ' 'R? ? ? ?. 8 8 X8 BF& & & &R BF   "      rG   r   c                        e Zd ZdZ fdZed             Zed             Zed             Zed             Z	d Z
d Z	 	 	 	 ddZddZd Zd ZddZ	 	 	 	 	 	 ddZd fd	Z xZS )r#  zR
    Results from an error, trend, seasonal (ETS) exponential smoothing model
    c           	          |\  }}|                     |           _        |                    |           _        | _        t	          j         j        dz            }t                                          |||           g d}|D ]!}t           |t          ||                     " fd j
        j        pg D              _         j
                            |          }	| _         j
        j        r j        j        }
n j        }
t	          j        |j                   _        |
d d df          _        |	d          _         j         j        d<    j        d          _         j         _         j        rK|
d d df          _        |	d          _         j         j        d<    j        d          _         j         _         j        rv|
d d  j
        j        f          _        |	d	d          d d d
          _          j          j         j
        j        d <    j         j
        j                  _!         j!         _"         j#        r|	d          _$         j$         _%         j&        tO           j(                  z
  }|dz    _)        t	          j         j*                   _+        t	          j,         j*        d           _-         j*         j+        z
   j-        z   _.        t_           d          si  _0        d _1        i  _2        d _3        d _4        d}	 d  _5         j&        dk    r,t	          j        d           _6        d _5        d j0        d<   d S  j7         _6        tp          d         9                    |           j0        d<   d S # t          j:        j;        $ rQ d _5        tO           j                  }t	          j        ||f          t          j<        z   _6        d j0        d<   Y d S w xY w)NrL   )scale)	r|   r$   r(   r+   r*   r0   r1   r,   r@   c                 0    g | ]}|j         v rd |z  n|S )z
%s (fixed))fixed_params)rv   r{   r?   s     rF   rx   z'ETSResults.__init__.<locals>.<listcomp>r  s@     
 
 
 $(4+<#<#<L4$
 
 
rG   r   r   r-   r   r   r   r'   )ddofcov_kwdsr'  TFzcomplex-stepr   zNo parameters estimated.description)approx_typezHCovariance matrix could not be calculated: singular. information matrix.cov_type)=r  _llfr  _fittedvaluesr4   r
  r.   r/   setattrgetattrmodelrS   r   r   r  ilocr   r   initial_stater   rA   r   alphar~   r0   sloperB   betar   r1   r   seasonrC   gammar   r*   phir   rT   r   rD  df_modelresid
mean_residstdscale_residstandardized_forecasts_errorhasattrrF  rI  _cache_cov_approx_complex_step_cov_approx_centered_rankcov_params_defaultcov_params_approxr   formatlinalgLinAlgErrornan)r?   rN  r   r!  r   r   rB  model_definition_attrsattrr   r   k_free_paramsapprox_type_strrT   rE   s   `             rF   r/   zETSResults.__init__Z  s   
dMM&))	**400! 1,--e444
"
 
"
 
"
 + 	6 	6DD$t 4 45555
 
 
 
/52
 
 
 *55f==:  	![%FF[FXe&=>>AAAqD\
,Q/ $ 21[^
#z> 	-1DJ!0!3D$($6Dq!ADI#'9D  	1 DJ$>!>?DK$3ABB$7"$=D! % 
*,, TZ%?@DJ&*jD# 	*&q)DH!%D D,=(>(>>%) '$*--6$*1555J(-) tZ(( 	DM   )-%$)!(	DJ}!!*,(6*:*:'
/Im,,,*.*@'/;H/E/L/L / 0M 0 0m,,, y$ 	 	 	DJ4;''H&(h(/C&D&Drv&MD#' M*%%%%		s   <N 5N A!O32O3c                     | j         S rh   ri   rj   s    rF   rk   zETSResults.nobs_effective  rl   rG   c                     | j         S rh   )rK  rj   s    rF   fittedvalueszETSResults.fittedvalues  s    !!rG   c                     | j         S rh   )r  rj   s    rF   rX  zETSResults.resid  s
    rG   c                     | j         S )zH
        log-likelihood function evaluated at the fitted params
        )rJ  rj   s    rF   llfzETSResults.llf  s    
 yrG   c                    | j                             | j                  }|dk    r|S | j                             | j        | j                  }t          j        d| j        z             }|dd         |dd<   ||dz
  ddf         |dd<   |S )z
        Returns internal parameter representation of smoothing parameters and
        "initial" states for prediction/simulation, that is the states just
        before the first prediction/simulation step.
        r   r   r   r-   N)rN  r   r   r   r   r4   r   r,   )r?   	start_idxr   r   start_states        rF   _get_prediction_paramsz!ETSResults._get_prediction_params  s     *55dkBB>>"""j==T[ O (1t'<#<==K.qs3K!-i!mQQQ.>?KOrG   c                    |}| j         }| j        r| j        }| j        r/| j        }| j        }t          j        |dz
  |z  t                    }| j	        r| j
        }| j        j        }	|	dk    rd|dz  |dz
  z  z   S |	dk    r,d|dz
  |dz  ||z  |z  z   |dz  |z  dz  d|z  dz
  z  z   z  z   S |	dk    rwd|dz  |dz
  z  z   ||z  |z  d|z
  dz  z  d|z  d|z
  z  ||z  z   z  z   ||z  d||z  z
  z  d|z
  dz  d|dz  z
  z  z  d|z  d|dz  z
  z  ||z  dd|z  z   ||z  z
  z  z   z  z
  S |	dk    rd|dz  |dz
  z  z   ||z  d|z  |z   z  z   S |	d	k    rGd|dz
  |dz  ||z  |z  z   |dz  dz  |z  d|z  dz
  z  z   z  z   ||z  d|z  |z   ||z  |dz   z  z   z  z   S |	d
k    rd|dz  |dz
  z  z   ||z  d|z  |z   z  z   ||z  |z  d|z
  dz  z  d|z  d|z
  z  ||z  z   z  z   ||z  d||z  z
  z  d|z
  dz  d|dz  z
  z  z  d|z  d|dz  z
  z  ||z  dd|z  z   ||z  z
  z  z   z  z
  d|z  |z  |z  d|z
  d||z  z
  z  z  |d||z  z
  z  ||z  d|||z  z  z
  z  z
  z  z   S t          )a   
        References
        ----------
        .. [1] Hyndman, R.J., & Athanasopoulos, G. (2019) *Forecasting:
           principles and practice*, 3rd edition, OTexts: Melbourne,
           Australia. OTexts.com/fpp3. Accessed on April 19th 2020.
        r-   r   ANNrL   AANr   AAdNANAAAAAAdA)r~   r0   r   r1   r   r,   r4   r   r   r*   r   rN  r|   r,  )
r?   stepshrQ  rS  rU  mr   rV  rN  s
             rF   _relative_forecast_variancez&ETSResults._relative_forecast_variance  s    $> 	('D 	3+E%A
AEQ;c222A 	%$C
%E>>uzQU+++e^^A
UT\A--	A0AQUQY0OO   f__1*A&' CZ!^CA~'5yAG,tcz9; CZ1sax<0CA~SAX68 E	Q\2*AGcQh(>?@" e^^uzQU++eai1u9u;L.MMMe^^q5QJdlQ&'qyAo)QUQY78 !)q5y504!8q1u3EEFG	 f__1*A&'!)q5y5012 #:>G>#u9C(4#:577 CZ1sax<0CA~SAX68 E	Q\2*AGcQh(>?@ X%+CAqL13AqL)C1HCAEN8J,KKM, &%rG   Nr-   c                 	   	 |                      |          }|                     |          }t          j        || j        j        f          }t          j        t          |          t          j                  }	t          j        |          }
t          j
        |||	|
          \  }}}}}}||z  }d|z
  |z  }|j        d         }t          j        t          j        |||df          |          }t          j        ||f          }t          j        | j                  }t#          |t          j                  r |j        ||fk    rt'          d          |}ns|dk    r+t          j                            | j        ||fd          }nB||%t          j                            ||          |z  }nt#          |t0                    r9t          j                            |          }|                    ||          |z  }nt#          |t          j        j                  r|                    ||          |z  }nt'          d          t#          |t4          t6          f          r*|                    | j                  } |j        |d	||fi}n=t#          |t<                    r|                    ||f
          }nt'          d          | j        dk    }| j         dk    }| j!        dk    }|rt          j"        }t          j#        }nt          j$        }t          j"        }|rt          j"        }nt          j$        }tK          |          D ]d} |||dz
  dddf         |          }  |||dz
  dddf         |           }!||dz
  d|z   dz
  ddf         }" ||!|"          }#| j!        dk    r,d}$|rd|"z  nd}%|r|%||dz
  dddf         z  n|%}&|rd|!z  nd}'n6|#}$|rdn|"}%|r|%||dz
  dddf         z  n|%||dz
  dddf         z   }&|rdn|!}'|#|$||ddf         z  z   ||ddf<   |!|||!z  |%z   z  ||ddf         z  z   ||dddf<   | ||| z  |&z   z  ||ddf         z  z   ||dddf<   |"|||"z  |'z   z  ||ddf         z  z   ||dddf<   ||dz
  ddddf         ||ddddf<   f|dk    rd tK          |          D             }(nd}(| j        &                    ||||z   dz
  |(          S )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 (i.e. using the
            initial values as simulation anchor), 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 'start'.
            Note: `anchor` corresponds to the observation right before the
            `start` observation in the `predict` method.
        repetitions : int, optional
            Number of simulated paths to generate. Default is 1 simulated path.
        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.
        r   r-   zHIf random is an ndarray, it must have shape (nsimulations, repetitions)!	bootstrapT)sizereplaceNzWArgument random_state must be None, an integer, or an instance of np.random.RandomStater  )r  z,Argument random_errors has unexpected value!r!   r   rL   r   r   r'   c                     g | ]}d |z  S )zsimulation.%dro   )rv   nums     rF   rx   z'ETSResults.simulate.<locals>.<listcomp>^  s    IIIs_s*IIIrG   
simulation)r   )'_get_prediction_start_indexru  r4   r   rN  r   r   r   
zeros_liker9   _initialize_ets_smoothrX   tilereshaper   sqrtrB  rY   ndarrayr3   randomchoicerX  randnr   RandomStater   r   r   rvsr   r+   r(   r$   multiplypowerr   r   
_wrap_data))r?   nsimulationsanchorrepetitionsrandom_errorsrandom_staters  r   xr   r   rQ  	beta_star
gamma_starrV  r  r  rS  rU  nstatesysigmaepsrngr   mul_seasonal	mul_trend	mul_errorop_bop_dop_stBLSYetakappa_lkappa_bkappa_sr   s)                                            rF   simulatezETSResults.simulate:  s   Nj	X 44V<<	 229==HlDJ$ABCC8C--RX>>>}\22 )!X|
 
	
 y Uj( '!*GBJq<!"<=={KKHlK011 
##mRZ00 	M"|[&AAA 3    CCk)))""
,!<d #  CC "#ioolK@@5HL#.. 	i++L99iik::UBL")*?@@ "(({CCeK >   {'CDD 	M"&&tz22F#-#VN<2MNNCCy11 	M##,)D#EECCKLLL }-J%'	J%'	  	;D8DD6D;D 	;DD6D |$$ 	, 	,AQq1ua{^S))AQq1ua{^Q''A!a%QAAA%&AQ

AzU""#/6!a%%Q6?L'Aa!eQkN22W#/6!a%%Q+2!! !2GaAq!!!n,, 1QUAqqq[>1 
  ,2!!#AqqqD	/)AadGUi!mg&=>QTJJAaAAAgJTY]W%<=AqqqD	IIAaAAAgJUi!mg&=>QTJJAaAAAgJAE1R4N+AaQQQhKK ??IIeK6H6HIIIEE Ez$$y)l2Q6e % 
 
 	
rG   c                 .    |                      |d          S )a  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int, str, or datetime, optional
            If an integer, the number of steps to forecast from the end of the
            sample. Can also be a date string to parse or a datetime type.
            However, if the dates index does not have a fixed frequency, steps
            must be an integer. Default

        Returns
        -------
        forecast : ndarray
            Array of out of sample forecasts. A (steps x k_endog) array.
        end)	_forecast)r?   r}  s     rF   forecastzETSResults.forecaste  s    " ~~eU+++rG   c                 Z    |                      ||t          j        |df                    S )z0
        Dynamic prediction/forecasting
        r-   )r  r  )r  r4   r   )r?   r}  r  s      rF   r  zETSResults._forecastx  s4    
 }}&%0D0D  
 
 	
rG   c           
      8   |d}| j                             |||          \  }}}}|||z   dz   k    rt          d          t          |t          t
          j        t          j        f          r$| j         	                    |          \  }}}||z
  }n"t          |t                    r|rd}n|dz   |z
  }|dk    r	d }d }d}	|}
n3|}t          ||z   dz
  |          }t          ||z
  dz   d          }	||z   }
|
dk    rd}n|
dz
  }||z   }||
z
  dz   }||||||
||	||f
S )Nr   r-   z2Prediction start cannot lie outside of the sample.start)rN  r  r3   rY   rt   dtdatetimer   	Timestamp_get_index_locboolminmax)r?   r  dynamicr  r   out_of_sampler  start_smooth
end_smoothnsmoothstart_dynamicanchor_dynamicend_dynamicndynamics                 rF   _handle_prediction_indexz#ETSResults._handle_prediction_index  s   =E (,z'G'G3(
 (
$sM1
 3&***D  
 gR[",?@@ 	* J55g>>MGQoGG&& 	* *'E/
 a<<LJG!MM !LUW_q0#66J*|3a7;;G!GOMA$NN*Q.N M).2
 	
rG   Fc           
      `   |                      ||||          \
  }}}}}}}	}
}}t          j        |
|z             }|
dk    r| j        ||dz            |d|
<   |dk    r|                     ||          ||
d<   ||dz   k    r||dz   z
  }||d         }| j                            |||	          S )aT  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., 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, i.e.,
            the last forecast is end. 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.
        dynamic : bool, int, str, or datetime, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Can also be an absolute date string to parse or a
            datetime type (these are not interpreted as offsets).
            Prior to this observation, true endogenous values will be used for
            prediction; starting with this observation and continuing through
            the end of prediction, forecasted endogenous values will be used
            instead.
        index : pd.Index, optional
            Optionally an index to associate the predicted results to. If None,
            an attempt is made to create an index for the predicted results
            from the model's index or model's row labels.

        Returns
        -------
        forecast : array_like or pd.Series.
            Array of out of in-sample predictions and / or out-of-sample
            forecasts. An (npredict,) array. If original data was a pd.Series
            or DataFrame, a pd.Series is returned.
        r   r-   N)r  r4   r   rn  r  rN  r  )r?   r  r  r  r   r  r  r  r  r  r  r  r  ndiscards                 rF   predictzETSResults.predict  s    b ))%#uEE	
 HWx'(( Q;;,\JN-JKAaiL a<<..>BBAghhK 37??a(H())A z$$Q{;;;rG   r   c                 B    t          t          | ||||||fi |          S )aq  
        Calculates mean prediction and prediction intervals.

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., 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, i.e.,
            the last forecast is end. 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.
        dynamic : bool, int, str, or datetime, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Can also be an absolute date string to parse or a
            datetime type (these are not interpreted as offsets).
            Prior to this observation, true endogenous values will be used for
            prediction; starting with this observation and continuing through
            the end of prediction, forecasted endogenous values will be used
            instead.
        index : pd.Index, optional
            Optionally an index to associate the predicted results to. If None,
            an attempt is made to create an index for the predicted results
            from the model's index or model's row labels.
        method : str or None, optional
            Method to use for calculating prediction intervals. 'exact'
            (default, if available) or 'simulated'.
        simulate_repetitions : int, optional
            Number of simulation repetitions for calculating prediction
            intervals when ``method='simulated'``. Default is 1000.
        **simulate_kwargs :
            Additional arguments passed to the ``simulate`` method.

        Returns
        -------
        PredictionResults
            Predicted mean values and prediction intervals
        )PredictionResultsWrapperPredictionResults)r?   r  r  r  r   r   simulate_repetitionssimulate_kwargss           rF   get_predictionzETSResults.get_prediction  sH    h ($	 	 "	 	
 
 	
rG   皙?c                   
 d| j          d}t                                          ||d|          }| j        j        dk    rt          j        | j                  

j        dk    r
d         
| j        j	        }d| j        j        z  g}|}
fd	t          t          
                    D             }t          |||t          
          }	|j                            d|	           |S )a(  
        Summarize the fitted model

        Parameters
        ----------
        alpha : float, optional
            Significance level for the confidence intervals. Default is 0.05.
        start : int, optional
            Integer of the start observation. Default is 0.

        Returns
        -------
        summary : 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
        zETS()zETS Results)rQ  r  title
model_namer   r-   r   zinitialization method: %sc                 @    g | ]}t          |         d           gS )r   )precr	   )rv   r   r   s     rF   rx   z&ETSResults.summary.<locals>.<listcomp>m  s:       ./fQia((()  rG   )txt_fmtr   )r|   r.   summaryrN  r@   r4   r   rP  rb   r   r   r   r   r   tablesinsert)r?   rQ  r  r  r  r   param_headerparams_stubsparams_datainitial_state_tabler   rE   s             @rF   r  zETSResults.summaryF  s   * /DO...
''//!	 " 
 
 :+{::Xd011F{QJ2E+dj.NNL !L   38V3E3E  K #.\<# # # N!!"&9:::rG   )Nr-   NNr-   )NNFNNNFNNr   )r  N)r6  r7  r8  r9  r/   r   rk   rn  rX  rq  ru  r  r  r  r  r  r  r  r  r>  r?  s   @rF   r#  r#  V  s        h h h h hT   ^ " " ^"   ^   ^  $O& O& O&h i
 i
 i
 i
V	, , , ,&
 
 
<
 <
 <
|D< D< D< D<P !?
 ?
 ?
 ?
B0 0 0 0 0 0 0 0 0 0rG   r#  c                       e Zd ZddddddZ ej        ej        j        e          ZdddZ	 ej        ej        j
        e	          Z
dS )r$  rows)rn  r   rX  rT  rR  r   )r  r  N)r6  r7  r8  _attrswrapunion_dictstsbaseTimeSeriesResultsWrapper_wrap_attrs_methods_wrap_methodsro   rG   rF   r$  r$  y  sx         F #$"'3V K #88H$D$'5x MMMrG   r$  c                   L    e Zd ZdZ	 	 	 	 	 	 ddZed             ZddZdd
ZdS )r  a  
    ETS mean prediction and prediction intervals

    Parameters
    ----------
    results : ETSResults
        Model estimation results.
    start : int, str, or datetime, optional
        Zero-indexed observation number at which to start forecasting,
        i.e., 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, i.e.,
        the last forecast is end. 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.
    dynamic : bool, int, str, or datetime, optional
        Integer offset relative to `start` at which to begin dynamic
        prediction. Can also be an absolute date string to parse or a
        datetime type (these are not interpreted as offsets).
        Prior to this observation, true endogenous values will be used for
        prediction; starting with this observation and continuing through
        the end of prediction, forecasted endogenous values will be used
        instead.
    index : pd.Index, optional
        Optionally an index to associate the predicted results to. If None,
        an attempt is made to create an index for the predicted results
        from the model's index or model's row labels.
    method : str or None, optional
        Method to use for calculating prediction intervals. 'exact' (default,
        if available) or 'simulated'.
    simulate_repetitions : int, optional
        Number of simulation repetitions for calculating prediction intervals.
        Default is 1000.
    **simulate_kwargs :
        Additional arguments passed to the ``simulate`` method.
    NFr   c           
      4   |j         j        | _        |g d}	|j         j        |	v rd}nd}|| _        |                    ||||          \
  }}}
}}}}}}}|                    ||||          | _        | j        j        | _        t          j
        ||z             t          j        z  | _        |dk    r'|j        j        ||dz            | j        d||z
  dz   <   t          |j         j                            | j        | j                            | _         | j        dk    rg }|dk    rI|
dk    rd	}n|
dz
  }t!          |          D ]+}|                     |j        	 d||d
|           |
|z   },|r$|                     |j        |f||d
|           |r<t'          |d         t(          j                  rt)          j        |d          | _        nt          j        |d          | _        | j                            d          | _        d S t          j        ||z             }|dk    r)t!          d|dz             ||t9          ||          z
  d <   ||dz   k    r||dz   z
  }||d          }|j        |                    |          z  | _        d S )N)rw  rx  ry  rz  r{  r|  exact	simulated)r  r  r  r   r   r-   )r6   predict_datesr  r  )r  r  axisr  )rN  r  r|   r   r  r  predicted_meanr   
row_labelsr4   r   rg  r6   re   r   rE   r   r   r  rY   r   r   concatsimulation_resultsconcatenatevarforecast_variancer   r  mser  )r?   r!  r  r  r  r   r   r  r  exact_availabler  r  r  r  r  r  r  sim_resultsr  r   r}  r  s                         rF   r/   zPredictionResults.__init__  sT    "-2>JJJO}'?:: $ ,,UGS%HH	
 &oo[' . 
 
 -3Xg011BF:
Q;;/6|/Aa 0DJq3;?+, #--j .  
 
 

 ;+%%K {{1$$$FF)A-Fw 
. 
.A&&((#)(<  .	    *A-FF ""$G$ -$8  *	     Nz+a.",GG N*,)Ka*H*H*H''*,.1*M*M*M'%)%<%@%@a%@%H%HD"""GHw.//E!|| aA.. "S%>%>>@@ sQw C!G,hii(gAA%HHH """rG   c                     | j         S )z"The variance of the predicted mean)r  rj   s    rF   var_pred_meanzPredictionResults.var_pred_mean	  s     %%rG   r  c                    | j         dk    r]t          j        | j        d|dz  z
  d          }t          j        | j        |dz  d          }t          j        ||f          j        }nat          j        d|dz  z
            }|t          j        | j	                  z  }t          j        | j
        |z
  | j
        |z   f          j        }| j        r0t          j        || j                  }d|ddd	|ddg}||_        |S )
a  
        Calculates prediction intervals by performing multiple simulations.

        Parameters
        ----------
        alpha : float, optional
            The significance level for the prediction interval. Default is
            0.05, that is, a 95% prediction interval.
        r  r-   rL   r  r  zlower PI (alpha=fr  zupper PI (alpha=)r   r4   quantiler  vstackTr   ppfr  r  r  r  r   r   r  r  )r?   rQ  simulated_upper_pisimulated_lower_pipred_intqhalf_interval_sizer   s           rF   r  zPredictionResults.pred_int	  s=    ;+%%!#'UQYQ" " " "$'" " " y"46H!IJJLHHUQY''A!"RWT-C%D%D!Dy'*<<'*<< 
   ? 	%|HDODDDH-5-----5----E  %HrG   r   c                 r   t          j        |                     |                    }i }| j        |d<   | j        dk    rt          j        | j        d          |d<   |d d df         |d<   |d d df         |d	<   t          j        || j	        t          |                                          
          }|S )N)rQ  r
  r  r-   r  mean_numericalr   pi_lowerpi_upperr  )r4   r   r  r  r   r
  r  r   r   r  r   keys)r?   r6   rQ  r  
to_includer  s         rF   summary_framezPredictionResults.summary_frameE	  s    :dmm%m8899
!0
6;+%%+-7'a, , ,J'( "*!!!Q$
:!)!!!Q$
:ldotJOO<M<M7N7N
 
 
 
rG   r  )r  )r   r  )	r6  r7  r8  r9  r/   r;  r  r  r  ro   rG   rF   r  r    s        & &V !b b b bH & & X&$ $ $ $L     rG   r  c                   ^    e Zd ZddddZ ej        e          Zi Z ej        e          ZdS )r  r   )r  r  r6   N)	r6  r7  r8  r  r  r  r  r  r  ro   rG   rF   r  r  V	  sN        !% F
 #$"6**KH$D$X..MMMrG   r  )<r9  collectionsr   r<  r  r  numpyr4   pandasr   scipy.statsr   r   r   scipy.stats.distributionsr   statsmodels.base.covtyper   statsmodels.base.wrapperr   wrapperr  statsmodels.iolib.summaryr
   statsmodels.iolib.tabler   !statsmodels.iolib.tableformattingr   statsmodels.tools.decoratorsr   statsmodels.tools.toolsr   statsmodels.tools.validationr   r   r   r   statsmodels.tsa.base.tsa_modeltsa	tsa_modelr  %statsmodels.tsa.exponential_smoothing1statsmodels.tsa.exponential_smoothing._ets_smoothexponential_smoothing_ets_smoothr9   4statsmodels.tsa.exponential_smoothing.initializationr   r   statsmodels.tsa.tsatoolsr   StateSpaceMLEModelr   StateSpaceMLEResultsr#  ResultsWrapperr$  populate_wrapperr  r  ro   rG   rF   <module>r1     s  L L\ $ # # # # #                 8 8 8 8 8 8 8 8 8 8 / / / / / / 1 1 1 1 1 1 ' ' ' ' ' ' ' ' ' * * * * * * / / / / / / 8 8 8 8 8 8 7 7 7 7 7 7 ) ) ) ) ) )            0 / / / / / / / / / / / 6 6 6 6 6 6 B B B B B B B B B B B B        4 3 3 3 3 3LA A A A At& A A AH$` ` ` ` `* ` ` `F    +   "  ' 4 4 4F F F F F F F FR	/ 	/ 	/ 	/ 	/t2 	/ 	/ 	/  .0A B B B B BrG   