
    M/Php                       d dl mZ d dlZd dlmZmZ d dlmZ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Z d dlmc mc mZ d d
lmZmZ d dlmZmZm Z  d dl!m"Z"m#Z# d dl$mc m%c m&Z& d dl'mc m%c m(Z) d dl*m+Z+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 	 	 	 	 d(de6de7de6fdZ8d)dZ9d*dZ:	 	 	 	 d+dZ;d Z<	 	 d,dZ=d Z>d Z? G d d          Z@	 d-d ZAd! ZB G d" d#          ZC G d$ d%ejD                  ZE G d& d'          ZFdS ).    )defaultdictN)hstackvstack)invsvd)Summary)SimpleTable)cache_readonly)HypothesisTestWarningstring_like)c_sjac_sjt)duplication_matrixlagmatvec)CausalityTestResultsWhitenessTestResults)	get_indexseasonal_dummies)VARLagOrderResults_compute_acovforecastforecast_intervalma_reporth_ma_reptest_normalitynmaxlagsdeterministicseasonsc           	         t          t                    }t          |d          }t          d|dz             D ]}g }d|v sd|v rH|                    t          j        t          |                                         dd                     d|v sd|v rK|                    dt          j	        t          |                                         dd          z              ||                    |           |d
k    rG|                    t          |t          |                                         d|dz
                       ||                    |           |rt          |          nd	}t          | |          }	|	                    ||dz   |z
            }
|
j                                        D ] \  }}||                             |           !d |                                D             }t!          ||d          S )aL  
    Compute lag order selections based on each of the available information
    criteria.

    Parameters
    ----------
    data : array_like (nobs_tot x neqs)
        The observed data.
    maxlags : int
        All orders until maxlag will be compared according to the information
        criteria listed in the Results-section of this docstring.
    deterministic : str {"n", "co", "ci", "lo", "li"}
        * ``"n"`` - no deterministic terms
        * ``"co"`` - constant outside the cointegration relation
        * ``"ci"`` - constant within the cointegration relation
        * ``"lo"`` - linear trend outside the cointegration relation
        * ``"li"`` - linear trend within the cointegration relation

        Combinations of these are possible (e.g. ``"cili"`` or ``"colo"`` for
        linear trend with intercept). See the docstring of the
        :class:`VECM`-class for more information.
    seasons : int, default: 0
        Number of periods in a seasonal cycle.
    exog : ndarray (nobs_tot x neqs) or `None`, default: `None`
        Deterministic terms outside the cointegration relation.
    exog_coint : ndarray (nobs_tot x neqs) or `None`, default: `None`
        Deterministic terms inside the cointegration relation.

    Returns
    -------
    selected_orders : :class:`statsmodels.tsa.vector_ar.var_model.LagOrderResults`
    r!         cociloliNr   )lagsoffsetc                 n    i | ]2\  }}|t          j        |                                          d z
  d z   3S )r$   )nparrayargmin).0ic_nameic_values      ^/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/vector_ar/vecm.py
<dictcomp>z select_order.<locals>.<dictcomp>f   sN       GX 	(##**,,q014      T)r   listr   rangeappendr.   oneslenreshapearanger   r   r   _estimate_varinfo_criteriaitemsr   )datar    r!   r"   exog
exog_cointicpexogs	var_model
var_resultkvselected_orderss                 r4   select_orderrL   $   s   P 
T		B??M1gk""  =  DM$9$9LLT++33B::;;;=  DM$9$9LLRYs4yy1199"a@@@AAA!LL$$$Q;;LL #d))44<<R1MM   LL!&0uDe$$	,,!GaK!O,LL
,2244 	 	DAqqELLOOOO	
 !#  O
 2555r6   Fc                 B    t          j        |           |z   }|s|dz  }|S )a  
    Construct an ndarray representing a linear trend in a VECM.

    Parameters
    ----------
    nobs : int
        Number of observations excluding the presample.
    k_ar : int
        Number of lags in levels.
    coint : bool, default: False
        If True (False), the returned array represents a linear trend inside
        (outside) the cointegration relation.

    Returns
    -------
    ret : ndarray (nobs)
        An ndarray representing a linear trend in a VECM

    Notes
    -----
    The returned array's size is nobs and not nobs_tot so it cannot be used to
    construct the exog-argument of VECM's __init__ method.
    r$   )r.   r=   )nobsk_arcointrets       r4   _linear_trendrR   n   s,    0 )D//D
 C qJr6   c                 z    d}t          | d          } d| v sd| v r|dz  }d| v sd| v r|dz  }|dk    r||dz
  z  }|S )aI  Gives the number of deterministic variables specified by det_string and
    seasons.

    Parameters
    ----------
    det_string : str {"n", "co", "ci", "lo", "li"}
        * "n" - no deterministic terms
        * "co" - constant outside the cointegration relation
        * "ci" - constant within the cointegration relation
        * "lo" - linear trend outside the cointegration relation
        * "li" - linear trend within the cointegration relation

        Combinations of these are possible (e.g. "cili" or "colo" for linear
        trend with intercept). See the docstring of the :class:`VECM`-class for
        more information.
    seasons : int
        Number of periods in a seasonal cycle.

    Returns
    -------
    num : int
        Number of deterministic terms and number dummy variables for seasonal
        terms.
    r   
det_stringr'   r&   r$   r*   r)   r   )rT   r"   nums      r4   _num_det_varsrV      sp    2 CZ66JzTZ//qzTZ//q{{w{Jr6   c                    g }t          | d          } d| v sd| v r'|                    t          j        |                     ||                    |           d| v sd| v r'|                    t          j        |                     |dk    r&|                    t          ||||                     ||                    |           |rt          j        |          ndS )	aX  
    Translate all information about deterministic terms into a single array.

    These information is taken from `deterministic` and `seasons` as well as
    from the `exog` and `exog_coint` arrays. The resulting array form can then
    be used e.g. in VAR's __init__ method.

    Parameters
    ----------
    deterministic : str
        A string specifying the deterministic terms in the model. See VECM's
        docstring for more information.
    seasons : int
        Number of periods in a seasonal cycle.
    nobs_tot : int
        Number of observations including the presample.
    first_season : int, default: 0
        Season of the first observation.
    seasons_centered : bool, default: False
        If True, the seasonal dummy variables are demeaned such that they are
        orthogonal to an intercept term.
    exog : ndarray (nobs_tot x #det_terms) or None, default: None
        An ndarray representing deterministic terms outside the cointegration
        relation.
    exog_coint : ndarray (nobs_tot x #det_terms_coint) or None, default: None
        An ndarray representing deterministic terms inside the cointegration
        relation.

    Returns
    -------
    exog : ndarray or None
        None, if the function's arguments do not contain deterministic terms.
        Otherwise, an ndarray representing these deterministic terms.
    r!   r&   r'   Nr)   r*   r   first_periodcentered)r   r9   r.   r:   r=   r   column_stack)r!   r"   nobs_totfirst_seasonseasons_centeredrB   rC   rF   s           r4   _deterministic_to_exogr_      s   V E??M} 5 5RWX&&'''Z   } 5 5RYx(())){{))	  	
 	
 	
 T%*42?5!!!4r6   c                     t          | d          \  }}}t          j        |          }|                    |dddf         |z            S )a  Calculates the square root of a matrix.

    Parameters
    ----------
    _2darray : ndarray
        A 2-dimensional ndarray representing a square matrix.

    Returns
    -------
    result : ndarray
        Square root of the matrix given as function argument.
    F)full_matricesN)r   r.   sqrtdot)_2darrayu_s_v_s       r4   	_mat_sqrtrh      sL     XU333JBB	B66"QQQW+"###r6   c                    t          |d          }|dz   }| }|j        d         }	|dd|df         }
|
j        d         }t          j        |          }|dd|dz
  df         }|dd|dz
  df         }d|v rd|v rt	          d          |g}d|v r'|                    t          j        |                     d	|v r%|                    t          ||d
                     |&|                    || dz
  d         j                   t          j	        |          }t          j
        ||	z  |f          }|dk    ret          |j        d                   D ]J}|dd||z   dz
  |dz
  dk     rdn|dz
  df         j                            |	|dz
  z            |dd|f<   K|g}d|v r'|                    t          j        |                     |dk    r<|                    t          ||j        d         ||z   dz   d
          j                   d|v r#|                    t          ||                     |#|                    || d         j                   t          j	        |          }|
|||fS )u%	  
    Returns different matrices needed for parameter estimation.

    Compare p. 186 in [1]_. The returned matrices consist of elements of the
    data as well as elements representing deterministic terms. A tuple of
    consisting of these matrices is returned.

    Parameters
    ----------
    endog : ndarray (neqs x nobs_tot)
        The whole sample including the presample.
    exog : ndarray (nobs_tot x neqs) or None
        Deterministic terms outside the cointegration relation.
    exog_coint : ndarray (nobs_tot x neqs) or None
        Deterministic terms inside the cointegration relation.
    diff_lags : int
        Number of lags in the VEC representation.
    deterministic : str {``"n"``, ``"co"``, ``"ci"``, ``"lo"``, ``"li"``}
        * ``"n"`` - no deterministic terms
        * ``"co"`` - constant outside the cointegration relation
        * ``"ci"`` - constant within the cointegration relation
        * ``"lo"`` - linear trend outside the cointegration relation
        * ``"li"`` - linear trend within the cointegration relation

        Combinations of these are possible (e.g. ``"cili"`` or ``"colo"`` for
        linear trend with intercept). See the docstring of the
        :class:`VECM`-class for more information.
    seasons : int, default: 0
        Number of periods in a seasonal cycle. 0 (default) means no seasons.
    first_season : int, default: 0
        The season of the first observation. `0` means first season, `1` means
        second season, ..., `seasons-1` means the last season.

    Returns
    -------
    y_1_T : ndarray (neqs x nobs)
        The (transposed) data without the presample.
        `.. math:: (y_1, \ldots, y_T)
    delta_y_1_T : ndarray (neqs x nobs)
        The first differences of endog.
        `.. math:: (y_1, \ldots, y_T) - (y_0, \ldots, y_{T-1})
    y_lag1 : ndarray (neqs x nobs)
        (dimensions assuming no deterministic terms are given)
        Endog of the previous period (lag 1).
        `.. math:: (y_0, \ldots, y_{T-1})
    delta_x : ndarray (k_ar_diff*neqs x nobs)
        (dimensions assuming no deterministic terms are given)
        Lagged differenced endog, used as regressor for the short term
        equation.

    References
    ----------
    .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
    r!   r$   r   Nr(   r&   r'   zNBoth 'co' and 'ci' as deterministic terms given. Please choose one of the two.r*   TrP   r%   rX   r)   )r   shaper.   diff
ValueErrorr9   r:   rR   Tr   zerosr8   r<   r   )endogrB   rC   	diff_lagsr!   r"   r]   rE   yKy_1_Trn   delta_ydelta_y_1_Ty_lag1y_lag1_stackdelta_xjdelta_x_stacks                      r4   _endog_matricesr|     s   ~  ??MAAA	
AaaaeHEAAgajjG!!!QUWW*%Kqqq!a%"*}F}!6!6.
 
 	
 8L}BGAJJ'''}M!Qd;;;<<<JrAv{35666Y|$$F h	Aq)**G1}}w}Q'(( 	% 	%A#1q519q1uqyytta!eb@@QU$$ AAAqDMM IM}RWQZZ((({{a )I59	  
 	
 	
 	
 }]1a00111T1"##Y[)))i&&G+vw..r6   c                 F   |j         d         }t          j        |          |j                            t          |                    |j                                                          |          z
  }|                     |          }|                    |          }||fS )u  Returns two ndarrays needed for parameter estimation as well as the
    calculation of standard errors.

    Parameters
    ----------
    delta_y_1_T : ndarray (neqs x nobs)
        The first differences of endog.
        `.. math:: (y_1, \ldots, y_T) - (y_0, \ldots, y_{T-1})
    y_lag1 : ndarray (neqs x nobs)
        (dimensions assuming no deterministic terms are given)
        Endog of the previous period (lag 1).
        `.. math:: (y_0, \ldots, y_{T-1})
    delta_x : ndarray (k_ar_diff*neqs x nobs)
        (dimensions assuming no deterministic terms are given)
        Lagged differenced endog, used as regressor for the short term
        equation.

    Returns
    -------
    result : tuple
        A tuple of two ndarrays. (See p. 292 in [1]_ for the definition of
        R_0 and R_1.)

    References
    ----------
    .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
    r$   )rk   r.   identityrn   rc   r   )rv   rw   ry   rN   mr0r1s          r4   _r_matricesr   x  s    < <?D
D	c'++gi00112266w??	A 
		B	ABr6Mr6   c                 d   |j         d         }t          |||           \  }}t          j        ||j                  |z  }t          j        ||j                  |z  }|j        }t          j        ||j                  |z  }	t          t          |	                    }
t          j        ||
          }t          j                            |j        t          |          z  |z            }|d         }|d         }t          j	        |          ddd         }||         }|dd|f         }||||	|
||fS )u  Returns matrices and eigenvalues and -vectors used for parameter
    estimation and the calculation of a models loglikelihood.

    Parameters
    ----------
    delta_x : ndarray (k_ar_diff*neqs x nobs)
        (dimensions assuming no deterministic terms are given)
    delta_y_1_T : ndarray (neqs x nobs)
        :math:`(y_1, \ldots, y_T) - (y_0, \ldots, y_{T-1})`
    y_lag1 : ndarray (neqs x nobs)
        (dimensions assuming no deterministic terms are given)
        :math:`(y_0, \ldots, y_{T-1})`

    Returns
    -------
    result : tuple
        A tuple of five ndarrays as well as eigenvalues and -vectors of a
        certain (matrix) product of some of the returned ndarrays.
        (See pp. 294-295 in [1]_ for more information on
        :math:`S_0, S_1, \lambda_i, \v_i` for
        :math:`i \in \{1, \dots, K\}`.)

    References
    ----------
    .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
    r$   r   Nr(   )
rk   r   r.   rc   rn   r   rh   linalgeigargsort)ry   rv   rw   rN   r   r   s00s01s10s11s11_s01_s11_r   lambdrJ   lambd_orders                   r4   _sijr     s   6 <?Dfg66FB
&RT

T
!C
&RT

T
!C
%C
&RT

T
!Cy~~Dvc4  H
)--
SXX-8
9
9CFEAA*U##DDbD)K+E	!!![.AS#tUA--r6   c                   (    e Zd ZdZ	 ddZd Zd ZdS )	CointRankResultsa  A class for holding the results from testing the cointegration rank.

    Parameters
    ----------
    rank : int (0 <= `rank` <= `neqs`)
        The rank to choose according to the Johansen cointegration rank
        test.
    neqs : int
        Number of variables in the time series.
    test_stats : array_like (`rank` + 1 if `rank` < `neqs` else `rank`)
        A one-dimensional array-like object containing the test statistics of
        the conducted tests.
    crit_vals : array_like (`rank` +1 if `rank` < `neqs` else `rank`)
        A one-dimensional array-like object containing the critical values
        corresponding to the entries in the `test_stats` argument.
    method : str, {``"trace"``, ``"maxeig"``}, default: ``"trace"``
        If ``"trace"``, the trace test statistic is used. If ``"maxeig"``, the
        maximum eigenvalue test statistic is used.
    signif : float, {0.1, 0.05, 0.01}, default: 0.05
        The test's significance level.
    trace皙?c                     || _         | _        fdt          t          |dz                       D             | _        || _        || _        | _        || _        d S )Nc                 *    g | ]}d k    rn|dz   S )r   r$    )r1   imethodneqss     r4   
<listcomp>z-CointRankResults.__init__.<locals>.<listcomp>  s;     
 
 
 g%%DD1q5
 
 
r6   r$   )	rankr   r8   minr_1
test_stats	crit_valsr   signif)selfr   r   r   r   r   r   s     `  ` r4   __init__zCointRankResults.__init__  s{     		
 
 
 
 
3tax..//
 
 
 %"r6   c                 D    g d}d j         dk    rdndz   d j        dz   dz   }t           j         j        dz
            } fd	t          |dz             D             }g d
dd}t          |          }d |d         D             |d<   t          ||||||          S )N)r_0r   ztest statisticzcritical valuez"Johansen cointegration test using r   zmaximum eigenvaluez test statistic with z.0%z significance levelr$   c                 ^    g | ])}|j         |         j        |         j        |         g*S r   )r   r   r   r1   r   r   s     r4   r   z,CointRankResults.summary.<locals>.<listcomp>  sF     
 
 
 T_Q/1BC
 
 
r6   )%sr   %#0.4gr   r)	data_fmtsdata_alignsc                     g | ]
}d |z   dz   S )z<td>z</td>r   )r1   r   s     r4   r   z,CointRankResults.summary.<locals>.<listcomp>  s.     &
 &
 &
%&FQJ &
 &
 &
r6   r   )rA   headerstitletxt_fmthtml_fmtltx_fmt)r   r   r   r   r   r8   dictr	   )r   r   r   	num_testsrA   data_fmthtml_data_fmts   `      r4   summaryzCointRankResults.summary  s   DDD0+00ww6JL7dk7778 $$ 	 	49q=11	
 
 
 
9q=))
 
 

 :99
 
 X&
 &
*7*D&
 &
 &
k" "
 
 
 	
r6   c                 N    |                                                                  S N)r   as_textr   s    r4   __str__zCointRankResults.__str__  s    ||~~%%'''r6   Nr   r   )__name__
__module____qualname____doc__r   r   r   r   r6   r4   r   r     sW         . IM   
 
 
<( ( ( ( (r6   r   r   r   c           	      0   |dvrt          d          |dvr:t          |          t          u r|dk    rt          d          t          d          g d}||vrt          d          t          | ||          }|d	k    r|j        n|j        }|d	k    r|j        n|j        }|                    |          }	| j	        d         }
d
}||
k     r ||         |||	f         k     rn|dz  }||
k      t          ||
|d|dz            |d|dz   |	f         ||          S )aO  Calculate the cointegration rank of a VECM.

    Parameters
    ----------
    endog : array_like (nobs_tot x neqs)
        The data with presample.
    det_order : int
        * -1 - no deterministic terms
        * 0 - constant term
        * 1 - linear trend
    k_ar_diff : int, nonnegative
        Number of lagged differences in the model.
    method : str, {``"trace"``, ``"maxeig"``}, default: ``"trace"``
        If ``"trace"``, the trace test statistic is used. If ``"maxeig"``, the
        maximum eigenvalue test statistic is used.
    signif : float, {0.1, 0.05, 0.01}, default: 0.05
        The test's significance level.

    Returns
    -------
    rank : :class:`CointRankResults`
        A :class:`CointRankResults` object containing the cointegration rank suggested
        by the test and allowing a summary to be printed.
    )r   maxeigzDThe method argument has to be either 'trace' or'maximum eigenvalue'.r(   r   r$   r$   zHA det_order greather than 1 is not supported.Use a value of -1, 0, or 1.zdet_order must be -1, 0, or 1.)g?r   g{Gz?z8Please choose a significance level from {0.1, 0.05,0.01}r   r   N)rm   typeintcoint_johansenlr1lr2cvtcvmindexrk   r   )rp   	det_order	k_ar_diffr   r   possible_signif_valuescoint_result	test_statr   signif_indexr   r   s               r4   select_coint_rankr     s   6 ((($
 
 	

 
""	??c!!i!mm.  
 =>>>...+++I
 
 	
 "%I>>L$*g$5$5  <;KI$*g$5$5  <;KI)//77L;q>D
C
**S>Ic<&78881HC	 ** )C!G))C!G)\)*  r6   c                   $ ddl }|dvr|                    dt          d           | j        d         dk    r|                    d	t          d           dd
lm$ $fd}d }t          j        |           } | j        \  }}|dk    rd}n|} || |          } t          j        | dd          }	t          |	|          }
|
|d         }
 ||
|          }
|	|d         }	 ||	|          }	 ||	|
          }| d| j        d         |z
           }|dd         } |||          }	 ||	|
          }t          j
        |j        |          |j        d         z  }t          j
        |j        |          |j        d         z  }t          j
        |j        |          |j        d         z  }t          j
        |t          j
        t          |          |j                            }t          |          }t          j                            t          j
        ||                    \  }}t          t          j                            t          j
        |j        t          j
        ||                                        }t          j
        ||          }t          j        |          }t          j        |          }||         }|dd|f         }|j        dk    }t          j        |          r(|t          j        |j        |         d                   z  }t          j        |          }t          j        |          }t          j        |df          }t          j        |df          }t          j        |          } |j        \  }!}"t/          d|          D ]}#t          j        | |z
            |#d         }|! t          j        |d          z  ||#<   |! t          j        d||#         z
            z  ||#<   t5          ||#z
  |          ||#ddf<   t7          ||#z
  |          ||#ddf<   |#||#<   t9          |||||||||	  	        S )u  
    Johansen cointegration test of the cointegration rank of a VECM

    Parameters
    ----------
    endog : array_like (nobs_tot x neqs)
        Data to test
    det_order : int
        * -1 - no deterministic terms
        * 0 - constant term
        * 1 - linear trend
    k_ar_diff : int, nonnegative
        Number of lagged differences in the model.

    Returns
    -------
    result : JohansenTestResult
        An object containing the test's results. The most important attributes
        of the result class are:

        * trace_stat and trace_stat_crit_vals
        * max_eig_stat and max_eig_stat_crit_vals

    Notes
    -----
    The implementation might change to make more use of the existing VECM
    framework.

    See Also
    --------
    statsmodels.tsa.vector_ar.vecm.select_coint_rank

    References
    ----------
    .. [1] Lütkepohl, H. 2005. New Introduction to Multiple Time Series
        Analysis. Springer.
    r   Nr   zBCritical values are only available for a det_order of -1, 0, or 1.r%   )category
stacklevelr$      zMCritical values are only available for time series with 12 variables at most.)OLSc                     |dk    r| S  | t          j        t          j        ddt          |                     |dz                                                       j        S )Nr(   r$   )r.   vanderlinspacer;   fitresid)rr   orderr   s     r4   detrendzcoint_johansen.<locals>.detrend  sU    B;;HC29R[QA77CCDDSUU	
r6   c           	          |j         dk    r| S | t          j        |t          j        t          j                            |          |                     z
  }|S Nr   )sizer.   rc   r   pinv)rr   xr   s      r4   r   zcoint_johansen.<locals>.resid  sG    6Q;;Hq"&!2!2A66777r6   r(   axis   )warningswarnr   rk   #statsmodels.regression.linear_modelr   r.   asarrayrl   r   rc   rn   r   r   r   choleskyr   flipudflatanysignro   r:   r8   logsumr   r   JohansenTestResult)%rp   r   r   r   r   r   rN   r   fdxzr0tlxrktskksk0r   sigtmpaudutempdtauindaindad
non_zero_dr   r   r   r   iotatjunkr   r   s%                                       @r4   r   r   [  sE   L OOO
""*	 	 	
 	
 	
 {1~)*	 	 	
 	
 	
 877777
 
 
 
 
   JuEJD$ 2~~GE9%%E		"	"	"Br9A	)**A1A	IJJB	QB
%A,,C	-%+a.9,-	.B	ABBB	QB
%A,,C
&

sy|
+C
&

sy|
+C
&

sy|
+C
&bfSXXsu--
.
.C
c((CY]]26#s++,,FBry!!"&rvc2"?"?@@AAD	D		B JrNNE9UD
4A
111d7A 1J	vj ,	RWQVJ'*+++ (4..C
(4..C
(D!9

C
(D!9

C74==DiGAt1d^^  fTAXqrr"bfS!nn$AbfQ1X&&&A$(I..AqqqD	$(I..AqqqD	Qc31c3S$GGGr6   c                   L   e Zd ZdZd 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ed             Zed             Zed             Zed             Zed             Zed             ZdS )r   u   
    Results class for Johansen's cointegration test

    Notes
    -----
    See p. 292 in [1]_ for r0t and rkt

    References
    ----------
    .. [1] Lütkepohl, H. 2005. New Introduction to Multiple Time Series
        Analysis. Springer.
    c
                     d| _         || _        || _        || _        || _        || _        || _        || _        || _        |	| _	        d S )Njohansen)
_meth_rkt_r0t_eig_evec_lr1_lr2_cvt_cvm_ind)
r   r   r   r   evecr   r   r   r   inds
             r4   r   zJohansenTestResult.__init__  sL    
			
							r6   c                     | j         S )zResiduals for :math:`Y_{-1}`)r  r   s    r4   r   zJohansenTestResult.rkt       yr6   c                     | j         S )zResiduals for :math:`\Delta Y`.)r  r   s    r4   r   zJohansenTestResult.r0t  r  r6   c                     | j         S )z&Eigenvalues of VECM coefficient matrix)r  r   s    r4   r   zJohansenTestResult.eig  r  r6   c                     | j         S )z'Eigenvectors of VECM coefficient matrix)r  r   s    r4   r  zJohansenTestResult.evec       zr6   c                     | j         S zTrace statisticr  r   s    r4   
trace_statzJohansenTestResult.trace_stat  r  r6   c                     | j         S r  r   r   s    r4   r   zJohansenTestResult.lr1  r  r6   c                     | j         S zMaximum eigenvalue statisticr  r   s    r4   max_eig_statzJohansenTestResult.max_eig_stat  r  r6   c                     | j         S r$  r%  r   s    r4   r   zJohansenTestResult.lr2!  r  r6   c                     | j         S z2Critical values (90%, 95%, 99%) of trace statisticr  r   s    r4   trace_stat_crit_valsz'JohansenTestResult.trace_stat_crit_vals&  r  r6   c                     | j         S r)  r*  r   s    r4   r   zJohansenTestResult.cvt+  r  r6   c                     | j         S z@Critical values (90%, 95%, 99%) of maximum eigenvalue statistic.r  r   s    r4   r   zJohansenTestResult.cvm0  r  r6   c                     | j         S r.  r/  r   s    r4   max_eig_stat_crit_valsz)JohansenTestResult.max_eig_stat_crit_vals5  r  r6   c                     | j         S )zOrder of eigenvalues)r  r   s    r4   r  zJohansenTestResult.ind:  r  r6   c                     | j         S )zTest method)r  r   s    r4   methzJohansenTestResult.meth?  r  r6   N)r   r   r   r   r   propertyr   r   r   r  r!  r   r&  r   r+  r   r   r1  r  r4  r   r6   r4   r   r     s        
 
 
   X   X   X   X   X   X   X   X   X   X   X   X   X   X  r6   r   c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d fd	Zdd	Zd
 Zed             Zed             Z	ed             Z
 xZS )VECMuX  
    Class representing a Vector Error Correction Model (VECM).

    A VECM(:math:`k_{ar}-1`) has the following form

    .. math:: \Delta y_t = \Pi y_{t-1} + \Gamma_1 \Delta y_{t-1} + \ldots + \Gamma_{k_{ar}-1} \Delta y_{t-k_{ar}+1} + u_t

    where

    .. math:: \Pi = \alpha \beta'

    as described in chapter 7 of [1]_.

    Parameters
    ----------
    endog : array_like (nobs_tot x neqs)
        2-d endogenous response variable.
    exog : ndarray (nobs_tot x neqs) or None
        Deterministic terms outside the cointegration relation.
    exog_coint : ndarray (nobs_tot x neqs) or None
        Deterministic terms inside the cointegration relation.
    dates : array_like of datetime, optional
        See :class:`statsmodels.tsa.base.tsa_model.TimeSeriesModel` for more
        information.
    freq : str, optional
        See :class:`statsmodels.tsa.base.tsa_model.TimeSeriesModel` for more
        information.
    missing : str, optional
        See :class:`statsmodels.base.model.Model` for more information.
    k_ar_diff : int
        Number of lagged differences in the model. Equals :math:`k_{ar} - 1` in
        the formula above.
    coint_rank : int
        Cointegration rank, equals the rank of the matrix :math:`\Pi` and the
        number of columns of :math:`\alpha` and :math:`\beta`.
    deterministic : str {``"n"``, ``"co"``, ``"ci"``, ``"lo"``, ``"li"``}
        * ``"n"`` - no deterministic terms
        * ``"co"`` - constant outside the cointegration relation
        * ``"ci"`` - constant within the cointegration relation
        * ``"lo"`` - linear trend outside the cointegration relation
        * ``"li"`` - linear trend within the cointegration relation

        Combinations of these are possible (e.g. ``"cili"`` or ``"colo"`` for
        linear trend with intercept). When using a constant term you have to
        choose whether you want to restrict it to the cointegration relation
        (i.e. ``"ci"``) or leave it unrestricted (i.e. ``"co"``). Do not use
        both ``"ci"`` and ``"co"``. The same applies for ``"li"`` and ``"lo"``
        when using a linear term. See the Notes-section for more information.
    seasons : int, default: 0
        Number of periods in a seasonal cycle. 0 means no seasons.
    first_season : int, default: 0
        Season of the first observation.

    Notes
    -----
    A VECM(:math:`k_{ar} - 1`) with deterministic terms has the form

    .. math::

       \Delta y_t = \alpha \begin{pmatrix}\beta' & \eta'\end{pmatrix} \begin{pmatrix}y_{t-1}\\D^{co}_{t-1}\end{pmatrix} + \Gamma_1 \Delta y_{t-1} + \dots + \Gamma_{k_{ar}-1} \Delta y_{t-k_{ar}+1} + C D_t + u_t.

    In :math:`D^{co}_{t-1}` we have the deterministic terms which are inside
    the cointegration relation (or restricted to the cointegration relation).
    :math:`\eta` is the corresponding estimator. To pass a deterministic term
    inside the cointegration relation, we can use the `exog_coint` argument.
    For the two special cases of an intercept and a linear trend there exists
    a simpler way to declare these terms: we can pass ``"ci"`` and ``"li"``
    respectively to the `deterministic` argument. So for an intercept inside
    the cointegration relation we can either pass ``"ci"`` as `deterministic`
    or `np.ones(len(data))` as `exog_coint` if `data` is passed as the
    `endog` argument. This ensures that :math:`D_{t-1}^{co} = 1` for all
    :math:`t`.

    We can also use deterministic terms outside the cointegration relation.
    These are defined in :math:`D_t` in the formula above with the
    corresponding estimators in the matrix :math:`C`. We specify such terms by
    passing them to the `exog` argument. For an intercept and/or linear trend
    we again have the possibility to use `deterministic` alternatively. For
    an intercept we pass ``"co"`` and for a linear trend we pass ``"lo"`` where
    the `o` stands for `outside`.

    The following table shows the five cases considered in [2]_. The last
    column indicates which string to pass to the `deterministic` argument for
    each of these cases.

    ====  ===============================  ===================================  =============
    Case  Intercept                        Slope of the linear trend            `deterministic`
    ====  ===============================  ===================================  =============
    I     0                                0                                    ``"n"``
    II    :math:`- \alpha \beta^T \mu`     0                                    ``"ci"``
    III   :math:`\neq 0`                   0                                    ``"co"``
    IV    :math:`\neq 0`                   :math:`- \alpha \beta^T \gamma`      ``"coli"``
    V     :math:`\neq 0`                   :math:`\neq 0`                       ``"colo"``
    ====  ===============================  ===================================  =============

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

    .. [2] Johansen, S. 1995. *Likelihood-Based Inference in Cointegrated *
           *Vector Autoregressive Models*. Oxford University Press.
    Nnoner$   r   r   c                    t                                          |||||           |+|j        d         |j        d         k    st          d          | j        j        dk    rt          d          | j        j        | _        || _        | j        j        d         | _	        |dz   | _
        || _        || _        |	| _        |
| _        || _        d| _        d S )N)missingr   z/exog_coint must have as many rows as enodg_tot!r$   zOnly gave one variable to VECMec)superr   rk   rm   rp   ndimrn   rr   rC   r   rO   r   
coint_rankr!   r"   r]   load_coef_repr)r   rp   rB   rC   datesfreqr:  r   r>  r!   r"   r]   	__class__s               r4   r   zVECM.__init__  s     	eT7CCC"$Q'5;q>99NOOO:?a=>>>$J$Q'	M	"$*("r6   mlc                 |    |dk    r|                                  S t          d                    |d                    )u  
        Estimates the parameters of a VECM.

        The estimation procedure is described on pp. 269-304 in [1]_.

        Parameters
        ----------
        method : str {"ml"}, default: "ml"
            Estimation method to use. "ml" stands for Maximum Likelihood.

        Returns
        -------
        est : :class:`VECMResults`

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        rC  z#{} not recognized, must be among {})_estimate_vecm_mlrm   format)r   r   s     r4   r   zVECM.fit  sD    & T>>))+++5<<VTJJ  r6   c                    t          | j        | j        | j        | j        | j        | j        | j                  \  }}}}|j        d         }t          |||          \  }}}}	}
}}|d d d | j
        f         j                            |
          j        }t          j        |          }t          j        |t          |d | j
                                     }|                    |                              t          |j                            |	                              |                              }||                    |j                                      |          z
                      |j                                      t          t          j        ||j                                      }||                    |j                                      |          z
  |                    |          z
  }|                    |j                  |z  }t!          | j        | j        | j        | j        | j
        ||||| j        | j        |||| | j        | j        j        | j                  S )Nr$   )	r!   r"   rv   rw   ry   modelnamesr@  r]   )r|   rr   rB   rC   r   r!   r"   r]   rk   r   r>  rn   rc   r.   real_if_closer   VECMResultsrO   endog_namesrA   r@  )r   rt   rv   rw   ry   rn   r   r   r   r   r   _rJ   
beta_tildealpha_tildegamma_tilder   sigma_u_tildes                     r4   rE  zVECM._estimate_vecm_ml  s8   .=FIONL/
 /
+{FG KN)-g{F)K)K&S#sD!Q,T_,,-/33D99<
%j11
VJJ7H7H,I(J(JKK
ggj))--
  %%))*5566
 
 ;??:<88<<VDDDS^^SRVGWY//0011 	 oojl++//778oog&&' 	
 ((1,FIOIO,L#")/*%
 
 
 	
r6   c                 |    g }d j         v r|d  j        D             z  } j        dk    r$| fdt          d j                  D             z  }d j         v r|d  j        D             z  } j        2| fd	t          d j        j        d         dz             D             z  }| fd
 j        D             z  }|S )u  
        Returns parameter names (for Gamma and deterministics) for the summary.

        Returns
        -------
        param_names : list of str
            Returns a list of parameter names for the lagged endogenous
            parameters which are called :math:`\Gamma` in [1]_
            (see chapter 6).
            If present in the model, also names for deterministic terms outside
            the cointegration relation are returned. They name the elements of
            the matrix C in [1]_ (p. 299).

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        r&   c                     g | ]}d |z  S )zconst.%sr   r1   r   s     r4   r   z,VECM._lagged_param_names.<locals>.<listcomp>5  s    EEEqJNEEEr6   r   c                 2    g | ]}j         D ]	}d ||fz  
S )zseason%d.%srL  )r1   sr   r   s      r4   r   z,VECM._lagged_param_names.<locals>.<listcomp>8  sL       )   A&   r6   r$   r)   c                     g | ]}d |z  S )zlin_trend.%sr   rT  s     r4   r   z,VECM._lagged_param_names.<locals>.<listcomp>?  s    III1NQ.IIIr6   Nc                 2    g | ]}j         D ]	}d ||fz  
S )z	exog%d.%srV  r1   exog_nor   r   s      r4   r   z,VECM._lagged_param_names.<locals>.<listcomp>B  sL       )   wl*   r6   c                 h    g | ].}t          j                  D ]}j        D ]}d |dz   ||fz  /S )z	L%d.%s.%sr$   )r8   r   rL  )r1   n2r   n1r   s       r4   r   z,VECM._lagged_param_names.<locals>.<listcomp>I  ss     
 
 
4>**
 
 &	
 
  1q5"b/)
 
 
 
 
r6   )r!   rL  r"   r8   rB   rk   r   param_namess   ` r4   _lagged_param_nameszVECM._lagged_param_names  s8   &  4%%%EED4DEEEEK<!    q$,//   K 4%%%II8HIIIIK9     $Q	(:Q(>??   K 	 
 
 
 
&
 
 
 	
 r6   c                 l     g } j         dk    rdS | fdt           j                  D             z  }|S )u  
        Returns parameter names (for alpha) for the summary.

        Returns
        -------
        param_names : list of str
            Returns a list of parameter names for the loading coefficients
            which are called :math:`\alpha` in [1]_ (see chapter 6).

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        r   Nc                 x    g | ]6}t          j                  D ]}j        d |dz   j        |         fz  z    7S )z%d.%sr$   )r8   r>  r?  rL  )r1   rz   r   r   s      r4   r   z/VECM._load_coef_param_names.<locals>.<listcomp>g  sh     
 
 
4?++
 
  'QUD4DQ4G,H"HH
 
 
 
r6   )r>  r8   r   r_  s   ` r4   _load_coef_param_nameszVECM._load_coef_param_namesR  s`     ?a4 	 
 
 
 
49%%
 
 
 	
 r6   c                 t    g }| fdt           j                  D             z  }d j        v r#| fdt           j                  D             z  }d j        v r#| fdt           j                  D             z  } j        2| fdt          d j        j        d         dz             D             z  }|S )	aZ  
        Returns parameter names (for beta and deterministics) for the summary.

        Returns
        -------
        param_names : list of str
            Returns a list of parameter names for the cointegration matrix
            as well as deterministic terms inside the cointegration relation
            (if present in the model).
        c                 n    g | ]1}t          j                  D ]}d j        z   dz   |dz   |dz   fz  2S )zbeta.%d.%dr$   )r8   r   r?  )r1   r   rz   r   s      r4   r   z+VECM._coint_param_names.<locals>.<listcomp>~  sh     
 
 
49%%
 
  $--4QAF
 
 
 
r6   r'   c                 6    g | ]}d j         z   d|dz   z  z   S )zconst.rg  r$   r?  r   s     r4   r   z+VECM._coint_param_names.<locals>.<listcomp>  s>        4..Q?  r6   r*   c                 6    g | ]}d j         z   d|dz   z  z   S )z
lin_trend.rg  r$   ri  r   s     r4   r   z+VECM._coint_param_names.<locals>.<listcomp>  s>        t22TQU^C  r6   Nc                 R    g | ]#}t          j                  D ]}d |dz   |fz  $S )zexog_coint%d.%sr$   )r8   r   rZ  s      r4   r   z+VECM._coint_param_names.<locals>.<listcomp>  sX       ty))   "QUG$44   r6   r$   )r8   r>  r!   rC   rk   r_  s   ` r4   _coint_param_nameszVECM._coint_param_nameso  s3     
 
 
 
4?++
 
 
 	
 4%%%    t//   K
 4%%%    t//   K
 ?&    $Q(=a(@1(DEE   K r6   )
NNNNr8  r$   r$   r   r   r   )rC  )r   r   r   r   r   r   rE  r5  ra  rd  rl  __classcell__)rB  s   @r4   r7  r7  E  s        e eT # # # # # #B   44
 4
 4
l 1 1 X1f   X8 ( ( X( ( ( ( (r6   r7  c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 d6d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ed             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ed             Zed             Zed             Zed             Zd Zd7dZd7dZd7dZd7d Zd7d!Z ed"             Z!ed#             Z"d8d%Z#ed&             Z$d9d'Z%d:d)Z&	 d;d+Z'd<d,Z(d7d-Z)d8d.Z*ed/             Z+ed0             Z,d7d1Z-d=d3Z.d>d4Z/d7d5Z0dS )?rK  u'  Class for holding estimation related results of a vector error
    correction model (VECM).

    Parameters
    ----------
    endog : ndarray (neqs x nobs_tot)
        Array of observations.
    exog : ndarray (nobs_tot x neqs) or `None`
        Deterministic terms outside the cointegration relation.
    exog_coint : ndarray (nobs_tot x neqs) or `None`
        Deterministic terms inside the cointegration relation.
    k_ar : int, >= 1
        Lags in the VAR representation. This implies that the number of lags in
        the VEC representation (=lagged differences) equals :math:`k_{ar} - 1`.
    coint_rank : int, 0 <= `coint_rank` <= neqs
        Cointegration rank, equals the rank of the matrix :math:`\Pi` and the
        number of columns of :math:`\alpha` and :math:`\beta`.
    alpha : ndarray (neqs x `coint_rank`)
        Estimate for the parameter :math:`\alpha` of a VECM.
    beta : ndarray (neqs x `coint_rank`)
        Estimate for the parameter :math:`\beta` of a VECM.
    gamma : ndarray (neqs x neqs*(k_ar-1))
        Array containing the estimates of the :math:`k_{ar}-1` parameter
        matrices :math:`\Gamma_1, \dots, \Gamma_{k_{ar}-1}` of a
        VECM(:math:`k_{ar}-1`). The submatrices are stacked horizontally from
        left to right.
    sigma_u : ndarray (neqs x neqs)
        Estimate of white noise process covariance matrix :math:`\Sigma_u`.
    deterministic : str {``"n"``, ``"co"``, ``"ci"``, ``"lo"``, ``"li"``}
        * ``"n"`` - no deterministic terms
        * ``"co"`` - constant outside the cointegration relation
        * ``"ci"`` - constant within the cointegration relation
        * ``"lo"`` - linear trend outside the cointegration relation
        * ``"li"`` - linear trend within the cointegration relation

        Combinations of these are possible (e.g. ``"cili"`` or ``"colo"`` for
        linear trend with intercept). See the docstring of the
        :class:`VECM`-class for more information.
    seasons : int, default: 0
        Number of periods in a seasonal cycle. 0 means no seasons.
    first_season : int, default: 0
        Season of the first observation.
    delta_y_1_T : ndarray or `None`, default: `None`
        Auxiliary array for internal computations. It will be calculated if
        not given as parameter.
    y_lag1 : ndarray or `None`, default: `None`
        Auxiliary array for internal computations. It will be calculated if
        not given as parameter.
    delta_x : ndarray or `None`, default: `None`
        Auxiliary array for internal computations. It will be calculated if
        not given as parameter.
    model : :class:`VECM`
        An instance of the :class:`VECM`-class.
    names : list of str
        Each str in the list represents the name of a variable of the time
        series.
    dates : array_like
        For example a DatetimeIndex of length nobs_tot.

    Attributes
    ----------
    nobs : int
        Number of observations (excluding the presample).
    model : see Parameters
    y_all : see `endog` in Parameters
    exog : see Parameters
    exog_coint : see Parameters
    names : see Parameters
    dates : see Parameters
    neqs : int
        Number of variables in the time series.
    k_ar : see Parameters
    deterministic : see Parameters
    seasons : see Parameters
    first_season : see Parameters
    alpha : see Parameters
    beta : see Parameters
    gamma : see Parameters
    sigma_u : see Parameters
    det_coef_coint : ndarray (#(determinist. terms inside the coint. rel.) x `coint_rank`)
        Estimated coefficients for the all deterministic terms inside the
        cointegration relation.
    const_coint : ndarray (1 x `coint_rank`)
        If there is a constant deterministic term inside the cointegration
        relation, then `const_coint` is the first row of `det_coef_coint`.
        Otherwise it's an ndarray of zeros.
    lin_trend_coint : ndarray (1 x `coint_rank`)
        If there is a linear deterministic term inside the cointegration
        relation, then `lin_trend_coint` contains the corresponding estimated
        coefficients. As such it represents the corresponding row of
        `det_coef_coint`. If there is no linear deterministic term inside
        the cointegration relation, then `lin_trend_coint` is an ndarray of
        zeros.
    exog_coint_coefs : ndarray (exog_coint.shape[1] x `coint_rank`) or `None`
        If deterministic terms inside the cointegration relation are passed via
        the `exog_coint` parameter, then `exog_coint_coefs` contains the
        corresponding estimated coefficients. As such `exog_coint_coefs`
        represents the last rows of `det_coef_coint`.
        If no deterministic terms were passed via the `exog_coint` parameter,
        this attribute is `None`.
    det_coef : ndarray (neqs x #(deterministic terms outside the coint. rel.))
        Estimated coefficients for the all deterministic terms outside the
        cointegration relation.
    const : ndarray (neqs x 1) or (neqs x 0)
        If a constant deterministic term outside the cointegration is specified
        within the deterministic parameter, then `const` is the first column
        of `det_coef_coint`. Otherwise it's an ndarray of size zero.
    seasonal : ndarray (neqs x seasons)
        If the `seasons` parameter is > 0, then seasonal contains the
        estimated coefficients corresponding to the seasonal terms. Otherwise
        it's an ndarray of size zero.
    lin_trend : ndarray (neqs x 1) or (neqs x 0)
        If a linear deterministic term outside the cointegration is specified
        within the deterministic parameter, then `lin_trend` contains the
        corresponding estimated coefficients. As such it represents the
        corresponding column of `det_coef_coint`. If there is no linear
        deterministic term outside the cointegration relation, then
        `lin_trend` is an ndarray of size zero.
    exog_coefs : ndarray (neqs x exog_coefs.shape[1])
        If deterministic terms outside the cointegration relation are passed
        via the `exog` parameter, then `exog_coefs` contains the
        corresponding estimated coefficients. As such `exog_coefs` represents
        the last columns of `det_coef`.
        If no deterministic terms were passed via the `exog` parameter, this
        attribute is an ndarray of size zero.
    _delta_y_1_T : see delta_y_1_T in Parameters
    _y_lag1 : see y_lag1 in Parameters
    _delta_x : see delta_x in Parameters
    coint_rank : int
        Cointegration rank, equals the rank of the matrix :math:`\Pi` and the
        number of columns of :math:`\alpha` and :math:`\beta`.
    llf : float
        The model's log-likelihood.
    cov_params : ndarray (d x d)
        Covariance matrix of the parameters. The number of rows and columns, d
        (used in the dimension specification of this argument),
        is equal to neqs * (neqs+num_det_coef_coint + neqs*(k_ar-1)+number of
        deterministic dummy variables outside the cointegration relation). For
        the case with no deterministic terms this matrix is defined on p. 287
        in [1]_ as :math:`\Sigma_{co}` and its relationship to the
        ML-estimators can be seen in eq. (7.2.21) on p. 296 in [1]_.
    cov_params_wo_det : ndarray
        Covariance matrix of the parameters
        :math:`\tilde{\Pi}, \tilde{\Gamma}` where
        :math:`\tilde{\Pi} = \tilde{\alpha} \tilde{\beta'}`.
        Equals `cov_params` without the rows and columns related to
        deterministic terms. This matrix is defined as :math:`\Sigma_{co}` on
        p. 287 in [1]_.
    stderr_params : ndarray (d)
        Array containing the standard errors of :math:`\Pi`, :math:`\Gamma`,
        and estimated parameters related to deterministic terms.
    stderr_coint : ndarray (neqs+num_det_coef_coint x `coint_rank`)
        Array containing the standard errors of :math:`\beta` and estimated
        parameters related to deterministic terms inside the cointegration
        relation.
    stderr_alpha :  ndarray (neqs x `coint_rank`)
        The standard errors of :math:`\alpha`.
    stderr_beta : ndarray (neqs x `coint_rank`)
        The standard errors of :math:`\beta`.
    stderr_det_coef_coint : ndarray (num_det_coef_coint x `coint_rank`)
        The standard errors of estimated the parameters related to
        deterministic terms inside the cointegration relation.
    stderr_gamma : ndarray (neqs x neqs*(k_ar-1))
        The standard errors of :math:`\Gamma_1, \ldots, \Gamma_{k_{ar}-1}`.
    stderr_det_coef : ndarray (neqs x det. terms outside the coint. relation)
        The standard errors of estimated the parameters related to
        deterministic terms outside the cointegration relation.
    tvalues_alpha : ndarray (neqs x `coint_rank`)
    tvalues_beta : ndarray (neqs x `coint_rank`)
    tvalues_det_coef_coint : ndarray (num_det_coef_coint x `coint_rank`)
    tvalues_gamma : ndarray (neqs x neqs*(k_ar-1))
    tvalues_det_coef : ndarray (neqs x det. terms outside the coint. relation)
    pvalues_alpha : ndarray (neqs x `coint_rank`)
    pvalues_beta : ndarray (neqs x `coint_rank`)
    pvalues_det_coef_coint : ndarray (num_det_coef_coint x `coint_rank`)
    pvalues_gamma : ndarray (neqs x neqs*(k_ar-1))
    pvalues_det_coef : ndarray (neqs x det. terms outside the coint. relation)
    var_rep : (k_ar x neqs x neqs)
        KxK parameter matrices :math:`A_i` of the corresponding VAR
        representation. If the return value is assigned to a variable ``A``,
        these matrices can be accessed via ``A[i]`` for
        :math:`i=0, \ldots, k_{ar}-1`.
    cov_var_repr : ndarray (neqs**2 * k_ar x neqs**2 * k_ar)
        This matrix is called :math:`\Sigma^{co}_{\alpha}` on p. 289 in [1]_.
        It is needed e.g. for impulse-response-analysis.
    fittedvalues : ndarray (nobs x neqs)
        The predicted in-sample values of the models' endogenous variables.
    resid : ndarray (nobs x neqs)
        The residuals.

    References
    ----------
    .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
    r   r   Nc                    || _         || _        || _        || _        || _        || _        |j        d         | _        || _        t          |
d          }
|
| _
        || _        || _        || _        |j        t          j        k    r>t          j        t          j        |          dk              rt          j        |          }|j        t          j        k    r>t          j        t          j        |          dk              rt          j        |          }|j        t          j        k    r>t          j        t          j        |          dk              rt          j        |          }|| _        t          j        || j        g          \  | _        | _        t          j        || j        | j        dz
  z  g          \  | _        | _        d|
v r| j        d dd d f         | _        n,t          j        |                              d          | _        d|
v r$d|
v rdnd}| j        ||dz   d d f         | _        n-t          j        |                              dd          | _        | j        "d|
v d|
v z   }| j        |d d d f         | _        nd | _        d|
v rdnd}||r|dz
  ndz   }d	|
v r|dz   }n|}t          j        | j        |||g          \  | _         | _!        | _"        | _#        |	| _$        ||||| _%        || _&        || _'        n,tQ          || j        ||
|          \  }| _%        | _&        | _'        | j&        j        d         | _)        d S )
Nr   r!   r$   r'   )r$   r(   r*   r(   r&   r)   )*rH  y_allrB   rC   rI  r@  rk   r   rO   r   r!   r"   r]   r>  dtyper.   
complex128allimagrJ  alphavsplitbetadet_coef_cointhsplitgammadet_coefconst_cointro   r<   lin_trend_cointexog_coint_coefsconstseasonal	lin_trend
exog_coefssigma_u_delta_y_1_T_y_lag1_delta_xr|   rN   )r   rp   rB   rC   rO   r>  ru  rw  rz  r  r!   r"   r]   rv   rw   ry   rH  rI  r@  startsplit_const_seasonsplit_season_linsplit_lin_exog_y_1_Ts                           r4   r   zVECMResults.__init___  sc   * 

	$

KN		#M?CC*($;"-''BF275>>Q3F,G,G'$U++E:&&26"'$--12D+E+E&#D))D;"-''BF275>>Q3F,G,G'$U++E
)+4$))E)E&	4&$&IDIQ/0%
 %
!
DM =  #22A2qqq59D!x
33;;GDDD=  ..AAAE#'#6uuqy7H!!!7K#LD  #%8J#7#7#?#?2#F#FD ?&]*t}/DEE$($7	$BD!!$(D!"&-"7"7QQQ-$+Wq[[!
 =  -1NN-NEGYM!1>BF
 F
B
DM4>4?
  #' +D!DL#DMM  ty$wOO!L&q)			r6   c           	         | j         }| j        }| j        }t          | j        | j        | j                  \  }}}}}}}| |z  t          j        dt          j	        z            z  dz  |t          j        t          j
                            |                    t          t          j        d|z
            d|                   z   z  dz  z
  ||z  dz  z
  S )z3
        Compute the VECM's loglikelihood.
        r%   r$   N)r   rN   r>  r   r  r  r  r.   r   pir   detr   )r   rs   rn   r   r   rM  r   s          r4   llfzVECMResults.llf  s    
 IIO$(M4,dl%
 %
!Q1a BFRVAI&&&*26")--,,--BF1u94E4Ebqb4I0J0JJKaOP!eai	
r6   c                     | j         }t          | j                  }t          j                            |          }d|t          j        ||          z  |j        z  z  S )Nr%   )r  r   r   r.   r   r   kronrn   )r   r  r  d_K_pluss       r4   
_cov_sigmazVECMResults._cov_sigma  sN    ,ty))9>>!$$Hrww8888:EFFr6   c                 Z   | j         }| j        j        dk    rt          || j        f          }| j        }d|v d|v z   }|| j        r
| j        dz
  ndz  }| j        || j        j        d         z  }t          j	        
                    |t          j        | j        | j        dz
  z  |z                       }| j        }|j                            |          }|                    |j                  }|                    | j        j                  }|j        }	| j                            | j        j                  }
t          j        ||g|	|
gg          j        }|                    t+          |                                        |j                  }t          j        || j                  S )Nr   r&   r)   r$   )rw  rx  r   r   r!   r"   rB   rk   scipyr   
block_diagr.   r~   r   rO   r  rn   rc   r  bmatAr   r  r  )r   rw  r   num_detb_idrw   b_yomega11omega12omega21omega22omegamat1s                r4   cov_params_defaultzVECMResults.cov_params_default  sy    y#a''4!4566D2:$"*-<DL1$$1<9 tyq))G|&&"+di49q=9GCDD
 
 fjj  ''#%..''$-/**)-##DMO44'7+gw-?@AACxxE

##''//wtT\***r6   c                    | j         dz  }|| j         | j        j        d         z  z   }t          j        ||          }| j        }t          |          }t          j        || j        j        z
  |          }t          j	        ||          }t          j
        |j        t                    }d||<   d|d d |f<   |                    d          d         }	||                             |	|	f          S )Nr%   r   rq  Fr   )r   rx  rk   r.   r=   r  r;   r{  r   union1dr:   boolr   r<   )
r   start_iend_i	to_drop_icovcov_size	to_drop_oto_dropmaskcov_size_news
             r4   cov_params_wo_detzVECMResults.cov_params_wo_det  s     )q.$)d&9&?&BBBIgu--	 %s88Ih);;XFF	*Y	22wsy---W QQQZxxQx''*4y  ,!=>>>r6   c                 X    t          j        t          j        | j                            S r   )r.   rb   diagr  r   s    r4   stderr_paramszVECMResults.stderr_params  s    wrwt677888r6   c           	      J   | j         }t          | j        | j        | j                  \  }}||d         }|j        dk    rt          j        ||f          S t          |	                    |j
                            }t          j        |j
        t          j        |                    }| j        j        d         }t          j        t          j        | j        |z
  |z             t          | j        j
        t          | j                  z  | j        z                      }t          j        ||f          }t          j        t          j        |	                    |                              }	|	                    | j        |z
  |z   |fd          }
t+          ||
f          S )u  
        Standard errors of beta and deterministic terms inside the
        cointegration relation.

        Notes
        -----
        See p. 297 in [1]_. Using the rule

        .. math::

           vec(B R) = (B' \otimes I) vec(R)

        for two matrices B and R which are compatible for multiplication.
        This is rule (3) on p. 662 in [1]_.

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        Nr   Fr   )r>  r   r  r  r  r   r.   ro   r   rc   rn   r  r~   rx  rk   r   ru  r  rb   r  r<   r   )r   r   rM  r   r12r  r  mat2
first_rowslast_rows_1d	last_rowss              r4   stderr_cointzVECMResults.stderr_coint  sX   * OD-t|T]KK2f8q==8QF###37735>>""wtvr{1~~..!'*wK	A+,,
s4<0004:=>>
 
 Xq!f%%
wrwtxx~~6677 (($)a-#*=q)A(MM	z9-...r6   c                 v    | j         d | j        j                 }|                    | j        j        d          S )Nr  r  )r  ru  r   r<   rk   r   ret_1dims     r4   stderr_alphazVECMResults.stderr_alpha2  s7    %&7
&78
 0<<<r6   c                     | j         d | j        j        d                  }|                    | j        j        d          S Nr   r  r  )r  rw  rk   r<   r  s     r4   stderr_betazVECMResults.stderr_beta7  s;    $%9tyq'9%9:	s;;;r6   c                     | j         j        dk    r| j         S | j        | j        j        d         d          }|                    | j         j        d          S r  )rx  r   r  rw  rk   r<   r  s     r4   stderr_det_coef_cointz!VECMResults.stderr_det_coef_coint<  sW    #q((&&$TY_Q%7%9%9: 3 9EEEr6   c                     | j         j        d         | j        j        d         | j        j        d         z   z  }| j        ||| j        j        z            }|                    | j        j        d          S r  )ru  rk   rw  rx  r  rz  r   r<   )r   r  r  s      r4   stderr_gammazVECMResults.stderr_gammaC  sm    
 #IOA!4!:1!==
 %eedjo.E&EF
 0<<<r6   c                     | j         j        dk    r| j         S | j        | j         j         d          }|                    | j         j        d          S r  )r{  r   r  r<   rk   )r   	ret1_1dims     r4   stderr_det_coefzVECMResults.stderr_det_coefK  sS    =""= &(:':'<'<=	  !4C @@@r6   c                      | j         | j        z  S r   )ru  r  r   s    r4   tvalues_alphazVECMResults.tvalues_alphaS      zD---r6   c                     | j         }t          j        ||f          }| j        |d          | j        |d          z  }t          ||f          S r   )r>  r.   ro   rw  r  r   )r   r   r  r  s       r4   tvalues_betazVECMResults.tvalues_betaW  sO    OXq!f%%
IabbMD$4QRR$88	z9-...r6   c                 N    | j         j        dk    r| j         S | j         | j        z  S r   )rx  r   r  r   s    r4   tvalues_det_coef_cointz"VECMResults.tvalues_det_coef_coint^  s-    #q((&&"T%???r6   c                      | j         | j        z  S r   )rz  r  r   s    r4   tvalues_gammazVECMResults.tvalues_gammad  r  r6   c                 N    | j         j        dk    r| j         S | j         | j        z  S r   )r{  r   r  r   s    r4   tvalues_det_coefzVECMResults.tvalues_det_coefh  s*    =""= }t333r6   c                 z    dt           j        j                            t	          | j                            z
  dz  S Nr$   r%   )r  statsnormcdfabsr  r   s    r4   pvalues_alphazVECMResults.pvalues_alphao  0    EK$((T-?)@)@AAAQFFr6   c                     t          j        | j        | j        f          }| j        | j        d          }dt          j        j                            t          |                    z
  dz  }t          ||f          S r  )
r.   ro   r>  r  r  r  r  r  r  r   )r   r  	tval_lastr  s       r4   pvalues_betazVECMResults.pvalues_betas  sj    Xt@AA
%do&7&78	)--c)nn===B	z9-...r6   c                     | j         j        dk    r| j         S dt          j        j                            t          | j                            z
  dz  S Nr   r$   r%   )rx  r   r  r  r  r  r  r  r   s    r4   pvalues_det_coef_cointz"VECMResults.pvalues_det_coef_cointz  sJ    #q((&&EK$((T-H)I)IJJJaOOr6   c                 z    dt           j        j                            t	          | j                            z
  dz  S r  )r  r  r  r  r  r  r   s    r4   pvalues_gammazVECMResults.pvalues_gamma  r  r6   c                     | j         j        dk    r| j         S dt          j        j                            t          | j                            z
  dz  S r  )r{  r   r  r  r  r  r  r  r   s    r4   pvalues_det_coefzVECMResults.pvalues_det_coef  sH    =""= EK$((T-B)C)CDDDIIr6   c                 (   t          j        |j        dt          fdt          fg          }|t          j        j                            d|dz  z
            |z  z
  |d<   |t          j        j                            d|dz  z
            |z  z   |d<   |S )Nlowerupperr  r$   r%   )r.   ro   rk   floatr  r  r  ppf)r   eststderrru  
struct_arrs        r4   _make_conf_intzVECMResults._make_conf_int  s    XIw.%0@A
 
 

 %+"&&q519}55>> 	7 %+"&&q519}55>> 	7 r6   r   c                 D    |                      | j        | j        |          S r   )r  ru  r  r   ru  s     r4   conf_int_alphazVECMResults.conf_int_alpha      ""4:t/@%HHHr6   c                 D    |                      | j        | j        |          S r   )r  rw  r  r  s     r4   conf_int_betazVECMResults.conf_int_beta  s    ""49d.>FFFr6   c                 D    |                      | j        | j        |          S r   )r  rx  r  r  s     r4   conf_int_det_coef_cointz#VECMResults.conf_int_det_coef_coint  s'    ""!;U
 
 	
r6   c                 D    |                      | j        | j        |          S r   )r  rz  r  r  s     r4   conf_int_gammazVECMResults.conf_int_gamma  r  r6   c                 D    |                      | j        | j        |          S r   )r  r{  r  r  s     r4   conf_int_det_coefzVECMResults.conf_int_det_coef  s    ""4=$2FNNNr6   c                    | j                             | j        j                  }| j        }| j        }t          j        | j        ||f          }|t          j	        |          z   |d<   | j        j
        dk    r|dxx         |d d d |f         z  cc<   |d d || j        dz
  z  d f          || j        dz
  <   t          d| j        dz
            D ]4}|d d ||z  ||dz   z  f         |d d ||dz
  z  ||z  f         z
  ||<   5|S )Nr   r%   r$   )ru  rc   rw  rn   rz  r   r.   ro   rO   r~   r   r8   )r   r  rz  rs   r  r   s         r4   var_repzVECMResults.var_rep  s6   Z^^DIK((
IHdiA&''BKNN"!:?QaDDDE!!!RaR%L DDD %aaadi!m)<)>)>&> ??Adi!m1di!m,,  !!!QUQ!a%[001AAAqAE{QU2234 ! r6   c           	         | j         dz
  dk    r| j        S t          j        | j        dz  | j         z  | j        dz  | j         z  f          }t          j        | j        dz            }t          ||f          |d| j        dz  dd| j        dz  z  f<   t          d| j                   D ]l}| j        dz  |dz
  | j        dz  z  z   }| j        dz  |dz
  | j        dz  z  z   }t          | |f          |||| j        dz  z   ||d| j        dz  z  z   f<   m| || j        dz   d| j        dz   df<   |}|| j        z  |j        z  S )a\  
        Gives the covariance matrix of the corresponding VAR-representation.

        More precisely, the covariance matrix of the vector consisting of the
        columns of the corresponding VAR coefficient matrices (i.e.
        vec(self.var_rep)).

        Returns
        -------
        cov : array (neqs**2 * k_ar x neqs**2 * k_ar)
        r$   r   r%   N)	rO   r  r.   ro   r   r~   r   r8   rn   )r   vecm_var_transformationeyer   	start_row	start_colvvts          r4   cov_var_reprzVECMResults.cov_var_repr  s   > 9q=A))"$(Y!^di'a$))CD#
 #
 k$)q.)) C: 	 di1n2DIN 222	
 q$)$$ 	$ 	$A	Q!a%49>)AAI	Q!a%49>)AAI c{## $I	Q66IDIN(:::< 
 JMa 1 1DIN?3D3D DE%T++ce33r6   
   c                 ,    t          | j        |          S r   )r   r  )r   maxns     r4   r   zVECMResults.ma_rep  s    dlD)))r6   c                 J    t           j                            | j                  S r   )r.   r   r   r  r   s    r4   _chol_sigma_uzVECMResults._chol_sigma_u  s    y!!$,///r6   c                 $    t          | ||          S )a/  Compute orthogonalized MA coefficient matrices.

        For this purpose a matrix  P is used which fulfills
        :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 (neqs x neqs), optional
            Matrix such that :math:`\Sigma_u = PP'`. Defaults to Cholesky
            decomposition.

        Returns
        -------
        coefs : ndarray (maxn x neqs x neqs)
        )r   )r   r  Ps      r4   r   zVECMResults.orth_ma_rep  s    & 4q)))r6      c           	         | j         |t          d          | j         |t          d          | |j        d         |k     rt          d          | j        |t          d          | j        |t          d          |#|j        d         |dz
  k     rt          d	          | j        j        | j         d         }g }g }t          j        |          }| j	        | j        z   }	| j
        j        dk    r4|                    |           |                    | j
        j                   | j        dk    r]| j        |	z   | j        z  }
t          | j        ||
d
          }|                    |           |                    | j        j                   t#          | j	        | j                  }|d         dz   t          j        |          z   }| j        j        dk    r4|                    |           |                    | j        j                   |<|                    |d|                    |                    | j        j                   d| j        v rQ|                    |           |                    | j                            | j        j                  j                   t#          | j	        | j        d
          }|d         dz   t          j        |          z   }d| j        v rQ|                    |           |                    | j                            | j        j                  j                   ||j        dk    r|dddf         }t          j        | j        dd         |d|dz
           f          }|                    |           |                    | j                            | j        j                  j                   |g k    rt          j        |          nd}|g k    rt          j        |          }nd}| t=          || j        || j         |||          S tC          || j        |||          S )a[  
        Calculate future values of the time series.

        Parameters
        ----------
        steps : int
            Prediction horizon.
        alpha : float, 0 < `alpha` < 1 or None
            If None, compute point forecast only.
            If float, compute confidence intervals too. In this case the
            argument stands for the confidence level.
        exog : ndarray (steps x self.exog.shape[1])
            If self.exog is not None, then information about the future values
            of exog have to be passed via this parameter. The ndarray may be
            larger in it's first dimension. In this case only the first steps
            rows will be considered.

        Returns
        -------
        forecast - ndarray (steps x neqs) or three ndarrays
            In case of a point forecast: each row of the returned ndarray
            represents the forecast of the neqs variables for a specific
            period. The first row (index [0]) is the forecast for the next
            period, the last row (index [steps-1]) is the steps-periods-ahead-
            forecast.
        Nzaexog_fc is None: Please pass the future values of the VECM's exog terms via the exog_fc argument!zxThis VECMResult-instance's exog attribute is None. Please do not pass a non-None value as the method's exog_fc-argument.r   zMThe argument exog_fc must have at least steps elements in its first dimensionzsexog_coint_fc is None: Please pass the future values of the VECM's exog_coint terms via the exog_coint_fc argument!zThis VECMResult-instance's exog_coint attribute is None. Please do not pass a non-None value as the method's exog_coint_fc-argument.r$   zSThe argument exog_coint_fc must have at least steps elements in its first dimensionTr(   r'   rj   r*   )ru  rB   )"rB   rm   rk   rC   rp  rn   rO   r.   r:   rN   r  r   r9   r"   r]   r   r  rR   r=   r  r  r!   ru  rc   r|  r}  r=  r   r~  r[   r   r  r  r   )r   stepsru  exog_fcexog_coint_fclast_observationsrB   trend_coefs
exog_constr\   first_future_seasonexog_seasonalexog_lin_trendexog_lin_trend_coints                 r4   predictzVECMResults.predict  s   6 9 W_  
 9!4-  
 7=#3e#;#;2  
 ?&=+@*  
 ?"}'@7  
 $)<Q)?%!))K)K8  
 !JL$)6 WU^^
9ty(:?QKK
###tz|,,,<!#'#4x#?4<"O,e%8$ M KK&&&t}///&ty$)<<'+a/")E2B2BB>""KK'''t~/000KK(((t0111 4%%%KK
###tz~~d.>.@AACDDD,TY	NNN3B7!;bi>N>NN4%%%KK,---tz~~d.B.DEEGHHH$!Q&& -aaag 6I%}[uqy['AB M KK&&&tz~~d.C.EFFHIII )-

rt$$$")K00KKK $!    !4<eT  r6   Tc           
          |                      ||          \  }}}| j        j        }||| j        d         n
|| d         }t	          j        ||||| j        |ddi           dS )a  
        Plot the forecast.

        Parameters
        ----------
        steps : int
            Prediction horizon.
        alpha : float, 0 < `alpha` < 1
            The confidence level.
        plot_conf_int : bool, default: True
            If True, plot bounds of confidence intervals.
        n_last_obs : int or None, default: None
            If int, restrict plotted history to n_last_obs observations.
            If None, include the whole history in the plot.
        ru  Nlocz
lower left)rI  plot_stderrlegend_options)r  rp  rn   rO   plotplot_var_forcrI  )	r   r  ru  plot_conf_int
n_last_obsmidr  r  rr   s	            r4   plot_forecastzVECMResults.plot_forecast  s    $ !LLeL<<UEJL(0AdikkNNao*%!<0	
 	
 	
 	
 	
 	
r6   c                 &	   "# d|cxk     rdk     sn t          d          t          t          f"t          |"          r|g}t	          "fd|D                       st          d           fd|D             } fd|D             #|Yt          |"          r|g}t	          "fd	|D                       st          d
           fd|D             } fd|D             }|.#fdt           j                  D             } fd|D             } j         j         j	        dz
   j
        dz   f\  }}}}t           j         j         j	         j
        z    j        d j         j                  }	t#          |j        |	                              |d          }
t)          |          t)          |          z  |dz
  z  }t+           j         j                  } j        | j        j        d         z  } j        | j        j        d         z  }t/          j        |||z  |dz  |dz
  z  z   ft2                    }||z  }d}t          |dz
            D ]*}|D ]%}#D ] }d||||z   ||z  z   |dz  |z  z   f<   |dz  }!&+t/          j        |t7          |
j        d|          j                            }g }|	#|                    |	| d         j                   t/          j        ||z  |f          }t          |dz
            D ];}|dd|dz
  |z
  d|z
  f         |ddd| f         z
  |||z  |dz   |z  ddf<   <|ddd| f         || dddf<   |                    |           t/          j        |          }t/          j        ||j                  }t?          |          d||dz
  z  |z   d||dz
  z  |z   f         }|
j         |||z  z
  |z
  z  |z  }|t/          j!        ||          z  }t?          ||z  |j        z            }||j        |z  |z  z  }||z  }|||
j"        z  f}tG          j$        j%        | }|&                    |          } |'                    d|z
            }!tQ          ||||!| ||dd	  	        S )u  
        Test for Granger-causality.

        The concept of Granger-causality is described in chapter 7.6.3 of [1]_.
        Test |H0|: "The variables in `causing` do not Granger-cause those in
        `caused`" against  |H1|: "`causing` is Granger-causal for
        `caused`".

        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` (the remaining variables of the system).
        signif : float, 0 < `signif` < 1, default 5 %
            Significance level for computing critical values for test,
            defaulting to standard 0.05 level.

        Returns
        -------
        results : :class:`statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults`

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

        .. |H0| replace:: H\ :sub:`0`

        .. |H1| replace:: H\ :sub:`1`
        r   r$   z signif has to be between 0 and 1c              3   8   K   | ]}t          |          V  d S r   
isinstancer1   callowed_typess     r4   	<genexpr>z5VECMResults.test_granger_causality.<locals>.<genexpr>  s-      @@A:a//@@@@@@r6   zFcaused has to be of type string or int (or a sequence of these types).c                 Z    g | ]'}t          |          t          u rj        |         n|(S r   r   r   rI  r1   r*  r   s     r4   r   z6VECMResults.test_granger_causality.<locals>.<listcomp>  s1    IIIQ477c>>$*Q--qIIIr6   c                 :    g | ]}t          j        |          S r   r   rI  r/  s     r4   r   z6VECMResults.test_granger_causality.<locals>.<listcomp>  s%    ???1i
A..???r6   Nc              3   8   K   | ]}t          |          V  d S r   r'  r)  s     r4   r,  z5VECMResults.test_granger_causality.<locals>.<genexpr>  s-      EEz!]33EEEEEEr6   zOcausing has to be of type string or int (or a sequence of these types) or None.c                 Z    g | ]'}t          |          t          u rj        |         n|(S r   r.  r/  s     r4   r   z6VECMResults.test_granger_causality.<locals>.<listcomp>  s1    OOO!Q3tz!}}AOOOr6   c                 :    g | ]}t          j        |          S r   r1  r/  s     r4   r   z6VECMResults.test_granger_causality.<locals>.<listcomp>  s%    EEE9TZ33EEEr6   c                     g | ]}|v|	S r   r   )r1   r   
caused_inds     r4   r   z6VECMResults.test_granger_causality.<locals>.<listcomp>  s#    NNN!::M:M1:M:M:Mr6   c                 *    g | ]}j         |         S r   )rI  r/  s     r4   r   z6VECMResults.test_granger_causality.<locals>.<listcomp>  s    :::tz!}:::r6   Tr\   r]   r^   rB   rC   r   r    trendr%   r  r(   grangerr   )testr   ))rm   strr   r(  rs  	TypeErrorr8   r   rp  rN   rO   r_   r!   r"   r]   rB   rC   r   rn   r   r;   rV   rk   r.   ro   r  rc   r   paramsr9   r   r   r  r  df_residr  r  r   sfr  r   )$r   causedcausingr   causing_indrr   rI   r  rE   rB   var_results	num_restrnum_det_termsCcols_detrowrz   ing_inded_indCax_min_p_componentsx_min_pr   x_xx_x_11r  sig_alpha_min_pmiddlewald_statisticf_statisticdff_distributionpvalue
crit_valuer+  r6  s$   `                                 @@r4   test_granger_causalityz"VECMResults.test_granger_causality  s   V FQ?@@@c
fm,, 	XF@@@@@@@@@ 	,   JIII&III???????
'=11 $")EEEEWEEEEE :   POOOwOOOGEEEEWEEEK?NNNNeDI&6&6NNNK::::k:::GZDIM49q=H
1a%LY**!
 
 
 !#tnn((#(>> LL3v;;.!a%8	%d&8$,GG9 TY_Q//M?&T_2155M HM)AFa!e,<<=U
 
 
 }$q1u 	 	A&  (  FKLAc8f,q7{:Q!VaZGGH1HCC VAs;-crc245566%%dA233ik222(AE1:&&q1u 	 	A!!!QUQYa''(1QQQ!V94 AEQUaK'*++ AAAssF)QQQ!!'***).//fWgi((S)a1q5kM))+HQ!a%[=-H+HH
 %QU])BCaGbgfg666Q(13.//bdVmb01$y0[112+"";//#''F
33
#

 

 

 
	
r6   c           	      R   t          | j        | j        | j        | j        z   | j        d| j        | j                  }| j        | j        | j        }}}t          | j
        j        |                              |d          }| j        |j        _        |                    ||          S )u  
        Test for instantaneous causality.

        The concept of instantaneous causality is described in chapters 3.6.3
        and 7.6.4 of [1]_. Test |H0|: "No instantaneous causality between the
        variables in `caused` and those in `causing`" against |H1|:
        "Instantaneous causality between `caused` and `causing` exists".
        Note that 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
        :meth:`test_granger_causality()`) may be misleading.

        Parameters
        ----------
        causing : int or str or sequence of int or str
            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, 0 < `signif` < 1, default 5 %
            Significance level for computing critical values for test,
            defaulting to standard 0.05 level.

        Returns
        -------
        results : :class:`statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults`

        Notes
        -----
        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. Reducing the lag order by one in `JMulTi`
        leads to equal results in `statsmodels` and `JMulTi`.

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

        .. |H0| replace:: H\ :sub:`0`

        .. |H1| replace:: H\ :sub:`1`
        Tr8  r   r9  )rC  r   )r_   r!   r"   rN   rO   r]   rB   rC   r   r   rp  rn   r   rI  _resultstest_inst_causality)r   rC  r   rB   rI   r  rE   rE  s           r4   r]  zVECMResults.test_inst_causalityM  s    Z &LY**!
 
 
 )TY	a1$*,--11!31GG%)Z"..wv.NNNr6   c                 0    t          j        | |d          S )NT)periodsvecm)irf
IRAnalysis)r   r_  s     r4   ra  zVECMResults.irf  s    ~dG$????r6   c                    | j         }| j        j        dk    rt          || j        f          }t	          j        | j        |j                  }| j        }| j	        j        dk    rt          || j	        f          }t	          j        || j                  t	          j        || j                  z   }|| j        d| j                 z   j        S )z
        Return the in-sample values of endog calculated by the model.

        Returns
        -------
        fitted : array (nobs x neqs)
            The predicted in-sample values of the models' endogenous variables.
        r   N)rw  rx  r   r   r.   rc   ru  rn   rz  r{  r   r  r  r   )r   rw  r  rz  ru   s        r4   fittedvalueszVECMResults.fittedvalues  s     y#a''4!4566DVDJ''
=!!E4=122E&T\**RVE4=-I-II$,{{3366r6   c                 D    | j         j        | j        d         | j        z
  S )z
        Return the difference between observed and fitted values.

        Returns
        -------
        resid : array (nobs x neqs)
            The residuals.
        N)rp  rn   rO   rd  r   s    r4   r   zVECMResults.resid  s!     z|DIKK(4+<<<r6   c                 $    t          | |          S )a  
        Test assumption of normal-distributed errors using Jarque-Bera-style
        omnibus :math:`\\chi^2` test.

        Parameters
        ----------
        signif : float
            The test's significance level.

        Returns
        -------
        result : :class:`statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults`

        Notes
        -----
        |H0| : data are generated by a Gaussian-distributed process

        .. |H0| replace:: H\ :sub:`0`
        )r   )r   )r   r   s     r4   r   zVECMResults.test_normality  s    ( d62222r6   Fc           	         d}t          j        | j                  }t          ||          }t	          | j                  }|j        t           j        k    r>t          j        t          j	        |          dk              rt          j
        |          }t          d|dz             D ]@}||         }	t          j        |	j        |z  |	z  |z            }
|r|
| j        |z
  z  }
||
z  }A||r
| j        dz  n| j        z  }| j        dz  || j        z
  dz   z  | j        | j        z  z
  }t$          j                            |          }|                    |          }|                    d|z
            }t/          |||||||          S )u$  
        Test the whiteness of the residuals using the Portmanteau test.

        This test is described in [1]_, chapter 8.4.1.

        Parameters
        ----------
        nlags : int > 0
        signif : float, 0 < `signif` < 1
        adjusted : bool, default False

        Returns
        -------
        result : :class:`statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults`

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        r   r$   r%   )r.   r   r   r   r   r  rq  rr  rs  rt  realr8   r   rn   rN   r   rO   r>  r  r  chi2rA  r  r   )r   nlagsr   adjusted	statisticu	acov_listc0_invr  ctto_addrV  distrX  rY  s                  r4   test_whitenesszVECMResults.test_whiteness  s   * 	Jtz""!!U++	 T\""<2=((RVBGFOOq4H-I-I(WV__Fq%!)$$ 	  	 A1BXbdVmb069::F ($)a-'IIx>TY!^^TY>	 INedi/!34i$/)* 	 {####XXa&j))
#z62vuh
 
 	
r6   c                     |r| j         n| j         dd| j        df         }| j        }|r| j        n| j        | j        d         }t	          j        |j        ||           dS )z
        Plot the input time series.

        Parameters
        ----------
        with_presample : bool, default: `False`
            If `False`, the pre-sample data (the first `k_ar` values) will
            not be plotted.
        N)rI  r   )rp  rO   rI  r@  r  plot_mtsrn   )r   with_presamplerr   rI  r@  s        r4   	plot_datazVECMResults.plot_data  sl     )HDJJdjDIKK.H
,I

$*TY[[2Iace444444r6   c                 ,  - ddl m- t                      }	 d-fd	}g }g }g }g }g }| j        j        dk    r/|                    | j                            d                     |                    | j                            d                     |                    | j                            d                     |                    | j	                            d                     | 
                              }	|	d                             d          }
|	d	                             d          }|                    t          j        |
|f                     | j        d
z
  dk    r#|                    | j                                                   |                    | j                                                   |                    | j                                                   |                    | j                                                   |                               }	|	d                                         }
|	d	                                         }|                    t          j        |
|f                     t'          |          dk    rkt)          |          }t)          |          }t)          |          }t)          |          }t+          |          }t-          | j                  D ]
}g }d}d| j        v r6|                    |t          j        |d
          z              || j        z  }| j        dk    rPt-          | j        d
z
            D ]8}|                    |t          j        |d
          z              || j        z  }9d| j        v r6|                    |t          j        |d
          z              || j        z  }| j        Xt-          | j        j        d
                   D ]8}|                    |t          j        |d
          z              || j        z  }9| j        d
z
  dk    rX|| j        z  | j        d
z
  z  }|d
z   | j        z  | j        d
z
  z  }|                    |t          j        ||          z              t          j        |          }| j        j         |         }dd|z  z   } || ||||||| j        j!        |	  	        }|j"                            |           | j#                                        }| j$                                        }| j%                                        }| j&                                        }| '                              }|d                                         }
|d	                                         }t          j        |
|f          }| j        j(        } g }!t-          | j                  D ]}| j)        dk    r)|| j)        z  }|| j)        z   }t          j        ||          }|!                    |           | j        j         |         }d|z  } || ||||||| |	  	        }|j"                            |           g }"g }#g }$g }%g }&| j)        dk    rA|"                    | j*        j+                                                   |#                    | j,        j+                                                   |$                    | j-        j+                                                   |%                    | j.        j+                                                   | /                              }	|	d         j+                                        }
|	d	         j+                                        }|&                    t          j        |
|f                     | j0        j        dk    r#|"                    | j0                                                   |#                    | j1                                                   |$                    | j2                                                   |%                    | j3                                                   | 4                              }	|	d                                         }
|	d	                                         }|&                    t          j        |
|f                     t)          |"          }'t)          |#          }(t)          |$          })t)          |%          }*t+          |&          }+| j        j5        },t-          | j)                  D ]}g }d}| j)        dk    rQ|| j        z  }|| j        z   }|                    |t          j        ||          z              || j        | j)        z  z  }d| j        v r6|                    |t          j        |d
          z              || j)        z  }d| j        v r6|                    |t          j        |d
          z              || j)        z  }| j6        Xt-          | j6        j        d
                   D ]8}|                    |t          j        |d
          z              || j)        z  }9t          j        |          }dd|d
z   z  z   } || |'|(|)|*|+||,|	  	        }|j"                            |           |S )a  
        Return a summary of the estimation results.

        Parameters
        ----------
        alpha : float 0 < `alpha` < 1, default 0.05
            Significance level of the shown confidence intervals.

        Returns
        -------
        summary : :class:`statsmodels.iolib.summary.Summary`
            A summary containing information about estimated parameters.
        r   )summary_paramsTc
                    	 | ||         ||         ||         ||         ||         f}
	fdt          j        |          |                                         D             } |
d |d|          S )Nc                 x    g | ]6}r0d                      |                    d           dd                   n|7S ).Nr(   )joinsplit)r1   name	strip_ends     r4   r   z;VECMResults.summary.<locals>.make_table.<locals>.<listcomp>0	  sR        3<EC"-...  r6   F)ynamexnameru  use_tr   )r.   r/   tolist)r   r?  std_errt_valuesp_valuesconf_intr  rI  r   r  resr`  ru  ry  s            `  r4   
make_tablez'VECMResults.summary.<locals>.make_table	  s     tC   HUOOD188::  K ">!   r6   r  r  r  r  r  r$   r&   )ndminr)   Nz'Det. terms outside the coint. relation z*& lagged endog. parameters for equation %sz,Loading coefficients (alpha) for equation %sr'   r*   zCointegration relations for zloading-coefficients-column %d)T)7statsmodels.iolib.summaryry  r   r{  r   r9   flattenr  r  r  r  r.   r[   rO   rz  r  r  r  r  r;   r   r   r8   r   r!   r/   r"   rB   rk   r=   concatenaterH  rL  ra  tablesru  r  r  r  r  rd  r>  rw  rn   r  r  r  r  rx  r  r  r  r  rl  rC   ).r   ru  r   r  lagged_params_componentsstderr_lagged_params_components tvalues_lagged_params_components pvalues_lagged_params_components!conf_int_lagged_params_componentsr  r  r  lagged_paramsstderr_lagged_paramstvalues_lagged_paramspvalues_lagged_paramsconf_int_lagged_paramsr   masksr,   rM  r  endr  eq_namer   tabler  se_at_ap_aci_aa_namesalpha_maskscoint_componentsstderr_coint_componentstvalues_coint_componentspvalues_coint_componentsconf_int_coint_componentsrP   r  tvalues_cointpvalues_cointconf_int_cointcoint_namesry  s.    `                                           @r4   r   zVECMResults.summary
	  sJ    	=<<<<<)) 	 	 	 	 	 	 	F $& *,'+-(+-(,.)=!!$++DM,A,A,A,L,LMMM+22$,,3,77   -33%--C-88   -33%--C-88   --E-::HW%--C-88EW%--C-88E-44//   9q=1$++DJ,>,>,@,@AAA+2243D3L3L3N3NOOO,33"**,,   -33"**,,   ***77HW%--//EW%--//E-44//  
 '((A--"#;<<M#)*I#J#J $*+K$L$L!$*+K$L$L!%+,M%N%N"49%% +- +-4---LL"(1A*>*>*>!>???di'F<!##"4<!#344 , ,Vbhq.B.B.B%BCCC$)+4---LL"(1A*>*>*>!>???di'F9("49?1#566 , ,Vbhq.B.B.B%BCCC$)+9q=1$$	MTY];Eq5DI-Q?CLL")E3*?*?!?@@@ ~e,,*03=BWLM  #
!())*J2
 
 %%e,,,, J   ((** ((** ((**"""//W%%''W%%''u~..*3ty!! 	) 	)A""DO+do-y,, t$$$j,Q/GBWLEJasCtWe E N!!%(((( "$#% #% $&!?Q##DIK$7$7$9$9:::#**4+;+=+E+E+G+GHHH$++D,=,?,G,G,I,IJJJ$++D,=,?,G,G,I,IJJJ)))66HW%'//11EW%'//11E%,,R_eU^-L-LMMM#a''##D$7$?$?$A$ABBB#***2244   %+++3355   %+++3355   33%3@@HW%--//EW%--//E%,,R_eU^-L-LMMM'((566788788 9::j3t'' (	) (	)AEF ""DIdi'Vbis&;&;;<<<$)do55 t)))Vbhq&:&:&::;;;$/)t)))Vbhq&:&:&::;;;$/)*t4Q788 . .ALL"(1A*>*>*>!>???do-FF >%((D.2a!e<=  J
 
E N!!%((((r6   )	r   r   r   NNNNNN)r   )r  )r  N)r  NNN)r   TN)Nr   )r  r   FF)1r   r   r   r   r   r
   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r
  r   r  r$  rZ  r]  ra  rd  r   r   rs  rw  r   r   r6   r4   rK  rK    s       A A\ ']* ]* ]* ]*~ 
 
 ^
  G G ^G + + ^+2 ? ? ^?, 9 9 ^9 #/ #/ ^#/J = = ^= < < ^< F F ^F = = ^= A A ^A . . ^. / / ^/ @ @ ^@
 . . ^. 4 4 ^4 G G ^G / / ^/ P P ^P
 G G ^G J J ^J
 
 
I I I IG G G G
 
 
 

I I I IO O O O   ^  44 44 ^44l* * * * 0 0 ^0* * * **D D D DN AE
 
 
 
@Y
 Y
 Y
 Y
v<O <O <O <O|@ @ @ @ 7 7 ^7( 	= 	= ^	=3 3 3 3,4
 4
 4
 4
l5 5 5 5| | | | | |r6   rK  )r   r   NNr  )r   )r   FNN)r   r   r   )Gcollectionsr   numpyr.   r   r   numpy.linalgr   r   r  scipy.statsr  r   statsmodels.iolib.tabler	   statsmodels.tools.decoratorsr
   statsmodels.tools.sm_exceptionsr   statsmodels.tools.validationr   statsmodels.tsa.base.tsa_modeltsabase	tsa_modeltsbasestatsmodels.tsa.coint_tablesr   r   statsmodels.tsa.tsatoolsr   r   r   1statsmodels.tsa.vector_ar.hypothesis_test_resultsr   r   statsmodels.tsa.vector_ar.irf	vector_arra  "statsmodels.tsa.vector_ar.plottingplottingr  statsmodels.tsa.vector_ar.utilr   r   #statsmodels.tsa.vector_ar.var_modelr   r   r   r   r   r   r   r   r   r=  rL   rR   rV   r_   rh   r|   r   r   r   r   r   r   TimeSeriesModelr7  rK  r   r6   r4   <module>r     s   # # # # # #                     ! ! ! ! ! ! ! !      - - - - - - / / / / / / 7 7 7 7 7 7 A A A A A A 4 4 4 4 4 4 / / / / / / / / / / / / 5 5 5 5 5 5 5 5 D D D D D D D D D D        , + + + + + + + + + + + 1 1 1 1 1 1 1 1 1 1 1 1 F F F F F F F F	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	G6 G6G6 G6 	G6 G6 G6 G6T   <! ! ! !P 	>5 >5 >5 >5B$ $ $0 r/ r/ r/ r/j$ $ $N+. +. +.\D( D( D( D( D( D( D( D(P 9=D D D DNFH FH FHR^ ^ ^ ^ ^ ^ ^ ^BS S S S S6! S S Sl
k k k k k k k k k kr6   