
    !g,                   >   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	Z
ddl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 dd
lmZ ddlmZ ddlmZm Z  ddl!m"c m#Z" ddl!m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 d,dZ3d-dZ4d.dZ5d Z6d Z7e7Z8d.dZ9d Z:	 d/dZ;d Z<d Z=d0dZ>d1dZ? G d d      Z@ G d  d!e      ZA G d" d#      ZB G d$ d%eB      ZC G d& d'ej                        ZE ej                  eEeC        G d( d)      ZGd2d*ZHd+ ZIy)3u   
Vector Autoregression (VAR) processes

References
----------
Lütkepohl (2005) New Introduction to Multiple Time Series Analysis
    )annotations)lrange)defaultdict)StringION)SimpleTable)cache_readonlydeprecated_alias)logdet_symm)OutputWarning)
array_like)TimeSeriesModelTimeSeriesResultsWrapper)duplication_matrixunvecvec)outputplottingutil)CausalityTestResultsNormalityTestResultsWhitenessTestResults)
IRAnalysis
VARSummaryc                D   | j                   \  }}}t        j                  |dz   ||f      }t        j                  |      |d<   t	        d|dz         D ]J  }t	        d|dz         D ]6  }||kD  r ||xx   t        j
                  |||z
     | |dz
           z  cc<   8 L |S )a   
    MA(\infty) representation of VAR(p) process

    Parameters
    ----------
    coefs : ndarray (p x k x k)
    maxn : int
        Number of MA matrices to compute

    Notes
    -----
    VAR(p) process as

    .. math:: y_t = A_1 y_{t-1} + \ldots + A_p y_{t-p} + u_t

    can be equivalently represented as

    .. math:: y_t = \mu + \sum_{i=0}^\infty \Phi_i u_{t-i}

    e.g. can recursively compute the \Phi_i matrices with \Phi_0 = I_k

    Returns
    -------
    phis : ndarray (maxn + 1 x k x k)
       r   )shapenpzeroseyerangedot)coefsmaxnpkphisijs          `/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/vector_ar/var_model.pyma_repr+   ,   s    4 kkGAq!88TAXq!$%DffQiDG 1dQh 9q!a% 	9A1uGrvvd1q5k5Q<88G		99 K    c                   t        j                  |       }t        j                  j	                  |      }|r0t        d       t        j                  |      D ]  }t        |        t        j                  |      dk  j                         S )z
    Determine stability of VAR(p) system by examining the eigenvalues of the
    VAR(1) representation

    Parameters
    ----------
    coefs : ndarray (p x k x k)

    Returns
    -------
    is_stable : bool
    zEigenvalues of VAR(1) repr   )r   comp_matrixr   linalgeigvalsprintabsall)r#   verboseA_var1eigsvals        r*   	is_stabler8   U   sp     e$F99V$D)*66$< 	C#J	 FF4LA""$$r,   c                $   | j                   \  }}}||}t        j                  |dz   ||f      }t        | |      |d| t	        ||dz         D ]?  }t	        |      D ]/  }||xx   t        j
                  | |   |||z
  dz
           z  cc<   1 A |S )u  
    Compute autocovariance function ACF_y(h) up to nlags of stable VAR(p)
    process

    Parameters
    ----------
    coefs : ndarray (p x k x k)
        Coefficient matrices A_i
    sig_u : ndarray (k x k)
        Covariance of white noise process u_t
    nlags : int, optional
        Defaults to order p of system

    Notes
    -----
    Ref: Lütkepohl p.28-29

    Returns
    -------
    acf : ndarray, (p, k, k)
    Nr   )r   r   r   _var_acfr!   r"   )	r#   sig_unlagsr%   r&   _resulthr)   s	            r*   var_acfr@   m   s    , kkGAq!} XXuqy!Q'(F%'F2AJ 1eai  = q 	=A1Ia&Q*;<<I	=	= Mr,   c           	        | j                   \  }}}||k(  sJ t        j                  |       }t        j                  ||z  ||z  f      }||d|d|f<   t        j
                  j                  t        j                  ||z  dz        t        j                  ||      z
  t        |            }t        |      }t        |      D 	cg c]  }	|d|||	z  ||	dz   z  f    }}	t        j                  |      }|S c c}	w )up   
    Compute autocovariance function ACF_y(h) for h=1,...,p

    Notes
    -----
    Lütkepohl (2005) p.29
    N   r   )r   r   r.   r   r   r/   solver    kronr   r   r!   array)
r#   r;   r%   r&   k2ASigUvecACFacfr(   s
             r*   r:   r:      s     {{HAq"7N7A88QUAEN#DD!RaRL YY__RVVQUqL1BGGAqMA3t9MF
-C16q
:A3rr1q51A;&&'
:C
:
((3-CJ ;s   C:c                    t        |      }t        j                  |||f      }t        j                  ||f      }t        |      D ]#  }| |   }||z  |j                  z  }||z   x||<   }% |S )a-  
    Compute theoretical forecast error variance matrices

    Parameters
    ----------
    steps : int
        Number of steps ahead

    Notes
    -----
    .. math:: \mathrm{MSE}(h) = \sum_{i=0}^{h-1} \Phi \Sigma_u \Phi^T

    Returns
    -------
    forc_covs : ndarray (steps x neqs x neqs)
    )lenr   r   r!   T)	ma_coefssigma_ustepsneqs	forc_covspriorr?   phivars	            r*   forecast_covrV      s|    " w<D%t,-IHHdD\"E5\ +qkGmcee#$s{*	!u	+ r,   c                   t        |      }t        |d         }| j                  d   |k  rt        d| d| j                  d    d      t        j                  ||f      }|||t        j
                  ||      z  }n	||||z  }t        d|dz         D ]d  }||dz
     }	t        d|dz         D ]@  }
||
z
  dk  r| ||
z
  dz
     }n|||
z
  dz
     }|	t        j
                  ||
dz
     |      z   }	B |	||dz
  <   f |S )um  
    Produce linear minimum MSE forecast

    Parameters
    ----------
    y : ndarray (k_ar x neqs)
    coefs : ndarray (k_ar x neqs x neqs)
    trend_coefs : ndarray (1 x neqs) or (neqs)
    steps : int
    exog : ndarray (trend_coefs.shape[1] x neqs)

    Returns
    -------
    forecasts : ndarray (steps x neqs)

    Notes
    -----
    Lütkepohl p. 37
    r   zy must by have at least order (z) observations. Got .r   )rL   r   
ValueErrorr   r   r"   r!   )yr#   trend_coefsrP   exogr%   r&   forcsr?   fr(   prior_ys               r*   forecastr`      sE   ( 	E
AE!HAwwqzA~-aS 1771:,a!
 	

 HHeQZ EK3k**	+1 1eai  !a%Lq!a% 
	2A1uzAEAI,  A	* BFF5Q<11A
	2 a!e" Lr,   c                p    t        |||       }t        |      }t        j                  |      }|dd||f   S )a  _forecast_vars function used by VECMResults. Note that the definition
    of the local variable covs is the same as in VARProcess and as such it
    differs from the one in VARResults!

    Parameters
    ----------
    steps
    ma_coefs
    sig_u

    Returns
    -------
    N)mserL   r   arange)rP   rN   r;   covsrQ   indss         r*   _forecast_varsrf     s9     x&Du:D99T?D4r,   c                    d|cxk  rdk  sJ  J t        j                  |      }t        | ||||      }t        ||      }	t	        j
                  t        ||	|            }
|||
z  z
  }|||
z  z   }|||fS Nr   r   )r   norm_signif_levelr`   r+   r   sqrtrf   )rZ   r#   r[   r;   rP   alphar\   qpoint_forecastrN   sigma
forc_lower
forc_uppers                r*   forecast_intervalrq   !  s     u=q===u%AaUDANeU#HGGN5(E:;E!e)+J!e)+J:z11r,   c                    t        t        j                  |            }t        |      }||z  dz   t        j                  dt        j
                  z        z  }|dz   ||z   z  }||z   S )a  
    Returns the value of the VAR(p) log-likelihood.

    Parameters
    ----------
    resid : ndarray (T x K)
    omega : ndarray
        Sigma hat matrix.  Each element i,j is the average product of the
        OLS residual for variable i and the OLS residual for variable j or
        np.dot(resid.T,resid)/nobs.  There should be no correction for the
        degrees of freedom.
    nobs : int

    Returns
    -------
    llf : float
        The value of the loglikelihood function for a VAR(p) model

    Notes
    -----
    The loglikelihood function for the VAR(p) is

    .. math::

        -\left(\frac{T}{2}\right)
        \left(\ln\left|\Omega\right|-K\ln\left(2\pi\right)-K\right)
    rB   )r
   r   asarrayrL   logpi)residomeganobslogdetrQ   part1part2s          r*   var_logliker|   1  sd    8 E*+Fu:DTkAoBEE	!22EQhK6D=)E5=r,   c                D   | j                   }| j                  }| j                  }| j                  }| j                  }| j
                  }t        j                  |      }t        j                  |      }	t        j                  |      }
t        j                  |      }t        j                  |      }t        j                  |      }t        | j                  d         }g }| j                  }t        |      D ]  \  }}| j                   d d |f   |d d |f<   |dkD  r|d|f   |
d|f<   |d d df   |	d d df<   t        |      D ]P  }| j                  |||z  z   |z   d d f   |
|||z  z   |z   d d f<   |d d |||z  z   |z   f   |	d d |||z  z   |z   f<   R ||d d f   ||d d f<   |j                  ||           t        |      D ]%  \  }}|
d d |f   |d d |f<   |d d |f   |d d |f<   ' t        ||	||| j
                  | j                  d|| j                  	      S )Nr   c)	endogendog_laggedparamsrO   	lag_ordermodeltrendnamesdates)r   r   r   rO   r   k_arr   
zeros_likerL   k_trend	enumerater!   append
VARResultsr   r   )selforderr   r   r   rO   r   r   	endog_newendog_lagged_newparams_new_inc
params_newsigma_u_new_incsigma_u_newnum_end	names_newr&   r(   r~   r)   s                       r*   
_reorderedr   T  sG   JJE$$L[[FllGJJE99De$I}}\2]]6*Nv&JmmG,O--(K$++a.!GI 	A%  #1**QT*	!Q$q5#)!Q$<N1a4 %1!Q$%7QT"t 	A59[[AK!#Q&6N1q7{?Q.12 8D1q7{?Q&&8QAK! 334		 !(11q"# %  21)!Q$/
1a4+AqD1AqD2 %))jjjj
 
r,   c           	         || j                   }| j                  |      }t        j                  |D cg c]  }t        j                  ||       c}      S c c}w )a  Compute Orthogonalized MA coefficient matrices using P matrix such
    that :math:`\Sigma_u = PP^\prime`. P defaults to the Cholesky
    decomposition of :math:`\Sigma_u`

    Parameters
    ----------
    results : VARResults or VECMResults
    maxn : int
        Number of coefficient matrices to compute
    P : ndarray (neqs x neqs), optional
        Matrix such that Sigma_u = PP', defaults to the Cholesky decomposition.

    Returns
    -------
    coefs : ndarray (maxn x neqs x neqs)
    r$   )_chol_sigma_ur+   r   rE   r"   )resultsr$   Pma_matsr#   s        r*   orth_ma_repr     sL    " 	y!!nn$n'G887;%RVVE1%;<<;s   Ac                   | j                   | j                   j                  d      z
  }t        j                  |j                  |      | j
                  z  }t        j                  j                  t        j                  j                  |            }t        j                  ||j                        }|dz  j                  d      dddf   | j
                  z  }|dz  j                  d      dddf   | j
                  z  dz
  }| j
                  t        j                  |j                  |      z  dz  }| j
                  t        j                  |j                  |      z  dz  }	t        t        j                  ||	z               }
t        j                  | j                  dz        }t        |j                  |
            }t        |j!                  d|z
              }t#        |
||| j                  dz  |      S )	u  
    Test assumption of normal-distributed errors using Jarque-Bera-style
    omnibus Chi^2 test

    Parameters
    ----------
    results : VARResults or statsmodels.tsa.vecm.vecm.VECMResults
    signif : float
        The test's significance level.

    Notes
    -----
    H0 (null) : data are generated by a Gaussian-distributed process

    Returns
    -------
    result : NormalityTestResults

    References
    ----------
    .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series*
       *Analysis*. Springer.

    .. [2] Kilian, L. & Demiroglu, U. (2000). "Residual-Based Tests for
       Normality in Autoregressions: Asymptotic Theory and Simulation
       Evidence." Journal of Business & Economic Statistics
    r      r   N         rB   )rv   meanr   r"   rM   rx   r/   invcholeskysumfloatsqueezestatschi2rQ   sfppfr   )r   signifresid_csigPinvwb1b2lam_skewlam_kurtlam_omni	omni_distomni_pvalue	crit_omnis                 r*   test_normalityr     s|   8 mmgmm0033G
&&G
$w||
3C99==++C01D
tWYYA
q&aD	!GLL	0B
q&aD	!GLL	01	4B||bffRTT2..2H||bffRTT2..3HRZZ8 345H

7<<!+,I	X./KimmAJ/0I)[',,*:F r,   c                  $    e Zd ZdZddZd Zd Zy)LagOrderResultsa  
    Results class for choosing a model's lag order.

    Parameters
    ----------
    ics : dict
        The keys are the strings ``"aic"``, ``"bic"``, ``"hqic"``, and
        ``"fpe"``. A corresponding value is a list of information criteria for
        various numbers of lags.
    selected_orders : dict
        The keys are the strings ``"aic"``, ``"bic"``, ``"hqic"``, and
        ``"fpe"``. The corresponding value is an integer specifying the number
        of lags chosen according to a given criterion (key).
    vecm : bool, default: `False`
        `True` indicates that the model is a VECM. In case of a VAR model
        this argument must be `False`.

    Notes
    -----
    In case of a VECM the shown lags are lagged differences.
    c                    |rdnddz   | _         | xj                   dz  c_         || _        || _        || _        |d   | _        |d   | _        |d   | _        |d   | _        y )	NVECMVARz Order Selectionz (* highlights the minimums)aicbichqicfpe)titleicsselected_ordersvecmr   r   r   r   )r   r   r   r   s       r*   __init__zLagOrderResults.__init__  sh     $f%3EE


44
.	"5)"5)#F+	"5)r,   c                   t        | j                        }t        j                  |D cg c]"  }| j                  |   D cg c]  }d|z  	 c}$ c}}t              j
                  }t        |      D ],  \  }}t        | j                  |         |f}||xx   dz  cc<   . t        ||D cg c]  }|j                          c}t        t        |            | j                        S c c}w c c}}w c c}w )Nz%#10.4gdtype*)r   )sortedr   r   rE   objectrM   r   intr   r   upperr   rL   r   )r   colsr~   vstr_datar(   colidxs           r*   summaryzLagOrderResults.summary  s    dhh88;?@aTXXa[1i!m1@

! 	  o 	!FAsd**3/0!3CSMS M	! $()SSYY[)3x=!**	
 	
 2@ *s   C/
 C*C/
-C5
*C/
c                    d| j                    d| j                  j                   dt        | j                         dt        | j
                         dt        | j                         dt        | j                         dS )N<rX   z% object. Selected orders are: AIC -> z	, BIC -> z	, FPE -> z, HQIC ->  >)
__module__	__class____name__strr   r   r   r   r   s    r*   __str__zLagOrderResults.__str__  sn     $.."9"9!: ;""%dhh-	#dhh- I$((m_KDII/?qB	
r,   NF)r   r   __qualname____doc__r   r   r    r,   r*   r   r     s    ,	*
 
r,   r   c                  ~     e Zd ZdZ eddd      Z	 d fd	ZddZ	 	 	 	 	 d	 ddZdd	Z	dd
Z
e	 dd       Z xZS )r   u  
    Fit VAR(p) process and do lag order selection

    .. math:: y_t = A_1 y_{t-1} + \ldots + A_p y_{t-p} + u_t

    Parameters
    ----------
    endog : array_like
        2-d endogenous response variable. The independent variable.
    exog : array_like
        2-d exogenous variable.
    dates : array_like
        must match number of rows of endog

    References
    ----------
    Lütkepohl (2005) New Introduction to Multiple Time Series Analysis
    rZ   r   z0.11.0)remove_versionc                    t         |   |||||       | j                  j                  dk(  rt	        d      | j                  j
                  d   | _        t        |      | _        y )N)missingr   zOnly gave one variable to VAR)	superr   r   ndimrY   r   rQ   rL   n_totobs)r   r   r\   r   freqr   r   s         r*   r   zVAR.__init__#  sZ     	eT7C::??a<==JJ$$Q'	E
r,   c                   t        j                  |      }||}| j                  ||      \  }}}}||k  rt        d      |||z   k(  rt        j                  g       S t	        j
                  |      }| j                  }	|}
t        j                  |dz   |z
  |z   |	f      }|dk7  r
|d| }||z  }| j                  }t	        j                  |||d      }t        j                  ||      }||
z
  }t        t        |      t        |      |z
        }t        t        |      ||
z
  dz         }||| |d| |s|S ||
 d }||d j                  |
|	|	f      j                  dd      }t        |||      ||d |S )z<
        Returns in-sample predictions or forecasts
        Nzend is before startr   r   raiser   has_constantrB   )r   rE   _get_prediction_indexrY   r   get_trendorderrQ   r   r   get_var_endogr"   minrL   reshapeswapaxesr`   )r   r   startendlagsr   out_of_sampleprediction_indexr   r&   r   predictedvalues	interceptrZ   xfittedvaluesfv_startpv_endfv_endr#   s                       r*   predictzVAR.predict,  s    &!=E &&uc2	
 ;233%-''88B<%%e,II((C!GeOm$CQ#GHa<x(Iy(OJJq$e'Jvva(4<S)3|+<x+GHS&d
Q7#/#@ "" tefIwx (($16??1E#+Aui#O r,   c                   |}|dvrt        d| d      |a| j                  |      }t        ||      st        |dt        |            t	        ||      }|r t        |       t        d||fz         n|d}t        j                  |      }| j                  }	t        j                  | j                  ||      | _        | j                  |z
  | _        | j                  ||	r|	}
n2t        | j                  j                  d         D cg c]  }d	|z  	 }
}| j                   j"                  d| |
z   | j                   j"                  |d z   | j                   _        t$        j&                  j)                  | j                   j"                  | j                   j*                  f      | j                   _        | j/                  ||
      S c c}w )ug  
        Fit the VAR model

        Parameters
        ----------
        maxlags : {int, None}, default None
            Maximum number of lags to check for order selection, defaults to
            12 * (nobs/100.)**(1./4), see select_order function
        method : {'ols'}
            Estimation method to use
        ic : {'aic', 'fpe', 'hqic', 'bic', None}
            Information criterion to use for VAR order selection.
            aic : Akaike
            fpe : Final prediction error
            hqic : Hannan-Quinn
            bic : Bayesian a.k.a. Schwarz
        verbose : bool, default False
            Print order selection output to the screen
        trend : str {"c", "ct", "ctt", "n"}
            "c" - add constant
            "ct" - constant and trend
            "ctt" - constant, linear and quadratic trend
            "n" - co constant, no trend
            Note that these are prepended to the columns of the dataset.

        Returns
        -------
        VARResults
            Estimation results

        Notes
        -----
        See Lütkepohl pp. 146-153 for implementation details.
        )r~   ctcttnztrend 'z' not supported for VARN)maxlagsz not recognized, must be among zUsing %d based on %s criterionr   zexog%d)r   )rY   select_orderhasattrr   getattrr1   r   r   
exog_namesmake_lag_namesendog_namesr   rx   r\   r!   r   dataxnamespd
MultiIndexfrom_productynames	cov_names_estimate_var)r   r  methodicr   r4   r   
selectionsr   orig_exog_namesx_names_to_addr(   s               r*   fitzVAR.fit]  s   ` //wug-DEFF>**7*;J:r* 6*-/  :r*Dj!6$CD|%%e,//--d.>.>gNMMD(	 99 !0 -2$))//!2D,E"'(X\" " 		  '* !))""78,- II
 !mm88YYtyy//0
		 !!$e!44"s   Gc                   t        j                  |      x| _        }|dk  rt        d      | j                  |z
  |z
  }| j
                  |d }| j                  dn| j                  |d }t        j                  |||d      }|t        j                  || d ddd      }	|| d }
t        j                  |	|
f      }	~
|}t        j                  |	j                  d   |	j                  d   |j                  d   z   f      }|ddd| j                  f   |ddd| j                  f<   |	|dd| j                  | j                  |	j                  d   z   f<   |dd| j                  df   |dd| j                  |	j                  d   z   df<   ~~	t        | j                        D ]  }t        j                  |dd|f         dk(  j                         r|dd|fxx   |z  cc<   t        j                  t        j                  |dd|f               dk(  j                         st        j                  |dd|f         |z   dz  |dd|f<    ||d }t        j                   j#                  ||d	
      d   }|t        j$                  ||      z
  }t'        |      }|||j                  d   z  }|| j(                  |z  |z   z
  }t        j$                  |j*                  |      }|r||z  }n$t        j,                  |t        j.                        }t1        |||||| j2                  || j4                  j6                  | | j                  
      }t9        |      S )a  
        lags : int
            Lags of the endogenous variable.
        offset : int
            Periods to drop from beginning-- for order selection so it's an
            apples-to-apples comparison
        trend : {str, None}
            As per above
        r   zoffset must be >= 0Nr   r   r  r   rB   gV瞯<)rcond)r   r   r   r   r\   )r   r   r   rY   r   r   r\   r   r   column_stackemptyr   r!   diffr3   rj   r/   lstsqr"   rL   rQ   rM   	full_likenanr   r  r  r   VARResultsWrapper)r   r   offsetr   r   rx   r   r\   zr   x_insttemp_zr(   y_sampler   rv   avobsdf_residsserw   varfits                        r*   r  zVAR._estimate_var  s#    "&!4!4U!;;wA:233}}t#f,

67#yy(tdii.@ud%gN ""dUVasA 4%&\FF,AF!''!*aggaj1771:&=>?A#)!^t||^*;#<Aa4<< =>Aaqwwqz 999:06q$,,.7H0IAa
*,,- t||$ 	9A!Q$ A%**,!Q$4!Q$()Q.335771QT7+d2q8!Q$	9 <HE:1=266!V,, Htzz!}$GDII,w67ffUWWe$(NELLbff-E""))//
 !((r,   c                   |j                  d      rt        |      nd}| j                  | j                  z
  |z
  d| j                  z   z  }|=t	        t        dt        | j                        dz  dz  z              }t        ||      }n||kD  rt        d      t        t              }| j                  |dk7  rdnd}t        ||dz         D ]O  }| j                  |||z
  |	      }|j                  j                         D ]  \  }	}
||	   j!                  |
        Q |j                         D 	
ci c],  \  }	}
|	t#        j$                  |
      j'                         |z   . }}	}
t)        ||d
      S c c}
}	w )a	  
        Compute lag order selections based on each of the available information
        criteria

        Parameters
        ----------
        maxlags : int
            if None, defaults to 12 * (nobs/100.)**(1./4)
        trend : str {"n", "c", "ct", "ctt"}
            * "n" - no deterministic terms
            * "c" - constant term
            * "ct" - constant and linear term
            * "ctt" - constant, linear, and quadratic term

        Returns
        -------
        selections : LagOrderResults
        r~   r   r      g      Y@g      ?zwmaxlags is too large for the number of observations and the number of equations. The largest model cannot be estimated.r  )r&  r   F)r   )
startswithrL   r   rQ   r   roundr   r   rY   r   listr\   r!   r  info_criteriaitemsr   r   rE   argminr   )r   r  r   ntrendmax_estimabler   p_minr%   r>   r&   r   r   s               r*   r	  zVAR.select_order
  su   &  %//4U!2V;TYYO?%c$**o&=7%K KLMG '=1G& !  $YY*eslugk* 	!A '''A+U'KF,,224 !1Aa !	! 9<		
041Arxx{!!#e++
 
 sO%@@	
s   21E4c                    t        d      )zM
        Not implemented. Formulas are not supported for VAR models.
        z*formulas are not supported for VAR models.NotImplementedError)clsformular  subset	drop_colsargskwargss          r*   from_formulazVAR.from_formula@  s     ""NOOr,   )NNNnone)NNr   r~   )NolsNr~   F)r  z
int | None)r   r~   )Nr~   NN)r   r   r   r   r	   rZ   r   r  r  r  r	  classmethodrC  __classcell__r   s   @r*   r   r     sr    & 	gh?A @F#/f #Y5Y5vP)d4Al 37P Pr,   r   c                      e Zd ZdZ	 ddZd Zd ZddZddZddZ	d	 Z
d
 ZddZddZd Zed        Zed        ZddZddZddZddZd ZeZd Zd dZd Zy)!
VARProcessa  
    Class represents a known VAR(p) process

    Parameters
    ----------
    coefs : ndarray (p x k x k)
        coefficients for lags of endog, part or params reshaped
    coefs_exog : ndarray
        parameters for trend and user provided exog
    sigma_u : ndarray (k x k)
        residual covariance
    names : sequence (length k)
    _params_info : dict
        internal dict to provide information about the composition of `params`,
        specifically `k_trend` (trend order) and `k_exog_user` (the number of
        exog variables provided by the user).
        If it is None, then coefs_exog are assumed to be for the intercept and
        trend.
    Nc                z   t        |      | _        |j                  d   | _        || _        || _        || _        || _        |i }|j                  dd      | _	        | j
                  D| j
                  j                  dk7  r| j
                  j                  d   nd}|| j                  z
  }nd}|j                  d|      | _        | j                  | j                  z   | _        | j                  dkD  r&|j                  dk(  r|d d df   | _        y || _        y t        j                  | j                        | _        y )Nr   k_exog_userr   r   rB   )rL   r   r   rQ   r#   
coefs_exogrO   r   getrM  r   r   k_exogr   r   r   )r   r#   rN  rO   r   _params_infok_exk_cs           r*   r   zVARProcess.__init___  s    J	KKN	
$
L'++M1=??&/3/C/Cq/H4??((+aD)))CC#''	37llT%5%55<<!!#!+AqD!1!+XXdii0DNr,   c                B    t        j                  | j                  |      S )z2Return integer position of requested equation name)r   	get_indexr   )r   names     r*   get_eq_indexzVARProcess.get_eq_index~  s    ~~djj$//r,   c                    d| j                   | j                  fz  }|d| j                         z  z  }|d| j                         z  z  }|S )Nz/VAR(%d) process for %d-dimensional response y_tz
stable: %sz	
mean: %s)r   rQ   r8   r   )r   r   s     r*   r   zVARProcess.__str__  sR    BIIIIF
 
 	.4>>#333,,,r,   c                0    t        | j                  |      S )aX  Determine stability based on model coefficients

        Parameters
        ----------
        verbose : bool
            Print eigenvalues of the VAR(1) companion

        Notes
        -----
        Checks if det(I - Az) = 0 for any mod(z) <= 1, so all the eigenvalues of
        the companion matrix must lie outside the unit circle
        )r4   )r8   r#   )r   r4   s     r*   r8   zVARProcess.is_stable  s     W55r,   c           	        d}|| j                   dkD  s| j                  dkD  r\| j                  ddd| j                  f   j	                  | j
                  j                        }| j                  j                  d   }n| j                  }n|j                  d   }||d}n|}n|||k7  rt        d      t        j                  | j                  || j                  ||||      }|S )a(  
        simulate the VAR(p) process for the desired number of steps

        Parameters
        ----------
        steps : None or int
            number of observations to simulate, this includes the initial
            observations to start the autoregressive process.
            If offset is not None, then exog of the model are used if they were
            provided in the model
        offset : None or ndarray (steps, neqs)
            If not None, then offset is added as an observation specific
            intercept to the autoregression. If it is None and either trend
            (including intercept) or exog were used in the VAR model, then
            the linear predictor of those components will be used as offset.
            This should have the same number of rows as steps, and the same
            number of columns as endogenous variables (neqs).
        seed : {None, int}
            If seed is not None, then it will be used with for the random
            variables generated by numpy.random.
        initial_values : array_like, optional
            Initial values for use in the simulation. Shape should be
            (nlags, neqs) or (neqs,). Values should be ordered from less to
            most recent. Note that this values will be returned by the
            simulation as the first values of `endog_simulated` and they
            will count for the total number of steps.
        nsimulations : {None, int}
            Number of simulations to perform. If `nsimulations` is None it will
            perform one simulation and return value will have shape (steps, neqs).

        Returns
        -------
        endog_simulated : nd_array
            Endog of the simulated VAR process. Shape will be (nsimulations, steps, neqs)
            or (steps, neqs) if `nsimulations` is None.
        Nr   r     zKif exog or offset are used, then steps mustbe equal to their length or None)rP   seedinitial_valuesnsimulations)rM  r   r   rP  r"   rN  rM   r   r   rY   r   varsimr#   rO   )r   rP   r&  r\  r]  r^  steps_rZ   s           r*   simulate_varzVARProcess.simulate_var  s    J >!#t||a'7 **1mm+;<@@OO%% **003\\!_F =~!evo 7 
 KKJJLL)%
 r,   c                T    | j                  |||      }t        j                  |      S )zc
        Plot a simulation from the VAR(p) process for the desired number of
        steps
        )rP   r&  r\  )ra  r   plot_mts)r   rP   r&  r\  rZ   s        r*   plotsimzVARProcess.plotsim  s,    
 E&tD  ##r,   c                j    t         j                  j                  | j                  | j                        S )u   
        Long run intercept of stable VAR process

        Lütkepohl eq. 2.1.23

        .. math:: \mu = (I - A_1 - \dots - A_p)^{-1} \alpha

        where \alpha is the intercept (parameter of the constant)
        )r   r/   rC   	_char_matr   r   s    r*   intercept_longrunzVARProcess.intercept_longrun  s!     yyt~~t~~>>r,   c                "    | j                         S )uS  
        Long run intercept of stable VAR process

        Warning: trend and exog except for intercept are ignored for this.
        This might change in future versions.

        Lütkepohl eq. 2.1.23

        .. math:: \mu = (I - A_1 - \dots - A_p)^{-1} \alpha

        where \alpha is the intercept (parameter of the constant)
        )rg  r   s    r*   r   zVARProcess.mean  s     %%''r,   c                0    t        | j                  |      S )z
        Compute MA(:math:`\infty`) coefficient matrices

        Parameters
        ----------
        maxn : int
            Number of coefficient matrices to compute

        Returns
        -------
        coefs : ndarray (maxn x k x k)
        r   )r+   r#   )r   r$   s     r*   r+   zVARProcess.ma_rep
  s     djjt,,r,   c                    t        | ||      S )a  
        Compute orthogonalized MA coefficient matrices using P matrix such
        that :math:`\Sigma_u = PP^\prime`. P defaults to the Cholesky
        decomposition of :math:`\Sigma_u`

        Parameters
        ----------
        maxn : int
            Number of coefficient matrices to compute
        P : ndarray (k x k), optional
            Matrix such that Sigma_u = PP', defaults to Cholesky descomp

        Returns
        -------
        coefs : ndarray (maxn x k x k)
        )r   )r   r$   r   s      r*   r   zVARProcess.orth_ma_rep  s    " 4q))r,   c                T    t         j                  j                  | j                        S )zwCompute long-run effect of unit impulse

        .. math::

            \Psi_\infty = \sum_{i=0}^\infty \Phi_i
        )r   r/   r   rf  r   s    r*   long_run_effectszVARProcess.long_run_effects,  s     yy}}T^^,,r,   c                T    t         j                  j                  | j                        S N)r   r/   r   rO   r   s    r*   r   zVARProcess._chol_sigma_u5  s    yy!!$,,//r,   c                x    t        j                  | j                        | j                  j	                  d      z
  S )z Characteristic matrix of the VARr   )r   r    rQ   r#   r   r   s    r*   rf  zVARProcess._char_mat9  s)     vvdii 4::>>!#444r,   c                F    t        | j                  | j                  |      S )zwCompute theoretical autocovariance function

        Returns
        -------
        acf : ndarray (p x k x k)
        r<   )r@   r#   rO   r   r<   s     r*   rJ   zVARProcess.acf>  s     tzz4<<u==r,   c                L    t        j                  | j                  |            S )a|  
        Autocorrelation function

        Parameters
        ----------
        nlags : int or None
            The number of lags to include in the autocovariance function. The
            default is the number of lags included in the model.

        Returns
        -------
        acorr : ndarray
            Autocorrelation and cross correlations (nlags, neqs, neqs)
        rq  )r   acf_to_acorrrJ   rr  s     r*   acorrzVARProcess.acorrG  s        !677r,   c                T    t        j                  | j                  |      |      }|S )z)Plot theoretical autocorrelation functionrq  	linewidth)r   plot_full_acorrru  r   r<   rx  figs       r*   
plot_acorrzVARProcess.plot_acorrX  s)    &&JJUJ#y
 
r,   c                F   | j                   |t        d      | j                   |t        d      t        |ddd      }|3|j                  d   |k7  r!d	|j                  d    d
| d}t        |      | j                  j
                  dk(  rdn| j                  j                  }g }| j                  j                  d      r$|j                  t        j                  |             t        j                  | j                  dz   | j                  dz   |z         }d| j                  v r|j                  |       d| j                  v r|j                  |dz         ||j                  |       |sd}nt        j                  |      }t        || j                   |||      S )uI  Produce linear minimum MSE forecasts for desired number of steps
        ahead, using prior values y

        Parameters
        ----------
        y : ndarray (p x k)
        steps : int

        Returns
        -------
        forecasts : ndarray (steps x neqs)

        Notes
        -----
        Lütkepohl pp 37-38
        NzANo exog in model, so no exog_future supported in forecast method.z>Please provide an exog_future argument to the forecast method.exog_futureTrB   )optionalr   r   zexog_future only has z# observations. It must have steps (z) observations.
r~   r   ttt)r\   rY   r   r   rN  sizerM   r   r1  r   r   onesrc   r   r  r`   r#   )r   rZ   rP   r~  err_msgr[   exogsexog_lin_trends           r*   r`   zVARProcess.forecast_  s   " 99!8&  99 [%8' 
 !A
 "  #u,!''*+ ,w  !))"oo22a7dT__=N=N::  %LL(MMAt}}q058
 $**LL(4::LL1,-"LL%K//%0K4::{E;GGr,   c                &   | j                  |      }t        | j                        }t        j                  |||f      }t        j                  ||f      }t        |      D ]-  }||   }|| j                  z  |j                  z  }||z   x||<   }/ |S )a]  
        Compute theoretical forecast error variance matrices

        Parameters
        ----------
        steps : int
            Number of steps ahead

        Notes
        -----
        .. math:: \mathrm{MSE}(h) = \sum_{i=0}^{h-1} \Phi \Sigma_u \Phi^T

        Returns
        -------
        forc_covs : ndarray (steps x neqs x neqs)
        )r+   rL   rO   r   r   r!   rM   )	r   rP   rN   r&   rR   rS   r?   rT   rU   s	            r*   rb   zVARProcess.mse  s    " ;;u%HHeQ]+	!Q u 	/A1+C$suu,C#(3;.IaL5		/ r,   c                v    | j                  |      }t        j                  | j                        }|d d ||f   S rn  )rV   r   rc   rQ   )r   rP   rd   re   s       r*   rf   zVARProcess._forecast_vars  s7      ' yy#AtTM""r,   c                
   d|cxk  rdk  st        d       t        d      t        j                  |      }| j                  |||      }t	        j
                  | j                  |            }|||z  z
  }|||z  z   }	|||	fS )u  
        Construct forecast interval estimates assuming the y are Gaussian

        Parameters
        ----------
        y : {ndarray, None}
            The initial values to use for the forecasts. If None,
            the last k_ar values of the original endogenous variables are
            used.
        steps : int
            Number of steps ahead to forecast
        alpha : float, optional
            The significance level for the confidence intervals.
        exog_future : ndarray, optional
            Forecast values of the exogenous variables. Should include
            constant, trend, etc. as needed, including extrapolating out
            of sample.
        Returns
        -------
        point : ndarray
            Mean value of forecast
        lower : ndarray
            Lower bound of confidence interval
        upper : ndarray
            Upper bound of confidence interval

        Notes
        -----
        Lütkepohl pp. 39-40
        r   r   zalpha must be between 0 and 1)r~  )rY   r   ri   r`   r   rj   rf   )
r   rZ   rP   rk   r~  rl   rm   rn   ro   rp   s
             r*   rq   zVARProcess.forecast_interval  s    > 5}1}<== <==""5)q%[I++E23#a%i/
#a%i/
z:55r,   c                   | j                   j                  d   }| j                   j                  d   }| j                   }t        j                  |      t        j                  |d      z
   }t        j
                  |dz
  ||f      }t        |dz
        D ]"  }t        j                  ||dz   d d       ||<   $ t        j                  |d      }||dS )to_vecmr   r   N)GammaPi)r#   r   r   identityr   r   r!   concatenate)r   r&   r%   rG   ru   gammar(   s          r*   r  zVARProcess.to_vecm  s    JJQJJQJJ{{1~q!,-!a%A'q1u 	0A!a%'
A./E!H	0ua(b))r,   rF  r   )NNNNN)NNN
   r  Nrn  r     )皙?N)r   r   r   r   r   rW  r   r8   ra  rd  rg  r   r+   r   rl  r   r   rf  rJ   ru  r|  r`   rb   rV   rf   rq   r  r   r,   r*   rK  rK  J  s    * DH1>06JX$
?(-*&- 0 0 5 5>8"9Hx> L#)6V
*r,   rK  c                      e Zd ZdZdZ	 	 	 	 	 d5 fd	Zd Zed        Zed        Z	e
d        Ze
d        Zd6d	Zd6d
Zd7dZd6dZd6dZe
d        Ze
d        Zd Zd Ze
d        Zed        Ze
d        Ze
d        Ze
d        ZeZe
d        Ze
d        Ze
d        Ze
d        Ze
d        Z e
d        Z!e
d        Z"e
d        Z#d8dZ$d9d Z%	 	 	 	 	 	 	 d:d!Z&	 d;d"Z'd# Z(d$ Z)d% Z*d<d&Z+d=d'Z,d( Z-d>d)Z.d?d*Z/d@d+Z0dAd,Z1d?d-Z2e
d.        Z3e
d/        Z4ed0        Z5ed1        Z6ed2        Z7ed3        Z8e
d4        Z9 xZ:S )Br   a  Estimate VAR(p) process with fixed number of lags

    Parameters
    ----------
    endog : ndarray
    endog_lagged : ndarray
    params : ndarray
    sigma_u : ndarray
    lag_order : int
    model : VAR model instance
    trend : str {'n', 'c', 'ct'}
    names : array_like
        List of names of the endogenous variables in order of appearance in
        `endog`.
    dates
    exog : ndarray

    Attributes
    ----------
    params : ndarray (p x K x K)
        Estimated A_i matrices, A_i = coefs[i-1]
    dates
    endog
    endog_lagged
    k_ar : int
        Order of VAR process
    k_trend : int
    model
    names
    neqs : int
        Number of variables (equations)
    nobs : int
    n_totobs : int
    params : ndarray (Kp + 1) x K
        A_i matrices and intercept in stacked form [int A_1 ... A_p]
    names : list
        variables names
    sigma_u : ndarray (K x K)
        Estimate of white noise process variance Var[u_t]
    r   c                   || _         || _        || _        |	| _        | j                  j                  \  | _        }| j
                  |z
  | _        || _        t        j                  |      }t        j                  ||||j                  j                        | _        || _        |
| _        |}|
|
j                  d   }||z  }nd}| j                  |d  }|j!                  |||f      }|j#                  dd      j%                         }|d | j&                  | _        | j(                  j                  d   | _        || _        |||d}t.        | a  || j(                  |||       y )Nr   r   rB   )r   rM  r   )r   rQ  )r   r   r   r   r   r   rx   r   r   r   r  r  	orig_exogr  r   r\   r   r   copyrM   rN  rP  rM  r   r   )r   r   r   r   rO   r   r   r   r   r   r\   rQ   r   endog_startrM  reshapedr#   rQ  r   s                     r*   r   zVARResults.__init__+  sj    

(
"jj..tMMI-	
%%e,--9guzz';';
 	
 **Q-K;&KK;;{|,##Yd$;<!!!Q',,. +.00oo++A.&
 &

 	OO% 	 	
r,   c                n    t        j                  | j                  | j                  | j                        S )zPlot input time series)r   index)r   rc  r   r   r   r   s    r*   plotzVARResults.ploti  s(      JJdjj


 	
r,   c                N    | j                   | j                  z  | j                  z   S )z_
        Number of estimated parameters per variable, including the intercept / trends
        )rQ   r   rP  r   s    r*   df_modelzVARResults.df_modelo  s     
 yy499$t{{22r,   c                4    | j                   | j                  z
  S )z;Number of observations minus number of estimated parameters)rx   r  r   s    r*   r,  zVARResults.df_residv  s     yy4==((r,   c                V    t        j                  | j                  | j                        S )zW
        The predicted insample values of the response variables of the model.
        )r   r"   r   r   r   s    r*   r   zVARResults.fittedvalues{  s    
 vvd''55r,   c                N    | j                   | j                  d | j                  z
  S )zV
        Residuals of response variable resulting from estimated coefficients
        N)r   r   r   r   s    r*   rv   zVARResults.resid  s$    
 zz$))+&):):::r,   c                J    t        | j                  | j                  d |      S )zSample acovNrq  )_compute_acovr   r   rr  s     r*   sample_acovzVARResults.sample_acov  s    TZZ		4EBBr,   c                <    | j                  |      }t        |      S )zSample acorrrq  )r  _acovs_to_acorrsr   r<   acovss      r*   sample_acorrzVARResults.sample_acorr  s       u -&&r,   c                T    t        j                  | j                  |      |      }|S )a  
        Plot sample autocorrelation function

        Parameters
        ----------
        nlags : int
            The number of lags to use in compute the autocorrelation. Does
            not count the zero lag, which will be returned.
        linewidth : int
            The linewidth for the plots.

        Returns
        -------
        Figure
            The figure that contains the plot axes.
        rq  rw  )r   ry  r  rz  s       r*   plot_sample_acorrzVARResults.plot_sample_acorr  s.    " &&E*i
 
r,   c                0    t        | j                  |      S )z
        Compute centered sample autocovariance (including lag 0)

        Parameters
        ----------
        nlags : int

        Returns
        -------
        rq  )r  rv   rr  s     r*   
resid_acovzVARResults.resid_acov  s     TZZu55r,   c                <    | j                  |      }t        |      S )z
        Compute sample autocorrelation (including lag 0)

        Parameters
        ----------
        nlags : int

        Returns
        -------
        rq  )r  r  r  s      r*   resid_acorrzVARResults.resid_acorr  s     e,&&r,   c                *    | j                  d      d   S )z6
        Centered residual correlation matrix
        r   )r  r   s    r*   
resid_corrzVARResults.resid_corr  s    
 "1%%r,   c                    | j                   st        j                  | j                        S | j                  | j                   z  | j                  z  S )z@(Biased) maximum likelihood estimate of noise process covariance)r,  r   r   rO   rx   r   s    r*   sigma_u_mlezVARResults.sigma_u_mle  s:     }}==..||dmm+dii77r,   c                    | j                   }t        j                  t        j                  j	                  |j
                  |z        | j                        S )uT  Estimated variance-covariance of model coefficients

        Notes
        -----
        Covariance of vec(B), where B is the matrix
        [params_for_deterministic_terms, A_1, ..., A_p] with the shape
        (K x (Kp + number_of_deterministic_terms))
        Adjusted to be an unbiased estimator
        Ref: Lütkepohl p.74-75
        )r   r   rD   r/   r   rM   rO   )r   r'  s     r*   
cov_paramszVARResults.cov_params  s9     wwryy}}QSS1W-t||<<r,   c                    t         j                  j                  t        j                  | j                        | j
                  j                  d      z
        }|| j                  z  |j                  z  S )u}  Asymptotically consistent estimate of covariance of the sample mean

        .. math::

            \sqrt(T) (\bar{y} - \mu) \rightarrow
                  {\cal N}(0, \Sigma_{\bar{y}}) \\

            \Sigma_{\bar{y}} = B \Sigma_u B^\prime, \text{where }
                  B = (I_K - A_1 - \cdots - A_p)^{-1}

        Notes
        -----
        Lütkepohl Proposition 3.3
        r   )	r   r/   r   r    rQ   r#   r   rO   rM   )r   Ainvs     r*   cov_ybarzVARResults.cov_ybar  sM      yy}}RVVDII.1BBCdll"TVV++r,   c                j    t        j                  | j                  j                  | j                        S rn  )r   r"   r   rM   r   s    r*   _zzzVARResults._zz  s'     vvd''))4+<+<==r,   c                f    | j                   | j                  z  }| j                         |d|df   S )zL
        Estimated covariance matrix of model coefficients w/o exog
        N)rP  rQ   r  )r   kns     r*   
_cov_alphazVARResults._cov_alpha  s0     [[499$ bc**r,   c                    t        j                  | j                        }t        j                  j                  |      }t        j                  | j                  | j                        }d|z  |z  |j                  z  S )z>
        Estimated covariance matrix of vech(sigma_u)
        rB   )	tsar   rQ   r   r/   pinvrD   rO   rM   )r   D_KD_Kinvsigxsigs       r*   
_cov_sigmazVARResults._cov_sigma  sZ    
 $$TYY/$''$,,56zG#fhh..r,   c                X    t        | j                  | j                  | j                        S )zCompute VAR(p) loglikelihood)r|   rv   r  rx   r   s    r*   llfzVARResults.llf  s!     4::t'7'7CCr,   c                    t        j                  t        j                  | j                                     }|j	                  | j
                  | j                  fd      S )z:Standard errors of coefficients, reshaped to match in sizeC)r   )r   rj   diagr  r   r  rQ   )r   stderrs     r*   r  zVARResults.stderr  sB     !234~~t}}dii8~DDr,   c                8    | j                   }| j                  |d S )Stderr_endog_laggedNrP  r  r   r   s     r*   stderr_endog_laggedzVARResults.stderr_endog_lagged  s     {{56""r,   c                8    | j                   }| j                  d| S )	Stderr_dtNr  r   r   s     r*   	stderr_dtzVARResults.stderr_dt!  s     kk{{4C  r,   c                4    | j                   | j                  z  S )zm
        Compute t-statistics. Use Student-t(T - Kp - 1) = t(df_resid) to
        test significance.
        )r   r  r   s    r*   tvalueszVARResults.tvalues'  s     {{T[[((r,   c                8    | j                   }| j                  |d S )tvalues_endog_laggedNrP  r  r  s     r*   r  zVARResults.tvalues_endog_lagged/       ||EF##r,   c                8    | j                   }| j                  d| S )
tvalues_dtNr  r  s     r*   r  zVARResults.tvalues_dt5       kk||DS!!r,   c                    dt         j                  j                  t        j                  | j
                              z  S )zW
        Two-sided p-values for model coefficients from Student t-distribution
        rB   )r   normr   r   r2   r  r   s    r*   pvalueszVARResults.pvalues;  s)     5::==!5666r,   c                8    | j                   }| j                  |d S )pvalues_endog_laggdNrP  r  r  s     r*   pvalues_endog_laggedzVARResults.pvalues_endog_laggedC  r  r,   c                8    | j                   }| j                  d| S )
pvalues_dtNr  r  s     r*   r  zVARResults.pvalues_dtI  r  r,   c                    | j                  | j                  | j                   d ||      \  }}}t        j                  | j                  |||| j
                  |      }|S )z
        Plot forecast
        N)rk   )r   plot_stderr)rq   r   r   r   plot_var_forcr   )r   rP   rk   r  midlowerr   r{  s           r*   plot_forecastzVARResults.plot_forecastQ  sk     !22JJ		z|$e5 3 
UE $$JJ**#
 
r,   c                   | j                  |      }|dk(  r	 |S |dk(  r]| j                  dk(  rL| j                  dk  r=|| j                  |      | j                  z  z  }ddl}|j                  dt        d       |S t        d	      )
uO  Compute forecast covariance matrices for desired number of steps

        Parameters
        ----------
        steps : int

        Notes
        -----
        .. math:: \Sigma_{\hat y}(h) = \Sigma_y(h) + \Omega(h) / T

        Ref: Lütkepohl pp. 96-97

        Returns
        -------
        covs : ndarray (steps x k x k)
        rb   autor   rB   r   Nz4forecast cov takes parameter uncertainty intoaccount)
stacklevelz'method has to be either 'mse' or 'auto')	rb   rP  r   _omega_forc_covrx   warningswarnr   rY   )r   rP   r  fc_covr  s        r*   rV   zVARResults.forecast_covd  s    " %U?  v{{aDLL1$4$..u5		AAM!!"    FGGr,   c                   | j                  ||||||      }t        j                  |d      }	t        t	        |dz  |z        dz
        }
t        t	        d|dz  z
  |z        dz
        }|	|
ddddddf   }|	|ddddddf   }||fS )u  
        Compute Monte Carlo integrated error bands assuming normally
        distributed for impulse response functions

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse response error bands
        repl : int
            number of Monte Carlo replications to perform
        steps : int, default 10
            number of impulse response periods
        signif : float (0 < signif <1)
            Significance level for error bars, defaults to 95% CI
        seed : int
            np.random.seed for replications
        burn : int
            number of initial observations to discard for simulation
        cum : bool, default False
            produce cumulative irf error bands

        Notes
        -----
        Lütkepohl (2005) Appendix D

        Returns
        -------
        Tuple of lower and upper arrays of ma_rep monte carlo standard errors
        )orthreplrP   r\  burncumr   axisrB   r   N)	irf_resimr   sortr   r2  )r   r  r  rP   r   r\  r  r  ma_collma_sortlow_idxupp_idxr  r   s                 r*   irf_errband_mczVARResults.irf_errband_mc  s    N ..DDt ! 
 '''*eFQJ-.23eQ!^t34q89Aq()Aq()e|r,   c           	          j                   } j                   j                  } j                  }	 j                  }
 j
                  }|z   }t        j                  |dz   ||f      } fd}t        |      D ]9  }t        j                  ||
|	|||z         }||d } ||      ||ddddddf<   ; |S )a  
        Simulates impulse response function, returning an array of simulations.
        Used for Sims-Zha error band calculation.

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse response error bands
        repl : int
            number of Monte Carlo replications to perform
        steps : int, default 10
            number of impulse response periods
        signif : float (0 < signif <1)
            Significance level for error bars, defaults to 95% CI
        seed : int
            np.random.seed for replications
        burn : int
            number of initial observations to discard for simulation
        cum : bool, default False
            produce cumulative irf error bands

        Notes
        -----
        .. [*] Sims, Christoper A., and Tao Zha. 1999. "Error Bands for Impulse
           Response." Econometrica 67: 1113-1155.

        Returns
        -------
        Array of simulated impulse response functions
        r   c                    t        | j                        j                  j                        }r|j	                        n|j                        }r|j                  d      S |S )N)r\   )r  r   r   r   r  )r   r\   r  r   r   r+   cumsum)simretr  r   r  r   rP   s     r*   	fill_collz'VARResults.irf_resim.<locals>.fill_coll  sc    c		*..t4::.NC/3U+9O  *-3::1:%5#5r,   )r\  rP   N)rQ   r   r#   rO   r   rx   r   r   r!   r   r_  )r   r  r  rP   r\  r  r  rQ   r#   rO   r   rx   nobs_originalr  r	  r(   r  r   s   `` `  `          @r*   r  zVARResults.irf_resim  s    B yyyy

,,NN	yyt((D%!)T489	6 	6 t 
	1A++#d*C de*C"+C.GAq!QJ
	1 r,   c                   | j                   }t        j                  j                  |      }| j	                         i fd}| j                  |      }| j                  }t        j                  || j                  | j                  f      }t        d|dz         D ]  }|dk(  r | j                  | j                  z  ||dz
  <   (||dz
     }	t        |      D ]t  }
t        |      D ]d  } ||dz
  |
z
        } ||dz
  |z
        }t        j                  |j                  |z  |z  |z        }|	|||
   z  |z  ||   j                  z  z  }	f v |	||dz
  <    |S )Nc                \    | vr#t         j                  j                  |       | <   |    S rn  )r   r/   matrix_power)r(   B_Bs    r*   bpowz(VARResults._omega_forc_cov.<locals>.bpow  s-    {		..q!41a5Lr,   r   )r  r   r/   r   _bmat_forc_covr+   rO   r   rQ   r!   r  tracerM   )r   rP   GGinvr  r'   r;   omegasr?   omr(   r)   BiBjmultr  r  s                  @@r*   r  zVARResults._omega_forc_cov  s[   HHyy}}Q
 !	 {{5!5$))TYY78q%!)$ 	AAv $ <q1uAB1X =q =Aa!eaiBa!eaiB88BDD4K"$4q$89D$a.504799<<B	== F1q5M	 r,   c                "   t        j                  | j                  | j                  f      }t        j                  | j                        |d d d | j                  f<   | j
                  | j                  dz
  z  }t        j                  |      }t        j                  t        j                  || j                  f      |t        j                  || j
                  f      f      }t        j                  || j                  j                  |f      S )Nr   )r   r   rP  r  r    rQ   r   r  vstackr   rM   )r   r   	lower_dimr    r  s        r*   r  zVARResults._bmat_forc_cov!  s    $++t}}56"$&&"5a4;;IIQ/	ffY)T[[12)TYY/0
 yy%677r,   c                    t        |       S )zrCompute console output summary of estimates

        Returns
        -------
        summary : VARSummary
        r   r   s    r*   r   zVARResults.summary2  s     $r,   c                8    |t        d      t        | ||      S )a  Analyze impulse responses to shocks in system

        Parameters
        ----------
        periods : int
        var_decomp : ndarray (k x k), lower triangular
            Must satisfy Omega = P P', where P is the passed matrix. Defaults
            to Cholesky decomposition of Omega
        var_order : sequence
            Alternate variable order for Cholesky decomposition

        Returns
        -------
        irf : IRAnalysis
        z.alternate variable order not implemented (yet)r   periods)r<  r   )r   r   
var_decomp	var_orders       r*   irfzVARResults.irf;  s+       %C  $*g>>r,   c                    t        | ||      S )z
        Compute forecast error variance decomposition ("fevd")

        Returns
        -------
        fevd : FEVD instance
        r  )FEVD)r   r   r!  s      r*   fevdzVARResults.fevdR  s     DJ88r,   c                .   t        |      t        | j                  dddf         k7  rt        d      t        |d   t              rDg }t        |      D ]2  \  }}|j                  | j                  j                  ||                4 |}t        | |      S )z.Reorder variables for structural specificationr   NzHReorder specification length should match number of endogenous variables)
rL   r   rY   
isinstancer   r   r   r   r  r   )r   r   	order_newr(   nams        r*   reorderzVARResults.reorder\  s    u:T[[A.//1 
 eAh$I#E* =3  !1!1%(!;<=E$&&r,   c                   d|cxk  rdk  st        d       t        d      t        t        ft        |      r|g}t	        fd|D              st        d      |D cg c]$  }t        |      t        u r| j                  |   n|& }}|D cg c]"  }t        j                  | j                  |      $ }}|t        |      r|g}t	        fd|D              st        d      |D cg c]$  }t        |      t        u r| j                  |   n|& }}|D cg c]"  }t        j                  | j                  |      $ }}nCt        | j                        D cg c]	  }||vs| }}|D cg c]  }| j                  |    }}| j                  | j                  }
}	|
dk(  rd}t        |      t        |      t        |      z  |
z  }| j                  }t!        j"                  ||	|z  |	d	z  |
z  z   ft$        
      }|	|z  }d}t        |
      D ].  }|D ]'  }|D ]   }d||||z   |	|z  z   |	d	z  |z  z   f<   |dz  }" ) 0 t!        j&                  |t)        | j*                  j,                              }t         j.                  j1                  || j3                         z  |j,                  z        }||z  |z  x}}|j5                         dk(  r|}t7        j8                  |      }nJ|j5                         dk(  r)||z  }||	| j:                  z  f}t7        j<                  | }nt        d|z        |j?                  |      }|jA                  d|z
        }tC        |||||||d|	      S c c}w c c}w c c}w c c}w c c}w c c}w )u  
        Test Granger causality

        Parameters
        ----------
        caused : int or str or sequence of int or str
            If int or str, test whether the variable specified via this index
            (int) or name (str) is Granger-caused by the variable(s) specified
            by `causing`.
            If a sequence of int or str, test whether the corresponding
            variables are Granger-caused by the variable(s) specified
            by `causing`.
        causing : int or str or sequence of int or str or None, default: None
            If int or str, test whether the variable specified via this index
            (int) or name (str) is Granger-causing the variable(s) specified by
            `caused`.
            If a sequence of int or str, test whether the corresponding
            variables are Granger-causing the variable(s) specified by
            `caused`.
            If None, `causing` is assumed to be the complement of `caused`.
        kind : {'f', 'wald'}
            Perform F-test or Wald (chi-sq) test
        signif : float, default 5%
            Significance level for computing critical values for test,
            defaulting to standard 0.05 level

        Notes
        -----
        Null hypothesis is that there is no Granger-causality for the indicated
        variables. The degrees of freedom in the F-test are based on the
        number of variables in the VAR system, that is, degrees of freedom
        are equal to the number of equations in the VAR times degree of freedom
        of a single equation.

        Test for Granger-causality as described in chapter 7.6.3 of [1]_.
        Test H0: "`causing` does not Granger-cause the remaining variables of
        the system" against  H1: "`causing` is Granger-causal for the
        remaining variables".

        Returns
        -------
        results : CausalityTestResults

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series*
           *Analysis*. Springer.
        r   r    signif has to be between 0 and 1c              3  6   K   | ]  }t        |        y wrn  r(  .0r~   allowed_typess     r*   	<genexpr>z,VARResults.test_causality.<locals>.<genexpr>  s     @A:a/@   zFcaused has to be of type string or int (or a sequence of these types).c              3  6   K   | ]  }t        |        y wrn  r/  r0  s     r*   r3  z,VARResults.test_causality.<locals>.<genexpr>  s     Ez!]3Er4  zOcausing has to be of type string or int (or a sequence of these types) or None.z5Cannot test Granger Causality in a model with 0 lags.rB   r   waldr^   zkind %s not recognizedgrangertestr  )"rY   r   r   r(  r3   	TypeErrortyper   r   rU  r!   rQ   r   RuntimeErrorrL   rP  r   r   r   r"   r   r   rM   r/   r   r  r  r   r   r,  r^   r   r   r   )r   causedcausingkindr   r~   
caused_indcausing_indr(   r&   r%   err	num_restrnum_det_termsr  cols_detrowr)   ing_inded_indCbmiddlelam_wald	statisticdfdistpvalue
crit_valuer2  s                               @r*   test_causalityzVARResults.test_causalityo  s   b FQ?@@ ?@@c
fm,XF@@@,  CIIQ47c>$**Q-q8II=CDdnnTZZ3D
D'=1")EWEE:  HOO!Q3tzz!}A=OGOBIJQ4>>$**a8JKJ&+DII&6N!::M1NKN.89tzz!}9G9yy$))16ICs## L3v;.2	 HHi]!2Q!VaZ!?@N}$q 	A& ( FKLAc8f,q7{:Q!VaZGGH1HC	 VVAs4;;==)*q4??#44qss:;  "F{R//9::<6!B::b>DZZ\S  9,IQ./B77B<D5<==#XXa&j)
#

 
	
s JD PJN9s*   ")M.'M3.)M8'M=	N(N2Nc                   d|cxk  rdk  st        d       t        d      t        t        ft        |      r|g}t	        fd|D              st        d      |D cg c]$  }t        |      t        u r| j                  |   n|& }}|D cg c]"  }t        j                  | j                  |      $ }}t        | j                        D cg c]	  }||vs| }}|D cg c]  }| j                  |    }}| j                  | j                  | j                  }
}	}t        |      t        |      z  }| j                  }t        j                   |      }t#        j$                  |j&                        }d|||f<   d|||f<   t        j                   |      }t#        j(                  |      d   }t#        j$                  |t        |      ft*              }t        |      D ]  }d||||   f<    t#        j,                  ||      }t"        j.                  j1                  t3        |            }t#        j,                  ||      }t"        j.                  j5                  |t#        j6                  ||      z  |j8                  z        dz  }|	|j8                  |z  |z  z  }|}t;        j<                  |      }|j?                  |      }|jA                  d|z
        }tC        |||||||dd	
	      S c c}w c c}w c c}w c c}w )u  
        Test for instantaneous causality

        Parameters
        ----------
        causing :
            If int or str, test whether the corresponding variable is causing
            the variable(s) specified in caused.
            If sequence of int or str, test whether the corresponding
            variables are causing the variable(s) specified in caused.
        signif : float between 0 and 1, default 5 %
            Significance level for computing critical values for test,
            defaulting to standard 0.05 level
        verbose : bool
            If True, print a table with the results.

        Returns
        -------
        results : dict
            A dict holding the test's results. The dict's keys are:

            "statistic" : float
              The calculated test statistic.

            "crit_value" : float
              The critical value of the Chi^2-distribution.

            "pvalue" : float
              The p-value corresponding to the test statistic.

            "df" : float
              The degrees of freedom of the Chi^2-distribution.

            "conclusion" : str {"reject", "fail to reject"}
              Whether H0 can be rejected or not.

            "signif" : float
              Significance level

        Notes
        -----
        Test for instantaneous causality as described in chapters 3.6.3 and
        7.6.4 of [1]_.
        Test H0: "No instantaneous causality between caused and causing"
        against H1: "Instantaneous causality between caused and causing
        exists".

        Instantaneous causality is a symmetric relation (i.e. if causing is
        "instantaneously causing" caused, then also caused is "instantaneously
        causing" causing), thus the naming of the parameters (which is chosen
        to be in accordance with test_granger_causality()) may be misleading.

        This method is not returning the same result as JMulTi. This is
        because the test is based on a VAR(k_ar) model in statsmodels
        (in accordance to pp. 104, 320-321 in [1]_) whereas JMulTi seems
        to be using a VAR(k_ar+1) model.

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series*
           *Analysis*. Springer.
        r   r   r-  c              3  6   K   | ]  }t        |        y wrn  r/  r0  s     r*   r3  z1VARResults.test_inst_causality.<locals>.<genexpr>6  s     AA:a/Ar4  zIcausing has to be of type string or int (or a a sequence of these types).r   rB   instr6  r8  )"rY   r   r   r(  r3   r:  r;  r   r   rU  r!   rQ   rx   r   rL   rO   vechr   r   r   nonzeror   r"   r/   r  r   r   rD   rM   r   r   r   r   r   )r   r>  r   r~   rA  r(   r@  r=  r&   r  r%   rC  rO   vech_sigma_usig_maskvech_sig_maskre   r  rF  CsdCdrJ  wald_statisticrM  rN  rO  rP  r2  s                               @r*   test_inst_causalityzVARResults.test_inst_causality  s   ~ FQ?@@ ?@@c
g}-iGAAA0  DKKaDGsN4::a=9KK>EFt~~djj!4FF!&tyy!1JAQk5IaJ
J)34A$**Q-44 ))TYY		a1L3v;.	,,yy)88GMM* -.j(),-[()		(+zz-(+ HHi\!235A# 	"C !Ac49n	"VVA|$IINN-a01VVAq\rBGGGW$==DEIbddVmb01zz"~(XXa&j)
#

 
	
K LFJ4s   ")K2'K7	K<K<%Lc           	        || j                   z
  dk  rt        d| j                    d      d}t        j                  | j                        }t        ||      }t        j                  j                  |d         }t        d|dz         D ]H  }||   }	t        j                  |	j                  |z  |	z  |z        }
|r|
| j                  |z
  z  }
||
z  }J ||r| j                  dz  n| j                  z  }| j                  dz  || j                   z
  z  }t        j                  |      }|j                  |      }|j!                  d|z
        }t#        |||||||      S )u6  
        Residual whiteness tests using Portmanteau test

        Parameters
        ----------
        nlags : int > 0
            The number of lags tested must be larger than the number of lags
            included in the VAR model.
        signif : float, between 0 and 1
            The significance level of the test.
        adjusted : bool, default False
            Flag indicating to apply small-sample adjustments.

        Returns
        -------
        WhitenessTestResults
            The test results.

        Notes
        -----
        Test the whiteness of the residuals using the Portmanteau test as
        described in [1]_, chapter 4.4.3.

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series*
           *Analysis*. Springer.
        r   zhThe whiteness test can only be used when nlags is larger than the number of lags included in the model (z).r   rB   )r   rY   r   rs   rv   r  r/   r   r!   r  rM   rx   rQ   r   r   r   r   r   )r   r<   r   adjustedrL  u	acov_listcov0_invr  r  to_addrM  rN  rO  rP  s                  r*   test_whitenesszVARResults.test_whitenessl  sT   : 499!"ii[, 
 	JJtzz"!!U+	99==1.q%!)$ 	 A1BXXbddXo2X=>F$))a-'I	  	xTYY!^TYY>	YY!^utyy01zz"~#XXa&j)
#z62vuh
 	
r,   c                   |r| j                  |      }n| j                  |      }dt        j                  | j                        z  }t        j                  |dd t        j                  d|dz         ||      }|j                  d       |S )ap  
        Plot autocorrelation of sample (endog) or residuals

        Sample (Y) or Residual autocorrelations are plotted together with the
        standard :math:`2 / \sqrt{T}` bounds.

        Parameters
        ----------
        nlags : int
            number of lags to display (excluding 0)
        resid : bool
            If True, then the autocorrelation of the residuals is plotted
            If False, then the autocorrelation of endog is plotted.
        linewidth : int
            width of vertical bars

        Returns
        -------
        Figure
            Figure instance containing the plot.
        rB   r   N)xlabel	err_boundrx  z3ACF plots for residuals with $2 / \sqrt{T}$ bounds )	r  r  r   rj   rx   r   ry  rc   suptitle)r   r<   rv   rx  acorrsboundr{  s          r*   r|  zVARResults.plot_acorr  s    , %%e,F&&u-FBGGDII&&&&12J99Q	*	
 	KL
r,   c                    t        | |      S )a  
        Test assumption of normal-distributed errors using Jarque-Bera-style
        omnibus Chi^2 test.

        Parameters
        ----------
        signif : float
            Test significance level.

        Returns
        -------
        result : NormalityTestResults

        Notes
        -----
        H0 (null) : data are generated by a Gaussian-distributed process
        )r   )r   )r   r   s     r*   r   zVARResults.test_normality  s    $ d622r,   c                T    t         j                  j                  | j                        S )z
        Return determinant of white noise covariance with degrees of freedom
        correction:

        .. math::

            \hat \Omega = \frac{T}{T - Kp - 1} \hat \Omega_{\mathrm{MLE}}
        )r   r/   detrO   r   s    r*   detomegazVARResults.detomega  s     yy}}T\\**r,   c                L   | j                   }| j                  }| j                  }||dz  z  || j                  z  z   }| j                  rt        | j                        }nt        j                   }|d|z  |z  z   }|t        j                  |      |z  |z  z   }|dt        j                  t        j                  |            z  |z  |z  z   }| j                  r6|| j                  z   | j                  z  |z  t        j                  |      z  }	nt        j                  }	||||	dS )z+information criteria for lagorder selectionrB   g       @)r   r   r   r   )rx   rQ   r   rP  r,  r
   r  r   infrt   r  exp)
r   rx   rQ   r   free_paramsldr   r   r   r   s
             r*   r4  zVARResults.info_criteria  s     yyyyII	$!)+dT[[.@@==T--.B&&B C$J+--BFF4L4';66S266"&&,//$6+EE==4==(DMM9dBRVVBZOC&&C3SAAr,   c                     | j                   d   S )zAkaike information criterionr   r4  r   s    r*   r   zVARResults.aic	       !!%((r,   c                     | j                   d   S )uS   Final Prediction Error (FPE)

        Lütkepohl p. 147, see info_criteria
        r   rv  r   s    r*   r   zVARResults.fpe	  s     !!%((r,   c                     | j                   d   S )zHannan-Quinn criterionr   rv  r   s    r*   r   zVARResults.hqic	  s     !!&))r,   c                     | j                   d   S )z&Bayesian a.k.a. Schwarz info criterionr   rv  r   s    r*   r   zVARResults.bic	  rw  r,   c                   | j                   }| j                  }||z  }t        j                  ||f      }t        j                  | j
                        |d|ddf<   t        j                  ||z
        ||dd| f<   t        j                  j                  |      d   dz  }t        j                  t        j                  |            ddd   }||   S )a  
        The roots of the VAR process are the solution to
        (I - coefs[0]*z - coefs[1]*z**2 ... - coefs[p-1]*z**k_ar) = 0.
        Note that the inverse roots are returned, and stability requires that
        the roots lie outside the unit circle.
        Nr   )rQ   r   r   r   r  r#   r    r/   eigargsortr2   )r   rQ   r   r%   arrrootsr   s          r*   r  zVARResults.roots	  s     yyyy4Khh1v

3ETE1HVVAH-DE6TE6M		c"1%+jj'"-Szr,   )Nr~   NNNr   r  )r  T)r   rb   )Fr[  r  r  Nd   F)Fr[  r  Nr  F)r  NNr  )Nr^   r  r  )r  r  F)r  Tr  );r   r   r   r   _model_typer   r  propertyr  r,  r   r   rv   r  r  r  r  r  r  r  r  r  r  r  r  r  r  bser  r  r  r  r  r  r  r  r  rV   r  r  r  r  r   r#  r&  r+  rQ  r^  re  r|  r   ro  r4  r   r   r   r   r  rH  rI  s   @r*   r   r     s   'R K <
|
 3 3 ) ) 6 6 ; ;C'
,6' & & 8 8=,, > > + + / / D D E E
 C# #
 ! !
 ) ) $ $
 " "
 7 7 $ $
 " "&"N 1h IN>@#J8" ?.9'&@
Dy
v5
n$L3( 	+ 	+ B B. ) ) ) ) * * ) )  r,   r   c            	          e Zd ZdddddddddZ ej
                  ej                  e      ZddiZ ej
                  ej                  e      Z	y)r%  
columns_eqcovcov_eq)r  r  r   r  r  rO   r  r  conf_intmultivariate_confintN)
r   r   r   _attrswrapunion_dictsr   _wrap_attrs_methods_wrap_methodsr   r,   r*   r%  r%  +	  sj    	F #$"" ,,fK 23H$D$$ ..Mr,   r%  c                  ,    e Zd ZdZddZd Zd ZddZy)	r%  zc
    Compute and plot Forecast error variance decomposition and asymptotic
    standard errors
    Nc                N   || _         || _        |j                  | _        |j                  j                  | _        |j                  ||      | _        | j                  j                  | _        | j                  d | dz  j                  d      }t        | j                        }| j                  j                  |      d d ||f   }t        j                  |      }t        |      D ]$  }||   j                  ||   z  j                  ||<   & |j                  dd      | _        y )N)r!  r   rB   r   r  r   )r   r   rQ   r  r   r#  irfobj	orth_irfsr  r   rb   r   
empty_liker!   rM   r   decomp)	r   r   r   r   irfsrngrb   r&  r(   s	            r*   r   zFEVD.__init__H	  s    
JJ	[[,,
ii1gi>.. x(A-5515=TYYjjnnW%ack2 }}T"w 	-AAwyy3q6),,DG	- mmAq)r,   c                n   t               }t        | j                        }t        | j                        D ]e  }t        j                  | j                  |   || j                        }|j                  d| j                  |   z         |j                  |dz          g t        |j                                y )NzFEVD for %s

)r   r   r   r!   rQ   r   pprint_matrixr  r   writer1   getvalue)r   bufr  r(   ppms        r*   r   zFEVD.summarya	  s    jT\\"tyy! 	"A&&t{{1~sDJJGCIIo

156IIcDj!		" 	cllnr,   c                    t         )zLCompute asymptotic standard errors

        Returns
        -------
        r;  r   s    r*   r  zFEVD.covm	  s
     "!r,   c           	     6   ddl m} | j                  }|xs | j                  }|j	                  ||      \  }}|j                  d       t        j                  |t              |z  D cg c]  }t        |       }	}t        j                  |      }
| j                  j                  d      }|d   }t        |      D ]  }||   }||   j                  }g }t        |      D ]R  }|dkD  r||dz
     nd}||   } |j                  |
||z
  f||	|   | j                  |   d|}|j!                  |       T |j#                  | j                  |           |j%                         \  }}|j'                  ||d	
       t)        j*                  d       |S c c}w )zPlot graphical display of FEVD

        Parameters
        ----------
        periods : int, default None
            Defaults to number originally specified. Can be at most that number
        r   N)nrowsfigsizez,Forecast error variance decomposition (FEVD)r   rB   r   )bottomcolorlabelzupper right)locg333333?)right)matplotlib.pyplotpyplotrQ   r   subplotsri  r   rc   r   r   r  r  r!   rM   barr   r   	set_titleget_legend_handles_labelslegendr   adjust_subplots)r   r   r  	plot_kwdspltr&   r{  axesr~   colorstickslimitsaxr(   this_limitshandlesr)   r  r   handlelabelss                        r*   r  z	FEVD.plotu	  s    	(II)T\\LLq'L:	TCD"$))AU";a"?@Q#a&@@		'"##A&!Wq 	(AaB )++KG1X './!eAE*#AEM ! )**Q-   v&' LLA'+	(0 668

7F
6  t,
A As   *FrF  )N)r  r  )r   r   r   r   r   r   r  r  r   r,   r*   r%  r%  B	  s    
*2
"1r,   r%  c                R   | | j                  d      z
  } g }t        |dz         D ]`  }|dkD  r(t        j                  | |d  j                  | d |        }n t        j                  | j                  |       }|j                  |       b t        j                  |      t        |       z  S rh   )r   r!   r   r"   rM   r   rE   rL   )r   r<   r>   lagrs        r*   r  r  	  s    	AFF1IAFUQY 7qwyy!EcT(+AqssAAa 88Fc!f$$r,   c                    t        j                  t        j                  | d               }| t        j                  ||      z  S )Nr   )r   rj   r  outer)r  sds     r*   r  r  	  s3    	q"	#B288B###r,   r  r   rn  )   r  r   r  r  r  )Jr   
__future__r   statsmodels.compat.pythonr   collectionsr   ior   numpyr   pandasr  scipy.statsr   statsmodels.base.wrapperbasewrapperr  statsmodels.iolib.tabler   statsmodels.tools.decoratorsr   r	   statsmodels.tools.linalgr
   statsmodels.tools.sm_exceptionsr   statsmodels.tools.validationr   statsmodels.tsa.base.tsa_modelr   r   statsmodels.tsa.tsatoolsr  tsatoolsr   r   r   statsmodels.tsa.vector_arr   r   r   1statsmodels.tsa.vector_ar.hypothesis_test_resultsr   r   r   statsmodels.tsa.vector_ar.irfr    statsmodels.tsa.vector_ar.outputr   r+   r8   r@   r:   rV   rb   r`   rf   rq   r|   r   r   r   r   r   rK  r   ResultsWrapperr%  populate_wrapperr%  r  r  r   r,   r*   <module>r     s%   # , #     ' ' / I 0 9 3 ' & C C < < 
 5 7&R%0&R4< 8v, =>2  F/d=0.b7
 7
|zP/ zPz	n* n*ji iX!++ (   ' 4d dT%$r,   