
    "g%                         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y)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_rissanenc                 d   t        | |      x}}|j                  } |r| | j                         z
  } |j                  st	        d      t        | d      }t        ||j                  dz         \  }}t        d|j                  dz         D cg c]  }||d|f    }	}|}
g }t        |j                  dz         D ]^  }t        |      }t        |      }|d	k(  r|
|   |_
        n#t        j                  |	|dz
     |
|   f   |_
        |j                  |       ` t        d
|i      }||fS c c}w )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   )nobsNspecr   r   )r	   endogmeanis_ma_consecutive
ValueErrorr   r   r   ranger
   paramsnpr_appendr   )r   r   demeanr   max_specsample_acovfthetavi	ma_paramssigma2outpother_resultss                 i/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/arima/estimators/innovations.pyinnovationsr(      sO   F +58DDD8NNE

$%% M N 	N D)L83D3Dq3HIHE1',Q0A0AA0E'FG!q"1"uGIGF
C8$$q() #Q/t$6ayAHuuYq1u-vay89AH

1  M % Hs   D-c                     t         ||d|      j                   j                  rBt        j                  d       t         j
                  j                  j                         |r  j                         z
   t              |t              }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.                  |_        |j0                  s*dg|j2                  z  |_        dg|j4                  z  |_        |j6                  s6j8                  r*dg|j:                  z  |_        dg|j<                  z  |_        |j                  }nMt              }||_        |j0                  st?        d
      j8                  r|j6                  st?        d       fd}jA                  |      }|i }d|vri |d<   |d   jC                  dd       tE        ||fi |}jG                  |jH                        _        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   F)ar_orderr   r   r   )r+   r,   r-   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                     j                  |       _        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   sg    ((0 --a//44QR88'',,QR0C C 	C    optionsmaxiterd   )r   minimize_resultsminimize_kwargsstart_params)&r	   r   is_integratedwarningswarnr   seasonal_diffr0   r   r
   r   r1   r   r   r   arrayseasonal_ar_lagsseasonal_ma_lagsresidr3   r"   seasonal_ar_paramsseasonal_ma_paramsr#   is_stationaryk_ar_paramsk_seasonal_ar_paramsis_invertibler-   k_ma_paramsk_seasonal_ma_paramsr   unconstrain_params
setdefaultr   r4   xr   )r   r*   r+   r   r-   r@   r?   sphr
hr_results_r1   r   seasonal_hrseasonal_hr_resultsr9   unconstrained_start_paramsr>   r&   r%   r   s   `                  @@r'   innovations_mler[   Y   s   |  U>!9NPD JJE % 	& U499%)%7%7&*&;&;= 

$4 A% )26--OJ  A%		BI %n%)&;=A
 xx 5 569N9NNHxx 5 569N9NNH/>  8h0,K,
 <<BL<<BL$/$9$9B!$/$9$9B!#**BI 3/BL%&C"*A*A$AB!D$>$>3/BL%&C"*A*A$AB!yy% 	 4 5 5 %%b.>.> N O OC "&!8!8!F '%'	"I)))S9%? 3"13 $$%5%7%78AH ,*$	 M mr:   )r   T))r   r   r   )r   r   r   r   TTNN)__doc__rB   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(   r[    r:   r'   <module>rg      sC      # ) 8 = 1 D 6 LAH <H7;7;br:   