
    !g                     6   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jT                  e)e(       y)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.
    c
                 ^    | _         | _        | _        | _        | _        t        |d          _        t        |d          _        |dvrt        d       j                  dk(  r j                  dk(  rt        d       j                  dkD  r j                  dkD  rt        dt               | _        |	 _        t         j                        \   _         _         j                  j                   dk(  xr  j                  d   dk(   _        t%        |      \   _        } j&                  dkD   _        t+        |d       st-        j.                  |      }t1         j                  d      }| j                  z    _        |j4                  d   }|}| j2                  z  }|
j7                  dd       |
j7                  d	t8        t:        z         t=         |  |f|||d
|
  j&                  dkD  s j                  dkD  r j"                  sd j@                  _!        i  _"         jF                   j                  z   jD                  d<    jF                  dz   j                  z   jD                  d<    jF                  dz   j                  z   jD                  d<    jF                   j&                  z   jD                  d<    j                   dk(  r jF                   jD                  d<   nD j                   dk(  r5t         jF                   jF                  dz   z  dz         jD                  d<    jF                   j                  z   jD                  d<   tI         jD                  jK                                _&        tO         j                   j                   jP                  dz    j                        }|d d  _)        |dd   _*         j                  dkD  r j"                  r j&                  dkD  r8t-        jV                   jX                   jP                  f       j@                  d<   t-        jZ                   jF                        }d j@                  d|z   <    j                  dkD  rXt-        jZ                   j                  dz
   jF                  z        }|d    jF                  z   |d   f}d j@                  d|z   <   t-        jZ                   j                  dz
   jF                  z        }|d   |dz    jF                  z  z   |d   | jF                  z  z   f}d j@                  d|z   <   t-        jZ                   jF                        }d j@                  d|z   <   |d   | jF                  z  z   |d   f} j                  dkD  rd j@                  d|z   <    j"                  r/ j&                  dk(  r t,        j\                  dd |d d f    _/        n= j                  dkD  s j&                  dkD  rt,        j\                  dd |d df    _/         j                  dkD  r t,        j\                  dd |d d f    _0        nt,        j\                  dd ||d f    _0         j                   dk(  r(dt-        jZ                   jF                        z    _1        n3 j                   dk(  r$t-        jd                   jF                         _3         j                  r'dt-        jZ                   jF                        z    _4         fd}d} |d|      \   _5        } |d|      \   _6        } |d|      \   _7        } |d|      \   _8        } |d|      \   _9        } |d|      \   _:        }d  _;         xjx                  g dt{        |
j}                               z   z  c_<        y ) Nr   r	   )diagonalunstructuredz3Invalid 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       ^/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/statespace/varmax.py_slicezVARMAX.__init__.<locals>._slice   s:    __S)F%%v7KfF&&    )orderr"   error_cov_typemeasurement_errorenforce_stationarityenforce_invertibility)?r<   r=   r>   r?   r;   intk_ark_ma
ValueErrorr   r   r"   trend_offsetr   polynomial_trendk_trendsize_trend_is_constr   k_exogmle_regressionr   r2   
asanyarraymax_k_ordershape
setdefaultr
   r   super__init__ssm_time_invariantr1   k_endogsumvaluesk_paramsr   nobs_trend_data_final_trendzerosr    diag_indicesr3   _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)r7   endogr   r;   r"   r<   r=   r>   r?   rD   kwargs	_min_k_arrT   r!   r    
trend_dataidxr9   r)   	__class__s   `                  r8   rQ   zVARMAX.__init__   s    -!2$8!%:" 
 aM	aM	 !== / 0 099>dii1n ? @ @ 99q=TYY] ="$
 
(.@.L+t| $ 5 5 : :a ? !> $ 5 5a 8A = 	 +40d #kkAo  t,MM%(E 		1%	!DII- ++a.T]]* 	*L9 	,.?(.JK 		
x(	
FL	

 ;;?t||a/8L8L',DHH$ #'<<$,,#>  $a$)) ; $a$)) ;(,t{{(B%*,+/<<DOOK(   N2DLLDLL1$459: OOK( &*\\D4J4J%J	"DOO2245
 (!!4<<Q$$&
 &cr?&rsO LL1T%9%9dkkAo*,((DMM4993M*NDHH&' oodll+&'s"#
 99q=//499q=DLL"@ACa&4<<'Q/C./DHH_s*+ ootyy1}<=1vQ$,,661v	DLL002*+3&' oodll+)*#%&!fy4<<//Q799q=-.DHH^c)* DKK1$4(*.?'1.L(MD%\\Aq(*.?'3B3.N(OD%99q=#%55xx)B#CD #%55xx)I#JD *,!>>   N2(*(ED%!! ,rt||/L LD	' %+GV%<"F"(v"6"(v"6*0v*F')/V)D&'-i'@$f   	 57;FKKM7JK 	Kr:   c                 ,     | j                   |fd|i|S )Nr   )_clone_from_init_kwds)r7   rm   r   rn   s       r8   clonezVARMAX.clone7  s    )t))%EdEfEEr:   c                     dt         t        fiS )Nfit)VARMAXResultsVARMAXResultsWrapper)r7   s    r8   _res_classeszVARMAX._res_classes:  s    ';<==r:   c                    t        j                  | j                  t         j                        }t	        j
                  | j                  j                               }|j                         }t        j                  |j                         d      }d }| j                  dkD  r9| j                  dkD  r*t         j                  | j                  | j                  f   }n7| j                  dkD  r| j                  }n| j                  dkD  r| j                  }t        j                   t        j"                  |            r7t        j                   t        j"                  |      d       }||   }|||   }t        j                  d      }t        j                  d      }| j                  dkD  s| j                  dkD  rt         j$                  j'                  |      j)                  |      }|t        j(                  ||      z  }| j                  dkD  r|d | j                   j*                  }| j,                  dkD  r|| j                  d  j*                  }g }| j.                  dkD  r| j.                  nd}	t1        j2                  |      }
|
j5                  |	d d      }| j.                  dkD  r7t        j6                  |j8                        j*                  j;                         }|j<                  }| j.                  dkD  r| j>                  r|jA                  | j,                  | j.                  z  | j,                        j*                  jA                  | j,                  | j,                  | j.                        j*                  }tC        dgtE        |       z         }|stG        d	       |dz  }g }| jH                  dkD  rt1        j2                  |      }|j5                  | jH                  d d      }t        j6                  |j8                  j*                        j;                         }| jJ                  r|jA                  | j,                  | jH                  z  | j,                        j*                  jA                  | j,                  | j,                  | jH                        j*                  }tC        dgtE        |       z         }|stG        d
       |dz  }| j.                  dkD  r| j                  dkD  s| jL                  r|jA                  | j,                  | j.                  z  | j,                        j*                  jA                  | j,                  | j,                  | j.                        j*                  }t        jN                  | j,                        t        jP                  |d      z
  }| j                  dkD  rt        j(                  ||      }| jL                  dkD  rt        j(                  ||      }| j                  dkD  r|j;                         || jR                  <   | j.                  dkD  r||| jT                  <   | jH                  dkD  r||| jV                  <   | jL                  r|j;                         || jX                  <   | jZ                  dk(  r(|j\                  j_                         || j`                  <   nb| jZ                  dk(  rSt         j$                  jc                  |j\                        }|| jd                     j;                         || j`                  <   | jf                  r_| jH                  dkD  r)j\                  j_                         || jh                  <   |S |j\                  j_                         || jh                  <   |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   )5r2   r[   rW   float64pd	DataFramerm   copyinterpolaterequirebfillrF   rI   c_rY   r   anyisnanlinalgpinvdotTrT   rA   r   VARrw   arrayparamsravelresidr>   reshaper   rk   r   rB   r?   rJ   eyerU   rc   rd   re   rf   r<   sigma_ur   rg   choleskyra   r=   rh   )r7   r   rm   r   masktrend_paramsexog_paramstrendexog_params	ar_paramsrA   mod_arres_arcoefficient_matricesr   	ma_paramsmod_mares_ma
invertibletmp
cov_factors                       r8   start_paramszVARMAX.start_params>  s   $--rzz: TZZ__./!!#

5;;=s;<<!a55))49945D\\A##D[[1_99D 66"((5/"FF288E?33D$KEDz xx{hhqk<<!t{{Q!yy~~d377>RVVD"233E||a/>@@||a.t||}=?? 	 IIMtyyqu%DT=99q=/11779I 99q=T66!!LL499,dll!gdllDLL$))<QQ	 ! 'sT3G2G-H'HIJ C DQ	 	99q=]]5)FZZ		d#ZFF1779I ))%%tyy0$,,a'$,,dii@	 % +A37K6K1L+LM
! G HNI 99q=dllQ.$2E2E!!LL499,dll!gdllDLL$))<QQ	 ! &&&0D1)MMC||a!vvc<8""Q& ffS+6 <<!)5););)=F4%%& 99q=&/F4??# 99q=&/F4??# .9.?.?.AF4**+ *,-3^^-D-D-FF4))*  N2++FNN;J4445;;= 4))* !!yy1}/5~~/F/F/Ht++,  06~~/F/F/Ht++,r:   c                    g }| j                   }t        | j                   t              s|g}| j                  dkD  rnt	        | j
                        D ]V  }| j                  j                         d   D ]4  }|dk(  r|d||   z  gz  }|dk(  r|d||   z  gz  }'|d|||   fz  gz  }6 X |t	        | j
                        D cg c]G  }t	        | j                        D ]-  }t	        | j
                        D ]  }d|dz   ||   ||   fz   / I c}}}z  }|t	        | j
                        D cg c]G  }t	        | j                        D ]-  }t	        | j
                        D ]  }d|dz   ||   ||   fz   / I c}}}z  }|t	        | j
                        D cg c]4  }t	        | j                        D ]  }d| j                  |    d	||     6 c}}z  }| j                  d
k(  r-|t	        | j
                        D cg c]
  }d||   z   c}z  }nc| j                  dk(  rT|t	        | j
                        D cg c]0  }t	        |dz         D ]  }||k(  rd||   z  nd||    d	||     2 c}}z  }| j                  r,|t	        | j
                        D cg c]
  }d||   z   c}z  }|S c c}}}w c c}}}w c c}}w c c}w c c}}w c c}w )Nr   zintercept.%sr	   zdrift.%sztrend.%d.%sz	L%d.%s.%szL%d.e(%s).%szbeta..r   z	sigma2.%sr   zsqrt.var.%sz	sqrt.cov.zmeasurement_variance.%s)endog_names
isinstancerk   rF   rangerT   rE   nonzerorA   rB   rI   
exog_namesr<   r=   )r7   param_namesr   jiks         r8   r   zVARMAX.param_names  sh   &&$**D1&-K <<!4<<( M..668; MAAv#Q(G'HHa#
[^(C'DD#KN8K(K'LLMM 	4<<(
 
499%
 4<<(	
  1Q3AA??
?
?
 	
 	4<<(
 
499%
 4<<(	
  ac;q>;q>BB
B
B
 	
 	4<<(
4;;'
  DOOA&'qQ(89
9
 	
 *,t||, k!n, K   N2 t||, qs	  456Q/[^,Ak!n-=>?? K !!t||, *KN: K
 W



s&   AJ4
0AJ;
9KK?5KKc                 ^   t        j                  |d      }t        j                  |j                  |j                        }|| j
                     || j
                  <   | j                  dkD  r2| j                  r%| j                  dk(  r&t        j                  || j                     dz        }n| j                  dk(  rtt        j                  | j                  d   j                  |j                        }|| j                     || j                  <   t        j                  ||j                        }|| j                     j!                  | j"                  | j"                  | j                  z        }t%        |      \  }}|j'                         || j                  <   n|| j                     || j                  <   | j(                  dkD  r| j*                  rt        j,                  | j"                  |j                        }|| j.                     j!                  | j"                  | j"                  | j(                  z        }t%        ||      \  }}|j'                         || j.                  <   n|| j.                     || j.                  <   || j0                     || j0                  <   | j                  dk(  r || j                     dz  || j                  <   n+| j                  dk(  r|| j                     || j                  <   | j2                  r|| j4                     dz  || j4                  <   |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'   )r2   r   r[   rN   r}   rc   rA   r>   r<   diagrg   rR   ra   r   r   rd   r   rT   r   r   rB   r?   r   re   rf   r=   rh   )r7   unconstrainedconstrainedr'   state_cov_lowercoefficientsr   variances           r8   transform_paramszVARMAX.transform_params  s   , a8hh}22-:M:MN +88J8J*KD&&' 99q=T66""j0GGM$2H2H$I1$LM	$$6"$((488K+@+F+F1>1D1D#F "$"8"89   9 9:FF?O4E4EF	 )9AAdllTYY68L 2,	J + (+?+E+E+GK(+8+IK( 99q=T77t||=3F3FGI(9AAdllTYY68L 2,	J + (+?+E+E+GK(+8+IK( $112 	D++,
 *,d445q8 ../   N2d445 ../ !! d223Q6 ,,- r:   c                 X   t        j                  |d      }t        j                  |j                  |j                        }|| j
                     || j
                  <   | j                  dkD  r/| j                  r"| j                  dk(  r#t        j                  || j                           }n| j                  dk(  rtt        j                  | j                  d   j                  |j                        }|| j                     || j                  <   t        j                  ||j                        }|| j                     j!                  | j"                  | j"                  | j                  z        }t%        |      \  }}|j'                         || j                  <   n|| j                     || j                  <   | j(                  dkD  r| j*                  rt        j,                  | j"                  |j                        }|| j.                     j!                  | j"                  | j"                  | j(                  z        }t%        ||      \  }}|j'                         || j.                  <   n|| j.                     || j.                  <   || j0                     || j0                  <   | j                  dk(  r || j                     dz  || j                  <   n+| j                  dk(  r|| j                     || j                  <   | j2                  r|| j4                     dz  || j4                  <   |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      ?)r2   r   r[   rN   r}   rc   rA   r>   r<   r   rg   rR   ra   r   r   rd   r   rT   r   r   rB   r?   r   re   rf   r=   rh   )r7   r   r   r'   r   r   unconstrained_matricesr   s           r8   untransform_paramszVARMAX.untransform_paramsR  s     hh{!4!2!2+:K:KL -88J8J,Kd(() 99q=T66""j0GGK0F0F$GH	$$6"$((488K+@+F+F1<1B1B#D   6 67   9 9:FF?O4E4EF	 't7??dllTYY68L 4L)L -"H-C-I-I-KM$//*-8-IM$//* 99q=T77t||;3D3DEI&t7??dllTYY68L 4L)L -"H-C-I-I-KM$//*-8-IM$//* //0 	d--.
 *,D223S8 $001   N2D223 $001 !! D00136 $../ r:   c                    t         |   |       t        j                  t	        | j
                  j                                     d d }d t        j                  | j                  |      D        \  }}}}}}| j                  rj| j                  dkD  r[| j                  dkD  s| j                  dkD  r=|j                  |      }t        |j                  |            dkD  }|r|st        d      | j                   rk| j"                  dkD  r[| j                  s| j"                  dkD  r?|j                  |      }t        |j                  |            dkD  }|r|st        d      y y y y y )Nr*   c              3   <   K   | ]  }|j                           y wr0   )tolist).0arrs     r8   	<genexpr>z2VARMAX._validate_can_fix_params.<locals>.<genexpr>  s      ,J CJJL,Js   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.)rP   _validate_can_fix_paramsr2   cumsumrk   r1   rV   array_splitr   r>   rA   rT   
issupersetlenintersectionrC   r?   rB   )	r7   r   ix_ar_namesma_namesfix_allfix_anyrr   s	           r8   r   zVARMAX._validate_can_fix_params  sS   (5YYtDOO22456s;,J$&NN43C3CR$H,J(Hh1a $$Q||a499q=%00:00:;a? 7$!" "
 %%$))a-||tyy1}%00:00:;a? 7$!" " $+7	  - +8%r:   c                    | j                  |||      }| j                  r|| j                     j                  | j                  | j
                        j                  }t        j                  | j                  dd  |      }|j                  | j                  | j                  <   | j                  <t        j                  | j                  |      | j                  dd | j                  df<   | j                  dkD  rR| j                  s4t        j                  d|j                        }|| j                  dd d f<   || j                      j                  | j                  | j                        j                  }| j"                  r|}n#t        j                  | j$                  dd  |      }| j                  | j                  xx   |j                  z  cc<   | j&                  l| j                  d   j(                  dk(  rP| j                  dd | j                  dd fxx   t        j                  | j&                  |      j                  z  cc<   | j                  rY| j                  Mt        j                  t        j*                  |j                        }	|	| j                  dd | j                  df<   || j,                     j                  | j                  | j                  | j.                  z        }
|| j0                     j                  | j                  | j                  | j2                  z        }t        j4                  |
|f   | j                  | j6                  <   | j8                  dk(  r'|| j:                     | j                  | j<                  <   n| j8                  dk(  rt        j>                  | j                  d	   j@                  |j                        }|| j:                     || jB                  <   t        j                  ||j                        | j                  d	<   | jD                  r'|| jF                     | j                  | jH                  <   y y )
N)transformedincludes_fixedr	   r+   r*   r   r|   r   r   r'   )%handle_paramsrJ   rf   r   rT   rI   r   r2   r   r   rR   r]   ri   rF   r   r}   rc   rH   rY   rZ   stopnanrd   rA   re   rB   r   r^   r<   rg   r_   r[   rN   ra   r=   rh   rb   )r7   r   r   r   complex_stepr   	interceptzeror   r   r$   r%   r   s                r8   updatezVARMAX.update  s   ##F3A $ C
  !8!89AAdkk++,1 tyy}k:I2;++DHHT../+AC$$kB3*MT\\M2=> <<! &&xx615*A-.!$"4"45==dll,,-A ##(	FF4#3#3AB#7F	HHT../9;;>/!!-11"5::b@*MT\\M23>?266%%|D556Q7?
 4#3#3#;((2666C=@DHH&r9: DOO$,,LL$,,24DOO$,,LL$,,24)+r2v%%& *,t--. HHT(()   N2 hhtxx'<'B'B-3\\;O t--. D556$&FF?O<M<M$NDHH[! !!*01E1E*FDHHT&&' "r:   c           	   #     K   | j                   }| j                  dkD  rW|Nt        j                  |      }|j                  dk(  r|dd }	 t        j
                  |dd | j                  f      }|| _         	 d || _         y# t        $ r: t        dt        | j                  f      dt        |j                        d      w xY w# || _         w xY w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   )	ri   rI   r2   
atleast_1dndimr   rC   strrN   )r7   r   cache_values      r8   _set_final_exogzVARMAX._set_final_exog   s     , &&;;?}}T*99>8D:::d2Ah?D  $D	+*D " :$(+T[[N(;(+DJJ&9 : ::  +Ds7   AC
$B .C6C :CACC	CCc                     | j                  |      5  t        |   ||f|||||||	|
||d
|}d d d        |S # 1 sw Y   S xY w)N)
measurement_shocksstate_shocksinitial_stateanchorrepetitionsr   extend_modelextend_kwargsr   r   )r   rP   simulate)r7   r   nsimulationsr   r   r   r   r   r   r   r   r   r   rn   outrr   s                  r8   r   zVARMAX.simulate)  sm     !!$' 	'"9K);T)' C	 
	 
s	   :A)N)r	   r   cr   FTTr	   r0   )TFF)
NNNNNNNNTF)__name__
__module____qualname____doc__rQ   ru   propertyrz   r   r   r   r   r   r   
contextlibcontextmanagerr   r   r   r   __classcell__rr   s   @r8   r   r      s    bH >ABGBFqKfF > > ~ ~@ = =~QfKZ"< ?D!AGF &+ &+P h''(@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 )rx   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
    c                 $   t        |   |||||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kD  rt%        j&                  | j(                  | j                  j*                           }| j                  j,                  }| j                  j                  }	|j/                  ||	z  |      j0                  j/                  |||	      j0                  | _        | j                  j                  dkD  rt%        j&                  | j(                  | j                  j2                           }
| j                  j,                  }| j                  j                  }|
j/                  ||z  |      j0                  j/                  |||      j0                  | _        y y )N)r<   r=   r>   r?   rD   r;   rA   rB   r"   rF   rI   r    )rP   rQ   r   modelr<   r=   r>   r?   rD   r;   rA   rB   r"   rF   rI   specificationcoefficient_matrices_varcoefficient_matrices_vmar2   r   r   rd   rT   r   r   re   )r7   r   r   filter_resultscov_typecov_kwdsrn   r   rT   rA   r   rB   rr   s               r8   rQ   zVARMAXResults.__init__S  s   6>8X	
AG	
 # "jj77!%!=!=$(JJ$C$C%)ZZ%E%E JJ33ZZ%% JJOOJJOO ZZ%%zz))jj''#&
 * )-%(,%::??QTZZ-B-B!CDIjj((G::??D!!'D.':<<ggw-aa ) ::??QTZZ-B-B!CDIjj((G::??D!!'D.':<<ggw-aa )	 r:   c                 n   |V| j                  | j                  | j                  |d d       }|j                  }|j                  d   }|j                  d   }n| j                  d   }| j                  d   }|j                  d| j                  | j                  j                  z           | j                  j                  |fd|i|}t        |j                  d||      |j                  _        | j                  |j                  | j                        }	|	S |j!                  | j                        }	|	S )	Nr	   )r   ).r   ).r*   rD   r   knownconstantstationary_cov)get_predictionrX   prediction_resultspredicted_statepredicted_state_covrO   r   rD   ru   r   r    rR   r   smoother_resultssmoothr   filter)
r7   rm   r   rn   fcastfcast_resultsr   initial_state_covmodress
             r8   extendzVARMAXResults.extend  s    ''		49948'LE!44M)99&AM - A A& I 009M $ 8 8 A.$))djj6M6M*MNdjju:4:6:!/LL'M,".   ,**T[[)C 
 **T[[)C
r:   c              #     K   | j                   }|j                  |      5  | j                  j                  dddf   }|j	                  | j
                         |dd|j                  df   | j                  j                  d|j                  df<   	 d || j                  j                  dddf<   	 ddd       y# || j                  j                  dddf<   w xY w# 1 sw Y   yxY ww)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   rT   )r7   r   r  r   s       r8   r   zVARMAXResults._set_final_exog  s     ( jj  & 	I--==aeDKJJt{{#%||R78 //b0@AI=H##33ArE:	I 	I >I##33ArE:	I 	Is5   C,A2C B>C 5	C,>CC  C)%C,c              #     K   |xr | j                   j                  dkD  }|r{t        | j                   j                  dd t	        j
                  d| j                   j                  f      g      }| j                   j                  dkD  r(t        | j                   j                  dd |dd g      }nd}| j                   j                  | j                  z   dz
  }| j                   j                  |||      }| j                  j                  dddf   }| j                  j                  dddddf   }	|j                  j                  ||	       |j!                  | j"                  ddd	      }
|
j                  dddf   | j                  j                  dddf<   	 d |r,t        j$                  | j                  j                  dddf<   yy# |r,t        j$                  | j                  j                  dddf<   w w xY w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   rD   r  T)r   r   
return_ssm)r   rI   r   rm   r2   r[   rT   r   rD   rX   ru   r   r
  r  rR   initialize_knownr  r   r   )r7   r   out_of_sampleflag	tmp_endogtmp_exogtmp_trend_offsettmp_modr  r  tmp_ress              r8   _set_final_predicted_statez(VARMAXResults._set_final_predicted_state  s    ( 6!2!2Q!6

  %rxxDJJ4F4F0G'H J KIzz  1$!4::??23#7bq"BC#zz66BQFjj&&yx4D ' FG**::1b5AH!00DDQ2XNNKK(((8F ) HnnT[[d48T % KG
 ''2. //26	D=?VV##33ArE: t=?VV##33ArE: s   FHG #/H0HHc                    |d}| j                   j                  |||d      \  }}	}
}| j                   j                  ||
      }i }| j                   j                  dkD  r&| j                   j                  | j
                  z   |d<   | j                  |      5  | j                  ||
      5  t        | $  d|||||||d|}d d d        d d d        S # 1 sw Y   xY w# 1 sw Y   S xY w)Nr   T)silentrD   )startenddynamicinformation_setindexr   r   r   )
r   _get_prediction_index_validate_out_of_sample_exogrF   rD   rX   r   r!  rP   r  )r7   r$  r%  r&  r'  r(  r   rn   _start_endr  r   r   r   rr   s                 r8   r  zVARMAXResults.get_prediction  s    =E JJ,,UCt,L 	'mQ zz66t]K ::!

''$))3 .) !!$' 	;00}E ;g, ;S'$35t"/; 4:;;	; 
; ;	; 
s$   C!+CC!C	C!!C+c
                    ||dk(  rd}n1|dk(  r| j                   }n| j                  j                  |      \  }}}|dk  r| j                   |z   }|| j                   kD  rt        d      t	        ||z   | j                   z
  d      }| j                  j                  ||      }| j                  ||      5  t        |    |f||||||||	d|
}d d d        |S # 1 sw Y   S xY w)Nr$  r   r%  z4Cannot anchor simulation after the estimated sample.)r   r   r   r   r   r   r   r   )	rX   r   _get_index_locrC   rL   r*  r!  rP   r   )r7   r   r   r   r   r   r   r   r   r   rn   ilocr   r  r   rr   s                  r8   r   zVARMAXResults.simulate  s
   
 >Vw.Du_99D226:JD!Q!899t#D$)) ( ) ) D</$));Q? zz66t]K,,T=A 	'"1C);T)	
 C	 
	 
s   5CC#c                    d }| j                   |j                   z
  }| j                  j                  dkD  r|dkD  r| j                  j                  | d  }t	        j
                         5 }	|	j                  |j                  j                  |             |	j                  |j                  ||             | j                  j                  |j                  ||||      }
d d d        |
S # 1 sw Y   
S xY w)Nr   )r$  r%  revisions_details_startstate_index)rX   r   rI   r   r   	ExitStackenter_contextr   r!  r  news)r7   previousr$  r%  periodsr1  r2  r   r  stackr   s              r8   _news_previous_resultsz$VARMAXResults._news_previous_results(  s     		HMM1::q ]Q%6::??M>?3D !!# 	)u > >t DE C Cm!% & '',,))C(?' - )C	) 
	) 
s   (A6C((C2c           	      	   ddl m | j                  }|j                  dkD  r/|j                  dkD  r d}d|j                   d|j                   d}n2|j                  dkD  rd}d|j                  z  }nd	}d|j                  z  }|j
                  dkD  r|d
z  }||z   g}|j                  dkD  r|j                  d       |j                  r|j                  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kD  r4|j                  t        j                  |||
|z  z   |
             ||
|z  z  }|dkD  rF||
z  |z  }|dz   |
z  |z  }|j                  |t        j                  ||      z          |||
dz  z  z  }|dkD  rF||
z  |z  }|dz   |
z  |z  }|j                  |t        j                  ||      z          |||
dz  z  z  }|dkD  r9|j                  |t        j                  ||z  |dz   |z        z          ||
|z  z  }| j                  j                  r@|j                  t        j$                  | j                  j&                  |z
  dz
  d             t        j(                  |      }|j                  |       | j                  j*                  }t-        |t.              s|g}d||   z  } |	| ||      }|j0                  j                  |        t        j                  t        | j                              | j                  j2                     } |	| |dd      }|j0                  j                  |       g }||gfD ]E  }t        j$                  |      j5                         }t        |      dkD  s5|j                  |       G t        j(                  |      }t        j$                  t/        t7        |      j9                  t7        |                        }t        |      dkD  r' |	| |dd      }|j0                  j                  |       |S )Nr   )summary_paramsVARMA(,)r   z(%s)VMAXr   zmeasurement error)alphar$  
model_namedisplay_paramsc                    | | j                   |   | j                  |   | j                  |   | j                  |   | j	                        |   f}g }t        j                  | j                  j                        |   j                         D ]N  }|r$dj                  |j                  d      d d       }n|}|| j                  v rd|z  }|j                  |       P  	|d |d|      S )Nr   r*   z
%s (fixed)F)ynamexnamerB  use_ttitle)r   bsezvaluespvaluesconf_intr2   r   datar   r   joinsplitfixed_paramsappend)
r7   r   rI  	strip_endr  r   name
param_namerB  r;  s
           r8   
make_tablez)VARMAXResults.summary.<locals>.make_tablef  s    T[[.||D)4<<+=}}U+D13 !HHTYY%:%:;DAHHJ 3D %(XXdjjocr.B%C
%)
t000%1J%>
&&z23 &c[,1eM Mr:   r	   r#   r   zResults for equation %szError covariance matrixF)rS  zOther parameters)T)statsmodels.iolib.summaryr;  r   rA   rB   rI   rF   rR  r=   rP   summaryr2   aranger   r   r   rT   r   r   rW   concatenater   r   rk   tablesrg   flattenset
difference)r7   rB  r$  separate_paramsspecrC  r;   rX  indicesrV  rT   rA   rB   rF   rI   endog_masksr   masksr)   r%  r   r   rI  tablestate_cov_maskminverse_maskr;  rr   s    `                         @r8   rX  zVARMAXResults.summaryE  sh   < !!99q=TYY] J		{!DII;a0EYY]Jdii(EJdii(E;;?#J 5()
<<!k*!!12'/u.. " 

 iiDKK 01GM& jj((G::??D::??Djj((GZZ&&FK7^ -- Q;LL1a'G2C.CW!MNg//F !8K$.Eq5G+d2CLL5#!668dWaZ//F !8K$.Eq5G+d2CLL5#!668dWaZ//F A:LL1v:A7G!HHJg..F :://LL!4!4q!81!<AFH ~~e,""4("jj44!+t4#.-K1KNB"4u5%%e,[--b 		#dkk*+DJJ,H,HI t^5N).0ENN!!%( E!N#34 $HHQK'')q6A:LLO$ NN5)E88DW)@)@U)L$MNL< 1$"47I-24%%e,r:   )NNr0   )NNF	predictedNN)NNNNNNNN)FN)g?NT)r   r   r   r   rQ   r  r   r   r   r!  r   r   r  r   r9  rX  r   r   s   @r8   rx   rx   :  s    0 @D*0X6 I I< .D .D` j''//0;@EI 18 j!!))*8<?C;?# +B 8=+/: j  (()| *|r:   rx   c                       e Zd Zi Z ej
                  ej                  e      Zi Z ej
                  ej                  e      Z	y)ry   N)
r   r   r   _attrswrapunion_dictsr   _wrap_attrs_methods_wrap_methodsr   r:   r8   ry   ry     sH    F"$""#4#@#@#)+KH$D$$%6%D%D%-/Mr:   ry   )+r   r   warningsr   pandasr   numpyr2   statsmodels.compat.pandasr   statsmodels.tools.toolsr   statsmodels.tools.datar   statsmodels.tsa.vector_arr   statsmodels.base.wrapperbasewrapperrk  statsmodels.tools.sm_exceptionsr   kalman_filterr
   r   mlemodelr   r   r   r   r   toolsr   r   r   r   r   r   r   r   rx   ry   populate_wrapperr   r:   r8   <module>r     s        . ) 3 / ' ' = 6 = = *  XX XvHJ HV/, /   *M :r:   