
    M/Ph                     F   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c 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e          Z' G d de          Z( G d de          Z) ej*        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                       e Zd ZdZ	 	 	 	 d fd		Zdd
Zed             Zed             Zed             Z	d Z
d Z fdZ	 	 ddZej        d             Z eej        j                  	 	 	 	 d fd	            Z x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
                 l    | _         | _        | _        | _        | _        t          |d                    _        t          |d                    _        |dvrt          d           j        dk    r j        dk    rt          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-          j        |          }t1           j        d          }| j        z    _        |j        d         }|}| j        z  }|
                    dd           |
                    d	t8          t:          z              t=                      j        |f|||d
|
  j        dk    s j        dk    r j        sd j         _!        i  _"         j#         j        z   j"        d<    j#        dz   j        z   j"        d<    j#        dz   j        z   j"        d<    j#         j        z   j"        d<    j         dk    r j#         j"        d<   n5 j         dk    r*t           j#         j#        dz   z  dz             j"        d<    j#         j        z   j"        d<   tI           j"        %                                           _&        tO           j         j         j(        dz    j                  }|d d          _)        |dd           _*         j        dk    r j        r j        dk    r(t-          j+         j,         j(        f           j         d<   t-          j-         j#                  }d j         d|z   <    j        dk    rIt-          j-         j        dz
   j#        z            }|d          j#        z   |d         f}d j         d|z   <   t-          j-         j        dz
   j#        z            }|d         |dz    j#        z  z   |d         | j#        z  z   f}d j         d|z   <   t-          j-         j#                  }d j         d|z   <   |d         | j#        z  z   |d         f} j        dk    rd j         d|z   <    j        r* j        dk    rt,          j.        dd |d d f          _/        n4 j        dk    s j        dk    rt,          j.        dd |d df          _/         j        dk    rt,          j.        dd |d d f          _0        nt,          j.        dd ||d f          _0         j         dk    r"dt-          j-         j#                  z    _1        n) j         dk    rt-          j2         j#                   _3         j        r!dt-          j-         j#                  z    _4         fd}d} |d|          \   _5        } |d|          \   _6        } |d|          \   _7        } |d|          \   _8        } |d|          \   _9        } |d|          \   _:        }d  _;         xj<        g dt{          |
>                                          z   z  c_<        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
stationaryinversion_method)exogk_statesk_posdefFtrend   arma
regressionr   	state_covr   obs_cov)offsetstate_intercept)design)
transition)	selectionr/   )r)   )r*   c                 ^    j         |          }t          j        |||z            }||z  }||fS N)
parametersnps_)keyr+   lengthparam_sliceselfs       a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/statespace/varmax.py_slicezVARMAX.__init__.<locals>._slice   s9    _S)F%v 67KfF&&    )orderr$   error_cov_typemeasurement_errorenforce_stationarityenforce_invertibility)?r>   r?   r@   rA   r=   intk_ark_ma
ValueErrorr   r   r$   trend_offsetr   polynomial_trendk_trendsize_trend_is_constr   k_exogmle_regressionr   r4   
asanyarraymax_k_ordershape
setdefaultr
   r   super__init__ssm_time_invariantr3   k_endogsumvaluesk_paramsr   nobs_trend_data_final_trendzerosr"   diag_indicesr5   _idx_state_intercept_idx_transition_idx_state_covtril_indices_idx_lower_state_cov_idx_obs_cov_params_trend
_params_ar
_params_ma_params_regression_params_state_cov_params_obs_cov_final_exog
_init_keyslistkeys)r9   endogr!   r=   r$   r>   r?   r@   rA   rF   kwargs	_min_k_arrV   r#   r"   
trend_dataidxr;   r+   	__class__s   `                  r:   rS   zVARMAX.__init__   s7    -!2$8!%:" 
 aMM	aMM	 !=== / 0 0 09>>di1nn ? @ @ @ 9q==TY]] ="$ $ $
 
(.@.L.L+t| $ 5 :a ? !> $ 5a 8A = 	 +400d #kAo  t,, 	)M%((E 	1%%	!DI- +a.T]* 	*L999 	,.?(.JKKK 		
x(	
 	
FL	
 	
 	

 ;??t|a//8L/',DH$ #'<$,#>  $a$) ; $a$) ;(,t{(B%*,,+/<DOK((  N22DLDL1$459:: OK( &*\D4J%J	"DO224455
 (!4<Q$& & &
 &crc?&rssO L1T%9dkAoo*,(DM493M*N*NDH&' odl++&'s"#
 9q==/49q=DL"@AACa&4<'Q/C./DH_s*+ oty1}<==1vQ$,661v	DL002*+3&' odl++)*#%&!fy4<//Q79q==-.DH^c)*  	PDK1$4$4(*.?'111.L(MD%%\Aq(*.?'3B3.N(OD%9q==#%5xx)B#CD  #%5xx)I#JD *,,!>!>>  N22(*(E(ED%! 	M ,rt|/L/L LD	' 	' 	' 	' 	' %+VGV%<%<"F"(&v"6"6"(&v"6"6*0&v*F*F')/V)D)D&'-vi'@'@$f   	 5 5 57;FKKMM7J7JK 	Kr<   c                 "     | j         |fd|i|S )Nr!   )_clone_from_init_kwds)r9   ro   r!   rp   s       r:   clonezVARMAX.clone7  s"    )t)%EEdEfEEEr<   c                 "    dt           t          fiS )Nfit)VARMAXResultsVARMAXResultsWrapper)r9   s    r:   _res_classeszVARMAX._res_classes:  s    ';<==r<   c                    t          j        | j        t           j                  }t	          j        | j                                                  }|                                }t          j	        |
                                d          }d }| j        dk    r*| j        dk    rt           j        | j        | j        f         }n%| j        dk    r| j        }n| j        dk    r| j        }t          j        t          j        |                    r;t          j        t          j        |          d           }||         }|||         }t          j        d          }t          j        d          }| j        dk    s| j        dk    rt           j                            |                              |          }|t          j        ||          z  }| j        dk    r|d | j                 j        }| j        dk    r|| j        d          j        }g }| j        dk    r| j        nd}	t1          j        |          }
|
                    |	d d          }| j        dk    r0t          j        |j                  j                                        }|j        }| j        dk    r| j        r|                     | j        | j        z  | j                  j                             | j        | j        | j                  j        }tC          dgtE          |           z             }|stG          d	           |dz  }g }| j$        dk    rt1          j        |          }|                    | j$        d d          }t          j        |j        j                                                  }| j%        r|                     | j        | j$        z  | j                  j                             | j        | j        | j$                  j        }tC          dgtE          |           z             }|stG          d
           |dz  }| j        dk    r| j        dk    s| j&        r|                     | j        | j        z  | j                  j                             | j        | j        | j                  j        }t          j'        | j                  t          j(        |d          z
  }| j        dk    rt          j        ||          }| j&        dk    rt          j        ||          }| j        dk    r|                                || j)        <   | j        dk    r
||| j*        <   | j$        dk    r
||| j+        <   | j&        r|                                || j,        <   | j-        dk    r"|j.        /                                || j0        <   nV| j-        dk    rKt           j        1                    |j.                  }|| j2                                                 || j0        <   | j3        rN| j$        dk    r"|j.        /                                || j4        <   n!|j.        /                                || j4        <   |S )NdtypeW)requirementsr   r	   )axisn)maxlags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   )5r4   r]   rY   float64pd	DataFramero   copyinterpolaterequirebfillrH   rK   c_r[   r!   anyisnanlinalgpinvdotTrV   rC   r   VARry   arrayparamsravelresidr@   reshaper   rm   r   rD   rA   rL   eyerW   re   rf   rg   rh   r>   sigma_ur   ri   choleskyrc   r?   rj   )r9   r   ro   r!   masktrend_paramsexog_paramstrendexog_params	ar_paramsrC   mod_arres_arcoefficient_matricesr   	ma_paramsmod_mares_ma
invertibletmp
cov_factors                       r:   start_paramszVARMAX.start_params>  s   $-rz::: TZ__..//!!##
5;;==s;;;<!a5)4945DD\A#DD[1__9D 6"(5//"" 	"F28E??3333D$KEDz x{{hqkk<!t{Q!y~~d3377>>RVD"2333E|a/>@|a.t|}}=? 	 IMMtyyqu%%DT==9q==//17799I 9q==T6=!!L49,dl gdlDL$)<<Q	 ! 'sT3G2G-H-H'HIIJ  C D D DQ	 	9q==]5))FZZ	d#ZFFF117799I ) #%%ty0$, '$,di@@	 % +A37K6K1L1L+LMM
! # G H H HNI 9q==dlQ..$2E.!!L49,dl gdlDL$)<<Q	 ! &&&0D1)M)M)MMC|a!vc<88"Q&& fS+66 <!)5););)=)=F4%& 9q==&/F4?# 9q==&/F4?#  	B.9.?.?.A.AF4*+ *,,-3^-D-D-F-FF4)** N22++FN;;J445;;== 4)* ! 	Iy1}}/5~/F/F/H/Ht+,,/5~/F/F/H/Ht+,r<   c                 >    g } j         t           j         t                    sg j        dk    rvt	           j                  D ]a} j                                        d         D ]?}|dk    r|d|         z  gz  }|dk    r|d|         z  gz  }.|d||         fz  gz  }@b| fdt	           j                  D             z  }| fdt	           j                  D             z  }| fdt	           j                  D             z  } j        d	k    r$|fd
t	           j                  D             z  }n. j        dk    r#|fdt	           j                  D             z  } j	        r#|fdt	           j                  D             z  }|S )Nr   zintercept.%sr	   zdrift.%sztrend.%d.%sc           	          g | ]G}t          j                  D ]0}t          j                  D ]}d |dz   |         |         fz  1HS )z	L%d.%s.%sr	   )rangerC   rV   .0jikendog_namesr9   s       r:   
<listcomp>z&VARMAX.param_names.<locals>.<listcomp>  s     
 
 
49%%
 
 4<((	
 
  1Q3AA??
 
 
 
 
r<   c           	          g | ]G}t          j                  D ]0}t          j                  D ]}d |dz   |         |         fz  1HS )zL%d.e(%s).%sr	   )r   rD   rV   r   s       r:   r   z&VARMAX.param_names.<locals>.<listcomp>  s     
 
 
49%%
 
 4<((	
 
  ac;q>;q>BB
 
 
 
 
r<   c                 p    g | ]2}t          j                  D ]}d j        |          d|          3S )zbeta..)r   rK   
exog_names)r   r   r   r   r9   s      r:   r   z&VARMAX.param_names.<locals>.<listcomp>  se     
 
 
4;''
 
  :DOA&99Q99
 
 
 
r<   r   c                 &    g | ]}d |         z  S )z	sigma2.%s r   r   r   s     r:   r   z&VARMAX.param_names.<locals>.<listcomp>  s2        k!n,  r<   r   c                     g | ]<}t          |d z             D ]'}||k    rd|         z  nd|          d|          (=S )r	   zsqrt.var.%sz	sqrt.cov.r   )r   )r   r   r   r   s      r:   r   z&VARMAX.param_names.<locals>.<listcomp>  s{        qs	   4566Q//>[^>>k!n>>   r<   c                 &    g | ]}d |         z  S )zmeasurement_variance.%sr   r   s     r:   r   z&VARMAX.param_names.<locals>.<listcomp>  s2        *KN:  r<   )
r   
isinstancerm   rH   r   rV   rG   nonzeror>   r?   )r9   param_namesr   r   r   s   `   @r:   r   zVARMAX.param_names  s   &$*D11 	(&-K <!4<(( M M.6688; M MAAvv#Q(G'HHa#
[^(C'DD#KN8K(K'LLM 	 
 
 
 
 
4<((
 
 
 	
 	 
 
 
 
 
4<((
 
 
 	
 	 
 
 
 
 
4<((
 
 
 	
 *,,    t|,,   KK  N22     t|,,   K ! 	    t|,,   K
 r<   c                    t          j        |d          }t          j        |j        |j                  }|| j                 || j        <   | j        dk    r| j        r| j        dk    r#t          j	        || j
                 dz            }ne| j        dk    rZt          j        | j        d         j        |j                  }|| j
                 || j        <   t          j        ||j                  }|| j                                     | j        | j        | j        z            }t%          ||          \  }}|                                || j        <   n|| j                 || j        <   | j        dk    r| j        rt          j        | j        |j                  }|| j                                     | j        | j        | j        z            }t%          ||          \  }}|                                || j        <   n|| j                 || j        <   || j                 || j        <   | j        dk    r|| j
                 dz  || j
        <   n | j        dk    r|| j
                 || j
        <   | j        r|| j                 dz  || 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	   ndminr~   r   r   r%   r   r)   )r4   r   r]   rP   r   re   rC   r@   r>   diagri   rT   rc   r   r   rf   r   rV   r   r   rD   rA   r   rg   rh   r?   rj   )r9   unconstrainedconstrainedr)   state_cov_lowercoefficientsr   variances           r:   transform_paramszVARMAX.transform_params  s   , a888h}2-:MNNN +88J*KD&' 9q==T6="j00GM$2H$I1$LMM		$66"$(48K+@+F1>1D#F #F #F "$"89   9:F?O4EFF	 )9AAdlTY68 8L 2,	JJ + (+?+E+E+G+GK((+8+IK( 9q==T7=t|=3FGGGI(9AAdlTY68 8L 2,	JJ + (+?+E+E+G+GK((+8+IK( $12 	D+,
 *,,d45q8 .//  N22d45 ./ ! 	8 d23Q6 ,- r<   c                    t          j        |d          }t          j        |j        |j                  }|| j                 || j        <   | j        dk    r| j        r| j        dk    r t          j	        || j
                           }ne| j        dk    rZt          j        | j        d         j        |j                  }|| j
                 || j        <   t          j        ||j                  }|| j                                     | j        | j        | j        z            }t%          ||          \  }}|                                || j        <   n|| j                 || j        <   | j        dk    r| j        rt          j        | j        |j                  }|| j                                     | j        | j        | j        z            }t%          ||          \  }}|                                || j        <   n|| j                 || j        <   || j                 || j        <   | j        dk    r|| j
                 dz  || j
        <   n | j        dk    r|| j
                 || j
        <   | j        r|| j                 dz  || 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   r~   r   r   r   r)   g      ?)r4   r   r]   rP   r   re   rC   r@   r>   r   ri   rT   rc   r   r   rf   r   rV   r   r   rD   rA   r   rg   rh   r?   rj   )r9   r   r   r)   r   r   unconstrained_matricesr   s           r:   untransform_paramszVARMAX.untransform_paramsR  s     h{!444!2+:KLLL -88J,Kd() 9q==T6="j00GK0F$GHH		$66"$(48K+@+F1<1B#D #D #D   67   9:F?O4EFF	 't7??dlTY68 8L 4L)LL -"H-C-I-I-K-KM$/**-8-IM$/* 9q==T7=t|;3DEEEI&t7??dlTY68 8L 4L)LL -"H-C-I-I-K-KM$/**-8-IM$/* /0 	d-.
 *,,D23S8 $011  N22D23 $01 ! 	8 D0136 $./ r<   c                     t                                          |           t          j        t	          | j                                                            d d         }d t          j        | j        |          D             \  }}}}}}| j	        ro| j
        dk    rd| j        dk    s| j
        dk    rN|                    |          }t          |                    |                    dk    }|r|st          d          | j        rk| j        dk    rb| j        s| j        dk    rT|                    |          }t          |                    |                    dk    }|r|st          d          d S d S d S d S d S )Nr,   c              3   >   K   | ]}|                                 V  d S r2   )tolist)r   arrs     r:   	<genexpr>z2VARMAX._validate_can_fix_params.<locals>.<genexpr>  sC       ,J ,J CJJLL,J ,J ,J ,J ,J ,Jr<   r   r	   zCannot fix individual autoregressive parameters when `enforce_stationarity=True`. In this case, must either fix all autoregressive parameters or none.zCannot fix individual moving average parameters when `enforce_invertibility=True`. In this case, must either fix all moving average parameters or none.)rR   _validate_can_fix_paramsr4   cumsumrm   r3   rX   array_splitr   r@   rC   rV   
issupersetlenintersectionrE   rA   rD   )	r9   r   ix_ar_namesma_namesfix_allfix_anyrt   s	           r:   r   zVARMAX._validate_can_fix_params  s   ((555YtDO22445566ss;,J ,J$&N43CR$H$H,J ,J ,J(Hh1a $ 
	"Q|a49q==%00::00::;;a?  "7 "$!" " "
 % 
	"$)a--| 	"ty1}}%00::00::;;a?  "7 "$!" " "
	" 
	"--
" "	  -}" "r<   c                    |                      |||          }| j        r|| j                                     | j        | j                  j        }t          j        | j	        dd          |          }|j        | j
        | j        <   | j        ,t          j        | j        |          | j
        dd | j        df<   | j        dk    r| j        s)t          j        d|j                  }|| j
        dd d f<   || j                                     | j        | j                  j        }| j        r|}n"t          j        | j        dd          |          }| j
        | j        xx         |j        z  cc<   | j        T| j        d         j        dk    r>| j
        dd | j        dd fxx         t          j        | j        |          j        z  cc<   | j        r@| j        9t          j        t          j        |j                  }	|	| j
        dd | j        df<   || j                                     | j        | j        | j        z            }
|| j                                     | j        | j        | j        z            }t          j        |
|f         | j
        | j        <   | j        dk    r|| j                 | j
        | j        <   nm| j        dk    rbt          j        | j
        d	         j         |j                  }|| j                 || j!        <   t          j        ||j                  | j
        d	<   | j"        r|| j#                 | j
        | j$        <   d S d S )
N)transformedincludes_fixedr	   r-   r,   r   r~   r   r   r)   )%handle_paramsrL   rh   r   rV   rK   r   r4   r   r!   rT   r_   rk   rH   r   r   re   rJ   r[   r\   stopnanrf   rC   rg   rD   r   r`   r>   ri   ra   r]   rP   rc   r?   rj   rd   )r9   r   r   r   complex_stepr   	interceptzeror   r   r&   r'   r   s                r:   updatezVARMAX.update  s   ##F3A $ C C
  	3 !89AAdk+ ++, ty}k::I2;+DHT./+AC$kB3 B3*MT\M2=> <! & 6x66615*AAA-.!$"45==dl, ,,- # G(		F4#3ABB#7FF	HT.///9;>///!-1"5:b@@*MT\M233>???26%|D5 D5567???
  	A4#3#;(26666C=@DH&r9: DO$,,L$,24 4DO$,,L$,24 4)+r2v%& *,,t-. HT())  N22 htx'<'B-3\; ; ;O t-. D56$&F?O<M$N$NDH[! ! 	G*01E*FDHT&'''	G 	Gr<   c           	   #     K   | j         }| j        dk    r|t          j        |          }|j        dk    r
|dd         }	 t          j        |dd         | j        f          }nI# t          $ r< t          dt          | j        f          dt          |j                  d          w xY w|| _         	 dV  || _         dS # || _         w xY w)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	   zEProvided exogenous values are not of the appropriate shape. Required z, got r   )	rk   rK   r4   
atleast_1dndimr   rE   strrP   )r9   r!   cache_values      r:   _set_final_exogzVARMAX._set_final_exog   s      , &;??}T**9>>8D::d2A2h??DD! : : :$*(+T[N(;(;(;(;(+DJ&9 : : ::
  $D	+EEE*D{D****s   #A% %AB+6C 	Cc                     |                      |          5   t                      j        ||f|||||||	|
||d
|}d d d            n# 1 swxY w Y   |S )N)
measurement_shocksstate_shocksinitial_stateanchorrepetitionsr!   extend_modelextend_kwargsr   r   )r   rR   simulate)r9   r   nsimulationsr   r   r   r   r   r!   r   r   r   r   rp   outrt   s                  r:   r   zVARMAX.simulate)  s     !!$'' 	 	"%''"9K);T)'   C	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
s   'A

AA)Nr   r   r   FTTr	   r2   )TFF)
NNNNNNNNTF)__name__
__module____qualname____doc__rS   rw   propertyr|   r   r   r   r   r   r   
contextlibcontextmanagerr   r   r   r   __classcell__rt   s   @r:   r   r      s       b bH >ABGBFqK qK qK qK qK qKfF F F F > > X> ~ ~ X~@ = = X=~Q Q QfK K KZ" " " " "< ?D!AG AG AG AGF &+ &+ &+P Xh'((@D?C;?FK     )(    r<   r   c                   N    e Zd ZdZ	 	 d fd	ZddZej        d             Zej        d             Z	 e
ej        j                  	 	 d fd		            Z e
ej        j                  	 	 	 	 d fd
	            Z	 	 ddZ e
ej        j                  d fd	            Z xZS )rz   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                     t                      j        |||||fi | t          di | 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
        }	|                    ||	z  |          j                            |||	          j        | _        | j        j        dk    rt%          j        | j        | j        j                           }
| j        j        }| j        j        }|
                    ||z  |          j                            |||          j        | _        d S d S )N)r>   r?   r@   rA   rF   r=   rC   rD   r$   rH   rK   r   r   )rR   rS   r   modelr>   r?   r@   rA   rF   r=   rC   rD   r$   rH   rK   specificationcoefficient_matrices_varcoefficient_matrices_vmar4   r   r   rf   rV   r   r   rg   )r9   r  r   filter_resultscov_typecov_kwdsrp   r   rV   rC   r   rD   rt   s               r:   rS   zVARMAXResults.__init__S  s   6>8X	
 	
AG	
 	
 	
 #  "j7!%!=$(J$C%)Z%E J3Z% JOJO Z%z)j'#&
 &
  * )-%(,%:?QTZ-B!CDDIj(G:?D!!'D.'::<ggw--a ) :?QTZ-B!CDDIj(G:?D!!'D.'::<ggw--a )))	 r<   c                    |L|                      | j        | j        |d d                   }|j        }|j        d         }|j        d         }n| j        d         }| j        d         }|                    d| j        | j        j        z               | j        j        |fd|i|}t          |j
        d||          |j        _        | j        |                    | j                  }	n|                    | j                  }	|	S )	Nr	   )r!   ).r   ).r,   rF   r!   knownconstantstationary_cov)get_predictionrZ   prediction_resultspredicted_statepredicted_state_covrQ   r  rF   rw   r   r"   rT   r   smoother_resultssmoothr   filter)
r9   ro   r!   rp   fcastfcast_resultsr   initial_state_covmodress
             r:   extendzVARMAXResults.extend  s    ''	4948'LLE!4M)9&AM - A& I 09M $ 8 A.$)dj6M*MNNNdju::4:6::!/L'M,". ". ".  ,**T[))CC**T[))C
r<   c              #     K   | j         }|                    |          5  | j        j        dddf         }|                    | j                   |dd|j        df         | j        j        d|j        df<   	 dV  || j        j        dddf<   n# || j        j        dddf<   w xY w	 ddd           dS # 1 swxY w Y   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   r   rV   )r9   r!   r  r   s       r:   r   zVARMAXResults._set_final_exog  sI     ( j  && 	I 	I-=aaaeDKJJt{###%||R78 /b0@AI=H#3AAArE::[#3AAArE:HHHH:	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	Is*   AB79B=B7B&&B77B;>B;c              #   D  K   |o| j         j        dk    }|r>t          | j         j        dd         t	          j        d| j         j        f          g          }| j         j        dk    r,t          | j         j        dd         |dd         g          }nd}| j         j        | j	        z   dz
  }| j         
                    |||          }| j        j        dddf         }| j        j        dddddf         }	|j                            ||	           |                    | j        ddd	          }
|
j        dddf         | j        j        dddf<   	 dV  |rt          j        | j        j        dddf<   dS dS # |rt          j        | j        j        dddf<   w xY w)
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!   rF   r  T)r   r   
return_ssm)r  rK   r   ro   r4   r]   rV   r!   rF   rZ   rw   r
  r  r  rT   initialize_knownr  r   r   )r9   r!   out_of_sampleflag	tmp_endogtmp_exogtmp_trend_offsettmp_modr  r  tmp_ress              r:   _set_final_predicted_statez(VARMAXResults._set_final_predicted_state  s     ( 6!2Q!6 	0
 %rxDJ4F0G'H'H J K KIz 1$$!4:?233#7bqb"BCC#z6BQFj&&yx4D ' F FG*:111b5AH!0DQQQ2XNNK(((8F ) H H HnnT[d48T % K KG
 '2. /26	DEEE D=?V#3AAArE:::D Dt D=?V#3AAArE:CCCCs   E> >!FF	predictedc                    |d}| j                             |||d          \  }}	}
}| j                             ||
          }i }| j         j        dk    r| j         j        | j        z   |d<   |                     |          5  |                     ||
          5   t                      j	        d|||||||d|}d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   |S )Nr   T)silentrF   )startenddynamicinformation_setindexr!   r   r   )
r  _get_prediction_index_validate_out_of_sample_exogrH   rF   rZ   r   r+  rR   r  )r9   r/  r0  r1  r2  r3  r!   rp   _start_endr$  r   r   r   rt   s                 r:   r  zVARMAXResults.get_prediction  s    =E J,,UCt,LL 	'mQ z66t]KK :!!
'$)3 .) !!$'' 	; 	;00}EE ; ;,egg, ;S'$35t"/; ; 4:; ;; ; ; ; ; ; ; ; ; ; ; ; ; ; ;	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 
s6   C"C;CC	CC	CC"%C"c
                    ||dk    rd}n,|dk    r| j         }n| j                            |          \  }}}|dk     r
| j         |z   }|| j         k    rt          d          t	          ||z   | j         z
  d          }| j                            ||          }|                     ||          5   t                      j        |f||||||||	d|
}d d d            n# 1 swxY w Y   |S )Nr/  r   r0  z4Cannot anchor simulation after the estimated sample.)r   r   r   r   r   r!   r   r   )	rZ   r  _get_index_locrE   rN   r5  r+  rR   r   )r9   r   r   r   r   r   r   r!   r   r   rp   ilocr   r$  r   rt   s                  r:   r   zVARMAXResults.simulate  sl   
 >Vw..DDu__9DD226::JD!Q!889t#D$) ( ) ) ) D</$);Q?? z66t]KK,,T=AA 	 	"%''"1C);T)	 
  C	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
s   /$CC#&C#c                    d }| j         |j         z
  }| j        j        dk    r|dk    r| j        j        | d          }t	          j                    5 }	|	                    |j                            |                     |	                    |                    ||                     | j	        
                    |j	        ||||          }
d d d            n# 1 swxY w Y   |
S )Nr   )r/  r0  revisions_details_startstate_index)rZ   r  rK   r!   r   	ExitStackenter_contextr   r+  r  news)r9   previousr/  r0  periodsr<  r=  r!   r$  stackr   s              r:   _news_previous_resultsz$VARMAXResults._news_previous_results(  s1    	HM1:q  ]Q%6%6:?M>??3D !## 	)u > >t D DEEE C Cm!% !% & & & ',,)C(?' - ) )C	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 
s   A;CCC皙?Tc           	      .	   ddl m | j        }|j        dk    r!|j        dk    rd}d|j         d|j         d}n$|j        dk    rd}d|j        z  }nd	}d|j        z  }|j        dk    r|d
z  }||z   g}|j        dk    r|                    d           |j        r|                    d           t                      
                    |||           }|rt          j        t          | j                            }dfd	}	| j        j        }
| j        j        }| j        j        }| j        j        }| j        j        }g }t#          |
          D ]}g }d}|dk    r7|                    t          j        |||
|z  z   |
                     ||
|z  z  }|dk    rI||
z  |z  }|dz   |
z  |z  }|                    |t          j        ||          z              |||
dz  z  z  }|dk    rI||
z  |z  }|dz   |
z  |z  }|                    |t          j        ||          z              |||
dz  z  z  }|dk    r<|                    |t          j        ||z  |dz   |z            z              ||
|z  z  }| j        j        r9|                    t          j        | j        j        |z
  dz
  d                     t          j        |          }|                    |           | j        j        }t-          |t.                    s|g}d||         z  } |	| ||          }|j                            |           t          j        t          | j                            | j        j                 } |	| |dd          }|j                            |           g }||gfD ]P}t          j        |                                          }t          |          dk    r|                    |           Qt          j        |          }t          j        t/          t7          |                              t7          |                                        }t          |          dk    r) |	| |dd          }|j                            |           |S )Nr   )summary_paramsVARMA(,)r   z(%s)VMAXr   zmeasurement error)alphar/  
model_namedisplay_paramsTc                    | | j         |         | j        |         | j        |         | j        |         |                               |         f}g }t          j        | j        j                  |         	                                D ]Z}|r1d
                    |                    d          d d                   }n|}|| j        v rd|z  }|                    |           [ 	|d |d|          S )Nr   r,   z
%s (fixed)F)ynamexnamerN  use_ttitle)r   bsezvaluespvaluesconf_intr4   r   datar   r   joinsplitfixed_paramsappend)
r9   r   rU  	strip_endr  r   name
param_namerN  rG  s
           r:   
make_tablez)VARMAXResults.summary.<locals>.make_tablef  s   T[.|D)4<+=}}U++D13 !HTY%:;;DAHHJJ 3 3D  *%(XXdjjoocrc.B%C%C

%)
t000%1J%>
&&z2222%~c[,1eM M M Mr<   r	   r%   r   zResults for equation %szError covariance matrixF)r_  zOther parameters)T)statsmodels.iolib.summaryrG  r  rC   rD   rK   rH   r^  r?   rR   summaryr4   aranger   r   r  rV   r   r   rY   concatenater   r   rm   tablesri   flattenset
difference)r9   rN  r/  separate_paramsspecrO  r=   rd  indicesrb  rV   rC   rD   rH   rK   endog_masksr   masksr+   r0  r   r   rU  tablestate_cov_maskminverse_maskrG  rt   s    `                         @r:   rd  zVARMAXResults.summaryE  s0   <<<<<< !9q==TY]] J0	00DI000EEY]]Jdi(EEJdi(E;??#J 5()
<!k***! 	31222''//u.. " 
 

  ]	-iDK 0 011GM M M M M M M& j(G:?D:?Dj(GZ&FK7^^ -- -- Q;;LL1a'G2C.CW!M!MNNNg//F !88K$.Eq5G+d2CLL5#!6!668 8 8dWaZ//F !88K$.Eq5G+d2CLL5#!6!668 8 8dWaZ//F A::LL1v:A7G!H!HHJ J Jg..F :/ HLL!4q!81!<AFFFH H H ~e,,""4((("j4!+t44 0#.-K1KNB"
4u55%%e,,,, 	#dk**++DJ,HI Jt^5N).0 0 0EN!!%((( E!N#34 $ $HQKK''))q66A::LLOOON5))E8DW)@)@U)L)L$M$MNNL<  1$$"
47I-24 4 4%%e,,,r<   )NNr2   )NNFr,  NN)NNNNNNNN)FN)rE  NT)r   r   r   r   rS   r  r   r  r   r+  r   r   r  r   rD  rd  r  r  s   @r:   rz   rz   :  s        0 @D*0 *0 *0 *0 *0 *0X   6 I I I< .D .D .D` Xj'/00;@EI     108 Xj!)**8<?C;?#     +*B 8=+/   : Xj ())| | | | | *)| | | | |r<   rz   c                   n    e Zd Zi Z ej        ej        e          Zi Z ej        ej	        e          Z	dS )r{   N)
r   r   r   _attrswrapunion_dictsr   _wrap_attrs_methods_wrap_methodsr   r<   r:   r{   r{     sR        F"$"#4#@#)+ +KH$D$%6%D%-/ /MMMr<   r{   )+r   r   warningsr   pandasr   numpyr4   statsmodels.compat.pandasr   statsmodels.tools.toolsr   statsmodels.tools.datar   statsmodels.tsa.vector_arr   statsmodels.base.wrapperbasewrapperrv  statsmodels.tools.sm_exceptionsr   kalman_filterr
   r   mlemodelr   r   r   r   r   toolsr   r   r   r   r   r   r   r   rz   r{   populate_wrapperr   r<   r:   <module>r     s                      . . . . . . ) ) ) ) ) ) 3 3 3 3 3 3 / / / / / / ' ' ' ' ' ' ' ' ' = = = = = = 6 6 6 6 6 6 6 6 = = = = = = = = = = * * * * * *                 X X X X XX X X XvH H H H HJ H H HV/ / / / /, / / /  *M : : : : :r<   