U
    Kvf%                     @   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 |_
|	| qt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   P/tmp/pip-unpacked-wheel-2v6byqio/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stdjr|jstd fdd} |}|dkri }d|kri |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maxiterd   )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   Z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       