U
    Kvfe                     @   s   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	 d	eZG d
d deZeee dS )    N)
inv_boxcox)boxcoxrv_continuousrv_discrete)	rv_frozen)
PandasData)Results)ResultsWrapperpopulate_wrapperunion_dictsc                       s$  e Zd ZdZd1 fdd	Zedd Zedd Zed	d
 Zedd Z	edd Z
e
jdd Z
edd Zedd Zedd Zedd Zedd Zedd Zedd Zedd Zed d! Zed"d# Zed$d% Zejd&d% Zd2d'd(Zd3d*d+Zd,d- Zd4d/d0Z  ZS )5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.
    Nc                    sz   |j | _ t || || _|| _|| _|| _|| _|| _|| _	|	| _
|
| _|| _|| _|| _|| _|| _|| _|| _d S 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__ G/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/tsa/holtwinters/results.pyr   B   s$    zHoltWintersResults.__init__c                 C   s   | j S )z3
        The Akaike information criterion.
        )r   r!   r5   r5   r6   r%   i   s    zHoltWintersResults.aicc                 C   s   | j S )z@
        AIC with a correction for finite sample sizes.
        )r   r7   r5   r5   r6   r&   p   s    zHoltWintersResults.aiccc                 C   s   | j S )z5
        The Bayesian information criterion.
        )r   r7   r5   r5   r6   r'   w   s    zHoltWintersResults.bicc                 C   s   | j S )zS
        The sum of squared errors between the data and the fittted value.
        )r   r7   r5   r5   r6   r$   ~   s    zHoltWintersResults.ssec                 C   s   | j S )zA
        The model used to produce the results instance.
        r   r7   r5   r5   r6   r"      s    zHoltWintersResults.modelc                 C   s
   || _ d S r   r8   r!   valuer5   r5   r6   r"      s    c                 C   s   | j S )zO
        An array of the levels values that make up the fitted values.
        )r   r7   r5   r5   r6   r)      s    zHoltWintersResults.levelc                 C   s   | j S )zU
        Flag indicating if model parameters were optimized to fit the data.
        )r   r7   r5   r5   r6   r(      s    zHoltWintersResults.optimizedc                 C   s   | j S )zN
        An array of the trend values that make up the fitted values.
        )r   r7   r5   r5   r6   r*      s    zHoltWintersResults.trendc                 C   s   | j S )zQ
        An array of the seasonal values that make up the fitted values.
        )r   r7   r5   r5   r6   r+      s    zHoltWintersResults.seasonc                 C   s   | 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   r7   r5   r5   r6   r,      s    z#HoltWintersResults.params_formattedc                 C   s   | j S )z/
        An array of the fitted values
        )r   r7   r5   r5   r6   r/      s    zHoltWintersResults.fittedvaluesc                 C   s   | j S )zI
        An array of both the fitted values and forecast values.
        )r   r7   r5   r5   r6   r0      s    zHoltWintersResults.fittedfcastc                 C   s   | j S )z1
        An array of the forecast values
        )r   r7   r5   r5   r6   r1      s    zHoltWintersResults.fcastvaluesc                 C   s   | j S )zR
        An array of the residuals of the fittedvalues and actual values.
        )r   r7   r5   r5   r6   r-      s    zHoltWintersResults.residc                 C   s   | j S )zJ
        The k parameter used to remove the bias in AIC, BIC etc.
        )r   r7   r5   r5   r6   r.      s    zHoltWintersResults.kc                 C   s   | j S )zX
        Optimization results if the parameters were optimized to fit the data.
        r    r7   r5   r5   r6   r2      s    zHoltWintersResults.mle_retvalsc                 C   s
   || _ d S r   r;   r9   r5   r5   r6   r2      s    c                 C   s   | 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endr5   r5   r6   r<      s    zHoltWintersResults.predict   c                 C   s   zt | jjdd}t|tsXt| jjtjtjfrX| jjd | }| jjd ||  }n| jjjd }|| d }| jj	| j
||dW S  tk
r   | jjf d|i| j
j Y S X dS )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
        freqr?   r   )r=   r>   hN)getattrr"   _index
isinstanceintpdZDatetimeIndexZPeriodIndexshaper<   r#   AttributeErrorZ_predictr1   )r!   Zstepsr@   r=   r>   r5   r5   r6   forecast   s     
zHoltWintersResults.forecastc                 C   s<  ddl m} ddlm} | j}|jjd }d}| jjj}t	|t
jrP|jd }nt	|t
jrb|j}| jjdkrrdn| jj}ddddd	d
}| jd }	|	rdnd}
t	|	tr|	n| jd }t	|trd|}d|gfd|jjgfdtt| 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t| jjgfdd| jgfdd| jgfdd| jgfdd| jgfddg}| }|j| |||d  | j }d!d" }g }|! D ]D\}}|"||j#d# d$|j#d d$tt$|j#d% g q||d&d'd(gd)t%|j&d*}|j'"| |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endogNZAdditiveZMultiplicativeNone)addadditivemulmultiplicativeN
use_boxcoxTFlamdaz	{:>10.5f}zDep. Variable:zModel:z
Optimized:zTrend:z	Seasonal:zSeasonal Periods:zBox-Cox:zBox-Cox Coeff.:zNo. Observations:ZSSEz{:5.3f}ZAICZBICZAICC)zDate:N)zTime:N)ZgleftZgrighttitlec                 S   sv   t | }d}t | r$t| dS |dkr:tt |}|dksJ|dk rTd| S td| d}d|}|| S )	Nr?   z>20r      z	{:>20.5g}   z{{:>20.{0}f}})npabsisnanstrrF   log10formatmin)xZabs_xZscaledecfmtr5   r5   r6   _fmtc  s    



z(HoltWintersResults.summary.<locals>._fmtr?   z{0:>20}   Zcoeffcoder(    )headersrU   Zstubs)(Zstatsmodels.iolib.summaryrK   Zstatsmodels.iolib.tablerL   r"   r4   __name__r   
orig_endogrE   rG   	DataFramecolumnsSeriesnameseasonalseasonal_periodsr#   r\   floatr^   rY   anyr(   r*   lenrM   r$   r%   r'   r&   Zadd_table_2colsr,   ZiterrowsappendZilocboollistindexZtables)r!   rK   rL   r"   rU   Zdep_variableri   ro   lookupZ	transformZbox_cox_transformZbox_cox_coeffZtop_leftZ	top_rightZsmry	formattedrc   tab_valsZparams_tabler5   r5   r6   summary  s    





   zHoltWintersResults.summaryrO   c           6      C   s  |dkrddd| }|dkr&t d|dks6|dkr@| jj}n0|dkrNd	}n"| j|\}}}t|trp|j}|d	k r|| jj7 }|| jjkrt 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  |d | jj  |
 }|dk}|	dk}|dk}|rNtj}tj}d}ntj}tj}d	}|rptj}d}n
tj}d	}| j}| j}| j}t||f}t|d |f} t|d |f}!t|| |f}"|d	kr| j
d | dddf< | j
d |!dddf< n0||d  | dddf< ||d  |!dddf< d	|kr||kr| j
d }#t|#|d |d| f}$t|$|dfj|"| dddf< n0t||| | |dfj|"| dddf< |	dkr||!ddddf< d}d	}|dkr||"ddddf< d	}|
sd}|r0t| j|}%n| j}%|dkrN| jj|% }&n| jj|% |% }&tt|&d t|&|  }'t|tjr|j ||fkrt d|}(n|dkrtj!j"|&||fdd}(n|dkrJ|dkrtj!#|||' }(nTt|t$rtj!%|})|)#|||' }(n*t|tj!j%r@|#|||' }(nt dnVt|t&t'frz|(|&}*|j)|*d||fi}(n&t|t*r|j)||fd}(nt dt+|D ]}+||!|+d ddf |},|| |+d ddf |,}-|"|+| ddf }.||-|.}/|dkrVd}0|rd|. nd}1|r>|1| |+d ddf  n|1}2|rPd|- nd}3nV|/}0|rdd	n|.}1|r|1| |+d ddf  n|1| |+d ddf  }2|rd	n|-}3|/|0|(|+ddf   ||+ddf< |-|||- |1  |(|+ddf   | |+ddf< |,|||, |2  |(|+ddf   |!|+ddf< |.|||. |3  |(|+ddf   |"|+ddf< q|rtt,||}t-t.|}4|j d	 dkr|j/dkr|4dddf }4t| jj0t1s|4S | j2||| d \}}}}5|dkrt3j4|4|5| jj5d}4nt3j6|4|5d }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.
        )rP   rR   rO   rQ   )rO   rQ   zerror must be 'add' or 'mul'!Nr>   r=   r   z/Cannot anchor simulation outside of the sample.rS   rT   Zsmoothing_levelZsmoothing_trendZsmoothing_seasonalZdamping_trendr?   rd   Zinitial_levelrA   Zinitial_trendinitial_seasonszNIf random_errors is an ndarray, it must have shape (nsimulations, repetitions)Z	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!)rv   rm   )rv   )7
ValueErrorr"   ZnobsZ_get_index_locrE   slicer=   r*   Zdamped_trendrn   r#   maxro   Z	has_trendZhas_seasonalrY   multiplypowerrO   r)   r+   emptyZconcatenateZtileTr   r/   Z_ysqrtsumrr   ZndarrayrH   randomchoiceZrandnrF   ZRandomStater   r   ZfitZrvsr   ranger   Z
atleast_1dZsqueezer~   r   r   Z_get_prediction_indexrG   rl   Zendog_namesrj   )6r!   ZnsimulationsanchorZrepetitionserrorZrandom_errorsZrandom_stateZ	start_idxrz   r*   Zdampedrn   rS   rT   alphabetagammaphimZn_paramsZmul_seasonalZ	mul_trendZ	mul_errorZop_bZop_dZ	neutral_bZop_sZ	neutral_sr)   r   r+   yZlvlbsr}   Z_sZfittedr-   sigmaZepsrngr#   tZb0Zl0s0Zy0etaZkappa_lZkappa_bZkappa_ssimrv   r5   r5   r6   simulate  s0    3










& 


 
  




"$004
 

zHoltWintersResults.simulate)N)NN)r?   )Nr?   rO   NN)rh   
__module____qualname____doc__r   propertyr%   r&   r'   r$   r"   setterr)   r(   r*   r+   r,   r/   r0   r1   r-   r.   r2   r<   rJ   r|   r   __classcell__r5   r5   r3   r6   r      s`   ? '










	








l     r   c                   @   s@   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dS )HoltWintersResultsWrapperZrows)r/   r)   r-   r+   r*   Zslopedates)r<   rJ   N)	rh   r   r   _attrsr   r	   Z_wrap_attrsZ_methodsZ_wrap_methodsr5   r5   r5   r6   r     s   
r   )ZnumpyrY   ZpandasrG   Zscipy.specialr   Zscipy.statsr   r   r   Zscipy.stats.distributionsr   Zstatsmodels.base.datar   Zstatsmodels.base.modelr   Zstatsmodels.base.wrapperr	   r
   r   r   r   r5   r5   r5   r6   <module>   s        a