U
    ÃmœdÍe  ã                   @   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__© ú\/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/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º   z†t | 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 }	|	rœdnd}
t	|	tƒr®|	n| jd }t	|tƒrÌd |¡}d|gfd|jjgfdtt | j¡ƒ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_xÚ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_variablerj   rp   ÚlookupZ	transformZbox_cox_transformZbox_cox_coeffÚtop_leftÚ	top_rightZsmryÚ	formattedrd   Ú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r˜t d
ƒ‚| jj}	| jj}
| jj	}| j
d }| j
d }| j
d }| j
d }| j
d }| j
d }t| jjdƒ}dd| jj  |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�r¤t dƒ‚|}(nö|dk�rÌtj!j"|&||fdd�}(nÔ|dk�rJ|dk�rôt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|�r¨d	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?   re   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!)rw   rn   )rw   )7Ú
ValueErrorr"   ZnobsZ_get_index_locrE   Úslicer=   r*   Zdamped_trendro   r#   Úmaxrp   Z	has_trendZhas_seasonalrY   ÚmultiplyÚpowerrO   r)   r+   ÚemptyZconcatenateZtileÚTr   r/   Z_yÚsqrtÚsumrs   ZndarrayrH   ÚrandomÚchoiceZrandnrF   ZRandomStater   r   ÚfitZrvsr   Úranger   Z
atleast_1dZsqueezer�   r   r   Z_get_prediction_indexrG   rm   Zendog_namesrk   )6r!   ZnsimulationsÚanchorZrepetitionsÚerrorZrandom_errorsZrandom_stateZ	start_idxr}   r*   Zdampedro   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Úsimrw   r5   r5   r6   Úsimulate„  s0    3








ÿþýÿ

ÿ& ÿ


 ÿ
  ÿ

ÿ


"ÿý$004
 
ÿ
zHoltWintersResults.simulate)N)NN)r?   )Nr?   rO   NN)ri   Ú
__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 )ÚHoltWintersResultsWrapperÚrows)r/   r)   r-   r+   r*   ZslopeÚdates)r<   rJ   N)	ri   r¡   r¢   Z_attrsr   r	   Z_wrap_attrsZ_methodsZ_wrap_methodsr5   r5   r5   r6   r§   ð  s   ú
r§   )Ú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