U
    Ãmœd]H  ã                   @   sf  d dl mZmZ d dlZd dlmZmZmZm	Z	 d dl
Zd dlZd dlmZ d dlmZmZ d dlmZmZmZ d dlmZ d dlmZmZ d d	lmZmZ d d
lm Z  e	e!e"ejej#ej$f Z%eej&ƒZ'e' (dedddgƒ¡ e' (dedddgƒ¡ e' )ddddddddddddddg¡Z*eej+j&ƒZ'e' )ddg¡Z,eee*dƒd �G d!d"„ d"ƒƒZ-G d#d$„ d$ƒZ.dS )%é    )ÚSubstitutionÚis_int_indexN)ÚAnyÚDictÚOptionalÚUnion)Ú
PandasData)ÚSimpleTableÚSummary)Ú	DocstringÚ	ParameterÚindent)ÚPredictionResults)Úget_index_locÚget_prediction_index)ÚSTLÚDecomposeResult)Ú_check_dynamicÚendogÚmodelZModelzQThe model used to forecast endog after the seasonality has been removed using STLÚmodel_kwargszDict[str, Any]zuAny additional arguments needed to initialized the model using the residuals produced by subtracting the seasonality.ÚperiodÚseasonalÚtrendÚlow_passÚseasonal_degÚ	trend_degÚlow_pass_degÚrobustÚseasonal_jumpÚ
trend_jumpÚlow_pass_jumpÚ
inner_iterÚ
outer_iterz    )Zstl_forecast_paramsc                   @   sV   e Zd ZdZdddddddddddddœdd„Zeeed	ƒd
�ddddœdd„ƒZdS )ÚSTLForecasta˜  
    Model-based forecasting using STL to remove seasonality

    Forecasts are produced by first subtracting the seasonality
    estimated using STL, then forecasting the deseasonalized
    data using a time-series model, for example, ARIMA.

    Parameters
    ----------
%(stl_forecast_params)s

    See Also
    --------
    statsmodels.tsa.arima.model.ARIMA
        ARIMA modeling.
    statsmodels.tsa.ar_model.AutoReg
        Autoregressive modeling supporting complex deterministics.
    statsmodels.tsa.exponential_smoothing.ets.ETSModel
        Additive and multiplicative exponential smoothing with trend.
    statsmodels.tsa.statespace.exponential_smoothing.ExponentialSmoothing
        Additive exponential smoothing with trend.

    Notes
    -----
    If :math:`\hat{S}_t` is the seasonal component, then the deseasonalize
    series is constructed as

    .. math::

        Y_t - \hat{S}_t

    The trend component is not removed, and so the time series model should
    be capable of adequately fitting and forecasting the trend if present. The
    out-of-sample forecasts of the seasonal component are produced as

    .. math::

        \hat{S}_{T + h} = \hat{S}_{T - k}

    where :math:`k = m - h + m \lfloor (h-1)/m \rfloor` tracks the period
    offset in the full cycle of 1, 2, ..., m where m is the period length.

    This class is mostly a convenience wrapper around ``STL`` and a
    user-specified model. The model is assumed to follow the standard
    statsmodels pattern:

    * ``fit`` is used to estimate parameters and returns a results instance,
      ``results``.
    * ``results`` must exposes a method ``forecast(steps, **kwargs)`` that
      produces out-of-sample forecasts.
    * ``results`` may also exposes a method ``get_prediction`` that produces
      both in- and out-of-sample predictions.

    See the notebook `Seasonal Decomposition
    <../examples/notebooks/generated/stl_decomposition.html>`__ for an
    overview.

    Examples
    --------
    >>> import numpy as np
    >>> import pandas as pd
    >>> from statsmodels.tsa.api import STLForecast
    >>> from statsmodels.tsa.arima.model import ARIMA
    >>> from statsmodels.datasets import macrodata
    >>> ds = macrodata.load_pandas()
    >>> data = np.log(ds.data.m1)
    >>> base_date = f"{int(ds.data.year[0])}-{3*int(ds.data.quarter[0])+1}-1"
    >>> data.index = pd.date_range(base_date, periods=data.shape[0], freq="QS")

    Generate forecasts from an ARIMA

    >>> stlf = STLForecast(data, ARIMA, model_kwargs={"order": (2, 1, 0)})
    >>> res = stlf.fit()
    >>> forecasts = res.forecast(12)

    Generate forecasts from an Exponential Smoothing model with trend

    >>> from statsmodels.tsa.statespace import exponential_smoothing
    >>> ES = exponential_smoothing.ExponentialSmoothing
    >>> config = {"trend": True}
    >>> stlf = STLForecast(data, ES, model_kwargs=config)
    >>> res = stlf.fit()
    >>> forecasts = res.forecast(12)
    Né   é   F)r   r   r   r   r   r   r   r   r   r   r    r!   c                C   sT   || _ t||||||	|
||||d�| _|| _|d kr8i n|| _t|dƒsPtdƒ‚d S )N)r   r   r   r   r   r   r   r   r   r    r!   Úfitz$model must expose a ``fit``  method.)Ú_endogÚdictÚ_stl_kwargsÚ_modelÚ_model_kwargsÚhasattrÚAttributeError)Úselfr   r   r   r   r   r   r   r   r   r   r   r   r    r!   © r0   úX/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/tsa/forecasting/stl.pyÚ__init__˜   s$    õ
zSTLForecast.__init__z        )Z
fit_params)r"   r#   Ú
fit_kwargsc          	      C   sz   |dkri n|}t | jf| jŽ}|j||d�}|j|j }| j|f| jŽ}|jf |Ž}t|dƒsht	dƒ‚t
||||| jƒS )aš  
        Estimate STL and forecasting model parameters.

        Parameters
        ----------
%(fit_params)s
        fit_kwargs : Dict[str, Any]
            Any additional keyword arguments to pass to ``model``'s ``fit``
            method when estimating the model on the decomposed residuals.

        Returns
        -------
        STLForecastResults
            Results with forecasting methods.
        N)r"   r#   Úforecastz5The model's result must expose a ``forecast`` method.)r   r(   r*   r'   r   Zresidr+   r,   r-   r.   ÚSTLForecastResults)	r/   r"   r#   r3   ÚstlZstl_fitZmodel_endogÚmodÚresr0   r0   r1   r'   ½   s     ÿ
ÿzSTLForecast.fit)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r2   r   r   Ú_fit_paramsr'   r0   r0   r0   r1   r$   A   s    Zð%r$   c                   @   s,  e Zd ZdZeeddœdd„Zeedœdd„ƒZ	eedœd	d
„ƒZ
eedœdd„ƒZeedœdd„ƒZeedœdd„ƒZedœdd„Zee ee eeef ejdœdd„Zd!eeej eejejf dœdd„Zd"eeeef eejejf dœdd„Zd#ee ee eeef eeef dœdd „ZdS )$r5   a«  
    Results for forecasting using STL to remove seasonality

    Parameters
    ----------
    stl : STL
        The STL instance used to decompose the data.
    result : DecomposeResult
        The result of applying STL to the data.
    model : Model
        The time series model used to model the non-seasonal dynamics.
    model_result : Results
        Model results instance supporting, at a minimum, ``forecast``.
    N)r6   ÚresultÚreturnc                 C   s    || _ || _|| _|| _t |¡| _| jjd | _t	|dt
 | j¡ƒ| _t| jt
jt
jfƒsœt| jƒsœzt
 | j¡| _W n" tk
rš   t
 | j¡| _Y nX d S )Nr   Úindex)Ú_stlÚ_resultr+   Ú_model_resultÚnpÚasarrayr(   ÚshapeÚ_nobsÚgetattrÚpdZ
RangeIndexÚ_indexÚ
isinstanceZDatetimeIndexZPeriodIndexr   Úto_datetimeÚ
ValueError)r/   r6   r>   r   Úmodel_resultr   r0   r0   r1   r2   ì   s    ÿþzSTLForecastResults.__init__)r?   c                 C   s   | j jS )z$The period of the seasonal component)rA   r   ©r/   r0   r0   r1   r   ÿ   s    zSTLForecastResults.periodc                 C   s   | j S )z2The STL instance used to decompose the time series)rA   rO   r0   r0   r1   r6     s    zSTLForecastResults.stlc                 C   s   | j S )z&The result of applying STL to the data)rB   rO   r0   r0   r1   r>   	  s    zSTLForecastResults.resultc                 C   s   | j S )z3The model fit to the additively deseasonalized data)r+   rO   r0   r0   r1   r     s    zSTLForecastResults.modelc                 C   s   | j S )z)The result class from the estimated model)rC   rO   r0   r0   r1   rN     s    zSTLForecastResults.model_resultc                    s2  t | jdƒstdƒ‚| j ¡ }t|tƒs0tdƒ‚d|jd j |jd _| j	j
}d}g }g }g }g }|D ]”‰ ˆ  ¡ }| dd¡}|d	kr�|d
7 }t‡ fdd„|D ƒƒ}	|d7 }|d›}
t|ˆ  ƒd›}|	râ| |
¡ | |g¡ qh| d|
 ¡ | |g¡ qht|t|ƒdd�}| t||d�¡ |j |¡ |S )aJ  
        Summary of both the STL decomposition and the model fit.

        Returns
        -------
        Summary
            The summary of the model fit and the STL decomposition.

        Notes
        -----
        Requires that the model's result class supports ``summary`` and
        returns a ``Summary`` object.
        Úsummaryz3The model result does not have a summary attribute.z3The model result's summary is not a Summary object.zSTL Decomposition and r   )r   r   r   Ú_ú )ZTrendzLow Passz Lengthc                 3   s   | ]}ˆ   |¡V  qd S )N)Ú
startswith)Ú.0Úval©Úkeyr0   r1   Ú	<genexpr>=  s     z-STLForecastResults.summary.<locals>.<genexpr>ú:z<23sz>13sz      zSTL Configuration)ÚstubsÚtitle)rZ   )r-   rC   r.   rP   rK   r
   Ú	TypeErrorZtablesr[   rA   ÚconfigÚ
capitalizeÚreplaceÚanyÚstrÚappendr	   ÚtupleZextend_right)r/   rP   r]   Z	left_keysZ	left_dataZ
left_stubsZ
right_dataZright_stubsÚnewZis_leftZstubrU   Útabr0   rV   r1   rP     sN    ÿ

ÿÿ

  ÿzSTLForecastResults.summary)ÚstartÚendÚdynamicr?   c                 C   sD  t t | j¡| jd�}|dkr"d}t||| j| j|d�\}}}}t|tt	j
tjfƒrpt|| jƒ\}}}|| }n|dkr~d}n|dkrŠd}| j}t||||ƒ\}}|dkr²|d n|}	t | jj¡}
|
||	… }t d¡}|dk	�r|| d | }| j|d|d	�}n,|�r2|  |d¡}t|| dƒ}||d… }tj||f }|S )
a­  
        Get STLs seasonal in- and out-of-sample predictions

        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.

        Returns
        -------
        ndarray
            Array containing the seasibak predictions.
        ©r@   Nr   )ÚdataTFr&   )r   )Úoffset)r   rI   ÚSeriesr(   rJ   r   rG   rK   ra   ÚdtÚdatetimeÚ	Timestampr   r   rD   rE   rB   r   ÚemptyÚ_seasonal_forecastÚmaxZr_)r/   rf   rg   rh   rj   Zout_of_sampleZprediction_indexrQ   ZnobsZin_sample_endr   ZpredictionsZoosÚnumZ	oos_startr0   r0   r1   Ú_get_seasonal_predictionN  s@    $    ÿ


z+STLForecastResults._get_seasonal_prediction)Ústepsr@   r?   c                 C   sx   | j }t | jj¡}|dkr"| jn|}||| |… }t ||| || dk ¡}|d|… }|dk	rttj||d�}|S )a×  
        Get the seasonal component of the forecast

        Parameters
        ----------
        steps : int
            The number of steps required.
        index : pd.Index
            A pandas index to use. If None, returns an ndarray.
        offset : int
            The index of the first out-of-sample observation. If None, uses
            nobs.

        Returns
        -------
        seasonal : {ndarray, Series}
            The seasonal component.
        Nr   ri   )	r   rD   rE   rB   r   rG   ZtilerI   rl   )r/   ru   r@   rk   r   r   r0   r0   r1   rq   ‘  s    z%STLForecastResults._seasonal_forecastr&   )ru   Úkwargsr?   c                 K   s<   | j jf d|i|—Ž}t|tjƒr(|jn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
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. These arguments are passed into the time series
            model results' ``forecast`` method.

        Returns
        -------
        forecast : {ndarray, Series}
            Out of sample forecasts
        ru   N)rC   r4   rK   rI   rl   r@   rq   )r/   ru   rv   r4   r@   r0   r0   r1   r4   ±  s    zSTLForecastResults.forecastF)rf   rg   rh   rv   c           
   	   K   sœ   | j jf |||dœ|—Ž}|  |||¡}|j| }z
|j}W nL ttfk
rˆ   ddl}	|	jd| j	j
j› d�tdd� tj| ¡  }Y nX t||d|jd	�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,
            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.
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. These arguments are passed into the time series
            model results' ``get_prediction`` method.

        Returns
        -------
        PredictionResults
            PredictionResults instance containing in-sample predictions,
            out-of-sample forecasts, and prediction intervals.
        )rf   rg   rh   r   Nz>The variance of the predicted mean is not available using the z model class.é   )Ú
stacklevelZnorm)ÚdistÚ
row_labels)rC   Úget_predictionrt   Zpredicted_meanÚvar_pred_meanr.   ÚNotImplementedErrorÚwarningsÚwarnr   Ú	__class__r9   ÚUserWarningrD   ÚnanÚcopyr   rz   )
r/   rf   rg   rh   rv   ÚpredZseasonal_predictionZmeanr|   r~   r0   r0   r1   r{   Ì  s:    *  ÿÿ  ÿ

ü   ÿz!STLForecastResults.get_prediction)N)r&   )NNF) r9   r:   r;   r<   r   r   r2   ÚpropertyÚintr   r6   r>   r   r   rN   r
   rP   r   ÚDateLiker   ÚboolrD   Zndarrayrt   rI   ÚIndexrl   rq   r   ra   r4   r{   r0   r0   r0   r1   r5   Ü   sT    þ8
ûD ÿ þ! ÿ 
þ   ü

ûr5   )/Zstatsmodels.compat.pandasr   r   rn   rm   Útypingr   r   r   r   ÚnumpyrD   ZpandasrI   Zstatsmodels.base.datar   Zstatsmodels.iolib.summaryr	   r
   Zstatsmodels.tools.docstringr   r   r   Zstatsmodels.tsa.base.predictionr   Zstatsmodels.tsa.base.tsa_modelr   r   Zstatsmodels.tsa.seasonalr   r   Z(statsmodels.tsa.statespace.kalman_filterr   r†   ra   ro   Z
datetime64r‡   r<   ZdsZinsert_parametersZextract_parametersZ_stl_forecast_paramsr'   r=   r$   r5   r0   r0   r0   r1   Ú<module>   sl   
ÿýþÿýþòÿ 