U
    ÃmœdÖÈ  ã                   @   s
  d Z ddlZddlm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 ddlm  m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!m"Z"m#Z#m$Z$m%Z%m&Z& G dd„ deƒZ'G dd„ deƒZ(G dd„ deƒZ)e *e)e(¡ dS )zs
Vector Autoregressive Moving Average with eXogenous regressors model

Author: Chad Fulton
License: Simplified-BSD
é    N)Úwarn)ÚAppender)ÚBunch)Ú_is_using_pandas)Ú	var_model)ÚEstimationWarningé   )ÚINVERT_UNIVARIATEÚSOLVE_LU)ÚMLEModelÚ
MLEResultsÚMLEResultsWrapper)ÚInitialization)Úis_invertibleÚconcatÚprepare_exogÚ!constrain_stationary_multivariateÚ#unconstrain_stationary_multivariateÚprepare_trend_specÚprepare_trend_datac                       sž   e Zd ZdZd‡ fd	d
„	Zd dd„Zedd„ ƒZedd„ ƒZedd„ ƒZ	dd„ Z
dd„ Z‡ fdd„Zd!dd„Zejdd„ ƒZeejjƒd"‡ fdd„	ƒZ‡  ZS )#ÚVARMAXuM  
    Vector Autoregressive Moving Average with eXogenous regressors model

    Parameters
    ----------
    endog : array_like
        The observed time-series process :math:`y`, , shaped nobs x k_endog.
    exog : array_like, optional
        Array of exogenous regressors, shaped nobs x k.
    order : iterable
        The (p,q) order of the model for the number of AR and MA parameters to
        use.
    trend : str{'n','c','t','ct'} or iterable, optional
        Parameter controlling the deterministic trend polynomial :math:`A(t)`.
        Can be specified as a string where 'c' indicates a constant (i.e. a
        degree zero component of the trend polynomial), 't' indicates a
        linear trend with time, and 'ct' is both. Can also be specified as an
        iterable defining the non-zero polynomial exponents to include, in
        increasing order. For example, `[1,1,0,1]` denotes
        :math:`a + bt + ct^3`. Default is a constant trend component.
    error_cov_type : {'diagonal', 'unstructured'}, optional
        The structure of the covariance matrix of the error term, where
        "unstructured" puts no restrictions on the matrix and "diagonal"
        requires it to be a diagonal matrix (uncorrelated errors). Default is
        "unstructured".
    measurement_error : bool, optional
        Whether or not to assume the endogenous observations `endog` were
        measured with error. Default is False.
    enforce_stationarity : bool, optional
        Whether or not to transform the AR parameters to enforce stationarity
        in the autoregressive component of the model. 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.
    trend_offset : int, optional
        The offset at which to start time trend values. Default is 1, so that
        if `trend='t'` the trend is equal to 1, 2, ..., nobs. Typically is only
        set when the model created by extending a previous dataset.
    **kwargs
        Keyword arguments may be used to provide default values for state space
        matrices or for Kalman filtering options. See `Representation`, and
        `KalmanFilter` for more details.

    Attributes
    ----------
    order : iterable
        The (p,q) order of the model for the number of AR and MA parameters to
        use.
    trend : str{'n','c','t','ct'} or iterable
        Parameter controlling the deterministic trend polynomial :math:`A(t)`.
        Can be specified as a string where 'c' indicates a constant (i.e. a
        degree zero component of the trend polynomial), 't' indicates a
        linear trend with time, and 'ct' is both. Can also be specified as an
        iterable defining the non-zero polynomial exponents to include, in
        increasing order. For example, `[1,1,0,1]` denotes
        :math:`a + bt + ct^3`.
    error_cov_type : {'diagonal', 'unstructured'}, optional
        The structure of the covariance matrix of the error term, where
        "unstructured" puts no restrictions on the matrix and "diagonal"
        requires it to be a diagonal matrix (uncorrelated errors). Default is
        "unstructured".
    measurement_error : bool, optional
        Whether or not to assume the endogenous observations `endog` were
        measured with error. Default is False.
    enforce_stationarity : bool, optional
        Whether or not to transform the AR parameters to enforce stationarity
        in the autoregressive component of the model. 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.

    Notes
    -----
    Generically, the VARMAX model is specified (see for example chapter 18 of
    [1]_):

    .. math::

        y_t = A(t) + A_1 y_{t-1} + \dots + A_p y_{t-p} + B x_t + \epsilon_t +
        M_1 \epsilon_{t-1} + \dots M_q \epsilon_{t-q}

    where :math:`\epsilon_t \sim N(0, \Omega)`, and where :math:`y_t` is a
    `k_endog x 1` vector. Additionally, this model allows considering the case
    where the variables are measured with error.

    Note that in the full VARMA(p,q) case there is a fundamental identification
    problem in that the coefficient matrices :math:`\{A_i, M_j\}` are not
    generally unique, meaning that for a given time series process there may
    be multiple sets of matrices that equivalently represent it. See Chapter 12
    of [1]_ for more information. Although this class can be used to estimate
    VARMA(p,q) models, a warning is issued to remind users that no steps have
    been taken to ensure identification in this case.

    References
    ----------
    .. [1] LÃ¼tkepohl, Helmut. 2007.
       New Introduction to Multiple Time Series Analysis.
       Berlin: Springer.
    N©r   r   ÚcÚunstructuredFTr   c
                    s>  |ˆ _ |ˆ _|ˆ _|ˆ _|ˆ _t|d ƒˆ _t|d ƒˆ _|dkrJtdƒ‚ˆ jdkrfˆ jdkrftdƒ‚ˆ jdkr„ˆ jdkr„t	dt
ƒ |ˆ _|	ˆ _tˆ jƒ\ˆ _ˆ _ˆ jjdkoºˆ jd dkˆ _t|ƒ\ˆ _}ˆ jdkˆ _t|d ƒsìt |¡}tˆ jdƒ}|ˆ j ˆ _|jd }|}|ˆ j }|
 dd¡ |
 d	ttB ¡ ttˆ ƒj |f|||d
œ|
—Ž ˆ jdk�sxˆ jdk�r€ˆ j�s€dˆ j!_"i ˆ _#ˆ j$ˆ j ˆ j#d< ˆ j$d ˆ j ˆ j#d< ˆ j$d ˆ j ˆ j#d< ˆ j$ˆ j ˆ j#d< ˆ j dk�rðˆ j$ˆ j#d< n*ˆ j dk�rtˆ j$ˆ j$d  d ƒˆ j#d< ˆ j$ˆ j ˆ j#d< t%ˆ j# &¡ ƒˆ _'t(ˆ jˆ jˆ j)d ˆ jd�}|d d… ˆ _*|dd … ˆ _+ˆ jdk�rˆˆ j�r”ˆ jdk�r¬t ,ˆ j-ˆ j)f¡ˆ j!d< t .ˆ j$¡}dˆ j!d| < ˆ jdk�rt .ˆ jd ˆ j$ ¡}|d ˆ j$ |d f}dˆ j!d| < t .ˆ jd ˆ j$ ¡}|d |d ˆ j$  |d |ˆ j$  f}dˆ j!d| < t .ˆ j$¡}dˆ j!d| < |d |ˆ j$  |d f}ˆ jdk�r¦dˆ j!d| < ˆ j�rÖˆ jdk�rÖtj/dd |…d d …f ˆ _0n2ˆ jdk�sîˆ jdk�rtj/dd |…d d…f ˆ _0ˆ jdk�r0tj/dd |…d d …f ˆ _1ntj/dd |…|d …f ˆ _1ˆ j dk�rjdt .ˆ j$¡ ˆ _2nˆ j dk�r„t 3ˆ j$¡ˆ _4ˆ j�rždt .ˆ j$¡ ˆ _5‡ fdd„}d}|d|ƒ\ˆ _6}|d|ƒ\ˆ _7}|d|ƒ\ˆ _8}|d|ƒ\ˆ _9}|d|ƒ\ˆ _:}|d|ƒ\ˆ _;}d ˆ _<ˆ  j=d dd!d"d#d$gt>|
 ?¡ ƒ 7  _=d S )%Nr   r   )Údiagonalr   z3Invalid error covariance matrix type specification.zNInvalid VARMAX(p,q) specification; at least one p,q must be greater than zero.zcEstimation of VARMA(p,q) models is not generically robust, due especially to identification issues.ÚinitializationÚ
stationaryZinversion_method)ÚexogÚk_statesÚk_posdefFÚtrendé   ÚarÚmaZ
regressionr   Ú	state_covr   Úobs_cov)ÚoffsetéÿÿÿÿÚstate_intercept)Zdesign)Ú
transition)Z	selectionr)   )r$   )r%   c                    s,   ˆ j |  }tj||| … }||7 }||fS )N)Ú
parametersÚnpÚs_)Úkeyr&   ÚlengthZparam_slice©Úself© úZ/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/tsa/statespace/varmax.pyÚ_slice!  s    
zVARMAX.__init__.<locals>._sliceÚorderÚerror_cov_typeÚmeasurement_errorÚenforce_stationarityÚenforce_invertibility)@r5   r6   r7   r8   r4   ÚintÚk_arÚk_maÚ
ValueErrorr   r   r    Útrend_offsetr   Úpolynomial_trendÚk_trendÚsizeÚ_trend_is_constr   Úk_exogÚmle_regressionr   r+   Z
asanyarrayÚmaxZ_k_orderÚshapeÚ
setdefaultr	   r
   Úsuperr   Ú__init__ÚssmZ_time_invariantr*   Úk_endogÚsumÚvaluesÚk_paramsr   ÚnobsÚ_trend_dataÚ_final_trendÚzerosr   Zdiag_indicesr,   Ú_idx_state_interceptÚ_idx_transitionÚ_idx_state_covZtril_indicesÚ_idx_lower_state_covÚ_idx_obs_covÚ_params_trendÚ
_params_arÚ
_params_maÚ_params_regressionÚ_params_state_covÚ_params_obs_covÚ_final_exogZ
_init_keysÚlistÚkeys)r0   Úendogr   r4   r    r5   r6   r7   r8   r=   ÚkwargsZ	_min_k_arrJ   r   r   Z
trend_dataÚidxr3   r&   ©Ú	__class__r/   r2   rH   …   sÞ    þÿ




ÿ  ÿÿ ÿ  þ ÿÿ þ
þzVARMAX.__init__c                 K   s   | j |fd|i|—ŽS )Nr   )Z_clone_from_init_kwds)r0   r`   r   ra   r1   r1   r2   Úclone8  s    zVARMAX.clonec                 C   s   dt tfiS )NÚfit)ÚVARMAXResultsÚVARMAXResultsWrapperr/   r1   r1   r2   Ú_res_classes;  s    zVARMAX._res_classesc                 C   s   t j| jt jd�}t | j ¡ ¡}| ¡ }t j	|j
dd�dd�}d }| jdkrl| jdkrlt j| j| jf }n"| jdkr~| j}n| jdkrŽ| j}t  t  |¡¡rÌt jt  |¡dd� }|| }|d k	rÌ|| }t  d¡}t  d¡}| jdksö| jdk�rPt j |¡ |¡}|t  ||¡8 }| jdk�r4|d | j… j}| jdk�rP|| jd … j}g }| jdk�rf| jnd}	t |¡}
|
j|	d d	d
�}| jdk�r¢t  |j¡j ¡ }|j}| jdk�r| j�r|  | j| j | j¡j  | j| j| j¡j}t!dgt"| ƒ ƒ}|�st#dƒ |d9 }g }| j$dk�rªt |¡}|j| j$d d	d
�}t  |jj¡ ¡ }| j%�rª|  | j| j$ | j¡j  | j| j| j$¡j}t!dgt"| ƒ ƒ}|�sªt#dƒ |d9 }| jdk�r>| jdk�sÊ| j&�r>|  | j| j | j¡j  | j| j| j¡j}t  '| j¡t j(|dd� }| jdk�r&t  ||¡}| j&dk�r>t  ||¡}| jdk�rX| ¡ || j)< | jdk�rn||| j*< | j$dk�r„||| j+< | j&�rš| ¡ || j,< | j-dk�r¸|j. /¡ || j0< n.| j-dk�ræt j 1|j.¡}|| j2  ¡ || j0< | j3�r| j$dk�r|j. /¡ || j4< n|j. /¡ || j4< |S )N©ÚdtypeZbackfill)ÚmethodÚW)Úrequirementsr   r   )ZaxisÚn)ZmaxlagsZicr    z\Non-stationary starting autoregressive parameters found. Using zeros as starting parameters.z\Non-stationary starting moving-average parameters found. Using zeros as starting parameters.r   r   )5r+   rQ   rM   Zfloat64ÚpdZ	DataFramer`   ÚcopyZinterpolateÚrequireZfillnar?   rB   Úc_rO   r   ÚanyÚisnanZlinalgZpinvÚdotÚTrJ   r:   r   ÚVARrf   ÚarrayÚparamsÚravelZresidr7   Úreshaper   r^   r   r;   r8   rC   ÚeyerK   rW   rX   rY   rZ   r5   Zsigma_ur   r[   ZcholeskyrU   r6   r\   )r0   rz   r`   r   ÚmaskÚtrend_paramsÚexog_paramsZtrendexog_paramsÚ	ar_paramsr:   Zmod_arZres_arÚcoefficient_matricesr   Ú	ma_paramsZmod_maZres_maZ
invertibleÚtmpZ
cov_factorr1   r1   r2   Ústart_params?  sÆ    





 ÿÿ  ü

 ÿÿ  ü 
 ÿÿ  ü

ÿzVARMAX.start_paramsc                    sl  g }ˆj ‰ tˆj tƒsˆ g‰ ˆjdkr˜tˆjƒD ]f}ˆj ¡ d D ]R}|dkrb|dˆ |  g7 }qB|dkr~|dˆ |  g7 }qB|d|ˆ | f g7 }qBq0|‡ ‡fdd„tˆjƒD ƒ7 }|‡ ‡fdd„tˆjƒD ƒ7 }|‡ ‡fd	d„tˆjƒD ƒ7 }ˆjd
k�r|‡ fdd„tˆjƒD ƒ7 }n(ˆjdk�rD|‡ fdd„tˆjƒD ƒ7 }ˆj	�rh|‡ fdd„tˆjƒD ƒ7 }|S )Nr   zintercept.%sr   zdrift.%sztrend.%d.%sc              	      sF   g | ]>}t ˆjƒD ].}t ˆjƒD ]}d |d ˆ | ˆ | f ‘q qqS )z	L%d.%s.%sr   )Úranger:   rJ   ©Ú.0ÚjÚiÚk©Úendog_namesr0   r1   r2   Ú
<listcomp>Ó  s     ýz&VARMAX.param_names.<locals>.<listcomp>c              	      sF   g | ]>}t ˆjƒD ].}t ˆjƒD ]}d |d ˆ | ˆ | f ‘q qqS )zL%d.e(%s).%sr   )r†   r;   rJ   r‡   rŒ   r1   r2   rŽ   Û  s     ýc                    s2   g | ]*}t ˆjƒD ]}d ˆj| ˆ | f ‘qqS )z
beta.%s.%s)r†   rB   Z
exog_names©rˆ   rŠ   r‰   rŒ   r1   r2   rŽ   ã  s    þr   c                    s   g | ]}d ˆ |  ‘qS )z	sigma2.%sr1   ©rˆ   rŠ   ©r�   r1   r2   rŽ   ë  s   ÿr   c                    sF   g | ]>}t |d  ƒD ],}||kr,dˆ |  ndˆ | ˆ | f ‘qqS )r   zsqrt.var.%szsqrt.cov.%s.%s)r†   r�   r‘   r1   r2   rŽ   ð  s
    ýc                    s   g | ]}d ˆ |  ‘qS )zmeasurement_variance.%sr1   r�   r‘   r1   r2   rŽ   ù  s   ÿ)
r�   Ú
isinstancer^   r?   r†   rJ   r>   Znonzeror5   r6   )r0   Úparam_namesr‰   rŠ   r1   rŒ   r2   r“   À  sD    
þþþþ
ýþzVARMAX.param_namesc                 C   sÈ  t j|dd�}t j|j|jd�}|| j || j< | jdkrÚ| jrÚ| jdkr`t  	|| j
 d ¡}n@| jdkr t j| jd j|jd�}|| j
 || j< t  ||j¡}|| j  | j| j| j ¡}t||ƒ\}}| ¡ || j< n|| j || j< | jdk�rJ| j�rJt j| j|jd�}|| j  | j| j| j ¡}t||ƒ\}}| ¡ || j< n|| j || j< || j || j< | jdk�rŒ|| j
 d || j
< n| jdk�r¨|| j
 || j
< | j�rÄ|| j d || j< |S )	a[  
        Transform unconstrained parameters used by the optimizer to constrained
        parameters used in likelihood evaluation

        Parameters
        ----------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer, to be
            transformed.

        Returns
        -------
        constrained : array_like
            Array of constrained parameters which may be used in likelihood
            evaluation.

        Notes
        -----
        Constrains the factor transition to be stationary and variances to be
        positive.
        r   ©Zndminrj   r   r   r!   r   r$   )r+   ry   rQ   rE   rk   rW   r:   r7   r5   Údiagr[   rI   rU   rv   rw   rX   r|   rJ   r   r{   r;   r8   r}   rY   rZ   r6   r\   )r0   ÚunconstrainedÚconstrainedr$   Ústate_cov_lowerÚcoefficientsr‚   Úvariancer1   r1   r2   Útransform_params   sV    

ÿÿ
 
ÿÿ
 
ÿÿÿÿ
ÿÿzVARMAX.transform_paramsc                 C   sÄ  t j|dd�}t j|j|jd�}|| j || j< | jdkrÖ| jrÖ| jdkr\t  	|| j
 ¡}n@| jdkrœt j| jd j|jd�}|| j
 || j< t  ||j¡}|| j  | j| j| j ¡}t||ƒ\}}| ¡ || j< n|| j || j< | jdk�rF| j�rFt j| j|jd�}|| j  | j| j| j ¡}t||ƒ\}}| ¡ || j< n|| j || j< || j || j< | jdk�rˆ|| j
 d || j
< n| jdk�r¤|| j
 || j
< | j�rÀ|| j d || j< |S )	aÆ  
        Transform constrained parameters used in likelihood evaluation
        to unconstrained parameters used by the optimizer.

        Parameters
        ----------
        constrained : array_like
            Array of constrained parameters used in likelihood evaluation, to
            be transformed.

        Returns
        -------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer.
        r   r”   rj   r   r   r   r$   g      à?)r+   ry   rQ   rE   rk   rW   r:   r7   r5   r•   r[   rI   rU   rv   rw   rX   r|   rJ   r   r{   r;   r8   r}   rY   rZ   r6   r\   )r0   r—   r–   r$   r˜   r™   Zunconstrained_matricesrš   r1   r1   r2   Úuntransform_paramsS  sV    

ÿÿ
 
ÿÿ
 
ÿÿÿÿ
ÿÿzVARMAX.untransform_paramsc                    sð   t t| ƒ |¡ t t| j ¡ ƒ¡d d… }dd„ t | j	|¡D ƒ\}}}}}}| j
r | jdkr | jdkst| jdkr | |¡}t| |¡ƒdk}|r |s tdƒ‚| jrì| jdkrì| jsÀ| jdkrì| |¡}t| |¡ƒdk}|rì|sìtdƒ‚d S )Nr'   c                 S   s   g | ]}|  ¡ ‘qS r1   )Útolist)rˆ   Zarrr1   r1   r2   rŽ   ¤  s    z3VARMAX._validate_can_fix_params.<locals>.<listcomp>r   r   z–Cannot fix individual autoregressive parameters when `enforce_stationarity=True`. In this case, must either fix all autoregressive parameters or none.z—Cannot fix individual moving average parameters when `enforce_invertibility=True`. In this case, must either fix all moving average parameters or none.)rG   r   Ú_validate_can_fix_paramsr+   Zcumsumr^   r*   rL   Zarray_splitr“   r7   r:   rJ   Ú
issupersetÚlenÚintersectionr<   r8   r;   )r0   r“   ZixÚ_Zar_namesZma_namesZfix_allZfix_anyrc   r1   r2   rž      s.    ÿ
ÿÿ
ÿÿzVARMAX._validate_can_fix_paramsc                 C   s\  | j |||d�}| jr||| j  | j| j¡j}t | j	dd … |¡}|j| j
| j< | jd k	r|t | j|¡| j
dd | j…df< | jdk�rL| js°tjd|jd�}|| j
dd d …f< || j  | j| j¡j}| jrÔ|}nt | jdd … |¡}| j
| j  |j7  < | jd k	�rL| jd jdk�rL| j
dd | j…dd …f  t | j|¡j7  < | j�rˆ| jd k�rˆtjtj|jd�}	|	| j
dd | j…df< || j  | j| j| j ¡}
|| j  | j| j| j ¡}tj|
|f | j
| j< | jdk�rö|| j | j
| j< nH| jdk�r>tj| j
d	 j |jd�}|| j || j!< t ||j¡| j
d	< | j"�rX|| j# | j
| j$< d S )
N)ÚtransformedÚincludes_fixedr   r(   r'   r   rj   r   r   r$   )%Zhandle_paramsrC   rZ   r|   rJ   rB   rw   r+   rv   r   rI   rR   r]   r?   ry   rk   rW   rA   rO   rP   ÚstopÚnanrX   r:   rY   r;   rs   rS   r5   r[   rT   rQ   rE   rU   r6   r\   rV   )r0   rz   r£   r¤   Zcomplex_stepr€   Ú	interceptÚzeror   r¦   r"   r#   r˜   r1   r1   r2   Úupdate¾  st    ÿ
 ÿ
 ÿ
 ÿÿ ÿ

 
ÿ
 
ÿÿÿÿzVARMAX.updatec                 c   s¦   | j }| jdkrŽ|dk	rˆt |¡}|jdkr8|dd… }zt |dd… | jf¡}W n2 tk
r†   tdt| jfƒt|jƒf ƒ‚Y nX || _ z
dV  W 5 || _ X dS )a8  
        Set the final state intercept value using out-of-sample `exog` / trend

        Parameters
        ----------
        exog : ndarray
            Out-of-sample `exog` values, usually produced by
            `_validate_out_of_sample_exog` to ensure the correct shape (this
            method does not do any additional validation of its own).
        out_of_sample : int
            Number of out-of-sample periods.

        Notes
        -----
        We need special handling for simulating or forecasting with `exog` or
        trend, because if we had these then the last predicted_state has been
        set to NaN since we did not have the appropriate `exog` to create it.
        Since we handle trend in the same way as `exog`, we still have this
        issue when only trend is used without `exog`.
        r   Nr!   r   zPProvided exogenous values are not of the appropriate shape. Required %s, got %s.)	r]   rB   r+   Z
atleast_1dÚndimr|   r<   ÚstrrE   )r0   r   Úcache_valuer1   r1   r2   Ú_set_final_exog  s$    



ÿþ
zVARMAX._set_final_exogc                    sJ   |   |¡�6 tt| ƒj||f|||||||	|
||dœ
|—Ž}W 5 Q R X |S )N)
Úmeasurement_shocksÚstate_shocksÚinitial_stateÚanchorÚrepetitionsr   Úextend_modelÚextend_kwargsr£   r¤   )r­   rG   r   Úsimulate)r0   rz   Únsimulationsr®   r¯   r°   r±   r²   r   r³   r´   r£   r¤   ra   Úoutrc   r1   r2   rµ   *  s&    
 ÿ     ûúzVARMAX.simulate)Nr   r   r   FTTr   )N)TFF)
NNNNNNNNTF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rH   re   Úpropertyri   r…   r“   r›   rœ   rž   r©   Ú
contextlibÚcontextmanagerr­   r   r   rµ   Ú__classcell__r1   r1   rc   r2   r       sJ   d        ý 4


 
?SM  ÿ
C
(
                ýr   c                	       s    e Zd ZdZd‡ fdd„	Zddd„Zejdd„ ƒZejd	d
„ ƒZ	e
ejjƒd‡ fdd„	ƒZe
ejjƒd‡ fdd„	ƒZddd„Ze
ejjƒd‡ fdd„	ƒZ‡  ZS )rg   aë  
    Class to hold results from fitting an VARMAX model.

    Parameters
    ----------
    model : VARMAX instance
        The fitted model instance

    Attributes
    ----------
    specification : dictionary
        Dictionary including all attributes from the VARMAX model instance.
    coefficient_matrices_var : ndarray
        Array containing autoregressive lag polynomial coefficient matrices,
        ordered from lowest degree to highest.
    coefficient_matrices_vma : ndarray
        Array containing moving average lag polynomial coefficients,
        ordered from lowest degree to highest.

    See Also
    --------
    statsmodels.tsa.statespace.kalman_filter.FilterResults
    statsmodels.tsa.statespace.mlemodel.MLEResults
    Nc                    s  t t| ƒj|||||f|Ž tf | jj| jj| jj| jj| jj	| jj
| jj| jj| jj| jj| jjdœŽ| _d | _d | _| jjdkrÈt | j| jj ¡}| jj}| jj}	| ||	 |¡j |||	¡j| _| jjdk�rt | j| jj ¡}
| jj}| jj}|
 || |¡j |||¡j| _d S )N)r5   r6   r7   r8   r=   r4   r:   r;   r    r?   rB   r   )rG   rg   rH   r   Úmodelr5   r6   r7   r8   r=   r4   r:   r;   r    r?   rB   ÚspecificationZcoefficient_matrices_varZcoefficient_matrices_vmar+   ry   rz   rX   rJ   r|   rw   rY   )r0   rÀ   rz   Úfilter_resultsZcov_typeZcov_kwdsra   r�   rJ   r:   rƒ   r;   rc   r1   r2   rH   T  sR     ÿÿï
ÿ  þÿ  þzVARMAXResults.__init__c           
      K   sÀ   |d k	r@| j | j| j|d d… d�}|j}|jd }|jd }n| jd }| jd }| d| j| jj ¡ | jj|fd|i|—Ž}t	|j
d||d�|j_| jd k	r°| | j¡}	n| | j¡}	|	S )	Nr   ©r   ).r   ).r'   r=   r   Zknown©ÚconstantÚstationary_cov)Úget_predictionrN   Zprediction_resultsÚpredicted_stateÚpredicted_state_covrF   rÀ   r=   re   r   r   rI   r   Úsmoother_resultsÚsmoothrz   Úfilter)
r0   r`   r   ra   ZfcastZfcast_resultsr°   Zinitial_state_covÚmodÚresr1   r1   r2   Úextend  s&    


  þ

zVARMAXResults.extendc                 c   sˆ   | j }| |¡�n | jjdd…df }| | j¡ |dd|j…df | jjd|j…df< z
dV  W 5 || jjdd…df< X W 5 Q R X dS )az  
        Set the final state intercept value using out-of-sample `exog` / trend

        Parameters
        ----------
        exog : ndarray
            Out-of-sample `exog` values, usually produced by
            `_validate_out_of_sample_exog` to ensure the correct shape (this
            method does not do any additional validation of its own).
        out_of_sample : int
            Number of out-of-sample periods.

        Notes
        -----
        This context manager calls the model-level context manager and
        additionally updates the last element of filter_results.state_intercept
        appropriately.
        Nr'   r(   )rÀ   r­   rÂ   r(   r©   rz   rJ   )r0   r   rÍ   r¬   r1   r1   r2   r­   š  s    ÿ
zVARMAXResults._set_final_exogc              
   c   s4  |o| j jdk}|�rt| j jdd… t d| j jf¡gƒ}| j jdkrjt| j jdd… |dd… gƒ}nd}| j j| j	 d }| j j
|||d�}| jjdd…df }| jjdd…dd…df }	|jj||	d� |j| jdddd	�}
|
jdd…df | jjdd…df< z
dV  W 5 |�r.tj| jjdd…df< X dS )
aŸ  
        Set the final predicted state value using out-of-sample `exog` / trend

        Parameters
        ----------
        exog : ndarray
            Out-of-sample `exog` values, usually produced by
            `_validate_out_of_sample_exog` to ensure the correct shape (this
            method does not do any additional validation of its own).
        out_of_sample : int
            Number of out-of-sample periods.

        Notes
        -----
        We need special handling for forecasting with `exog`, because
        if we had these then the last predicted_state has been set to NaN since
        we did not have the appropriate `exog` to create it.
        r   r'   Nr   )r   r=   éþÿÿÿrÄ   T)r£   r¤   Z
return_ssm)rÀ   rB   r   r`   r+   rQ   rJ   r   r=   rN   re   rÂ   rÈ   rÉ   rI   Zinitialize_knownrÌ   rz   r¦   )r0   r   Úout_of_sampleÚflagZ	tmp_endogZtmp_exogZtmp_trend_offsetZtmp_modrÅ   rÆ   Ztmp_resr1   r1   r2   Ú_set_final_predicted_state¹  s8     ÿ"
ÿÿ
 ÿÿ
z(VARMAXResults._set_final_predicted_stateFÚ	predictedc                    s°   |d krd}| j j|||dd�\}}	}
}| j  ||
¡}i }| j jdkrX| j j| j |d< |  |¡�D |  ||
¡�, tt	| ƒj
f |||||||dœ|—Ž}W 5 Q R X W 5 Q R X |S )Nr   T)Zsilentr=   )ÚstartÚendÚdynamicÚinformation_setÚindexr   r´   )rÀ   Z_get_prediction_indexÚ_validate_out_of_sample_exogr?   r=   rN   r­   rÓ   rG   rg   rÇ   )r0   rÕ   rÖ   r×   rØ   rÙ   r   ra   Ú_startÚ_endrÑ   r¢   r´   r·   rc   r1   r2   rÇ   ê  s.    ÿ
ÿ    ýýzVARMAXResults.get_predictionc
                    sÄ   |d ks|dkrd}n"|dkr&| j }n| j |¡\}}}|dk rJ| j | }|| j kr\tdƒ‚t|| | j  dƒ}| j ||¡}|  ||¡�0 tt| ƒj	|f||||||||	dœ|
—Ž}W 5 Q R X |S )NrÕ   r   rÖ   z4Cannot anchor simulation after the estimated sample.)r®   r¯   r°   r±   r²   r   r³   r´   )
rN   rÀ   Z_get_index_locr<   rD   rÚ   rÓ   rG   rg   rµ   )r0   r¶   r®   r¯   r°   r±   r²   r   r³   r´   ra   Zilocr¢   rÑ   r·   rc   r1   r2   rµ     s6    


ÿ    üûzVARMAXResults.simulatec              	   C   sF  d }| j |j  }| jjdkr6|dkr6| jj| d … }| jjd |j …  ¡ }tj||jj	 
t¡j< tj||jjdd� }	d }
|	rÂd }| jjd k	r¦| jjd |j …  ¡ }|jj||d�}| | j¡}t ¡ �r}| |j |¡¡ | | ||¡¡ |	�r | |j |¡¡ | | ||¡¡ |j}
| jj|j|||
|d�}W 5 Q R X |S )Nr   T)Z	equal_nanrÃ   )rÕ   rÖ   ÚrevisedÚstate_index)rN   rÀ   rB   r   r`   rq   r+   r¦   rÂ   ÚmissingZastypeÚboolrw   Zallclosere   rË   rz   r½   Ú	ExitStackÚenter_contextr­   rÓ   rÊ   Únews)r0   ÚpreviousrÕ   rÖ   ZperiodsrÞ   r   rÑ   Z	rev_endogZhas_revisionsZrevised_resultsZrev_exogZrev_modrÝ   Ústackr·   r1   r1   r2   Ú_news_previous_results(  sJ    ÿ
 ÿ ÿ   þz$VARMAXResults._news_previous_resultsçš™™™™™©?Tc              	      sl  ddl m‰ | j}|jdkr<|jdkr<d}d|j|jf }n(|jdkrVd}d|j }nd}d|j }|jdkrv|d7 }|| g}|jdkr”| d	¡ |jr¤| d
¡ t	t
| ƒjˆ ||| d�}|�rht t| jƒ¡}d‡ ‡fdd„	}	| jj}
| jj}| jj}| jj}| jj}g }t|
ƒD �]Œ}g }d}|dk�rX| t |||
|  |
¡¡ ||
| 7 }|dk�r¤||
 | }|d |
 | }| |t ||¡ ¡ |||
d  7 }|dk�rð||
 | }|d |
 | }| |t ||¡ ¡ |||
d  7 }|dk�r(| |t || |d | ¡ ¡ ||
| 7 }| jj�rR| tj| jj| d dd�¡ t |¡}| |¡ | jj}t|tƒ�s€|g}d||  }|	| ||ƒ}|j |¡ �qt t| jƒ¡| jj }|	| |ddd�}|j |¡ g }||gfD ],}t |¡ ¡ }t|ƒdk�rê| |¡ �qêt |¡}t tt|ƒ t|ƒ¡ƒ¡}t|ƒdk�rh|	| |ddd�}|j |¡ |S )Nr   )Úsummary_paramsZVARMAz(%s,%s)rx   z(%s)ZVMAÚXr§   zmeasurement error)ÚalpharÕ   Ú
model_nameZdisplay_paramsTc                    s¤   | | j | | j| | j| | j| |  ˆ ¡| f}g }t | jj¡|  	¡ D ]B}|rnd 
| d¡d d… ¡}n|}|| jkr„d| }| |¡ qLˆ|d |ˆ d|d�S )NÚ.r'   z
%s (fixed)F)ZynameZxnamerê   Zuse_tÚtitle)rz   ZbseZzvaluesZpvaluesZconf_intr+   ry   Údatar“   r�   ÚjoinÚsplitZfixed_paramsÚappend)r0   r~   rí   Ú	strip_endrÎ   r“   ÚnameÚ
param_name©rê   rè   r1   r2   Ú
make_tablep  s$     þ
  ÿz)VARMAXResults.summary.<locals>.make_tabler   r!   r”   zResults for equation %szError covariance matrixF)rò   zOther parameters)T)Zstatsmodels.iolib.summaryrè   rÁ   r:   r;   rB   r?   rñ   r6   rG   rg   Úsummaryr+   Zaranger    rz   rÀ   rJ   r†   ry   rM   Zconcatenater�   r’   r^   Ztablesr[   ÚflattenÚsetÚ
difference)r0   rê   rÕ   Zseparate_paramsÚspecrë   r4   r÷   Úindicesrö   rJ   r:   r;   r?   rB   Zendog_masksrŠ   Úmasksr&   rÖ   r~   r�   rí   ÚtableZstate_cov_maskÚmZinverse_maskrc   rõ   r2   r÷   O  s°    







  þ

ÿ
ÿ
ÿ
ÿ

ÿÿ
ÿzVARMAXResults.summary)NN)N)NNFrÔ   NN)NNNNNNNN)N)rç   NT)r¸   r¹   rº   r»   rH   rÏ   r½   r¾   r­   rÓ   r   r   rÇ   rµ   ræ   r÷   r¿   r1   r1   rc   r2   rg   ;  s:     ÿ+


0
      ÿ
            ý! ÿ
'
rg   c                   @   s0   e Zd Zi Ze eje¡Zi Ze ej	e¡Z	dS )rh   N)
r¸   r¹   rº   Z_attrsÚwrapZunion_dictsr   Z_wrap_attrsZ_methodsZ_wrap_methodsr1   r1   r1   r2   rh   Ï  s   ÿÿrh   )+r»   r½   Úwarningsr   Zpandasrp   Únumpyr+   Zstatsmodels.compat.pandasr   Zstatsmodels.tools.toolsr   Zstatsmodels.tools.datar   Zstatsmodels.tsa.vector_arr   Zstatsmodels.base.wrapperÚbaseÚwrapperr   Zstatsmodels.tools.sm_exceptionsr   Zkalman_filterr	   r
   Zmlemodelr   r   r   r   r   Ztoolsr   r   r   r   r   r   r   r   rg   rh   Zpopulate_wrapperr1   r1   r1   r2   Ú<module>   s6   $      !   