
    M/Ph%                         d Z ddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddZ	 	 	 ddZdS )zs
Innovations algorithm for MA(q) and SARIMA(p,d,q)x(P,D,Q,s) model parameters.

Author: Chad Fulton
License: BSD-3
    N)minimize)Bunch)arma_innovations)acovfinnovations_algo)diff)SARIMAXSpecification)SARIMAXParams)hannan_rissanenTc                    t          | |          x}}|j        } |r| |                                 z
  } |j        st	          d          t          | d          }t          ||j        dz             \  }fdt          d|j        dz             D             }|}g }	t          |j        dz             D ]s}
t          |
          }t          |          }|
d	k    r||
         |_
        n(t          j        ||
dz
           ||
         f         |_
        |	                    |           tt          d
|i          }|	|fS )aq  
    Estimate MA parameters using innovations algorithm.

    Parameters
    ----------
    endog : array_like or SARIMAXSpecification
        Input time series array, assumed to be stationary.
    ma_order : int, optional
        Maximum moving average order. Default is 0.
    demean : bool, optional
        Whether to estimate and remove the mean from the process prior to
        fitting the moving average coefficients. Default is True.

    Returns
    -------
    parameters : list of SARIMAXParams objects
        List elements correspond to estimates at different `ma_order`. For
        example, parameters[0] is an `SARIMAXParams` instance corresponding to
        `ma_order=0`.
    other_results : Bunch
        Includes one component, `spec`, containing the `SARIMAXSpecification`
        instance corresponding to the input arguments.

    Notes
    -----
    The primary reference is [1]_, section 5.1.3.

    This procedure assumes that the series is stationary.

    References
    ----------
    .. [1] Brockwell, Peter J., and Richard A. Davis. 2016.
       Introduction to Time Series and Forecasting. Springer.
    )ma_orderzcInnovations estimation unavailable for models with seasonal or otherwise non-consecutive MA orders.T)fft   )nobsc                 (    g | ]}|d |f         S )N ).0ithetas     l/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/arima/estimators/innovations.py
<listcomp>zinnovations.<locals>.<listcomp>D   s%    GGG!q"1"uGGG    specr   r   )r	   endogmeanis_ma_consecutive
ValueErrorr   r   r   ranger
   paramsnpr_appendr   )r   r   demeanr   max_specsample_acovfv	ma_paramssigma2outr   pother_resultsr   s                @r   innovationsr-      sz   F +58DDDDD8NE %

$% N M N N 	N D)))L83Dq3HIIIHE1GGGGuQ0AA0E'F'FGGGIF
C8$q())  #Q///t$$$66ayAHHuYq1u-vay89AH

1   M r   r   r   r   r   r   r   r   c                 Z    t           ||d|          j         j        r6t          j        d           t           j        j        j                   |r                                  z
   t                    |Qt                    }t           j        j        d          \  }}	j        d	k    r|j        |_        nt           |d|
          }
t          j        j                  j        z  }t          j        j                  j        z  }t          |	j        ||d          \  }}|j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        s d	g|j        z  |_        d	g|j        z  |_        |j        s'j        r d	g|j        z  |_        d	g|j        z  |_        |j        }nJt                    }||_        |j        st?          d          j        r|j        st?          d           fd}                     |          }|i }d|vri |d<   |d         !                    dd           tE          ||fi |}#                    |j$                  _        tK          |||d          }|fS )a	  
    Estimate SARIMA parameters by MLE using innovations algorithm.

    Parameters
    ----------
    endog : array_like
        Input time series array.
    order : tuple, optional
        The (p,d,q) order of the model for the number of AR parameters,
        differences, and MA parameters. Default is (0, 0, 0).
    seasonal_order : tuple, optional
        The (P,D,Q,s) order of the seasonal component of the model for the
        AR parameters, differences, MA parameters, and periodicity. Default
        is (0, 0, 0, 0).
    demean : bool, optional
        Whether to estimate and remove the mean from the process prior to
        fitting the SARIMA coefficients. Default is True.
    enforce_invertibility : bool, optional
        Whether or not to transform the MA parameters to enforce invertibility
        in the moving average component of the model. Default is True.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization. The
        AR polynomial must be stationary. If `enforce_invertibility=True` the
        MA poylnomial must be invertible. If not provided, default starting
        parameters are computed using the Hannan-Rissanen method.
    minimize_kwargs : dict, optional
        Arguments to pass to scipy.optimize.minimize.

    Returns
    -------
    parameters : SARIMAXParams object
    other_results : Bunch
        Includes four components: `spec`, containing the `SARIMAXSpecification`
        instance corresponding to the input arguments; `minimize_kwargs`,
        containing any keyword arguments passed to `minimize`; `start_params`,
        containing the untransformed starting parameters passed to `minimize`;
        and `minimize_results`, containing the output from `minimize`.

    Notes
    -----
    The primary reference is [1]_, section 5.2.

    Note: we do not include `enforce_stationarity` as an argument, because this
    function requires stationarity.

    TODO: support concentrating out the scale (should be easy: use sigma2=1
          and then compute sigma2=np.sum(u**2 / v) / len(u); would then need to
          redo llf computation in the Cython function).

    TODO: add support for fixed parameters

    TODO: add support for secondary optimization that does not enforce
          stationarity / invertibility, starting from first step's parameters

    References
    ----------
    .. [1] Brockwell, Peter J., and Richard A. Davis. 2016.
       Introduction to Time Series and Forecasting. Springer.
    T)orderseasonal_orderenforce_stationarityenforce_invertibilityziProvided `endog` series has been differenced to eliminate integration prior to ARMA parameter estimation.)k_diffk_seasonal_diffseasonal_periodsr   NF)ar_orderr   r$   r   )r2   r3   r4   zqGiven starting parameters imply a non-stationary AR process. Innovations algorithm requires a stationary process.z^Given starting parameters imply a non-invertible MA process with `enforce_invertibility=True`.c                                          |           _        t          j        j        j        dd           j        j        dd          j                   S )Nr   )	ar_paramsr(   r)   )constrain_paramsr    r   arma_loglikereduced_ar_polycoefreduced_ma_polyr)   )r    r   r+   r   s    r   objzinnovations_mle.<locals>.obj   si    ((00 -a/4QRR88',QRR0C C C C 	Cr   optionsmaxiterd   )r   minimize_resultsminimize_kwargsstart_params)&r	   r   is_integratedwarningswarnr   seasonal_diffr7   r   r
   r   r8   r   r    r!   arrayseasonal_ar_lagsseasonal_ma_lagsresidr:   r(   seasonal_ar_paramsseasonal_ma_paramsr)   is_stationaryk_ar_paramsk_seasonal_ar_paramsis_invertibler4   k_ma_paramsk_seasonal_ma_paramsr   unconstrain_params
setdefaultr   r;   xr   )r   r1   r2   r$   r4   rF   rE   sphr
hr_results_r8   r   seasonal_hrseasonal_hr_resultsr@   unconstrained_start_paramsrD   r,   r+   r   s   `                  @@r   innovations_mlera   Y   s   |  U>!9NP P PD JE = % 	& 	& 	& U49%)%7&*&;= = =  %

$4   A%%% )26-O O OJ A%%	BII %n%)&;= = =A
 x 5669NNHx 5669NNH/> 8h0 0 0,K,
 <BL<BL$/$9B!$/$9B!#*BI  	B3/BL%&C"*A$AB! 	BD$> 	B3/BL%&C"*A$AB!y%%% 	 	5 4 5 5 5 % 	Ob.> 	O N O O OC C C C C C C "&!8!8!F!F ''%'	"I)))S999%? 3 3"13 3 $$%5%788AH ,*$	   M mr   )r   T)r.   r/   TTNN)__doc__rH   numpyr!   scipy.optimizer   statsmodels.tools.toolsr   statsmodels.tsa.innovationsr   statsmodels.tsa.stattoolsr   r    statsmodels.tsa.statespace.toolsr   #statsmodels.tsa.arima.specificationr	   statsmodels.tsa.arima.paramsr
   0statsmodels.tsa.arima.estimators.hannan_rissanenr   r-   ra   r   r   r   <module>rl      s         # # # # # # ) ) ) ) ) ) 8 8 8 8 8 8 = = = = = = = = 1 1 1 1 1 1 D D D D D D 6 6 6 6 6 6 L L L L L LA A A AH <H7;7;b b b b b br   