
    !gWH                     Z   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jD                  e
jF                  f   Z$ eejJ                        Z&e&jO                  d edddg             e&jO                  d edddg             e&jQ                  g d      Z) eejT                  jJ                        Z&e&jQ                  ddg      Z+ e ee)d             G d d             Z, G d d      Z-y)    )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                   h    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y)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      y )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/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/forecasting/stl.py__init__zSTLForecast.__init__   sl    $ %%'!'
 #/#7R\ue$ !GHH %    z        )
fit_params)r#   r$   
fit_kwargsc                d   |i n|}t        | j                  fi | j                  }|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.
        )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      &-R:
$++2!1!12#&77!j $+ $
 mmgmm3dkk+<););<cgg#
#sJ' G  "#wS$++FFr6   )	__name__
__module____qualname____doc__r5   r   r   _fit_paramsr+   r;   r6   r4   r'   r'   A   s_    St !#IJ VK9: $$ 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j2                     deej4                  ej,                  f   fdZ	 ddedeeef   deej,                  ej4                  f   fdZ	 	 	 ddee   dee   deeef   deeef   fdZy)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                 P   || _         || _        || _        || _        t	        j
                  |      | _        | j                  j                  d   | _        t        |dt        j                  | j                              | _        t        | j                  t        j                  t        j                  f      s<t!        | j                        s&	 t        j"                  | j                        | _        y y y # t$        $ r' t        j                  | j                        | _        Y y w xY w)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     	)jj'[[&&q)
eWbmmDJJ.GHt{{R%5%5r~~$FGDKK(8 nnT[[9 ) H
  8 mmDJJ78s   $C5 5-D%$D%c                 .    | j                   j                  S )z$The period of the seasonal component)rM   r   r3   s    r4   r   zSTLForecastResults.period   s     yyr6   c                     | j                   S )z2The STL instance used to decompose the time series)rM   r_   s    r4   r>   zSTLForecastResults.stl  s     yy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                 B   t        | j                  d      st        d      | j                  j                         }t	        |t
              st        d      d|j                  d   j                  z   |j                  d   _        | j                  j                  }d}g }g }g }g }|D ]  j                         }|j                  dd      }|d	v r|d
z  }t        fd|D              }	|dz  }|d}
t        |         d}|	r$|j                  |
       |j                  |g       |j                  d|
z          |j                  |g        t!        |t#        |      d      }|j%                  t!        ||             |j                  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   @   K   | ]  }j                  |        y wN)
startswith).0valkeys     r4   	<genexpr>z-STLForecastResults.summary.<locals>.<genexpr>=  s     C##..-Cs   :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 E   --557'7+E  %w~~a'8'>'>> 	q !!4		

 	)C.."C++c3'C++y CCCG3JC$ZD%d+C!!$'  #'""7T>2!!3%(	) U:.6I
 	Z{C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
  }| j'                  |d|	      }n(|r&| j'                  |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 "))DKK0D=E8L3

DKKd9
5]$4 gR[[",,?@)'4;;?MGQoG_GGzz#GUC>
#*?a::dll334u]3hhtn#%)G3C))#tG)DC))->CEDL!,Iij/CeeK,-r6   stepsrL   c                     | j                   }t        j                  | j                  j                        }|| j
                  n|}|||z
  | }t        j                  |||z  ||z  dk7  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    , ::dll334%~6FVOf5778Uf_A8M%NOFU#yy7Hr6   kwargsc                      | j                   j                  dd|i|}t        |t        j                        r|j
                  nd}|| j                  ||      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  sT    . /4%%..EUEfE",Xryy"At$11%???r6   c                     | j                   j                  d
|||d|}| j                  |||      }|j                  |z   }	 |j                  }t!        ||d|j"                  	      S # t
        t        f$ rb ddl}	|	j                  d| j                  j                  j                   dt        d       t        j                  |j                         z   }Y w xY w)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0 
S'
5;
 #;;3
 ""%88	1 ..M !-f
 	
  34 
	1MMzz++445]D	   FFTYY[0M
	1s   A) )A.CC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&       S      s   "c " "4 4lA!A hA tX~&	A
 
AH =A!)"((!3	ryy"**$	%B @@(,S#X@	rzz299$	%@: %)"&).	@
!@
 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 = N 9 Cc2;;bmmCDs{{    	

   E	

 ,, & sww##\<$@A &)=v"FGWG WG HWGtp
 p
r6   