
    >h                   4   S r SSKJr  SSKJr  SSKJr  SSKJr  SSK	J
r
  SSKJrJr  SSKrSSKrSS	KJr  SSKrSS
KJr  SSKJr  SSKJr  SSKJrJr  SSKJrJ r J!r!J"r"J#r#  SSK$J%r%J&r&  SSK'J(r(J)r)J*r*J+r+J,r,J-r-  SSK.J/r/  SSK0J1r1J2r2  SSK3J4r4J5r5  SSK6J7r7J8r8J9r9  \\Rt                  \Rv                  \<\=   4   r>/ SQr?\R                  " \R                  " \R                  5      R                  5      rD   S2S jrE     S3 S4S jjrF\" SS5      S5S j5       rGS rH       S6S jrI  S7       S8S jjrJ S9       S:S jjrK\" SS5         S;         S<S jj5       rL   S=         S>S  jjrM\" SS5      S?S! j5       rN\" SS5      S@SSS".S# jj5       rOSAS$ jrPSBS% jrQ SCS& jrRSDS' jrS     SE SFS( jjrTSBS) jrU SGS* jrVS+ rW   SH       SIS, jjrXS- rYS. rZSJS/ jr[ " S0 S15      r\\\" 5       r]\]R                  R                   \]l         g)Kz,
Statistical tools for time series analysis
    )annotations)lstsq)deprecate_kwarg)lzip)_next_regular)LiteralUnionN)LinAlgError)stats)interp1d)	correlate)OLSyule_walker)CollinearityWarningInfeasibleTestErrorInterpolationWarningMissingDataErrorValueWarning)Bunchadd_constant)
array_like	bool_like	dict_like
float_likeint_likestring_like)bds)innovations_algoinnovations_filter)mackinnoncrit
mackinnonp)	add_trendlagmat	lagmat2ds)acovfacfpacfpacf_ywpacf_olsccovfccfq_statcointarma_order_select_icadfullerkpssr   	pacf_burgr   r   levinson_durbin_pacflevinson_durbinzivot_andrewsrange_unit_root_testc	                R   0 n	UR                  5       n[        X3U-   S-   5       H'  n
U " XSS2SU
24   /UQ76 nUR                  5       X'   M)     US:X  a#  [        S U	R	                  5        5       5      u  pOUS:X  a#  [        S U	R	                  5        5       5      u  pOzUS:X  ae  SnX4-   nS	n[        X4-   US-
  S
5       HF  n
[
        R                  " X   R                  S
   5      nU
n[
        R                  " U5      U:  d  MF    O   O[        SU S35      eU(       d  X4$ XU	4$ )a  
Returns the results for the lag length that maximizes the info criterion.

Parameters
----------
mod : Model class
    Model estimator class
endog : array_like
    nobs array containing endogenous variable
exog : array_like
    nobs by (startlag + maxlag) array containing lags and possibly other
    variables
startlag : int
    The first zero-indexed column to hold a lag.  See Notes.
maxlag : int
    The highest lag order for lag length selection.
method : {"aic", "bic", "t-stat"}
    aic - Akaike Information Criterion
    bic - Bayes Information Criterion
    t-stat - Based on last lag
modargs : tuple, optional
    args to pass to model.  See notes.
fitargs : tuple, optional
    args to pass to fit.  See notes.
regresults : bool, optional
    Flag indicating to return optional return results

Returns
-------
icbest : float
    Best information criteria.
bestlag : int
    The lag length that maximizes the information criterion.
results : dict, optional
    Dictionary containing all estimation results

Notes
-----
Does estimation like mod(endog, exog[:,:i], *modargs).fit(*fitargs)
where i goes from lagstart to lagstart+maxlag+1.  Therefore, lags are
assumed to be in contiguous columns from low to high lag length with
the highest lag in the last column.
   Naicc              3  B   #    U  H  u  pUR                   U4v   M     g 7fN)r8   .0kvs      lC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/tsa/stattools.py	<genexpr>_autolag.<locals>.<genexpr>        E_TQquuaj_   bicc              3  B   #    U  H  u  pUR                   U4v   M     g 7fr:   )rD   r;   s      r?   r@   rA      rB   rC   t-statgjg	RQ?g        zInformation Criterion z not understood.)	lowerrangefitminitemsnpabstvalues
ValueError)modendogexogstartlagmaxlagmethodmodargsfitargs
regresultsresultslagmod_instanceicbestbestlagstops                  r?   _autolagr`   G   s2   t G\\^FX&01455q$3$w-:':#'') 6 EW]]_EE	5EW]]_EE	8	!#*HqL"=CVVGL0045FGvvf~% > 1&9IJKK''    c           
        [        U S5      n [        USSS9n[        USSS9n[        USSS	S
9n[        US5      n[        US5      nU R	                  5       U R                  5       :X  a  [        S5      eU(       a  SnSSSSS.nUb  [        U[        5      (       a  Xb   nUR                  5       nU R                  S   nUS:w  a  [        U5      OSnUca  [        [        R                  " S[        R                  " US-  S5      -  5      5      n[        US-  U-
  S-
  U5      nUS:  a  [        S5      eOXS-  U-
  S-
  :  a  [        S5      e[        R                  " U 5      n	[!        U	SS2S4   USSS9n
U
R                  S   nX* S-
  S U
SS2S4'   X* S nU(       a  SS KJn  U" 5       nU(       a  US:w  a  ['        XSS!9nOU
nUR                  S   U
R                  S   -
  S-   nU(       d  [)        [*        XXU5      u  nnO[)        [*        UUUUUUS"9u  nnnUWl        UU-  n[!        U	SS2S4   USSS9n
U
R                  S   nX* S-
  S U
SS2S4'   X* S nUnOUnSnUS:w  a1  [+        U['        U
SS2SUS-   24   U5      5      R/                  5       nO%[+        XSS2SUS-   24   5      R/                  5       nUR0                  S   n[3        UUSS#9n[5        SX'S$9nUS   US   US   S%.nU(       aJ  UWl        Xl        UUl        UUl        UUl        X}l         S&Ul!        S'Ul"        UUl#        S(Ul$        UUUU4$ U(       d  UUUUU4$ UUUUUU4$ ))a`  
Augmented Dickey-Fuller unit root test.

The Augmented Dickey-Fuller test can be used to test for a unit root in a
univariate process in the presence of serial correlation.

Parameters
----------
x : array_like, 1d
    The data series to test.
maxlag : {None, int}
    Maximum lag which is included in test, default value of
    12*(nobs/100)^{1/4} is used when ``None``.
regression : {"c","ct","ctt","n"}
    Constant and trend order to include in regression.

    * "c" : constant only (default).
    * "ct" : constant and trend.
    * "ctt" : constant, and linear and quadratic trend.
    * "n" : no constant, no trend.

autolag : {"AIC", "BIC", "t-stat", None}
    Method to use when automatically determining the lag length among the
    values 0, 1, ..., maxlag.

    * If "AIC" (default) or "BIC", then the number of lags is chosen
      to minimize the corresponding information criterion.
    * "t-stat" based choice of maxlag.  Starts with maxlag and drops a
      lag until the t-statistic on the last lag length is significant
      using a 5%-sized test.
    * If None, then the number of included lags is set to maxlag.
store : bool
    If True, then a result instance is returned additionally to
    the adf statistic. Default is False.
regresults : bool, optional
    If True, the full regression results are returned. Default is False.

Returns
-------
adf : float
    The test statistic.
pvalue : float
    MacKinnon's approximate p-value based on MacKinnon (1994, 2010).
usedlag : int
    The number of lags used.
nobs : int
    The number of observations used for the ADF regression and calculation
    of the critical values.
critical values : dict
    Critical values for the test statistic at the 1 %, 5 %, and 10 %
    levels. Based on MacKinnon (2010).
icbest : float
    The maximized information criterion if autolag is not None.
resstore : ResultStore, optional
    A dummy class with results attached as attributes.

Notes
-----
The null hypothesis of the Augmented Dickey-Fuller is that there is a unit
root, with the alternative that there is no unit root. If the pvalue is
above a critical size, then we cannot reject that there is a unit root.

The p-values are obtained through regression surface approximation from
MacKinnon 1994, but using the updated 2010 tables. If the p-value is close
to significant, then the critical values should be used to judge whether
to reject the null.

The autolag option and maxlag for it are described in Greene.

See the notebook `Stationarity and detrending (ADF/KPSS)
<../examples/notebooks/generated/stationarity_detrending_adf_kpss.html>`__
for an overview.

References
----------
.. [1] W. Green.  "Econometric Analysis," 5th ed., Pearson, 2003.

.. [2] Hamilton, J.D.  "Time Series Analysis".  Princeton, 1994.

.. [3] MacKinnon, J.G. 1994.  "Approximate asymptotic distribution functions for
    unit-root and cointegration tests.  `Journal of Business and Economic
    Statistics` 12, 167-76.

.. [4] MacKinnon, J.G. 2010. "Critical Values for Cointegration Tests."  Queen"s
    University, Dept of Economics, Working Papers.  Available at
    http://ideas.repec.org/p/qed/wpaper/1227.html
xrU   Toptional
regression)cctcttnoptionsautolagr8   rD   rF   re   rl   storerY   zInvalid input, x is constantrj   rg   rh   ri   )Nr   r7      Nr         (@      Y@      ?rq   r7   z=sample size is too short to use selected regression componentzomaxlag must be less than (nobs/2 - 1 - ntrend) where n trend is the number of included deterministic regressorsbothin)trimoriginalrG   ResultsStoreprepend)rY   rf   Nr~   rf   nobs1%5%10%z8The coefficient on the lagged level equals 1 - unit rootz4The coefficient on the lagged level < 1 - stationaryz$Augmented Dickey-Fuller Test Results)%r   r   r   r   maxrK   rP   
isinstanceintrH   shapelenrM   ceilpowerdiffr#   statsmodels.stats.diagnosticrz   r"   r`   r   autolag_resultsrJ   rO   r!   r    resolsrU   usedlagadfstat
critvaluesr   H0HAr]   _str)rc   rU   rf   rm   rp   rY   	trenddictr   ntrendxdiffxdallxdshortrz   resstorefullRHSrT   r]   r^   alresr   r   r   pvaluer   s                           r?   r/   r/      s   ~ 	1cAfh6FL*AJ T3KG eW%E:|4Juuw!%%'788st6IZ
C88*
!!#J771:D *c 1S_qF~RWWTBHHTE\7$CCDETQY'!+V4A:'  
 
!)f$q(	('
 	

 GGAJE5D>6FE;;q>DEAI#E!Q$KEFmG=>4@GG==#ekk!n4q8 &WxOFG &.%&"FGU (-H$8 uQW~wVdK{{1~	B'ad-SYuQ'A+%56
C

#% 	 WA}1}$456::<nnQG J!<FzEJmm!}J
   ""(I 	 M >
H44FGT:==FGT:vEEra   unbiasedadjustedc                P   [        US5      n[        US5      n[        USSS9n[        USSS9n[        US	S
S9n[        U SSS9n UR	                  5       nUS:X  a  SnO[        U 5      nU(       a]  US:X  a  [        S5      e[        R                  " U 5      ) nUS:X  a  U R                  5       n SX) '   OX   n UR                  [        5      nU(       a7  U(       a0  X R                  5       WR                  5       -  -
  n	US:X  a  SU	W) '   OU(       a  X R                  5       -
  n	OU n	[        U 5      n
UnUc  U
S-
  nOXZS-
  :  a  [        S5      eU(       Gd6  UGb2  [        R                   " US-   5      nU	R#                  U	5      US'   [%        U5       H%  nXS-   S R#                  U	SUS-   *  5      XS-   '   M'     U(       a  US:X  a.  U(       a   X[        R&                  " US-   5      -
  -  nU$ X-  n U$ U(       az  [        R                   " US-   [        R(                  S9nWR                  5       US'   [%        U5       H%  nXS-   S R#                  USUS-   *  5      XS-   '   M'     SXS:H  '   X-  nU$ UWR                  5       -  nU$ U(       a-  U(       a&  US:X  a   [        R*                  " WUS5      nSXS:H  '   OU(       a<  [        R&                  " SU
S-   5      n[        R,                  " UUSS SSS2   45      nOTU(       a.  WR                  5       [        R.                  " SU
-  S-
  5      -  nOU
[        R.                  " SU
-  S-
  5      -  nU(       a  [        U	5      n[1        SU-  S-   5      n
[        R2                  R3                  XS9n[        R2                  R5                  U[        R6                  " U5      -  5      SU UUS-
  S -  nUR8                  nO%[        R*                  " XS5      U
S-
  S XS-
  S -  nUb  USUS-    R                  5       $ U$ )ag  
Estimate autocovariances.

Parameters
----------
x : array_like
    Time series data. Must be 1d.
adjusted : bool, default False
    If True, then denominators is n-k, otherwise n.
demean : bool, default True
    If True, then subtract the mean x from each element of x.
fft : bool, default True
    If True, use FFT convolution.  This method should be preferred
    for long time series.
missing : str, default "none"
    A string in ["none", "raise", "conservative", "drop"] specifying how
    the NaNs are to be treated. "none" performs no checks. "raise" raises
    an exception if NaN values are found. "drop" removes the missing
    observations and then estimates the autocovariances treating the
    non-missing as contiguous. "conservative" computes the autocovariance
    using nan-ops so that nans are removed when computing the mean
    and cross-products that are used to estimate the autocovariance.
    When using "conservative", n is set to the number of non-missing
    observations.
nlag : {int, None}, default None
    Limit the number of autocovariances returned.  Size of returned
    array is nlag + 1.  Setting nlag when fft is False uses a simple,
    direct estimator of the autocovariances that only computes the first
    nlag + 1 values. This can be much faster when the time series is long
    and only a small number of autocovariances are needed.

Returns
-------
ndarray
    The estimated autocovariances.

References
----------
.. [1] Parzen, E., 1963. On spectral analysis with missing observations
       and amplitude modulation. Sankhya: The Indian Journal of
       Statistics, Series A, pp.383-392.
r   demeanfftFrd   missingnoneraiseconservativedroprk   nlagTrc   r7   ndimr   r   z!NaNs were encountered in the datar   r   Nz"nlag must be smaller than nobs - 1r   dtypefullrG   rq   )rj   )r   r   r   r   rH   has_missingr   rM   isnancopyastyper   summeanr   rP   emptydotrI   arangeint64r   hstackonesr   r   ifft	conjugatereal)rc   r   r   r   r   r   deal_with_maskednotmask_boolnotmask_intxorj   lag_lenacovidivisordxir   Frfs                      r?   r%   r%     s   X :.Hvx(F
C
/C$MG D&40D1c"AmmoG& &q>g"#FGG|n$A AmA"))#.";??,,,n$ !B}	\AAG|a%	A=>>4#xx!$&&*QwAUW+//"ZQx.9DQK  7f#4BIIgk222  	  ((7Q;bhh?(__.
wA%0Q%9%=%=#JAh/&GEN ( )*1%  ))$N)BLLk6:q&		YYq!a% IIr2cr74R4=)*	OOA	 22A	""
2w!d(Q,'ffjjj!vv{{3c!223ET:Qtaxz]Jyy||BF+AEG4qQzAMgk"''))Kra   c                R   [        U S5      n [        US5      nUUS-   -  [        R                  " SU[        R                  " S[        U 5      S-   5      -
  -  U S-  -  5      -  n[        R                  R                  U[        R                  " S[        U 5      S-   5      5      nX#4$ )a  
Compute Ljung-Box Q Statistic.

Parameters
----------
x : array_like
    Array of autocorrelation coefficients.  Can be obtained from acf.
nobs : int, optional
    Number of observations in the entire sample (ie., not just the length
    of the autocorrelation function results.

Returns
-------
q-stat : ndarray
    Ljung-Box Q-statistic for autocorrelation parameters.
p-value : ndarray
    P-value of the Q statistic.

See Also
--------
statsmodels.stats.diagnostic.acorr_ljungbox
    Ljung-Box Q-test for autocorrelation in time series based
    on a time series rather than the estimated autocorrelation
    function.

Notes
-----
Designed to be used with acf.
rc   r   rq         ?r7   )	r   r   rM   cumsumr   r   r   chi2sf)rc   r   retr   s       r?   r,   r,     s    < 	1cAD&!D 	!8	
))SD299QA
#;;<QF
G	H 
 ::==bii3q6A:67D9ra   c                `   [        US5      n[        USSS9n[        US5      n[        USSS9n[        USSS9n[        US	S
S9n[	        U S5      n U R
                  S   nUc/  [        [        S[        R                  " U5      -  5      US-
  5      n[        XSXGS9n	U	SUS-    U	S   -  n
U(       d	  U(       d  U
$ Ub  UOSnU(       aU  [        R                  " U
5      U-  nSUS'   SU-  US'   USS=== SS[        R                  " U
SS S-  5      -  -   -  sss& OS[        U 5      -  n[        R                  R!                  SUS-  -
  5      [        R"                  " U5      -  n[        R$                  " ['        X-
  X-   5      5      nU(       d  X4$ [)        U
SS US9u  p?Ub  XX?4$ XU4$ )a&  
Calculate the autocorrelation function.

Parameters
----------
x : array_like
   The time series data.
adjusted : bool, default False
   If True, then denominators for autocovariance are n-k, otherwise n.
nlags : int, optional
    Number of lags to return autocorrelation for. If not provided,
    uses min(10 * np.log10(nobs), nobs - 1). The returned value
    includes lag 0 (ie., 1) so size of the acf vector is (nlags + 1,).
qstat : bool, default False
    If True, returns the Ljung-Box q statistic for each autocorrelation
    coefficient.  See q_stat for more information.
fft : bool, default True
    If True, computes the ACF via FFT.
alpha : scalar, default None
    If a number is given, the confidence intervals for the given level are
    returned. For instance if alpha=.05, 95 % confidence intervals are
    returned where the standard deviation is computed according to
    Bartlett"s formula.
bartlett_confint : bool, default True
    Confidence intervals for ACF values are generally placed at 2
    standard errors around r_k. The formula used for standard error
    depends upon the situation. If the autocorrelations are being used
    to test for randomness of residuals as part of the ARIMA routine,
    the standard errors are determined assuming the residuals are white
    noise. The approximate formula for any lag is that standard error
    of each r_k = 1/sqrt(N). See section 9.4 of [2] for more details on
    the 1/sqrt(N) result. For more elementary discussion, see section 5.3.2
    in [3].
    For the ACF of raw data, the standard error at a lag k is
    found as if the right model was an MA(k-1). This allows the possible
    interpretation that if all autocorrelations past a certain lag are
    within the limits, the model might be an MA of order defined by the
    last significant autocorrelation. In this case, a moving average
    model is assumed for the data and the standard errors for the
    confidence intervals should be generated using Bartlett's formula.
    For more details on Bartlett formula result, see section 7.2 in [2].
missing : str, default "none"
    A string in ["none", "raise", "conservative", "drop"] specifying how
    the NaNs are to be treated. "none" performs no checks. "raise" raises
    an exception if NaN values are found. "drop" removes the missing
    observations and then estimates the autocovariances treating the
    non-missing as contiguous. "conservative" computes the autocovariance
    using nan-ops so that nans are removed when computing the mean
    and cross-products that are used to estimate the autocovariance.
    When using "conservative", n is set to the number of non-missing
    observations.

Returns
-------
acf : ndarray
    The autocorrelation function for lags 0, 1, ..., nlags. Shape
    (nlags+1,).
confint : ndarray, optional
    Confidence intervals for the ACF at lags 0, 1, ..., nlags. Shape
    (nlags + 1, 2). Returned if alpha is not None. The confidence
    intervals are centered on the estimated ACF values. This behavior
    differs from plot_acf which centers the confidence intervals on 0.
qstat : ndarray, optional
    The Ljung-Box Q-Statistic for lags 1, 2, ..., nlags (excludes lag
    zero). Returned if q_stat is True.
pvalues : ndarray, optional
    The p-values associated with the Q-statistics for lags 1, 2, ...,
    nlags (excludes lag zero). Returned if q_stat is True.

Notes
-----
The acf at lag 0 (ie., 1) is returned.

For very long time series it is recommended to use fft convolution instead.
When fft is False uses a simple, direct estimator of the autocovariances
that only computes the first nlag + 1 values. This can be much faster when
the time series is long and only a small number of autocovariances are
needed.

If adjusted is true, the denominator for the autocovariance is adjusted
for the loss of data.

References
----------
.. [1] Parzen, E., 1963. On spectral analysis with missing observations
   and amplitude modulation. Sankhya: The Indian Journal of
   Statistics, Series A, pp.383-392.
.. [2] Brockwell and Davis, 1987. Time Series Theory and Methods
.. [3] Brockwell and Davis, 2010. Introduction to Time Series and
   Forecasting, 2nd edition.

See Also
--------
statsmodels.tsa.stattools.acf
    Estimate the autocorrelation function.
statsmodels.graphics.tsaplots.plot_acf
    Plot autocorrelations and confidence intervals.
r   nlagsTrd   qstatr   Falphar   r   rk   rc   r   N
   r7   )r   r   r   r   皙?r   rq   rG          @)r   )r   r   r   r   r   r   rK   r   rM   log10r%   	ones_liker   r   r   normppfsqrtarrayr   r,   )rc   r   r   r   r   r   bartlett_confintr   r   avfr&   _alphavaracfintervalconfintr   s                   r?   r&   r&   C  s   X :.HUGd3EeW%E
C
/Cug5E$MG 	1cA771:D}CRXXd^+,dQh7
Ts
LC
k	
SV
#CU
'UTFc"T)q	$Jq	qr
a!biiAb	Q7777
s1vzz~~a&3,./"''&/AHhhtCNCN;<G|3qr7.MEU**6!!ra   c           
        [        U S5      n [        USSS9nU R                  S   nUc9  [        [	        [        S[        R                  " U5      -  5      US-
  5      S5      n[        US	S
S9nS/n[        R                  " 5          [        R                  " S[        5        [        SUS-   5       H"  nUR                  [        XUS9S   S   5        M$     SSS5        [        R                   " U5      $ ! , (       d  f       N$= f)ak  
Partial autocorrelation estimated with non-recursive yule_walker.

Parameters
----------
x : array_like
    The observations of time series for which pacf is calculated.
nlags : int, optional
    Number of lags to return autocorrelation for. If not provided,
    uses min(10 * np.log10(nobs), nobs - 1).
method : {"adjusted", "mle"}, default "adjusted"
    The method for the autocovariance calculations in yule walker.

Returns
-------
ndarray
    The partial autocorrelations, maxlag+1 elements.

See Also
--------
statsmodels.tsa.stattools.pacf
    Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_ols
    Partial autocorrelation estimation using OLS.
statsmodels.tsa.stattools.pacf_burg
    Partial autocorrelation estimation using Burg"s method.

Notes
-----
This solves yule_walker for each desired lag and contains
currently duplicate calculations.
rc   r   Trd   r   Nr   r7   rV   )r   mlerk   r   oncerV   rG   )r   r   r   r   rK   r   rM   r   r   warningscatch_warningssimplefilterr   rI   appendr   r   )rc   r   rV   r   r'   r=   s         r?   r(   r(     s    J 	1cAUGd3E771:D}CB$/0$(;Q?3FGF5D		 	 	"fl3q%!)$AKKA8;B?@ % 
# 88D>	 
#	"s   AC55
Dc                   [        U S5      n U(       a  X R                  5       -
  n U R                  S   nUb  UO.[        [	        S[
        R                  " U5      -  5      US-
  5      n[        US5      nXCS-
  :  a  [        S5      e[
        R                  " US-   5      nSU R                  U 5      -  US'   [
        R                  " US-   5      nU SSS2   R                  5       nU SSS2   R                  5       nUSS R                  USS 5      USS R                  USS 5      -   US'   SUS   -  USS R                  USS 5      -  US'   [
        R                  " U5      n	[
        R                  " U5      n
[        SU5       H~  nXySS& XSS& U	SS Xk   U
SS -  -
  USS& U
SS Xk   U	SS -  -
  USS& SXk   S-  -
  X[   -  X   S-  -
  US   S-  -
  X[S-   '   SX[S-      -  XS-   S R                  X{S 5      -  XkS-   '   M     SUS-  -
  U-  S	U[
        R                  " SUS-   5      -
  -  -  nSUS'   Xl4$ )
a  
Calculate Burg"s partial autocorrelation estimator.

Parameters
----------
x : array_like
    Observations of time series for which pacf is calculated.
nlags : int, optional
    Number of lags to return autocorrelation for. If not provided,
    uses min(10 * np.log10(nobs), nobs - 1).
demean : bool, optional
    Flag indicating to demean that data. Set to False if x has been
    previously demeaned.

Returns
-------
pacf : ndarray
    Partial autocorrelations for lags 0, 1, ..., nlag.
sigma2 : ndarray
    Residual variance estimates where the value in position m is the
    residual variance in an AR model that includes m lags.

See Also
--------
statsmodels.tsa.stattools.pacf
    Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_yw
     Partial autocorrelation estimation using Yule-Walker.
statsmodels.tsa.stattools.pacf_ols
    Partial autocorrelation estimation using OLS.

References
----------
.. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
    and forecasting. Springer.
rc   r   Nr   r7   z#nlags must be smaller than nobs - 1rq   rG   r   )r   r   r   rK   r   rM   r   r   rP   zerosr   r   
empty_likerI   r   )rc   r   r   r   pr   r'   ur>   last_ulast_vr   sigma2s                r?   r1   r1     s^   N 	1cAL771:D"CRXXd^0C,DdQh(OAAq	A!8|>??
QAquuQx<AaD88AE?D	$B$A	$B$ASb6::af!"		!AB% 00AaD!A$h121Sb6**DG]]1F]]1F1a[q	q	sdgqr
22!"qr
TWvcr{22!"1$,qtqy81R5A:Ea%!E(lQ1uwZ^^AG%<<U  $'kQ#		!QU0C)C"DEFDG<ra   c           
     l   [        U S5      n [        USSS9n[        US5      n[        US5      nU R                  S   nUc9  [	        [        [        S	[        R                  " U5      -  5      US
-  5      S5      nXS
-  :  a  [        SUS
-   S35      e[        R                  " US-   5      nSUS'   U(       ad  [        XSS9u  pg[        U5      n[        SUS-   5       H9  n[        XhS2SUS-   24   XxS SS9S   n	[        R                  " U	S   5      XX'   M;     OnU [        R                   " U 5      -
  n [        XSSS9u  pg[        SUS-   5       H5  n[        USS2SU24   USS9S   n	[        R                  " U	S   5      XX'   M7     U(       a!  XTU[        R"                  " US-   5      -
  -  -  nU$ )a   
Calculate partial autocorrelations via OLS.

Parameters
----------
x : array_like
    Observations of time series for which pacf is calculated.
nlags : int, optional
    Number of lags to return autocorrelation for. If not provided,
    uses min(10 * np.log10(nobs), nobs - 1).
efficient : bool, optional
    If true, uses the maximum number of available observations to compute
    each partial autocorrelation. If not, uses the same number of
    observations to compute all pacf values.
adjusted : bool, optional
    Adjust each partial autocorrelation by n / (n - lag).

Returns
-------
ndarray
    The partial autocorrelations, (maxlag,) array corresponding to lags
    0, 1, ..., maxlag.

See Also
--------
statsmodels.tsa.stattools.pacf
    Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_yw
     Partial autocorrelation estimation using Yule-Walker.
statsmodels.tsa.stattools.pacf_burg
    Partial autocorrelation estimation using Burg"s method.

Notes
-----
This solves a separate OLS estimation for each desired lag using method in
[1]_. Setting efficient to True has two effects. First, it uses
`nobs - lag` observations of estimate each pacf.  Second, it re-estimates
the mean in each regression. If efficient is False, then the data are first
demeaned, and then `nobs - maxlag` observations are used to estimate each
partial autocorrelation.

The inefficient estimator appears to have better finite sample properties.
This option should only be used in time series that are covariance
stationary.

OLS estimation of the pacf does not guarantee that all pacf values are
between -1 and 1.

References
----------
.. [1] Box, G. E., Jenkins, G. M., Reinsel, G. C., & Ljung, G. M. (2015).
   Time series analysis: forecasting and control. John Wiley & Sons, p. 66
rc   r   Trd   	efficientr   r   Nr   rq   r7   z&nlags must be smaller than nobs // 2 ()r   sep)rx   )rcondrG   ru   )rx   rw   )r   r   r   r   r   rK   r   rM   r   rP   r   r#   r   rI   r   squeezer   r   )
rc   r   r   r   r   r'   xlagsx0r=   paramss
             r?   r)   r)   K  s   x 	1cAUGd3E)[1I:.H771:D}CB$/0$!)<a@QwA$'!LMM88EAIDDG1e4	U#q%!)$A5Wq1uW-r"vTB1EFjj,DG % 
N1e&A	q%!)$A5BQB<48;Fjj,DG % ryy3344Kra   c                ~   [        USSS9nSn[        U SSS9n [        USUS	9n[        US
SS9nU R                  S   nUc2  [        [        S[        R                  " U5      -  5      US-  S-
  5      n[        US5      nXR                  S   S-  :  a"  [        SU SU R                  S   S-   S35      eUS;   a  SU;  nSU;   n[        XXgS9nOpUS;   a  [        XSS9nO_US;   a  [        XSS9nONUS;   a  [        U SSS9n	[        XSS9n
U
S   nO-US:X  a  [        XSS9u  pO[        U SSS9n	[        XSS9n
U
S   nUby  S[!        U 5      -  n["        R$                  R'                  SUS -  -
  5      [        R(                  " U5      -  n[        R*                  " [-        X-
  X-   5      5      nUS   US'   X4$ U$ )!a"
  
Partial autocorrelation estimate.

Parameters
----------
x : array_like
    Observations of time series for which pacf is calculated.
nlags : int, optional
    Number of lags to return autocorrelation for. If not provided,
    uses min(10 * np.log10(nobs), nobs // 2 - 1). The returned value
    includes lag 0 (ie., 1) so size of the pacf vector is (nlags + 1,).
method : str, default "ywunbiased"
    Specifies which method for the calculations to use.

    - "yw" or "ywadjusted" : Yule-Walker with sample-size adjustment in
      denominator for acovf. Default.
    - "ywm" or "ywmle" : Yule-Walker without adjustment.
    - "ols" : regression of time series on lags of it and on constant.
    - "ols-inefficient" : regression of time series on lags using a single
      common sample to estimate all pacf coefficients.
    - "ols-adjusted" : regression of time series on lags with a bias
      adjustment.
    - "ld" or "ldadjusted" : Levinson-Durbin recursion with bias
      correction.
    - "ldb" or "ldbiased" : Levinson-Durbin recursion without bias
      correction.
    - "burg" :  Burg"s partial autocorrelation estimator.

alpha : float, optional
    If a number is given, the confidence intervals for the given level are
    returned. For instance if alpha=.05, 95 % confidence intervals are
    returned where the standard deviation is computed according to
    1/sqrt(len(x)).

Returns
-------
pacf : ndarray
    The partial autocorrelations for lags 0, 1, ..., nlags. Shape
    (nlags+1,).
confint : ndarray, optional
    Confidence intervals for the PACF at lags 0, 1, ..., nlags. Shape
    (nlags + 1, 2). Returned if alpha is not None.

See Also
--------
statsmodels.tsa.stattools.acf
    Estimate the autocorrelation function.
statsmodels.tsa.stattools.pacf
    Partial autocorrelation estimation.
statsmodels.tsa.stattools.pacf_yw
     Partial autocorrelation estimation using Yule-Walker.
statsmodels.tsa.stattools.pacf_ols
    Partial autocorrelation estimation using OLS.
statsmodels.tsa.stattools.pacf_burg
    Partial autocorrelation estimation using Burg's method.
statsmodels.graphics.tsaplots.plot_pacf
    Plot partial autocorrelations and confidence intervals.

Notes
-----
Based on simulation evidence across a range of low-order ARMA models,
the best methods based on root MSE are Yule-Walker (MLW), Levinson-Durbin
(MLE) and Burg, respectively. The estimators with the lowest bias included
included these three in addition to OLS and OLS-adjusted.

Yule-Walker (adjusted) and Levinson-Durbin (adjusted) performed
consistently worse than the other options.
r   Trd   )olsols-inefficientols-adjustedywywald
ywadjustedyw_adjustedywmywmleyw_mlelda
ldadjustedld_adjustedldbldbiased	ld_biasedburgrc   rq   )maxdimrV   rk   r   r   r   r7   zaCan only compute partial correlations for lags up to 50% of the sample size. The requested nlags z must be < .)r   r   r   inefficientr   )r   r   r   )r   r  r  r  )r   rV   )r  r  r  r   )r  r  r	  r
  F)r   r   )r   isacovr  )r   r   r   r   )r   r   r   r   r   rK   r   rM   r   r   rP   r)   r(   r%   r3   r1   r   r   r   r   r   r   r   )rc   r   rV   r   methodsr   r   r   r   acvld__r   r   r   s                  r?   r'   r'     s   n UGd3EG( 	1c!$A7;Fug5E771:D}CRXXd^+,dai!m<qMEwwqzQ005wkwwqzQq"
 	

 ;;!/	'qN	=	=aZ8	-	-aU3	=	=A%0ct<!f	6	1$7Q A51ct<!fs1v::>>#"34rwwvF((4?@V
|
ra   c                p   [        U S5      n [        US5      n[        US5      n[        US5      n[        USSS9n[        U 5      nU(       a%  X R                  5       -
  nXR                  5       -
  nOU nUnU(       a  [        R
                  " USS	5      nOUnU(       a  SOS
n	[        XgSU	S9US-
  S U-  $ )a  
Calculate the cross-covariance between two series.

Parameters
----------
x, y : array_like
   The time series data to use in the calculation.
adjusted : bool, optional
   If True, then denominators for cross-covariance are n-k, otherwise n.
demean : bool, optional
    Flag indicating whether to demean x and y.
fft : bool, default True
    If True, use FFT convolution.  This method should be preferred
    for long time series.

Returns
-------
ndarray
    The estimated cross-covariance function: the element at index k
    is the covariance between {x[k], x[k+1], ..., x[n]} and {y[0], y[1], ..., y[m-k]},
    where n and m are the lengths of x and y, respectively.
rc   yr   r   r   Frd   r   rG   directr   r   r7   N)r   r   r   r   rM   r   r   )
rc   r  r   r   r   rj   r   yor   rV   s
             r?   r*   r*   <  s    0 	1cA1cA:.Hvx(F
C
/CAA\\IIaBUxFRVF3AEF;a??ra   )r   r   c                  [        U S5      n [        US5      n[        US5      n[        USSS9n[        XUSUS9nU[        R                  " U 5      [        R                  " U5      -  -  nUS	U nUbv  [
        R                  R                  S
US-  -
  5      [        R                  " [        U 5      5      -  nUR                  SS5      U[        R                  " SS/5      -  -   n	Xy4$ U$ )a  
The cross-correlation function.

Parameters
----------
x, y : array_like
    The time series data to use in the calculation.
adjusted : bool
    If True, then denominators for cross-correlation are n-k, otherwise n.
fft : bool, default True
    If True, use FFT convolution.  This method should be preferred
    for long time series.
nlags : int, optional
    Number of lags to return cross-correlations for. If not provided,
    the number of lags equals len(x).
alpha : float, optional
    If a number is given, the confidence intervals for the given level are
    returned. For instance if alpha=.05, 95 % confidence intervals are
    returned where the standard deviation is computed according to
    1/sqrt(len(x)).

Returns
-------
ndarray
    The cross-correlation function of x and y: the element at index k
    is the correlation between {x[k], x[k+1], ..., x[n]} and {y[0], y[1], ..., y[m-k]},
    where n and m are the lengths of x and y, respectively.
confint : ndarray, optional
    Confidence intervals for the CCF at lags 0, 1, ..., nlags-1 using the level given by
    alpha and the standard deviation calculated as 1/sqrt(len(x)) [1]. Shape (nlags, 2).
    Returned if alpha is not None.

Notes
-----
If adjusted is True, the denominator for the cross-correlation is adjusted.

References
----------
.. [1] Brockwell and Davis, 2016. Introduction to Time Series and
   Forecasting, 3rd edition, p. 242.
rc   r  r   r   Frd   T)r   r   r   Nr   r   rG   r7   )r   r   r*   rM   stdr   r   r   r   r   reshaper   )
rc   r  r   r   r   r   cvfr   r   r   s
             r?   r+   r+   j  s    V 	1cA1cA:.H
C
/C
x#
>C
RVVAY&
'C
fu+C::>>#"34rwws1vF++b!$x"((B72C'CC|
ra   c           	        [        U S5      n [        US5      n[        US5      nUnU(       a  U nO[        U SS9SUS-    n[        R
                  " US-   US-   4S5      n[        R
                  " US-   5      nUS   US	   -  US
'   US	   US
   US   -  -
  US'   [        SUS-   5       H  nXG   [        R                  " USU2US-
  4   USU SSS2   5      -
  XgS-
     -  XWU4'   [        SU5       H$  nXXUS-
  4   XWU4   XWU-
  US-
  4   -  -
  XXU4'   M&     XgS-
     SXWU4   S-  -
  -  Xg'   M     US   n	USS2S4   n
[        R                  " U5      R                  5       nSUS	'   XXU4$ )a  
Levinson-Durbin recursion for autoregressive processes.

Parameters
----------
s : array_like
    If isacov is False, then this is the time series. If iasacov is true
    then this is interpreted as autocovariance starting with lag 0.
nlags : int, optional
    The largest lag to include in recursion or order of the autoregressive
    process.
isacov : bool, optional
    Flag indicating whether the first argument, s, contains the
    autocovariances or the data series.

Returns
-------
sigma_v : float
    The estimate of the error variance.
arcoefs : ndarray
    The estimate of the autoregressive coefficients for a model including
    nlags.
pacf : ndarray
    The partial autocorrelation function.
sigma : ndarray
    The entire sigma array from intermediate result, last value is sigma_v.
phi : ndarray
    The entire phi array from intermediate result, last column contains
    autoregressive coefficients for AR(nlags).

Notes
-----
This function returns currently all results, but maybe we drop sigma and
phi from the returns.

If this function is called with the time series (isacov=False), then the
sample autocovariance function is calculated with the default options
(biased, no fft).
sr   r  F)r   Nr7   r   r   )r7   r7   rq   rG   r   )
r   r   r   r%   rM   r   rI   r   diagr   )r   r   r  ordersxx_mphisigr=   jsigma_varcoefspacf_s               r?   r3   r3     s   P 	1cAUG$Evx(FEaU#Keai0
((EAIuqy)3
/C
((519
Ca58#CI1XD	E!H,,CF1eai Hrvvc!A#q1u*ouQqz$B$/?@@AJqD	 q!Aq1uHqD	CAq1u4E(EEC1I Uq3!t9>12 ! "gG!"b&kGGGCLEE!HU,,ra   c                   [        U S5      n [        USSS9n[        R                  " [        R                  " U 5      5      n U S   S:w  a  [        S5      eU SS n U R                  S   nUb$  X:  a  [        S	5      eU SU n U R                  S   n[        R                  " US-   5      nU S   US'   [        R                  " SU S
-  -
  5      nU R                  5       n[        SU5       H^  nUSX&-
  *  R                  5       nXuU   USSS2   -  -
  USX&-
  * & XV   XFS-
     -  UR                  USX&-
  *  SSS2   5      -   X6S-   '   M`     SUS'   XS4$ )a  
Levinson-Durbin algorithm that returns the acf and ar coefficients.

Parameters
----------
pacf : array_like
    Partial autocorrelation array for lags 0, 1, ... p.
nlags : int, optional
    Number of lags in the AR model.  If omitted, returns coefficients from
    an AR(p) and the first p autocorrelations.

Returns
-------
arcoefs : ndarray
    AR coefficients computed from the partial autocorrelations.
acf : ndarray
    The acf computed from the partial autocorrelations. Array returned
    contains the autocorrelations corresponding to lags 0, 1, ..., p.

References
----------
.. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
    and forecasting. Springer.
r'   r   Trd   r   r7   zCThe first entry of the pacf corresponds to lags 0 and so must be 1.NzIMust provide at least as many values from the pacf as the number of lags.rq   rG   )r   r   rM   r   asarrayrP   r   r   cumprodr   rI   r   )r'   r   rj   r&   nur(  r   prevs           r?   r2   r2     s|   2 dF#DUGd3E::bjj&'DAw!| 
 	
 8D

1A9.  FU|JJqM
((1q5/C!WCF	A	M	"BiikG1a[z15"'')"QZ$tt*%<<
AE(Z"U)+dhhs1x7H27N.OOE
  CF<ra   c                  ^^^^ [         R                  " U [        S9S-  nUR                  S:X  a  UR	                  SS5      n[        U 5      nSUs=:  a  S:  a%  O  O"[        [         R                  " XQ-  5      5      nO[        U5      [        L a  US:  a  UnUW* S n[         R                  " U5      ) R                  SS9m[         R                  " USS9n[        T5       H7  u  pU
S:  d  M  [        R                  " SU	-  SS	9  [         R                  X'   M9     USU n[         R                  " U5      ) R                  SS9m[         R                  " USS9n[        T5       H7  u  pU
S:  d  M  [        R                  " S
U	-  SS	9  [         R                  X'   M9     X-  nU(       a  SSKJm  UUU4S jnUUU4S jnOSSKJm  UUU4S jnUUU4S jnUR'                  5       nUS;   a	  U" U5      nOLUS;   a  SU-  nU" U5      nO8US;   a'  S[         R(                  " U" U5      U" U5      5      -  nO[+        S5      e[        U5      S:X  a
  US   US   4$ UU4$ )a_
  
Test for heteroskedasticity of residuals

Tests whether the sum-of-squares in the first subset of the sample is
significantly different than the sum-of-squares in the last subset
of the sample. Analogous to a Goldfeld-Quandt test. The null hypothesis
is of no heteroskedasticity.

Parameters
----------
resid : array_like
    Residuals of a time series model.
    The shape is 1d (nobs,) or 2d (nobs, nvars).
subset_length : {int, float}
    Length of the subsets to test (h in Notes below).
    If a float in 0 < subset_length < 1, it is interpreted as fraction.
    Default is 1/3.
alternative : str, 'increasing', 'decreasing' or 'two-sided'
    This specifies the alternative for the p-value calculation. Default
    is two-sided.
use_f : bool, optional
    Whether or not to compare against the asymptotic distribution
    (chi-squared) or the approximate small-sample distribution (F).
    Default is True (i.e. default is to compare against an F
    distribution).

Returns
-------
test_statistic : {float, ndarray}
    Test statistic(s) H(h).
p_value : {float, ndarray}
    p-value(s) of test statistic(s).

Notes
-----
The null hypothesis is of no heteroskedasticity. That means different
things depending on which alternative is selected:

- Increasing: Null hypothesis is that the variance is not increasing
    throughout the sample; that the sum-of-squares in the later
    subsample is *not* greater than the sum-of-squares in the earlier
    subsample.
- Decreasing: Null hypothesis is that the variance is not decreasing
    throughout the sample; that the sum-of-squares in the earlier
    subsample is *not* greater than the sum-of-squares in the later
    subsample.
- Two-sided: Null hypothesis is that the variance is not changing
    throughout the sample. Both that the sum-of-squares in the earlier
    subsample is not greater than the sum-of-squares in the later
    subsample *and* that the sum-of-squares in the later subsample is
    not greater than the sum-of-squares in the earlier subsample.

For :math:`h = [T/3]`, the test statistic is:

.. math::

    H(h) = \sum_{t=T-h+1}^T  \tilde v_t^2
    \Bigg / \sum_{t=1}^{h} \tilde v_t^2

This statistic can be tested against an :math:`F(h,h)` distribution.
Alternatively, :math:`h H(h)` is asymptotically distributed according
to :math:`\chi_h^2`; this second test can be applied by passing
`use_f=False` as an argument.

See section 5.4 of [1]_ for the above formula and discussion, as well
as additional details.

References
----------
.. [1] Harvey, Andrew C. 1990. *Forecasting, Structural Time Series*
        *Models and the Kalman Filter.* Cambridge University Press.
r   rq   r7   rG   r   NaxiszfEarly subset of data for variable %d has too few non-missing observations to calculate test statistic.
stacklevelzfLater subset of data for variable %d has too few non-missing observations to calculate test statistic.)fc                *   > TR                  U TT5      $ r:   cdftest_statistics	denom_dofr4  	numer_dofs    r?   <lambda>2breakvar_heteroskedasticity_test.<locals>.<lambda>  s    QUUY	.
ra   c                *   > TR                  U TT5      $ r:   r   r8  s    r?   r<  r=    s    QTTY	.
ra   )r   c                .   > TR                  TU -  T5      $ r:   r6  r9  r   r:  r;  s    r?   r<  r=    s    TXX'.
ra   c                .   > TR                  TU -  T5      $ r:   r?  rA  s    r?   r<  r=    s    TWW'.
ra   )r   inc
increasing)r   dec
decreasingr   )2z2-sided	two-sidedzInvalid alternative.)rM   r+  floatr   r  r   r   roundtyper   r   nansum	enumerater   warnnanscipy.statsr4  r   rH   minimumrP   )residsubset_lengthalternativeuse_fsquared_residr   hnumer_residnumer_squared_sumr   dofdenom_residdenom_squared_sumtest_statistic
pval_lower
pval_upperp_valuer   r:  r4  r;  s                    @@@@r?    breakvar_heteroskedasticity_testra  (  s`   V JJuE2a7MQ%--b!4u:D=1-./	m		#(:$K((;'',,!,4I		+A6I&7MM-/01 	 $&66  '  #K((;'',,!,4I		+A6I&7MM-/01 	 $&66  ' ':N !



 	%




 ##%K00^,	2	2~-^,	5	5bjj~&
>(B
 
 /00
>aa '!*,,7""ra   c           
        [        U SSS9n [        R                  " U 5      R                  5       (       d  [	        S5      e[        US5      nUb(  [        US5      n[        R                  " S[        5        OS	n [        US
5      nUS::  a  [	        S5      e[        R                  " SUS-   5      nU R"                  S   SU-  [        U5      -   ::  aB  [	        SR%                  [        U R"                  S   [        U5      -
  S-  5      S-
  5      5      e0 nU GH  n0 nU(       a  ['        S5        ['        SU5        Un	[)        X	SSS9n
U(       a  [+        U
SS2SU	S-   24   SS9n[+        U
SS2SS24   SS9nUR"                  S   U
R"                  S   S-
  :X  d5  UR                  S5      UR                  S5      :H  R-                  5       S:w  a  [/        S5      eO[1        S5      e[3        U
SS2S4   U5      R5                  5       n[3        U
SS2S4   U5      R5                  5       nUR6                  R8                  (       a  UR:                  nOUR<                  nUS:X  d  UR>                  S:X  d  [        R@                  " URB                  5      (       d_  UR>                  U-  [        RD                  " [F        5      RH                  :  d*  URJ                  R"                  S   UR"                  S   :w  a  [/        S5      eUR>                  UR>                  -
  UR>                  -  U	-  URL                  -  nU(       aD  ['        SU[N        RP                  RS                  UXRL                  5      URL                  U	4-  5        U[N        RP                  RS                  UXRL                  5      URL                  U	4US'   URT                  UR>                  UR>                  -
  -  UR>                  -  nU(       a/  ['        SU[N        RV                  RS                  UU	5      U	4-  5        U[N        RV                  RS                  UU	5      U	4US'   SURX                  URX                  -
  -  nU(       a/  ['        SU[N        RV                  RS                  UU	5      U	4-  5        U[N        RV                  RS                  UU	5      U	4US '   [        RZ                  " [        R\                  " X45      [        R^                  " X5      [        R\                  " U	S45      45      nURa                  U5      nU(       a:  ['        S!URb                  URd                  URf                  URh                  4-  5        [        Rj                  " URb                  5      S"   [        Rj                  " URd                  5      S"   URf                  URh                  4US#'   XUU/4Xi'   GM     U$ ! [         ay    [        R                  " U Vs/ s H  n[        U5      PM     Os  snf sn5      nUR                  5       nUR                  5       S::  d  UR                   S:X  a  [	        S5      e GNf = f)$a`	  
Four tests for granger non causality of 2 time series.

All four tests give similar results. `params_ftest` and `ssr_ftest` are
equivalent based on F test which is identical to lmtest:grangertest in R.

Parameters
----------
x : array_like
    The data for testing whether the time series in the second column Granger
    causes the time series in the first column. Missing values are not
    supported.
maxlag : {int, Iterable[int]}
    If an integer, computes the test for all lags up to maxlag. If an
    iterable, computes the tests only for the lags in maxlag.
addconst : bool
    Include a constant in the model.
verbose : bool
    Print results. Deprecated

    .. deprecated: 0.14

       verbose is deprecated and will be removed after 0.15 is released



Returns
-------
dict
    All test results, dictionary keys are the number of lags. For each
    lag the values are a tuple, with the first element a dictionary with
    test statistic, pvalues, degrees of freedom, the second element are
    the OLS estimation results for the restricted model, the unrestricted
    model and the restriction (contrast) matrix for the parameter f_test.

Notes
-----
TODO: convert to class and attach results properly

The Null hypothesis for grangercausalitytests is that the time series in
the second column, x2, does NOT Granger cause the time series in the first
column, x1. Grange causality means that past values of x2 have a
statistically significant effect on the current value of x1, taking past
values of x1 into account as regressors. We reject the null hypothesis
that x2 does not Granger cause x1 if the pvalues are below a desired size
of the test.

The null hypothesis for all four test is that the coefficients
corresponding to past values of the second time series are zero.

`params_ftest`, `ssr_ftest` are based on F distribution

`ssr_chi2test`, `lrtest` are based on chi-square distribution

References
----------
.. [1] https://en.wikipedia.org/wiki/Granger_causality

.. [2] Greene: Econometric Analysis

Examples
--------
>>> import statsmodels.api as sm
>>> from statsmodels.tsa.stattools import grangercausalitytests
>>> import numpy as np
>>> data = sm.datasets.macrodata.load_pandas()
>>> data = data.data[["realgdp", "realcons"]].pct_change().dropna()

All lags up to 4

>>> gc_res = grangercausalitytests(data, 4)

Only lag 4

>>> gc_res = grangercausalitytests(data, [4])
rc   rq   r   zx contains NaN or inf values.addconstNverbosez>verbose is deprecated since functions should not print resultsTrU   r   z!maxlag must be a positive integerr7   zAmaxlag must be a non-empty list containing only positive integers   z6Insufficient observations. Maximum allowable lag is {}z
Granger Causalityznumber of lags (no zero)ru   )rw   dropexFr{   z`The x values include a column with constant values and so the test statistic cannot be computed.zNot ImplementedzfThe Granger causality test statistic cannot be computed because the VAR has a perfect fit of the data.zDssr based F test:         F=%-8.4f, p=%-8.4f, df_denom=%d, df_num=%d	ssr_ftestz3ssr based chi2 test:   chi2=%-8.4f, p=%-8.4f, df=%dssr_chi2testz3likelihood ratio test: chi2=%-8.4f, p=%-8.4f, df=%dlrtestzDparameter F test:         F=%-8.4f, p=%-8.4f, df_denom=%d, df_num=%d params_ftest)6r   rM   isfiniteallrP   r   r   rN  FutureWarningr   r   	TypeErrorr   r   r   rK   sizer   formatprintr$   r   r   r   NotImplementedErrorr   rJ   model
k_constantcentered_tssuncentered_tssssrr   rsquaredfinforI  epsr   df_residr   r4  r   r   r   llfcolumn_stackr   eyef_testfvaluer   df_denomdf_numr   )rc   rU   rc  rd  lagsr[   reslimlgresultmxlgdtadtaowndtajointres2down
res2djointtssfgc1fgc2lrrconstrftress                        r?   grangercausalitytestsr    s   Z 	1c"A;;q>899:.HGY/L	

 &(+Q;@AAyyFQJ' 	wwqzQZ#h-//sAGGAJX$>!#CDqHI
 	

 E'(,c2 fQ7 !#adQh&7"8%HF#C12J>Hq!ciilQ&67LLOx||A6;;=B)>  C &&788
 s1a4y&)--/QTH-113
 &&))C++C1H~~"xx
++,,$(;(;;  &&q)X^^A->>%A 
 \\JNN*nn !!" 	  GGJJtT+>+>?''		 GGJJtT#6#67	
{ }}z~~ =>OtT!:DAB #'

dD(A4!H~ 8<<*..01Euzz}}R.56 

b$ 7>x //XXtl#RVVD%74)9LM
 !!'*<<u~~u||LM JJu||$R(JJu||$R(NNLL	"
~ *g>?a d LG  xxV4VcSV4588:?dii1n$  -s   :7W Y"=X
AY"!Y"c                N   [        U S5      n [        USSS9n[        USSS9n[        USS	S9  [        US
SS9n[        USSSS9n[        USSS9nUR                  u  pxUS-  nUS:X  a  Un	O
[        XSS9n	[        X	5      R                  5       n
U
R                  SS[        -  -
  :  a  [        U
R                  XESS9nO,[        R                  " S[        SS9  [        R                   * 4nUS:X  a  [        R"                  /S-  nO[%        XUS-
  S9n['        US   X(S9nUS   X4$ )a  
Test for no-cointegration of a univariate equation.

The null hypothesis is no cointegration. Variables in y0 and y1 are
assumed to be integrated of order 1, I(1).

This uses the augmented Engle-Granger two-step cointegration test.
Constant or trend is included in 1st stage regression, i.e. in
cointegrating equation.

**Warning:** The autolag default has changed compared to statsmodels 0.8.
In 0.8 autolag was always None, no the keyword is used and defaults to
"aic". Use `autolag=None` to avoid the lag search.

Parameters
----------
y0 : array_like
    The first element in cointegrated system. Must be 1-d.
y1 : array_like
    The remaining elements in cointegrated system.
trend : str {"c", "ct"}
    The trend term included in regression for cointegrating equation.

    * "c" : constant.
    * "ct" : constant and linear trend.
    * also available quadratic trend "ctt", and no constant "n".

method : {"aeg"}
    Only "aeg" (augmented Engle-Granger) is available.
maxlag : None or int
    Argument for `adfuller`, largest or given number of lags.
autolag : str
    Argument for `adfuller`, lag selection criterion.

    * If None, then maxlag lags are used without lag search.
    * If "AIC" (default) or "BIC", then the number of lags is chosen
      to minimize the corresponding information criterion.
    * "t-stat" based choice of maxlag.  Starts with maxlag and drops a
      lag until the t-statistic on the last lag length is significant
      using a 5%-sized test.
return_results : bool
    For future compatibility, currently only tuple available.
    If True, then a results instance is returned. Otherwise, a tuple
    with the test outcome is returned. Set `return_results=False` to
    avoid future changes in return.

Returns
-------
coint_t : float
    The t-statistic of unit-root test on residuals.
pvalue : float
    MacKinnon"s approximate, asymptotic p-value based on MacKinnon (1994).
crit_value : dict
    Critical values for the test statistic at the 1 %, 5 %, and 10 %
    levels based on regression curve. This depends on the number of
    observations.

Notes
-----
The Null hypothesis is that there is no cointegration, the alternative
hypothesis is that there is cointegrating relationship. If the pvalue is
small, below a critical size, then we can reject the hypothesis that there
is no cointegrating relationship.

P-values and critical values are obtained through regression surface
approximation from MacKinnon 1994 and 2010.

If the two series are almost perfectly collinear, then computing the
test is numerically unstable. However, the two series will be cointegrated
under the maintained assumption that they are integrated. In this case
the t-statistic will be set to -inf and the pvalue to zero.

TODO: We could handle gaps in data by dropping rows with nans in the
Auxiliary regressions. Not implemented yet, currently assumes no nans
and no gaps in time series.

References
----------
.. [1] MacKinnon, J.G. 1994  "Approximate Asymptotic Distribution Functions
   for Unit-Root and Cointegration Tests." Journal of Business & Economics
   Statistics, 12.2, 167-76.
.. [2] MacKinnon, J.G. 2010.  "Critical Values for Cointegration Tests."
   Queen"s University, Dept of Economics Working Papers 1227.
   http://ideas.repec.org/p/qed/wpaper/1227.html
y0y1rq   r   trend)rg   rj   rh   ri   rk   rV   )aegrU   Trd   rm   rn   ro   return_resultsr7   rj   F)r  r|   d   )rU   rm   rf   zZy0 and y1 are (almost) perfectly colinear.Cointegration test is not reliable in this case.r2  re  r   r   r}   )r   r   r   r   r   r"   r   rJ   rz  SQRTEPSr/   rR  r   rN  r   rM   infrO  r    r!   )r  r  r  rV   rU   rm   r  r   k_varsxxres_cores_adfcritpval_asys                 r?   r-   r-     sD   | 
B	B	B1	%Bw0GHE(3fh6FT3KG ~/?$ON88LD
aKF|r6[__FS7]**LLS
 	?		
 FF7* |x!|vdQhG '!*AH1:x%%ra   c           	     H   SSK Jn   U" U 4SU0UDSU0D6R                  " S	SU0UD6$ ! [         a     g [         aa  nUb   S nAg SUR
                  S   ;  d  S[        U5      ;   a-  S/[        U5      -  nUS:X  a  S/U-   n[        XX#XE5      s S nA$  S nAg S nAf   g = f)
Nr   )ARIMAr"  r  start_paramsinitial皙?rg   rk  )	statsmodels.tsa.arima.modelr  rJ   r
   rP   argsstrr   _safe_arma_fit)r  r"  model_kwr  fit_kwr  r  errors           r?   r  r  2  s    1Q=e=x=u=AA 
%
)/
 	
   #ejjm+yCJ/F53u:-L| #u|3!(6  s&    ) 
B!	B!BA	BB!B!c           	        [        US5      n[        US5      n[        USSS9n[        USSS9n[        US	SS9n[        US
-   5       Vs/ s H  owPM     nn[        US
-   5       Vs/ s H  owPM     n	n[	        U[
        5      (       a  U/nO&[	        U[        [        45      (       d  [        S5      e[        R                  " [        U5      US
-   US
-   45      n
Uc  0 OUnUc  0 OUn[        U SSS9nU H[  nU	 HR  n[        XSU4XTU5      nUc  [        R                  U
SS2X4'   M/  [        U5       H  u  p[!        X5      XX4'   M     MT     M]     U
 Vs/ s H  n["        R$                  " UXS9PM     nn['        [)        UU5      5      n0 nUR+                  5        H  u  nn[        R,                  " [        R.                  " UR1                  5       R1                  5       U-
  5      5      nUR2                  S
   n[        R4                  " U5      nUR7                  US-   UU-  UU-  405        M     UR7                  U5        [9        S0 UD6$ s  snf s  snf s  snf )a  
Compute information criteria for many ARMA models.

Parameters
----------
y : array_like
    Array of time-series data.
max_ar : int
    Maximum number of AR lags to use. Default 4.
max_ma : int
    Maximum number of MA lags to use. Default 2.
ic : str, list
    Information criteria to report. Either a single string or a list
    of different criteria is possible.
trend : str
    The trend to use when fitting the ARMA models.
model_kw : dict
    Keyword arguments to be passed to the ``ARMA`` model.
fit_kw : dict
    Keyword arguments to be passed to ``ARMA.fit``.

Returns
-------
Bunch
    Dict-like object with attribute access. Each ic is an attribute with a
    DataFrame for the results. The AR order used is the row index. The ma
    order used is the column index. The minimum orders are available as
    ``ic_min_order``.

Notes
-----
This method can be used to tentatively identify the order of an ARMA
process, provided that the time series is stationary and invertible. This
function computes the full exact MLE estimate of each model and can be,
therefore a little slow. An implementation using approximate estimates
will be provided in the future. In the meantime, consider passing
{method : "css"} to fit_kw.

Examples
--------

>>> from statsmodels.tsa.arima_process import arma_generate_sample
>>> import statsmodels.api as sm
>>> import numpy as np

>>> arparams = np.array([.75, -.25])
>>> maparams = np.array([.65, .35])
>>> arparams = np.r_[1, -arparams]
>>> maparam = np.r_[1, maparams]
>>> nobs = 250
>>> np.random.seed(2014)
>>> y = arma_generate_sample(arparams, maparams, nobs)
>>> res = sm.tsa.arma_order_select_ic(y, ic=["aic", "bic"], trend="n")
>>> res.aic_min_order
>>> res.bic_min_order
max_armax_mar  )rj   rg   rk   r  Trd   r  r7   z.Need a list or a tuple for ic if not a string.Nr  )
contiguousr   )columnsindex
_min_orderrk  )r   r   r   rI   r   r  listtuplerP   rM   r   r   r   r  rO  rM  getattrpd	DataFramedictziprL   ascontiguousarrayrN   rK   r   argminupdater   )r  r  r  icr  r  r  r   ar_rangema_rangerZ   y_arrarmarQ   criteriaresdfsmin_resr  deltancolslocs                          r?   r.   r.   O  sJ   v fh'Ffh'Fw
;E:=Hvx$7F !,-,a,H- !,-,a,H-"cTT5M**IJJhhB!VaZ89G%r8H>RvFq#$/EB QXfMC{%'VV2	"(}%,S%;2	"  -   HOGNS(;w   s2s|
C GYY[	6$$RVVFJJL,<,<,>,G%HIAiiL(3%<u*EFG	 !
 JJw<3<I .-(s   
I'IIc                V    [         R                  " [         R                  " U 5      5      $ )zB
Returns True if "data" contains missing entries, otherwise False
)rM   r   r   )datas    r?   r   r     s     88BFF4L!!ra   c           
     V   [        U S5      n [        USSS9n[        US5      nU R                  S   nUnX@R                  :w  a  [        SU R                   S35      eUS	:X  aJ  [        U [        [        R                  " S
US
-   5      5      5      R                  5       R                  n/ SQnOX R                  5       -
  n/ SQnUS:X  aI  [        [        R                  " S[        R                  " US-  S5      -  5      5      n[!        X$S
-
  5      nOUS:X  d  Uc7  Uc  ["        R$                  " S[&        SS9  [)        Xd5      n[!        X$S
-
  5      nOB[+        U[,        5      (       a  [        S5      e[/        USSS9nX$:  a  [        SU SU S35      e/ SQn[        R0                  " UR3                  5       S-  5      US-  -  n	[5        XdU5      n
X-  n[        R6                  " XU5      nSnXS   :X  a(  ["        R$                  " UR9                  SS 9[:        SS9  O/XS   :X  a'  ["        R$                  " UR9                  S!S 9[:        SS9  US   US
   US   US"   S#.nU(       a@  SS$KJn  U" 5       nUUl         UUl!        US%:X  a  S&OS'nS(U S)3Ul"        S*U S)3Ul#        XUU4$ XX.4$ )+a4  
Kwiatkowski-Phillips-Schmidt-Shin test for stationarity.

Computes the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test for the null
hypothesis that x is level or trend stationary.

Parameters
----------
x : array_like, 1d
    The data series to test.
regression : str{"c", "ct"}
    The null hypothesis for the KPSS test.

    * "c" : The data is stationary around a constant (default).
    * "ct" : The data is stationary around a trend.
nlags : {str, int}, optional
    Indicates the number of lags to be used. If "auto" (default), lags
    is calculated using the data-dependent method of Hobijn et al. (1998).
    See also Andrews (1991), Newey & West (1994), and Schwert (1989). If
    set to "legacy",  uses int(12 * (n / 100)**(1 / 4)) , as outlined in
    Schwert (1989).
store : bool
    If True, then a result instance is returned additionally to
    the KPSS statistic (default is False).

Returns
-------
kpss_stat : float
    The KPSS test statistic.
p_value : float
    The p-value of the test. The p-value is interpolated from
    Table 1 in Kwiatkowski et al. (1992), and a boundary point
    is returned if the test statistic is outside the table of
    critical values, that is, if the p-value is outside the
    interval (0.01, 0.1).
lags : int
    The truncation lag parameter.
crit : dict
    The critical values at 10%, 5%, 2.5% and 1%. Based on
    Kwiatkowski et al. (1992).
resstore : (optional) instance of ResultStore
    An instance of a dummy class with results attached as attributes.

Notes
-----
To estimate sigma^2 the Newey-West estimator is used. If lags is "legacy",
the truncation lag parameter is set to int(12 * (n / 100) ** (1 / 4)),
as outlined in Schwert (1989). The p-values are interpolated from
Table 1 of Kwiatkowski et al. (1992). If the computed statistic is
outside the table of critical values, then a warning message is
generated.

Missing values are not handled.

See the notebook `Stationarity and detrending (ADF/KPSS)
<../examples/notebooks/generated/stationarity_detrending_adf_kpss.html>`__
for an overview.

References
----------
.. [1] Andrews, D.W.K. (1991). Heteroskedasticity and autocorrelation
   consistent covariance matrix estimation. Econometrica, 59: 817-858.

.. [2] Hobijn, B., Frances, B.H., & Ooms, M. (2004). Generalizations of the
   KPSS-test for stationarity. Statistica Neerlandica, 52: 483-502.

.. [3] Kwiatkowski, D., Phillips, P.C.B., Schmidt, P., & Shin, Y. (1992).
   Testing the null hypothesis of stationarity against the alternative of a
   unit root. Journal of Econometrics, 54: 159-178.

.. [4] Newey, W.K., & West, K.D. (1994). Automatic lag selection in
   covariance matrix estimation. Review of Economic Studies, 61: 631-653.

.. [5] Schwert, G. W. (1989). Tests for unit roots: A Monte Carlo
   investigation. Journal of Business and Economic Statistics, 7 (2):
   147-159.
rc   rf   )rg   rh   rk   rp   r   x of shape  not understoodrh   r7   )gX9v?g㥛 ?gI+?gS?)gh|?5?goʡ?g|?5^?gS?legacyrr   rs   rt   autozpNone is not a valid value for nlags. It must be an integer, 'auto' or 'legacy'. None will raise starting in 0.14rq   r2  z0nvals must be 'auto' or 'legacy' when not an intr   Frd   zlags (z$) must be < number of observations (r   )r  r   皙?{Gz?The test statistic is outside of the range of p-values available in the
look-up table. The actual p-value is {direction} than the p-value returned.
rG   smaller	directiongreaterre  r   r   z2.5%r   ry   rg   levelr  zThe series is z stationaryzThe series is not )$r   r   r   r   rq  rP   r   r   rM   r   rJ   rR  r   r   r   r   rK   r   rN  ro  _kpss_autolagr   r  r   r   r   _sigma_est_kpssinterprr  r   r   rz   r  r   r   r   )rc   rf   r   rp   r   hyporesidsr  pvalsetas_hat	kpss_statr`  warn_msg	crit_dictrz   rstorestationary_types                     r?   r0   r0     s   f 	1cAZ{KJeW%E771:DD vv~;qwwi?@@t| QRYYq$(%;<=AACII+ VVX+BGGD288D5L'#BBCDE!8$	&EM=MMG	 f+E!8$	E3		KLL%8=CD6K  &E
&&A%
&$!)
4CF%0EIii	/GH )OOiO0 	

 
!H	OOiO0 	
 QtAwQtAwOI=%)S['g$_$5[A	((9E	9f44533ra   c                    [         R                  " U S-  5      n[        SUS-   5       H4  n[         R                  " XS U SX-
   5      nUSU-  SXBS-   -  -
  -  -  nM6     X1-  $ )zo
Computes equation 10, p. 164 of Kwiatkowski et al. (1992). This is the
consistent estimator for the variance.
rq   r7   Nr   )rM   r   rI   r   )r  r   r  r  r   resids_prods         r?   r  r  l  sq    
 FF6Q;E1dQhffVBZ
$();<[C1s
+;$<==   <ra   c                   [        [        R                  " US5      5      n[        R                  " U S-  5      U-  nSn[	        SUS-   5       H3  n[        R
                  " XS U SX-
   5      nXaS-  -  nX6-  nXEU-  -  nM5     XC-  nSnS[        R                  " Xw-  U5      -  n	[        U	[        R                  " X5      -  5      n
U
$ )	z
Computes the number of lags for covariance matrix estimation in KPSS test
using method of Hobijn et al (1998). See also Andrews (1991), Newey & West
(1994), and Schwert (1989). Assumes Bartlett / Newey-West kernel.
gqq?rq   r   r7   Nr   UUUUUU?g{P?)r   rM   r   r   rI   r   )r  r   covlagss0s1r   r  r  pwr	gamma_hatautolagss              r?   r  r  x  s     "((4+,G	!	t	#B	
B1gk"ffVBZ
$();<cz!

+o	 #
 GE
C%-55I9rxx223HOra   c                   [        U S5      n [        US5      nU R                  S   nX R                  :w  a  [	        SU R                   S35      e/ SQn[
        R                  " / SQ5      n[
        R                  " / SQ/ S	Q/ S
Q/ SQ/ SQ/ SQ/ SQ/ SQ/ SQ/ SQ/ SQ/ SQ/5      n[
        R                  " SUR                  S   45      n[        UR                  S   5       H"  n[        XESS2U4   5      nU" U5      USU4'   M$     [        R                  " U 5      n	U	R                  S5      R                  5       R                  S5      n
U	R                  S5      R                  5       R                  S5      nX:  R!                  5       X:  R!                  5       -   nU[
        R"                  " [%        U 5      5      -  n[%        U5      S-
  n[        [%        U5      S-
  SS5       H  nXSU4   :  a  UnM    O   X>   nSnSnXS   :X  a  SnO
XS   :X  a  SnU(       a'  [&        R(                  " UR+                  US9[,        SS9  US   US   US    US!   S".nU(       a'  SS#KJn  U" 5       nUUl        S$Ul        S%Ul        XUU4$ XU4$ )&aE  
Range unit-root test for stationarity.

Computes the Range Unit-Root (RUR) test for the null
hypothesis that x is stationary.

Parameters
----------
x : array_like, 1d
    The data series to test.
store : bool
    If True, then a result instance is returned additionally to
    the RUR statistic (default is False).

Returns
-------
rur_stat : float
    The RUR test statistic.
p_value : float
    The p-value of the test. The p-value is interpolated from
    Table 1 in Aparicio et al. (2006), and a boundary point
    is returned if the test statistic is outside the table of
    critical values, that is, if the p-value is outside the
    interval (0.01, 0.1).
crit : dict
    The critical values at 10%, 5%, 2.5% and 1%. Based on
    Aparicio et al. (2006).
resstore : (optional) instance of ResultStore
    An instance of a dummy class with results attached as attributes.

Notes
-----
The p-values are interpolated from
Table 1 of Aparicio et al. (2006). If the computed statistic is
outside the table of critical values, then a warning message is
generated.

Missing values are not handled.

References
----------
.. [1] Aparicio, F., Escribano A., Sipols, A.E. (2006). Range Unit-Root (RUR)
    tests: robust against nonlinearities, error distributions, structural breaks
    and outliers. Journal of Time Series Analysis, 27 (4): 545-576.
rc   rp   r   r  r  )r  r  r   r  ?gffffff?)   2   r           i  i  i  i  i  i  )gJ4?gX ?g`vOj?gkw#?g[ A@g}b@)gI&?gB?g?gMSt$?gDt@g(@)g/$?gOec?gcZB?gW[?ge`TR@gQI	@)gaTR'?g&S:?gZڊ?g48E?go!@gkw	@)gŏ1w?g?g;Nё\?gSt$?g58EGr@gHP	@)g[ A?gX?g6<R?g䃞ͪ?gGx$@g/L
F
@)g'W?gk	?gͪV?gݓ?g7d*@gY 
@)gݓZ?g	h"?g@?gOjM?g/n@gRI&B@)g	^)?gQ?g^I+?g9#J?gRI&@g"uq@)g(?gy&1?gH?gHPs?g@g3@)g0*?goT?gk	g?gn4@?g;O@g/L
@)gJ4?g?ggs?gTt$?gqh 	@gc=y@r7   NrG   r   r  largerr  rq   r2  )r   re  )r   rq   )r   r7   )r   r   r  ry   zThe series is not stationaryzThe series is stationary)r   r   r   rq  rP   rM   r   r   rI   r   r  Series	expandingr   shiftrK   r   r   r   r   rN  rr  r   r   rz   r   r   r   )rc   rp   r   r  rj   r  
inter_critr   r4  xsexp_maxexp_mincountrur_statr=   r`  r  r  r  rz   r  s                        r?   r5   r5     sy   \ 	1cAeW%E771:D vv~;qwwi?@@ 2E
G	A 88<<<<<<<<<<<<	
D$ 1djjm,-J4::a=!QQT
#T7
1a4 "
 
1Bll1o!!#))!,Gll1o!!#))!,G\ BL#5#5#77Erwws1v&HE
QA3u:>2r*A&&A	 + hGH I)		!H		OOiO0 	
 $4 	I =2	.	)V33)++ra   c                  P    \ rS rSrSrS rSS jrS rS rS r	SS	 jr
 SS
 jrSrg)ZivotAndrewsUnitRooti	  zA
Class wrapper for Zivot-Andrews structural-break unit-root test
c                J   0 U l         SU l        [        R                  " U R                  5      U R                   S'   SU l        [        R                  " U R                  5      U R                   S'   SU l        [        R                  " U R
                  5      U R                   S'   g)z
Critical values for the three different models specified for the
Zivot-Andrews unit-root test.

Notes
-----
The p-values are generated through Monte Carlo simulation using
100,000 replications and 2000 data points.
)0)MbP?g3P>#)r  g#S)皙?g(IL)333333?g V)皙?g>d)      ?g=)333333?g)^Ҙ)ffffff?g&"p)皙?g;)T)r  gٙB56)r   g9])      @g3")      @gdF >)      @gMJA)      $@gݘC)      )@g[B>)      .@g\ʞ)     1@gz[)      4@gUN )     6@gF)      9@g؁sF)     ;@gE|')      >@gd#W)     @@@g%䃞-)     A@g2%)     B@ght)      D@g|])     @E@g"2)     F@gm)     G@gR
q)      I@gAJ))     @J@gA} R)     K@g rh)     L@go_G)      N@g)W)     @P@g Ac])     Q@g6qr)     R@giW!')      T@g16T
)     @U@g!A	3m	)     V@g_LU)      W@g{)     W@gd)      X@gY )     @X@gek})     X@gv)     X@g 4)皙X@g
ܺ:rg   )0)r  g3T)r  gMSt+)r  g߾C")r  gytM)r  gjn)r  g=$@)r  g ~:)r  g9ֿ)r  gm)r  gQ)r   g<#)r  g :̗)r  g	)r  g0)r  gj)r  gǺ&)r  gec)r  gӼ	)r  gC)r  geN)r  g.=)r  gt.)r  gZ)r  gjHci)r   gGȰ
)r!  gJRЭ)r"  gKqU)r#  g:H
)r$  g$
)r%  gY
)r&  g->x
)r'  g"	)r(  g"^	)r)  g	)r*  gdw)r+  gz6>)r,  g҇n)r-  g+j)r.  g(D!T)r/  gsF)r0  g	)r1  g.9N)r2  gŏ1w)r3  gJR)r4  gn2d)r5  gAf )r6  g"^F)r7  gHht)0)r  gX9C)r  g%jj)r  gC5vJ)r  g)r  g=s)r  gu7O)r  g)r  g9z)r  g^D)r  gGȰj)r   gÙ_M)r  gUj@+0)r  g%eK)r  g2Y)r  gt3N)r  g7)r  gFx)r  gQ[)r  g46<)r  gM)r  gP1)r  gt~)r  g1N)r  g )r   g)r!  g	/)r"  goʡ)r#  g|Sz)r$  gmJR)r%  g9}+)r&  gLOX)r'  gkC8)r(  g~jt)r)  gF()r*  g.)r+  gb=9)r,  gڏa)r-  g`)r.  gq2)r/  g_LU)r0  gG=D;H
)r1  gN	)r2  gk}Ж)r3  gp>?)r4  g1)r5  gԷ)r6  g	c)r7  gR%Mrh   N)_za_critical_values_crM   r+  _t_ct)selfs    r?   __init__ZivotAndrewsUnitRoot.__init__	  s     $& 1
d )+

477(;  %1
d )+

477(;  %1
d *,DHH)=  &ra   c                    U R                   U   nUSS2S4   nUSS2S4   n[        R                  " XU5      S-  n/ SQn[        R                  " XtU5      nUS   US   US   S.n	Xi4$ )a  
Linear interpolation for Zivot-Andrews p-values and critical values

Parameters
----------
stat : float
    The ZA test statistic
model : {"c","t","ct"}
    The model used when computing the ZA statistic. "c" is default.

Returns
-------
pvalue : float
    The interpolated p-value
cvdict : dict
    Critical values for the test statistic at the 1%, 5%, and 10%
    levels

Notes
-----
The p-values are linear interpolated from the quantiles of the
simulated ZA test statistic distribution
Nr   r7   rs   )r   r  r  rq   r   )r9  rM   r  )
r=  statru  tablepcntsr   r   cv
crit_valuecvdicts
             r?   _za_critZivotAndrewsUnitRoot._za_crit	  s~    0 ((/adad4.6YYr%0
Q-Q-a=

 ~ra   c                   [         R                  R                  UR                  R	                  U5      5      nUR                  R	                  U5      nUR
                  u  pVUR	                  U5      nXR	                  U5      -
  nUR                  R	                  U5      XV-
  -  n	U[         R                  " [         R                  " X-  5      5      -  $ )z9
Minimal implementation of LS estimator for internal use
)rM   linalginvTr   r   r   r!  )
r=  rR   rS   xpxixpyr   k_exogber   s
             r?   
_quick_olsZivotAndrewsUnitRoot._quick_ols	  s     yy}}TVVZZ-.ffjjzzHHSMHHQKt}-2772776=1222ra   c                   [         R                  " USS9nU[         R                  " UR                  R	                  U5      5      -  nU[         R                  " UR                  R	                  U5      5      -  n[         R
                  " XvS R                  S   XV-   45      nX8SS2S4'   XUS-
   USS2US-
  4'   [        XvSS9XhR                  S   U-    USS2US24'   Xx4$ )zn
Create the endog/exog data for the auxiliary regressions
from the original (standardized) series under test.
r   r0  Nr7   r   )rw   )rM   r   r   rL  r   r   r   r#   )	r=  seriesr   constr  colsr  rR   rS   s	            r?   _format_regression_data,ZivotAndrewsUnitRoot._format_regression_data	  s     Q'U+,,"''&((,,v"677xxu++A.<=QT
"4!85Qq[&9::a=4'
QX {ra   c	                   X8S-   -
  n	US:w  aC  SUSU	2S4'   XQU	S2S4'   XhS-   US-    USS2S4'   US:X  a  SUSU	2S4'   USXC-
  S-    XS2S4'   U$ XhS-   US-    USS2S4'   SUSU	S-
  2S4'   USXC-
  S-    XS-
  S2S4'   U$ )z0
Update the exog array for the next regression.
r7   r8  r   Nrq   rh   re  rk  )
r=  rS   rf   periodr   rV  r  rW  r  cutoffs
             r?   _update_regression_exog,ZivotAndrewsUnitRoot._update_regression_exog

  s     !8$ D&!$!qTAX7DAJT!#$WfWaZ #(dma.?#AWaZ 
  qTAX7DAJ&'DFQJ"#&+A1B&DD1*"#ra   Nc                *   [        US[        R                  SS9n[        US5      n[	        USSS9n[        USS	S
9n[        USSSS9nUS:  d  US:  a  [        S5      eUR                  S   nU(       a  [        XSUS9nUS   nO0U(       a  UnO&[        S[        R                  " US-  S5      -  5      n[        Xb-  5      n	U	n
Xi-
  nUS:X  a  SnOSnS[        R                  " U5      -  n[        R                  " SUS-   5      nU[        R                  " S5      US-  -  -  nU R                  XXX5      u  nn[        R                  " US-   [        R                  5      n[!        U
S-   US-   5       H  nU R#                  UUUUUUUU5      nUU
S-   :X  a  [%        XS USS9R'                  5       nUR(                  UR                  S   S-
  :  a5  [        SR+                  UR                  S   S-
  UR(                  5      5      eUR,                  US-
     UU'   M  U R/                  XS U5      US-
     UU'   M     [        R0                  " U5      n[        R2                  " U5      S-
  nU R5                  UU5      nUS   nUS   nUUUUU4$ )a
  
Zivot-Andrews structural-break unit-root test.

The Zivot-Andrews test tests for a unit root in a univariate process
in the presence of serial correlation and a single structural break.

Parameters
----------
x : array_like
    The data series to test.
trim : float
    The percentage of series at begin/end to exclude from break-period
    calculation in range [0, 0.333] (default=0.15).
maxlag : int
    The maximum lag which is included in test, default is
    12*(nobs/100)^{1/4} (Schwert, 1989).
regression : {"c","t","ct"}
    Constant and trend order to include in regression.

    * "c" : constant only (default).
    * "t" : trend only.
    * "ct" : constant and trend.
autolag : {"AIC", "BIC", "t-stat", None}
    The method to select the lag length when using automatic selection.

    * if None, then maxlag lags are used,
    * if "AIC" (default) or "BIC", then the number of lags is chosen
      to minimize the corresponding information criterion,
    * "t-stat" based choice of maxlag.  Starts with maxlag and drops a
      lag until the t-statistic on the last lag length is significant
      using a 5%-sized test.

Returns
-------
zastat : float
    The test statistic.
pvalue : float
    The pvalue based on MC-derived critical values.
cvdict : dict
    The critical values for the test statistic at the 1%, 5%, and 10%
    levels.
baselag : int
    The number of lags used for period regressions.
bpidx : int
    The index of x corresponding to endogenously calculated break period
    with values in the range [0..nobs-1].

Notes
-----
H0 = unit root with a single structural break

Algorithm follows Baum (2004/2015) approximation to original
Zivot-Andrews method. Rather than performing an autolag regression at
each candidate break period (as per the original paper), a single
autolag regression is run up-front on the base model (constant + trend
with no dummies) to determine the best lag length. This lag length is
then used for all subsequent break-period regressions. This results in
significant run time reduction but also slightly more pessimistic test
statistics than the original Zivot-Andrews method, although no attempt
has been made to characterize the size/power trade-off.

References
----------
.. [1] Baum, C.F. (2004). ZANDREWS: Stata module to calculate
   Zivot-Andrews unit root test in presence of structural break,"
   Statistical Software Components S437301, Boston College Department
   of Economics, revised 2015.

.. [2] Schwert, G.W. (1989). Tests for unit roots: A Monte Carlo
   investigation. Journal of Business & Economic Statistics, 7:
   147-159.

.. [3] Zivot, E., and Andrews, D.W.K. (1992). Further evidence on the
   great crash, the oil-price shock, and the unit-root hypothesis.
   Journal of Business & Economic Studies, 10: 251-270.
rc   r7   )r   r   rw   rU   Trd   rf   )rg   r8  rh   rk   rm   rn   )rl   re   r   r  z,trim value must be a float in range [0, 1/3)rh   )rU   rf   rm   rq   rr   rs   rt         r   re  g      ?N)hasconstzRZA: auxiliary exog matrix is not full rank.
  cols (exc intercept) = {}  rank = {})r   rM   doubler   r   r   rP   r   r/   r   r   r   r   rX  r   r  rI   r]  r   rJ   df_modelrr  rO   rR  rK   r  rG  )r=  rc   rw   rU   rf   rm   r   adf_resbaselagstrimcntstart_period
end_periodbasecolsc_constt_constrR   rS   r   bpozastatbpidxr  pvalrF  s                            r?   runZivotAndrewsUnitRoot.run
  s   Z q#RYYQ7$'&(T: .>

 Y(@4
 !8ty)KLLwwqzT7G qzHH4"((4%<"AABHdk"^
HHbggdm#))C*2771://22Wx
t 
Q/q(*q.9B//	D \A%%i($;??A::

1 11$AAG JJqMA-qzzB  IIhl3b	 OOE),<dCqLb	1 :8 		% 1$}}VZ0AwatVXu44ra   c                $    U R                  XX4US9$ )N)rw   rU   rf   rm   )rr  )r=  rc   rw   rU   rf   rm   s         r?   __call__ZivotAndrewsUnitRoot.__call__
  s!     xx  
 	
ra   )r:  r<  r;  r9  )rg   )g333333?Nrg   AIC)__name__
__module____qualname____firstlineno____doc__r>  rG  rR  rX  r]  rr  ru  __static_attributes__rk  ra   r?   r	  r	  	  s6    f>P$L
3&(T5n BG
ra   r	  )rk  rk  F)Nrg   rw  FF)rU   
int | None)FTTr   N)FNFTNTr   )Nr   )rc   ArrayLike1Dr   r~  rV   zLiteral['adjusted', 'mle']return
np.ndarray)NT)rc   r  r   r~  r   boolr  ztuple[np.ndarray, np.ndarray])NTF)
rc   r  r   r~  r   r  r   r  r  r  )Nr  N)
rc   r  r   r~  rV   zLiteral['yw', 'ywadjusted', 'ols', 'ols-inefficient', 'ols-adjusted', 'ywm', 'ywmle', 'ld', 'ldadjusted', 'ldb', 'ldbiased', 'burg']r   zfloat | Noner  z*np.ndarray | tuple[np.ndarray, np.ndarray])TTT)TT)r   Fr:   )r  rH  T)TN)rg   r  Nr8   N)rm   z
str | None)ra  rq   rD   rg   NN)rg   r  F)rf   zLiteral['c', 'ct']r   zLiteral['auto', 'legacy'] | intrp   r  r  z*tuple[float, float, int, dict[str, float]])F)_r|  
__future__r   statsmodels.compat.numpyr   statsmodels.compat.pandasr   statsmodels.compat.pythonr   statsmodels.compat.scipyr   typingr   r	   r   numpyrM   numpy.linalgr
   pandasr  scipyr   scipy.interpolater   scipy.signalr   #statsmodels.regression.linear_modelr   r   statsmodels.tools.sm_exceptionsr   r   r   r   r   statsmodels.tools.toolsr   r   statsmodels.tools.validationr   r   r   r   r   r   statsmodels.tsa._bdsr   statsmodels.tsa._innovationsr   r   statsmodels.tsa.adfvaluesr    r!   statsmodels.tsa.tsatoolsr"   r#   r$   ndarrayr  r  rI  r  __all__r   r{  rc  r|  r  r`   r/   r%   r,   r&   r(   r1   r)   r'   r*   r+   r3   r2   ra  r  r-   r  r.   r   r0   r  r  r5   r	  r4   rr  rk  ra   r?   <module>r     s<   # * 5 * 2 !   $   & " @  8  % M ? A ABJJ		4;67. ''"((299%))
* V(F 
`F`FF Z(G )GT'^ 


N"d )3000 '0 	0h >BBB%B6:B"BJ Z( 	VVV V 	V
 V )Vv  	#TTTT" #T$ 0%Tn Z(*@ )*@Z Z(8D 8 )8zD-N6t @DV#rbP I& I&X< GKeP" &)-3	k4"k4 +k4 	k4
 0k4\	*H,Va
 a
H %&%))11 ra   