
    M/PhWH                     |   d dl mZmZ d dlZd dl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&(                    g d          Z) eej*        j%                  Z&e&(                    ddg          Z+ e ee)d                     G d d                      Z, G d d          Z-dS )    )Substitutionis_int_indexN)AnyOptionalUnion)
PandasData)SimpleTableSummary)	Docstring	Parameterindent)PredictionResults)get_index_locget_prediction_index)STLDecomposeResult)_check_dynamicendogmodel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.)r   r   r   periodseasonaltrendlow_passseasonal_deg	trend_deglow_pass_degrobustseasonal_jump
trend_jumplow_pass_jump
inner_iter
outer_iterz    )stl_forecast_paramsc                   |    e Zd ZdZddddddddddddddZ e ee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                    || _         t          ||||||	|
||||          | _        || _        |i n|| _        t          |d          st          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"   s                  _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/forecasting/stl.py__init__zSTLForecast.__init__   s    $ %%'!'
 
 
 #/#7RR\ue$$ 	I !GHHH	I 	I    z        )
fit_params)r#   r$   
fit_kwargsc                6   |i n|}t          | j        fi | j        }|                    ||          }|j        |j        z   } | j        |fi | j        } |j        di |}t          |d          st          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   residr/   r0   r1   r2   STLForecastResults)	r3   r#   r$   r8   stlstl_fitmodel_endogmodress	            r4   r+   zSTLForecast.fit   s      &-RR:
$+22!122#&77!j $+ $
 $
 mgm3dk+<<);<<cg##
##sJ'' 	 G   "#wS$+FFFr6   )	__name__
__module____qualname____doc__r5   r   r   _fit_paramsr+   r;   r6   r4   r'   r'   A   s        S St !#I #I #I #I #IJ \VVK99::: $$ G G G G ;:G G Gr6   r'   c                      e Zd ZdZdededdfdZedefd            Z	edefd            Z
edefd	            Zedefd
            Zedefd            ZdefdZdee         dee         deeef         dej        fdZ	 ddedeej                 deej        ej        f         fdZ	 ddedeeef         deej        ej        f         fdZ	 	 	 ddee         dee         deeef         deeef         fdZdS )r=   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``.
    r>   resultreturnNc                    || _         || _        || _        || _        t	          j        |          | _        | j        j        d         | _        t          |dt          j        | j                            | _        t          | j        t          j        t          j        f          sdt!          | j                  sR	 t          j        | j                  | _        d S # t$          $ r" t          j        | j                  | _        Y d S w xY wd S d S )Nr   index)_stl_resultr/   _model_resultnpasarrayr,   shape_nobsgetattrpd
RangeIndex_index
isinstanceDatetimeIndexPeriodIndexr   to_datetime
ValueError)r3   r>   rI   r   model_resultr   s         r4   r5   zSTLForecastResults.__init__   s     	)j''[&q)
eWbmDJ.G.GHHt{R%5r~$FGG	8DK((	88 nT[99 8 8 8 mDJ778	8 	8 	8 	8s   :C (DDc                     | j         j        S )z$The period of the seasonal component)rM   r   r3   s    r4   r   zSTLForecastResults.period   s     yr6   c                     | j         S )z2The STL instance used to decompose the time series)rM   r_   s    r4   r>   zSTLForecastResults.stl  s     yr6   c                     | j         S )z&The result of applying STL to the data)rN   r_   s    r4   rI   zSTLForecastResults.result	  s     |r6   c                     | j         S )z3The model fit to the additively deseasonalized data)r/   r_   s    r4   r   zSTLForecastResults.model  s     {r6   c                     | j         S )z)The result class from the estimated model)rO   r_   s    r4   r]   zSTLForecastResults.model_result  s     !!r6   c                    t          | j        d          st          d          | j                                        }t	          |t
                    st          d          d|j        d         j        z   |j        d         _        | j	        j
        }d}g }g }g }g }|D ]̊                                }|                    dd          }|d	v r|d
z  }t          fd|D                       }	|dz  }|d}
t          |                   d}|	r,|                    |
           |                    |g           |                    d|
z              |                    |g           t!          |t#          |          d          }|                    t!          ||                     |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   _ )TrendzLow Passz Lengthc              3   B   K   | ]}                     |          V  d S N)
startswith).0valkeys     r4   	<genexpr>z-STLForecastResults.summary.<locals>.<genexpr>=  s/      CC##..--CCCCCCr6   :z<23sz>13sz      zSTL Configuration)stubstitle)rq   )r1   rO   r2   re   rX   r
   	TypeErrortablesrr   rM   config
capitalizereplaceanystrappendr	   tupleextend_right)r3   re   ru   	left_keys	left_data
left_stubs
right_dataright_stubsnewis_leftstubrm   tabrn   s                @r4   re   zSTLForecastResults.summary  s    t)955 	 E    -5577'7++ 	E   %w~a'8'>> 	q !4		

 	) 	)C..""C++c3''C+++y CCCCCCCCCG3JC==D%%,,C )!!$'''  #''''""7T>222!!3%((((U:..6I
 
 
 	Z{CCCDDDc"""r6   startenddynamicc                    t          t          j        | j                  | j                  }|d}t          ||| j        | j        |          \  }}}}t          |t          t          j
        t          j        f          rt          || j                  \  }}}||z
  }n|du rd}n|du rd}| j        }t          ||||          \  }}||dz   n|}	t          j        | j        j                  }
|
||	         }t          j        d          }|$||z   dz   |z
  }|                     |d|	          }n5|r3|                     |d          }t)          ||z
  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.
        rL   Nr   )dataTFr)   )r   )offset)r   rU   Seriesr,   rW   r   rS   rX   ry   dtdatetime	Timestampr   r   rP   rQ   rN   r   empty_seasonal_forecastmaxr_)r3   r   r   r   r   out_of_sampleprediction_indexrf   nobsin_sample_endr   predictionsoosnum	oos_starts                  r4   _get_seasonal_predictionz+STLForecastResults._get_seasonal_predictionN  s   H ")DK00DDD=E8L3
DKd9
 9
 9
5]$4 gR[",?@@ 	)'4;??MGQoGG__GGGz#GUC>>
#*?a:dl344u]23htnn#%)G3C))#tG)DDCC 	"))->>CEDL!,,Iijj/CeK,-r6   stepsrL   c                    | j         }t          j        | j        j                  }|| j        n|}|||z
  |         }t          j        |||z  ||z  dk    z             }|d|         }|t          j        ||          }|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   r   )	r   rP   rQ   rN   r   rS   tilerU   r   )r3   r   rL   r   r   r   s         r4   r   z%STLForecastResults._seasonal_forecast  s    , :dl344%~6FVOf4578Uf_A8M%NOOFUF#y777Hr6   r)   kwargsc                      | j         j        dd|i|}t          |t          j                  r|j        nd}||                     ||          z   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
        r   Nr;   )rO   r:   rX   rU   r   rL   r   )r3   r   r   r:   rL   s        r4   r:   zSTLForecastResults.forecast  s[    . /4%.EEUEfEE",Xry"A"AKt$11%????r6   Fc                     | j         j        d
|||d|}|                     |||          }|j        |z   }	 |j        }nl# t
          t          f$ rX ddl}	|	                    d| j	        j
        j         dt          d           t          j        |                                z   }Y nw xY wt!          ||d|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,
            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.
        )r   r   r   r   Nz>The variance of the predicted mean is not available using the z model class.   )
stacklevelnorm)dist
row_labelsr;   )rO   get_predictionr   predicted_meanvar_pred_meanr2   NotImplementedErrorwarningswarnr   	__class__rC   UserWarningrP   nancopyr   r   )
r3   r   r   r   r   predseasonal_predictionmeanr   r   s
             r4   r   z!STLForecastResults.get_prediction  s   T 1t!0 
S'
 
5;
 
 #;;3
 
 "%88	1 .MM 34 
	1 
	1 
	1OOOMMDz+4D D D	     FTYY[[0MMM
	1 !-f
 
 
 	
s   A A&B*)B*rj   )r)   )NNF) rC   rD   rE   rF   r   r   r5   propertyintr   r>   rI   r   r   r]   r
   re   r   DateLiker   boolrP   ndarrayr   rU   Indexr   r   r-   ry   r:   r   r;   r6   r4   r=   r=      s        88 /8	8 8 8 8&         X  S    X     X s    X "c " " " X"4 4 4 4 4lA!A hA tX~&	A
 
A A A AH =A !)"(!3	ry"*$	%   B @ @@(,S#X@	rz29$	%@ @ @ @: %)"&).	@
 @
!@
 h@
 tX~&	@

 sCx.@
 @
 @
 @
 @
 @
r6   r=   ).statsmodels.compat.pandasr   r   r   r   typingr   r   r   numpyrP   pandasrU   statsmodels.base.datar   statsmodels.iolib.summaryr	   r
   statsmodels.tools.docstringr   r   r   statsmodels.tsa.base.predictionr   statsmodels.tsa.base.tsa_modelr   r   statsmodels.tsa.seasonalr   r   (statsmodels.tsa.statespace.kalman_filterr   r   ry   r   
datetime64r   rF   dsinsert_parametersextract_parameters_stl_forecast_paramsr+   rG   r'   r=   r;   r6   r4   <module>r      s   @ @ @ @ @ @ @ @     ' ' ' ' ' ' ' ' ' '         , , , , , , : : : : : : : : D D D D D D D D D D = = = = = = N N N N N N N N 9 9 9 9 9 9 9 9 C C C C C Cc2;bmCDYs{   I 	
 
 
 
   IE	
 
 
 
 ,,    & Ysw##\<$@AA &&)=v"F"FGGGWG WG WG WG WG WG WG HGWGtp
 p
 p
 p
 p
 p
 p
 p
 p
 p
r6   