U
    ÃmœdÂ%  ã                   @   s�   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d„Zd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                    sò   t | |d� }}|j} |r&| |  ¡  } |js4tdƒ‚t| dd�}t||jd d�\‰ }‡ fdd„td|jd ƒD ƒ}|}g }	t|jd ƒD ]R}
t |
d�}t	|d	�}|
d
kr¶||
 |_
ntj||
d  ||
 f |_
|	 |¡ qŠt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)Zffté   )Znobsc                    s   g | ]}ˆ |d |…f ‘qS )N© )Ú.0Úi©Úthetar   úe/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/tsa/arima/estimators/innovations.pyÚ
<listcomp>D   s     zinnovations.<locals>.<listcomp>©Úspecr   r   )r   ÚendogÚmeanZis_ma_consecutiveÚ
ValueErrorr   r   r   Úranger	   ÚparamsÚnpZr_Úappendr   )r   r   Údemeanr   Zmax_specZsample_acovfÚvÚ	ma_paramsÚsigma2Úoutr   ÚpÚother_resultsr   r   r   Úinnovations   s.    #

 ÿr$   ©r   r   r   ©r   r   r   r   c                    s  t ˆ ||d|d�‰ˆj‰ ˆjr>t d¡ tˆ ˆjˆjˆjd�‰ |rNˆ ˆ  ¡  ‰ t	ˆd�‰|dk�rbt	ˆd�}t
ˆ ˆjˆjdd�\}}	ˆjd	kr˜|j|_nrt ˆ |d|d
�}
t ˆj¡ˆj }t ˆj¡ˆj }t
|	j||dd�\}}|j|_|j|_|j|_|j|_|j|_|j�s.d	g|j |_d	g|j |_|j�sZˆj�rZd	g|j |_d	g|j |_|j}n8t	ˆd�}||_|j�s‚tdƒ‚ˆj�rš|j�sštdƒ‚‡ ‡‡fdd„}ˆ  |¡}|dk�rÂi }d|k�rÔi |d< |d  !dd¡ t"||f|Ž}ˆ #|j$¡ˆ_t%ˆ|||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.)Zk_diffZk_seasonal_diffÚseasonal_periodsr   NF)Ú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                    s<   ˆ  | ¡ˆ_tjˆ ˆjjdd …  ˆjjdd … ˆjd� S )Nr   )Ú	ar_paramsr   r    )Úconstrain_paramsr   r   Zarma_loglikeZreduced_ar_polyZcoefZreduced_ma_polyr    )r   ©r   r"   r   r   r   ÚobjÛ   s      þzinnovations_mle.<locals>.objÚoptionsÚmaxiteréd   )r   Úminimize_resultsÚminimize_kwargsÚstart_params)&r   r   Zis_integratedÚwarningsÚwarnr   Zseasonal_diffr+   r   r	   r
   r,   r   r   r   ÚarrayZseasonal_ar_lagsZseasonal_ma_lagsZresidr-   r   Zseasonal_ar_paramsZseasonal_ma_paramsr    Zis_stationaryZk_ar_paramsZk_seasonal_ar_paramsZis_invertibler*   Zk_ma_paramsZk_seasonal_ma_paramsr   Zunconstrain_paramsÚ
setdefaultr   r.   Úxr   )r   r'   r(   r   r*   r6   r5   ÚspÚhrZ
hr_resultsÚ_r,   r   Zseasonal_hrZseasonal_hr_resultsr0   Zunconstrained_start_paramsr4   r#   r   r/   r   Úinnovations_mleY   s–    >   þ
þ


 ÿ


 ý  þ




ÿür?   )r   T)r%   r&   TTNN)Ú__doc__r7   Únumpyr   Zscipy.optimizer   Zstatsmodels.tools.toolsr   Zstatsmodels.tsa.innovationsr   Zstatsmodels.tsa.stattoolsr   r   Z statsmodels.tsa.statespace.toolsr   Z#statsmodels.tsa.arima.specificationr   Zstatsmodels.tsa.arima.paramsr	   Z0statsmodels.tsa.arima.estimators.hannan_rissanenr
   r$   r?   r   r   r   r   Ú<module>   s"   
D       þ