
    M/Phx                      d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	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Zdd
lmZ ddlmZ ddlmZ ddlmZmZ ddlmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 eej:        ej;        e<e=         f         Z>g dZ? ej@         ejA        ejB                  jC                  ZD	 	 	 dZdZE	 	 	 	 	 d[d\dZF edd          d]d"            ZGd# ZH	 	 	 	 	 	 	 d^d$ZI	 	 d_d`d,ZJ	 dadbd0ZK edd          	 	 	 dcddd2            ZL	 	 	 dedfd8ZM edd          dgd9            ZN edd          dhddd:d;            ZOdid=ZPdjd>ZQ	 dkdAZRdldBZS	 	 	 	 	 dmdndGZTdjdHZU	 dodLZVdM ZW	 	 	 dpdqdTZXdU ZYdV ZZdrdWZ[ G dX dY          Z\ e\            Z]e]j^        j         e]_         dS )sz,
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_test Fc	                   i }	|                                 }t          |||z   dz             D ]/}
 | ||ddd|
f         g|R  }|                                |	|
<   0|dk    r/t          d |	                                D                       \  }}n|dk    r/t          d |	                                D                       \  }}n~|dk    red}||z   }d	}t          ||z   |dz
  d
          D ]C}
t          j        |	|
         j        d
                   }|
}t          j        |          |k    r nDnt          d| d          |s||fS |||	fS )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  .   K   | ]\  }}|j         |fV  d S N)r9   .0kvs      Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/stattools.py	<genexpr>z_autolag.<locals>.<genexpr>   ,      EETQquajEEEEEE    bicc              3  .   K   | ]\  }}|j         |fV  d S r;   )rD   r<   s      r@   rA   z_autolag.<locals>.<genexpr>   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   s   t G\\^^FXx&01455 * *s5$qqq$3$w-:':::#''))EEW]]__EEEEE	5EEW]]__EEEEE	8		!V#F*HqL"== 	 	CVGCL0455FGvf~~%% & J&JJJKKK (ww''rC   cAICrU   
int | Nonec           
        t          | d          } t          |dd          }t          |dd          }t          |ddd	
          }t          |d          }t          |d          }|                                 |                                 k    rt          d          |rd}ddddd}|t          |t                    r||         }|	                                }| j
        d         }|dk    rt          |          nd}|it          t          j        dt          j        |dz  d          z                      }t          |dz  |z
  dz
  |          }|dk     rt          d          n||dz  |z
  dz
  k    rt          d          t          j        |           }	t!          |	dddf         |dd          }
|
j
        d         }| | dz
  d         |
dddf<   |	| d         }|rdd lm}  |            }|r|dk    rt'          |
|d!          }n|
}|j
        d         |
j
        d         z
  dz   }|st)          t*          |||||          \  }}n&t)          t*          ||||||"          \  }}}||_        ||z  }t!          |	dddf         |dd          }
|
j
        d         }| | dz
  d         |
dddf<   |	| d         }|}n|}d}|dk    r@t+          |t'          |
ddd|dz   f         |                                                    }n1t+          ||
ddd|dz   f                                                   }|j        d         }t3          ||d#          }t5          d||$          }|d         |d         |d         d%}|rL||_        ||_        ||_        ||_        ||_        ||_         d&|_!        d'|_"        ||_#        d(|_$        ||||fS |s|||||fS ||||||fS ))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)ra   ctcttnoptionsautolagr9   rD   rF   rg   rm   storerY   zInvalid input, x is constantrk   ra   ri   rj   )Nr   r8      Nr         (@      Y@      ?rr   r8   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   rh   Nr   rh   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.diagnosticr{   r"   r`   r   autolag_resultsrJ   rO   r!   r    resolsrU   usedlagadfstat
critvaluesr   H0HAr]   _str)re   rU   rh   rn   rq   rY   	trenddictr   ntrendxdiffxdallxdshortr{   resstorefullRHSrT   r]   r^   alresr   r   r   pvaluer   s                           r@   r/   r/      s   ~ 	1cAfh666FL*A  J T3K  G eW%%E:|44Juuww!%%''7888 st66IZ
C88z*
!!##J71:D *c 1 1S___qF~RWTBHTE\7$C$CCDDEETQY'!+V44A::'   
 
$!)f$q(	(	('
 
 	

 GAJJE5D>6FFFE;q>DTEAIN#E!!!Q$KTEFFmG "======<>> %z4@@@GGG=#ek!n4q8  	-&Wgx OFGG &.%& & &"FGU (-H$8 uQQQW~wVdKKK{1~	B'aaad-SYuQQQ'A+%56
CC
 

#%% 	 WeAAA}1}$4566::<<nQG J!<<<FzEEEJmm!} J
  F  ""(I 	 M >
H44 	FFGT:==FGT:vEErC   unbiasedadjustedTnonec                	   t          |d          }t          |d          }t          |dd          }t          |dd          }t          |d	d
          }t          | dd          } |                                }|dk    rd}nt          |           }|rm|dk    rt          d          t          j        |            }|dk    r| 	                                } d| | <   n| |         } |
                    t                    }|r;|r9| |                                 |                                z  z
  }	|dk    rd|	| <   n|r| |                                 z
  }	n| }	t          |           }
|}||
dz
  }n||
dz
  k    rt          d          |sL|It          j        |dz             }|	                    |	          |d<   t%          |          D ]4}|	|dz   d                             |	d|dz                       ||dz   <   5|r|dk    r&|r||
t          j        |dz             z
  z  }n||
z  }n|rt          j        |dz   t          j                  }|                                |d<   t%          |          D ]4}||dz   d                             |d|dz                       ||dz   <   5d||dk    <   ||z  }n||                                z  }|S |r(|r&|dk    r t          j        ||d          }d||dk    <   n|r@t          j        d|
dz             }t          j        ||dd         ddd         f          }nO|r0|                                t          j        d|
z  dz
            z  }n|
t          j        d|
z  dz
            z  }|rt          |	          }t1          d|z  dz             }
t          j                            |	|
          }t          j                            |t          j        |          z            d|         ||dz
  d         z  }|j        }n/t          j        |	|	d          |
dz
  d         ||
dz
  d         z  }||d|dz            	                                S |S )a  
    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fftFrf   missingr   raiseconservativedroprl   nlagTre   r8   ndimr   r   z!NaNs were encountered in the datar   r   Nz"nlag must be smaller than nobs - 1r   dtypefullrG   rr   )rk   )r   r   r   r   rH   has_missingr   rM   isnancopyastyper   summeanr   rP   emptydotrI   arangeint64r   hstackonesr   r   ifft	conjugatereal)re   r   r   r   r   r   deal_with_maskednotmask_boolnotmask_intxork   lag_lenacovidivisordxir   Frfs                      r@   r%   r%     s   X :..Hvx((F
C
/
/
/C$M  G D&4000D1c"""AmmooG& &q>> 
/g"#FGGG|n$$A A|m,A"))#.. " ;??,,,,n$$ !B}	 \AAG|a%	A=>>> 4#x!$$&&**Qw 	: 	:AQUWW+//"ZQxZ.99DQKK 	*7f#4#4 BIgk2222	 
*(7Q;bh???(__..
w  A%0Q%9%=%=#JAhJ/& &GAENN )*1%))) 
#$ 
#N)B)BLk6::!q&			 #Yq!a%  Ir2crc744R4=)**	 #OOA	 2 22A	"""
 B2ww!d(Q,''fjjqj!!v{{3c!2!2233ETE:Qtaxzz]Jy|BF++AEGG4qQzAMgkM"'')))KrC   c                h   t          | d          } t          |d          }||dz   z  t          j        d|t          j        dt          |           dz             z
  z  | dz  z            z  }t          j                            |t          j        dt          |           dz                       }||fS )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.
    re   r   rr         ?r8   )	r   r   rM   cumsumr   r   r   chi2sf)re   r   retr   s       r@   r,   r,     s    < 	1cAD&!!D 	!8	
)SD29QA
#;#;;<QF
G
G	H 
 :==bi3q66A:6677D9rC   c           
        t          |d          }t          |dd          }t          |d          }t          |dd          }t          |dd          }t          |d	d
          }t	          | d          } | j        d         }|5t          t          dt          j	        |          z            |dz
            }t          | |d||          }	|	d|dz            |	d         z  }
|s|s|
S ||nd}|rZt          j        |
          |z  }d|d<   d|z  |d<   |ddxx         ddt          j        |
dd         dz            z  z   z  cc<   ndt          |           z  }t          j                            d|dz  z
            t          j        |          z  }t          j        t'          |
|z
  |
|z                       }|s|
|fS t)          |
dd         |          \  }}||
|||fS |
||fS )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   nlagsTrf   qstatr   Falphar   r   rl   re   r   N
   r8   )r   r   r   r   皙?r   rr   rG          @)r   )r   r   r   r   r   r   rK   r   rM   log10r%   	ones_liker   r   r   normppfsqrtarrayr   r,   )re   r   r   r   r   r   bartlett_confintr   r   avfr&   _alphavaracfintervalconfintr   s                   r@   r&   r&   C  s2   X :..HUGd333EeW%%E
C
/
/
/Cug555E$M  G 	1cA71:D}CRXd^^+,,dQh77
HTsG
L
L
LC
k	k
SV
#C U 
'UUTF c""T)q	$Jq	qrr


a!biAbD	Q77777



s1vvz~~a&3,.//"'&//AHhtC(NC(N;;<<G G|3qrr7...ME6GUF**E6!!rC   re   ArrayLike1Dr   rV   Literal['adjusted', 'mle']return
np.ndarrayc           
     V   t          | d          } t          |dd          }| j        d         }|Ct          t	          t          dt          j        |          z            |dz
            d          }t          |d	d
          }dg}t          j
                    5  t          j        dt                     t          d|dz             D ]3}|                    t          | ||          d         d                    4	 ddd           n# 1 swxY w Y   t          j        |          S )a  
    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.
    re   r   Trf   r   Nr   r8   rV   )r   mlerl   r   oncerV   rG   )r   r   r   r   rK   r   rM   r   r   warningscatch_warningssimplefilterr   rI   appendr   r   )re   r   rV   r   r'   r>   s         r@   r(   r(     sq   J 	1cAUGd333E71:D}CB$/00$(;;Q??3FGGGF5D		 	"	" A Afl333q%!)$$ 	A 	AAKKAq888;B?@@@@	AA A A A A A A A A A A A A A A 8D>>s   A"DDDr   booltuple[np.ndarray, np.ndarray]c                   t          | d          } |r| |                                 z
  } | j        d         }||n4t          t	          dt          j        |          z            |dz
            }t          |d          }||dz
  k    rt          d          t          j	        |dz             }d| 
                    |           z  |d<   t          j	        |dz             }| ddd                                         }| ddd                                         }|dd         
                    |dd                   |dd         
                    |dd                   z   |d<   d|d         z  |dd         
                    |dd                   z  |d<   t          j        |          }	t          j        |          }
t          d|          D ]}||	dd<   ||
dd<   |	dd         ||         |
dd         z  z
  |dd<   |
dd         ||         |	dd         z  z
  |dd<   d||         dz  z
  ||         z  ||         dz  z
  |d         dz  z
  ||dz   <   d||dz            z  ||dz   d         
                    ||d                   z  ||dz   <   d|dz  z
  |z  d	|t          j        d|dz             z
  z  z  }d|d<   ||fS )
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.
    re   r   Nr   r8   z#nlags must be smaller than nobs - 1rr   rG   r   )r   r   r   rK   r   rM   r   r   rP   zerosr   r   
empty_likerI   r   )re   r   r   r   pr   r'   ur?   last_ulast_vr   sigma2s                r@   r1   r1     s   N 	1cA L71:D"CRXd^^0C,D,DdQh(O(OAAq		A4!8||>???
QAquuQxx<AaD8AE??D	$$B$A	$$B$ASbS6::af!""		!ABB% 0 00AaD!A$h1221SbS6***DG]1F]1F1a[[ = =qqq	qqq	ssd1gqrr
22!""qrr
T!Wvcrc{22!""Q1$!,qtqy81R5A:E!a%!AE(lQq1uwwZ^^AadG%<%<<QU$'kQ#	!QU0C0C)C"DEFDG<rC   	efficientc           
        t          | d          } t          |dd          }t          |d          }t          |d          }| j        d         }|Ct	          t          t          d	t          j        |          z            |d
z            d          }||d
z  k    rt          d|d
z   d          t          j
        |dz             }d|d<   |rt          | |d          \  }}t          |          }t          d|dz             D ]N}t          ||dd|dz   f         ||d         d          d         }	t          j        |	d                   ||<   On| t          j        |           z
  } t          | |dd          \  }}t          d|dz             D ]C}t          |ddd|f         |d          d         }	t          j        |	d                   ||<   D|r |||t          j        |dz             z
  z  z  }|S )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
    re   r   Trf   r   r   r   Nr   rr   r8   z&nlags must be smaller than nobs // 2 ()r   sep)ry   )rcondrG   rv   )ry   rx   )r   r   r   r   r   rK   r   rM   r   rP   r   r#   r   rI   r   squeezer   r   )
re   r   r   r   r   r'   xlagsx0r>   paramss
             r@   r)   r)   K  s(   x 	1cAUGd333E)[11I:..H71:D}CB$/00$!)<<a@@tQwL$'LLLMMM8EAIDDG -1ee444	rU##q%!)$$ 	- 	-A5Wq1uW-r!""vTBBB1EFj,,DGG	- 

N1ee&AAA	rq%!)$$ 	- 	-A5BQB<4888;Fj,,DGG 5ry33344KrC   
ywadjustedLiteral['yw', 'ywadjusted', 'ols', 'ols-inefficient', 'ols-adjusted', 'ywm', 'ywmle', 'ld', 'ldadjusted', 'ldb', 'ldbiased', 'burg']r   float | None*np.ndarray | tuple[np.ndarray, np.ndarray]c                P   t          |dd          }d}t          | dd          } t          |d|	          }t          |d
d          }| j        d         }|8t          t          dt          j        |          z            |dz  dz
            }t          |d          }|| j        d         dz  k    r$t          d| d| j        d         dz   d          |dv rd|v}d|v }t          | |||          }n|dv rt          | |d          }n|dv rt          | |d          }ny|dv r-t          | dd          }	t          |	|d          }
|
d         }nH|dk    rt          | |d          \  }}n,t          | dd          }	t          |	|d          }
|
d         }|d t!          |           z  }t"          j                            d |d!z  z
            t          j        |          z  }t          j        t-          ||z
  ||z                       }|d         |d<   ||fS |S )"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   Trf   )olsols-inefficientols-adjustedywywaldr  yw_adjustedywmywmleyw_mlelda
ldadjustedld_adjustedldbldbiased	ld_biasedburgre   rr   )maxdimrV   rl   r   r   Nr   r8   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   )re   r   rV   r   methodsr   r   r   r   acvld__r   r   r   s                  r@   r'   r'     s   n UGd333EG( 	1c!$$$A7;;;Fug555E71:D}CRXd^^+,,dai!m<<qMMEqwqzQ"05" "wqzQ" " "
 
 	

 ;;;!/	'qXNNN	=	=	=auZ888	-	-	-auU333	=	=	=A%000ct<<<!f	6		1E$777QQ A5111ct<<<!fs1vv:>>#"344rwvF(4hh??@@V
G|
rC   c                   t          | d          } t          |d          }t          |d          }t          |d          }t          |dd          }t          |           }|r/| |                                 z
  }||                                z
  }n| }|}|rt	          j        |dd	          }n|}|rdnd
}	t          ||d|	          |dz
  d         |z  S )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.
    re   yr   r   r   Frf   r   rG   directr   r   r8   N)r   r   r   r   rM   r   r   )
re   r"  r   r   r   rk   r   yor   rV   s
             r@   r*   r*   <  s    0 	1cA1cA:..Hvx((F
C
/
/
/CAA \\ IaB'UUxFRVF333AEFF;a??rC   )r   r   c                  t          | d          } t          |d          }t          |d          }t          |dd          }t          | ||d|          }|t          j        |           t          j        |          z  z  }|d	|         }|{t
          j                            d
|dz  z
            t          j        t          |                     z  }|
                    dd          |t          j        ddg          z  z   }	||	fS |S )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.
    re   r"  r   r   Frf   T)r   r   r   Nr   r   rG   r8   )r   r   r*   rM   stdr   r   r   r   r   reshaper   )
re   r"  r   r   r   r   cvfr   r   r   s
             r@   r+   r+   j  s    V 	1cA1cA:..H
C
/
/
/C
1x#
>
>
>C
RVAYY&
'C
fuf+C:>>#"344rws1vvF++b!$$x"(B72C2C'CCG|
rC   r   c           	        t          | d          } t          |d          }t          |d          }|}|r| }nt          | d          d|dz            }t	          j        |dz   |dz   fd          }t	          j        |dz             }|d         |d	         z  |d
<   |d	         |d
         |d         z  z
  |d<   t          d|dz             D ]}||         t	          j        |d||dz
  f         |d|         ddd                   z
  ||dz
           z  |||f<   t          d|          D ]0}|||dz
  f         |||f         |||z
  |dz
  f         z  z
  |||f<   1||dz
           d|||f         dz  z
  z  ||<   |d         }	|dddf         }
t	          j        |          	                                }d|d	<   |	|
|||fS )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   Nr8   r   r   )r8   r8   rr   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 1aU###KeaiK0
(EAIuqy)3
/
/C
(519

Ca58#CI1XD	E!H,,CF1eai   3 3!Hrvc!A#q1u*ouQqSz$$B$/?@@@AJAqD	 q! 	F 	FAAq1uHAqD	CAq1u4E(EEC1IIQUq3q!t9>12A"gG!""b&kGGCLLEE!HGUC,,rC   c                4   t          | d          } t          |dd          }t          j        t          j        |                     } | d         dk    rt          d          | dd         } | j        d         }|,||k    rt          d	          | d|         } | j        d         }t          j        |dz             }| d         |d<   t          j        d| d
z  z
            }| 	                                }t          d|          D ]}|d||z
            	                                }|||         |ddd         z  z
  |d||z
   <   ||         ||dz
           z  |                    |d||z
            ddd                   z   ||dz   <   d|d<   ||fS )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   Trf   r   r8   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.rr   rG   )r   r   rM   r   asarrayrP   r   r   cumprodr   rI   r   )r'   r   rk   r&   nur2  r   prevs           r@   r2   r2     s   2 dF##DUGd333E:bj&&''DAw!|| 
 
 	
 8D
1A199.   FUF|JqM
(1q5//C!WCF	A	M	"	"BiikkG1a[[ P Pz1q5z"''))"WQZ$ttt*%<<
AE(
QZ"QU)+dhhs1Qx<7H27N.O.OOAE

CFC<rC   UUUUUU?	two-sidedc                   t          j        | t                    dz  }|j        dk    r|                    dd          }t          |           }d|cxk     rdk     r(n n%t          t          j        ||z                      }nt          |          t          u r|dk    r|}|| d         }t          j	        |           
                    d          t          j        |d          }t                    D ]3\  }	}
|
dk     r(t          j        d|	z  d	           t           j        ||	<   4|d|         }t          j	        |           
                    d          t          j        |d          }t                    D ]3\  }	}
|
dk     r(t          j        d
|	z  d	           t           j        ||	<   4||z  }|rddlm fd}fd}nddlm fd}fd}|                                }|dv r ||          }nS|dv rd|z  } ||          }n>|dv r+dt          j         ||           ||                    z  }nt+          d          t          |          dk    r|d         |d         fS ||fS )aO  
    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   rr   r8   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                2                         |           S r;   cdftest_statistics	denom_dofr@  	numer_dofs    r@   <lambda>z2breakvar_heteroskedasticity_test.<locals>.<lambda>  s    QUUY	.
 .
 rC   c                2                         |           S r;   r   rD  s    r@   rH  z2breakvar_heteroskedasticity_test.<locals>.<lambda>  s    QTTY	.
 .
 rC   )r   c                6                         | z            S r;   rB  rE  r   rF  rG  s    r@   rH  z2breakvar_heteroskedasticity_test.<locals>.<lambda>  s    TXX'.
 .
 rC   c                6                         | z            S r;   rJ  rL  s    r@   rH  z2breakvar_heteroskedasticity_test.<locals>.<lambda>  s    TWW'.
 .
 rC   )r   inc
increasing)r   dec
decreasingr   )2z2-sidedr:  zInvalid alternative.)rM   r5  floatr   r'  r   r   roundtyper   r   nansum	enumerater   warnnanscipy.statsr@  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   rF  r@  rG  s                    @@@@r@    breakvar_heteroskedasticity_testrk  (  s   V JuE222a7MQ%--b!44u::D=1-..//	m			#	#(:(:$K(;''',,!,44I	+A666I&& * *377M-/01 	    $&6a #K(;''',,!,44I	+A666I&& * *377M-/01 	    $&6a &)::N  
!!!!!!
 
 
 
 
 


 
 
 
 
 


 	%$$$$$
 
 
 
 
 


 
 
 
 
 


 ##%%K000*^,,	2	2	2~-*^,,	5	5	5bjJ~&&

>(B(B
 
 
 /000
>aa '!*,,7""rC   c           
        t          | dd          } t          j        |                                           st	          d          t          |d          }|+t          |d          }t          j        dt                     nd	}	 t          |d
          }|dk    rt	          d          t          j
        d|dz             }nt# t          $ rg t          j        d |D                       }|                                }|                                dk    s|j        dk    rt	          d          Y nw xY w| j        d         d|z  t#          |          z   k    rPt	          d                    t#          | j        d         t#          |          z
  dz            dz
                      i }|D ]W}i }|rt'          d           t'          d|           |}t)          | |dd          }	|rt+          |	ddd|dz   f         d          }
t+          |	ddddf         d          }|j        d         |	j        d         dz
  k    sB|                    d          |                    d          k                                    dk    rt/          d          nt1          d          t3          |	dddf         |
                                          }t3          |	dddf         |                                          }|j        j        r|j        }n|j        }|dk    so|j        dk    sdt          j         |j!                  sK|j        |z  t          j"        tF                    j$        k     s!|j%        j        d         |j        d         k    rt/          d          |j        |j        z
  |j        z  |z  |j&        z  }|r?t'          d|tN          j(        )                    |||j&                  |j&        |fz             |tN          j(        )                    |||j&                  |j&        |f|d<   |j*        |j        |j        z
  z  |j        z  }|r3t'          d|tN          j+        )                    ||          |fz             |tN          j+        )                    ||          |f|d<   d|j,        |j,        z
  z  }|r3t'          d |tN          j+        )                    ||          |fz             |tN          j+        )                    ||          |f|d!<   t          j-        t          j.        ||f          t          j/        ||          t          j.        |df          f          }|0                    |          }|r*t'          d"|j1        |j2        |j3        |j4        fz             t          j5        |j1                  d#         t          j5        |j2                  d#         |j3        |j4        f|d$<   ||||gf||<   Y|S )%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])
    re   rr   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 integerr8   c                ,    g | ]}t          |          S r6   )r   )r=   r[   s     r@   
<listcomp>z)grangercausalitytests.<locals>.<listcomp>!  s    444cS444rC   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)rv   )rx   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=%dr6   params_ftest)6r   rM   isfiniteallrP   r   r   rX  FutureWarningr   r   	TypeErrorr   r   rK   sizer   r   formatprintr$   r   r   r   NotImplementedErrorr   rJ   model
k_constantcentered_tssuncentered_tssssrr   rsquaredfinforS  epsr  df_residr   r@  r   r   r   llfcolumn_stackr   eyef_testfvaluer   df_denomdf_numr   )re   rU   rm  rn  lagsreslimlgresultmxlgdtadtaowndtajointres2down
res2djointtssfgc1fgc2lrrconstrftress                       r@   grangercausalitytestsr    su   Z 	1c"""A;q>> :8999:..HGY//L	
 	
 	
 	

 &(++Q;;@AAAyFQJ''   x44V4445588::??di1nn$   -n 	wqzQZ#h--///sAGAJX$>!#CDDqHII
 
 	

 E p@ p@ 	3'(((,c222 4fQ777  	9!#aaadQh&7"8%HHHF#C122J>>>Hq!cilQ&677LLOOx||A6;;==BB)>   C &&7888
 s111a4y&))--//QQQTH--1133
 & 	,)CC+C1HH~""x
+,, #$(;;; &q)X^A->>>%A  
 \JN*n !" 	  
	 GJJtT:+>??'		 	 	 GJJtT:#677	
{ }z~ =>O 	tT!:!:DAB   #'
dD(A(A4!H~ 8<*.01 	Euz}}R..56   
b$ 7 7>x /XtTl##RVD$%7%74)9L9LM
 
 !!'** 	<u~u|LM   Ju|$$R(Ju|$$R(NL	"
~ *g>?dLs   =C A.D76D7aegr9   rn   
str | Nonec                   t          | d          } t          |dd          }t          |dd          }t          |dd	           t          |d
d          }t          |ddd          }t          |dd          }|j        \  }}|dz  }|dk    r|}	nt          ||d          }	t          | |	                                          }
|
j        ddt          z  z
  k     rt          |
j        ||d          }n*t          j        dt          d           t          j         f}|dk    rt          j        gdz  }nt%          |||dz
            }t'          |d         ||          }|d         ||fS )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y1rr   r   trend)ra   rk   ri   rj   rl   rV   )r  rU   Trf   rn   ro   rp   return_resultsr8   rk   F)r  r}   d   )rU   rn   rh   zZy0 and y1 are (almost) perfectly colinear.Cointegration test is not reliable in this case.r>  rq  r   r   r~   )r   r   r   r   r   r"   r   rJ   r  SQRTEPSr/   r\  r   rX  r   rM   infrY  r    r!   )r  r  r  rV   rU   rn   r  r   k_varsxxres_cores_adfcritpval_asys                 r@   r-   r-     s   | 
B		B	B1	%	%	%Bw0GHHHE(3333fh666FT3K  G ~/?$OOON8LD&
aKF||r666R[[__FS7]***LS
 
 
 	?		
 	
 	
 	
 F7* ||x!|v%dQhGGG '!*&AAAH1:x%%rC   c           	     V   ddl m} 	   || fd|i|d|ij        d	d|i|S # t          $ r Y d S t          $ rk}|Y d }~d S d|j        d         vsdt          |          v r8dgt          |          z  }|dk    rdg|z   }t          | |||||          cY d }~S Y d }~d S d }~w Y d S xY w)
Nr   )ARIMAr,  r  start_paramsinitial皙?ra   r6   )	statsmodels.tsa.arima.modelr  rJ   r
   rP   argsstrr   _safe_arma_fit)r"  r,  model_kwr  fit_kwr  r  errors           r@   r  r  2  sJ   111111AuuQ==e=x==u===A 
 
%
)/
 
 	
       #FFFFFejm++yCJJ/F/F53u::-L|| #u|3!5(E6<        FFFFFs&   $ 
B(	B(B AB B( B(   rr   rD   c           	        t          |d          }t          |d          }t          |dd          }t          |dd          }t          |d	d          }d
 t          |dz             D             d t          |dz             D             t	          |t
                    r|g}n+t	          |t          t          f          st          d          t          j
        t          |          |dz   |dz   f          }|i n|}|i n|}t          | dd          }D ]_}	D ]Z}
t          ||	d|
f|||          }|t          j        |dd|	|
f<   /t          |          D ]\  }}t!          ||          |||	|
f<   [`fd|D             }t#          t%          ||                    }i }|                                D ]\  }}t          j        t          j        |                                                                |z
                      }|j        d         }t          j        |          }|                    |dz   ||z  ||z  fi           |                    |           t5          di |S )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  )rk   ra   rl   r  Trf   r  c                    g | ]}|S r6   r6   r=   r   s     r@   rp  z(arma_order_select_ic.<locals>.<listcomp>      ---a---rC   r8   c                    g | ]}|S r6   r6   r  s     r@   rp  z(arma_order_select_ic.<locals>.<listcomp>  r  rC   z.Need a list or a tuple for ic if not a string.Nr"  )
contiguousr   c                >    g | ]}t          j        |           S ))columnsindex)pd	DataFrame)r=   resar_rangema_ranges     r@   rp  z(arma_order_select_ic.<locals>.<listcomp>  s7       @CS((;;;  rC   
_min_orderr6   )r   r   r   rI   r   r  listtuplerP   rM   r   r   r   r  rY  rW  getattrdictziprL   ascontiguousarrayrN   rK   r   argminupdater   )r"  r  r  icr  r  r  rZ   y_arrarmarQ   r   criteriadfsr  min_resr  deltancolslocr  r  s                        @@r@   r.   r.   O  s   v fh''Ffh''Fw
;;;E:===Hvx$777F--5!,,---H--5!,,---H"c KTT5M** KIJJJhB!VaZ899G%rr8H>RRvFq#$///E < < 	< 	<B QXufMMC{%'V2r	"(}} < <8%,S(%;%;2r	""<	<    GN  C s2s||

C GYY[[ H H	6$RVFJJLL,<,<,>,>,G%H%HIIAiL(3%<u*EFGGGGJJw<<3<<rC   c                N    t          j        t          j        |                     S )zJ
    Returns True if "data" contains missing entries, otherwise False
    )rM   r   r   )datas    r@   r   r     s     8BF4LL!!!rC   autorh   Literal['c', 'ct']Literal['auto', 'legacy'] | intrq   *tuple[float, float, int, dict[str, float]]c           
        t          | d          } t          |dd          }t          |d          }| j        d         }|}|| j        k    rt          d| j         d          |d	k    rOt          | t          t          j	        d
|d
z                                 
                                j        }g d}n| |                                 z
  }g d}|dk    rNt          t          j        dt          j        |dz  d          z                      }t!          ||d
z
            }n|dk    s|B|t#          j        dt&          d           t)          ||          }t!          ||d
z
            }nRt+          |t,                    rt          d          t/          |dd          }||k    rt          d| d| d          g d}t          j        |                                dz            |dz  z  }	t5          |||          }
|	|
z  }t          j        |||          }d}||d         k    r1t#          j        |                    d !          t:          d           n<||d         k    r0t#          j        |                    d"!          t:          d           |d         |d
         |d         |d#         d$}|rDdd%lm}  |            }||_         ||_!        |d&k    rd'nd(}d)| d*|_"        d+| d*|_#        ||||fS ||||fS ),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.
    re   rh   )ra   ri   rl   rq   r   x of shape  not understoodri   r8   )gX9v?g㥛 ?gI+?gS?)gh|?5?goʡ?g|?5^?gS?legacyrs   rt   ru   r  NzpNone is not a valid value for nlags. It must be an integer, 'auto' or 'legacy'. None will raise starting in 0.14rr   r>  z0nvals must be 'auto' or 'legacy' when not an intr   Frf   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greaterrq  r   r   z2.5%r   rz   ra   levelr  zThe series is z stationaryzThe series is not )$r   r   r   r   r|  rP   r   r   rM   r   rJ   r\  r   r   r   r   rK   r   rX  rz  _kpss_autolagr   r  r   r   r   _sigma_est_kpssinterpr}  r   r   r{   r  r   r   r   )re   rh   r   rq   r   hyporesidsr  pvalsetas_hat	kpss_statrj  warn_msg	crit_dictr{   rstorestationary_types                     r@   r0   r0     s   f 	1cAZ{KKKJeW%%E71:DD qv~~?qw???@@@t|| QRYq$(%;%;<<==AACCI+++ QVVXX+++BGD28D5L'#B#BBCCDDE4!8$$	&EM=MG	    fd++E4!8$$	E3		 KLLL%888D==KKKDKKK   &%%E
&A%
&
&$!)
4CFD%00EeIi	4//GH %)OOiO00 	
 	
 	
 	
 	

 
E!H		OOiO00 	
 	
 	
 	
 QtAwQtAwOOI 4======%)S[[''gA_AAA	EEEE	'9f44'5)33rC   c                    t          j        | dz            }t          d|dz             D ]>}t          j        | |d         | d||z
                     }|d|z  d||dz   z  z
  z  z  }?||z  S )z{
    Computes equation 10, p. 164 of Kwiatkowski et al. (1992). This is the
    consistent estimator for the variance.
    rr   r8   Nr   )rM   r   rI   r   )r  r   r  r  r   resids_prods         r@   r  r  l  s    
 F6Q;E1dQh > >fVABBZ
$(
);<<[C1s
+;$<==4<rC   c                   t          t          j        |d                    }t          j        | dz            |z  }d}t	          d|dz             D ]?}t          j        | |d         | d||z
                     }||dz  z  }||z  }|||z  z  }@||z  }d}dt          j        ||z  |          z  }	t          |	t          j        ||          z            }
|
S )	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?rr   r   r8   Nr   r9  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""  fVABBZ
$(
);<<tcz!
k
a+oGE
C%%-555I9rxc22233HOrC   c                   t          | d          } t          |d          }| j        d         }|| j        k    rt	          d| j         d          g d}t          j        g d          }t          j        g dg d	g d
g dg dg dg dg dg dg dg dg dg          }t          j        d|j        d         f          }t          |j        d                   D ],}t          ||dd|f                   } ||          |d|f<   -t          j        |           }	|	                    d                                                              d          }
|	                    d                                                              d          }|	|
k                                    |	|k                                     z   }|t          j        t%          |                     z  }t%          |          dz
  }t          t%          |          dz
  dd          D ]}||d|f         k     r|} ||         }d}d}||d         k    rd}n||d         k    rd}|r0t'          j        |                    |          t,          d           |d         |d         |d          |d!         d"}|r+dd#lm}  |            }||_        d$|_        d%|_        ||||fS |||fS )&a  
    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.
    re   rq   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@r8   NrG   r   r  largerr  rr   r>  )r   rq  )r   rr   )r   r8   )r   r   r  rz   zThe series is not stationaryzThe series is stationary)r   r   r   r|  rP   rM   r   r   rI   r   r  Series	expandingr   shiftrK   r   r   r   r   rX  r}  r   r   r{   r   r   r   )re   rq   r   r  rk   r  
inter_critr   r@  xsexp_maxexp_mincountrur_statr>   rj  r  r  r  r{   r  s                        r@   r5   r5     sc   \ 	1cAeW%%E71:D qv~~?qw???@@@ 211E
GGG	 	A 8<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<	
 D$ 1djm,--J4:a=!! # #QQQQT
##1T77
1a4 
1Bll1oo!!##))!,,Gll1oo!!##))!,,G'\  BL#5#5#7#77Erws1vv&HE

QA3u::>2r**  jA&&&AAAhGH I%)			E!H			 
OOiO00 	
 	
 	
 	
 $4 	 I  ,======2	.	)V33)++rC   c                  D    e Zd ZdZd ZddZd Zd Zd ZddZ		 ddZ
d	S )ZivotAndrewsUnitRootzI
    Class wrapper for Zivot-Andrews structural-break unit-root test
    c                   i | _         d| _        t          j        | j                  | j         d<   d| _        t          j        | j                  | j         d<   d| _        t          j        | j                  | j         d<   dS )a  
        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
ܺ:ra   )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)r0  g.=)r1  gt.)r2  gZ)r3  gjHci)r4  gGȰ
)r5  gJRЭ)r6  gKqU)r7  g:H
)r8  g$
)r9  gY
)r:  g->x
)r;  g"	)r<  g"^	)r=  g	)r>  gdw)r?  gz6>)r@  g҇n)rA  g+j)rB  g(D!T)rC  gsF)rD  g	)rE  g.9N)rF  gŏ1w)rG  gJR)rH  gn2d)rI  gAf )rJ  g"^F)rK  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)r0  gP1)r1  gt~)r2  g1N)r3  g )r4  g)r5  g	/)r6  goʡ)r7  g|Sz)r8  gmJR)r9  g9}+)r:  gLOX)r;  gkC8)r<  g~jt)r=  gF()r>  g.)r?  gb=9)r@  gڏa)rA  g`)rB  gq2)rC  g_LU)rD  gG=D;H
)rE  gN	)rF  gk}Ж)rG  gp>?)rH  g1)rI  gԷ)rJ  g	c)rK  gR%Mri   N)_za_critical_values_crM   r5  _t_ct)selfs    r@   __init__zZivotAndrewsUnitRoot.__init__	  s     $& 1
d )+
47(;(; %1
d )+
47(;(; %1
d *,DH)=)= &&&rC   ra   c                    | j         |         }|dddf         }|dddf         }t          j        |||          dz  }g d}t          j        |||          }|d         |d         |d         d}	||	fS )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   r8   rt   )r   r(  r*  rr   r   )rM  rM   r  )
rQ  statr  tablepcntsr   r   cv
crit_valuecvdicts
             r@   _za_critzZivotAndrewsUnitRoot._za_crit	  s    0 (/aaadaaad4..6Yr5%00
Q-Q-a=
 

 v~rC   c                   t           j                            |j                            |                    }|j                            |          }|j        \  }}|                    |          }||                    |          z
  }|j                            |          ||z
  z  }	|t          j        t          j        |	|z                      z  S )zI
        Minimal implementation of LS estimator for internal use
        )rM   linalginvTr   r   r   r+  )
rQ  rR   rS   xpxixpyr   k_exogber   s
             r@   
_quick_olszZivotAndrewsUnitRoot._quick_ols	  s     y}}TVZZ--..fjjzfHHSMMDHHQKKtf}-27276D=112222rC   c                   t          j        |d          }|t          j        |j                            |                    z  }|t          j        |j                            |                    z  }t          j        ||d         j        d         ||z   f          }||dddf<   |||dz
           |dd|dz
  f<   t          ||d          ||j        d         |z            |dd|df<   ||fS )z
        Create the endog/exog data for the auxiliary regressions
        from the original (standardized) series under test.
        r   r<  Nr8   r   )rx   )rM   r   r   r^  r   r   r   r#   )	rQ  seriesr   constr  colsr  rR   rS   s	            r@   _format_regression_dataz,ZivotAndrewsUnitRoot._format_regression_data	  s    Q'''U++,,,"'&(,,v"6"6777xtuu+A.t<==QQQT
"44!8#45QQQq[t&9994:a=4''
QQQX d{rC   c	                <   ||dz   z
  }	|dk    rPd|d|	df<   |||	ddf<   ||dz   |dz            |dddf<   |dk    r d|d|	df<   |d||z
  dz            ||	ddf<   n=||dz   |dz            |dddf<   d|d|	dz
  df<   |d||z
  dz            ||	dz
  ddf<   |S )z@
        Update the exog array for the next regression.
        r8   rL  r   Nrr   ri   rq  r6   )
rQ  rS   rh   periodr   rg  r  rh  r  cutoffs
             r@   _update_regression_exogz,ZivotAndrewsUnitRoot._update_regression_exog

  s    4!8$ D&!$D!qTAX67DAJT!!#$WfWaZ #(dVma.?)@#AVWWaZ qTAX67DAJ&'DFQJ"#&+A1B,C&DD&1*"#rC   333333?Nrb   c                   t          |dt          j        d          }t          |d          }t	          |dd          }t          |dd	
          }t          |ddd          }|dk     s|dk    rt          d          |j        d         }|rt          ||d|          }|d         }n-|r|}n(t          dt          j
        |dz  d          z            }t          ||z            }	|	}
||	z
  }|dk    rd}nd}dt          j        |          z  }t          j        d|dz             }|t          j        d          |dz  z  z  }|                     ||||||          \  }}t          j        |dz   t          j                  }t!          |
dz   |dz             D ]}|                     ||||||||          }||
dz   k    rt%          ||d         |d                                          }|j        |j        d         dz
  k     r6t          d                    |j        d         dz
  |j                            |j        |dz
           ||<   |                     ||d         |          |dz
           ||<   t          j        |          }t          j        |          dz
  }|                     ||          }|d         }|d         }|||||fS )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.
        re   r8   )r   r   rx   rU   Trf   rh   )ra   rL  ri   rl   rn   ro   )rm   rg   r   r9  z,trim value must be a float in range [0, 1/3)ri   )rU   rh   rn   rr   rs   rt   ru      r  r   rq  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   ri  r   r  rI   rm  r   rJ   df_modelr}  rO   rd  rK   r  rZ  )rQ  re   rx   rU   rh   rn   r   adf_resbaselagstrimcntstart_period
end_periodbasecolsc_constt_constrR   rS   r   bpozastatbpidxr  pvalrY  s                            r@   runzZivotAndrewsUnitRoot.run
  sC   Z q#RYQ777$''&(T::: .>
 
 

 Y(@4
 
 
 !88ty))KLLLwqz 	C&T7  G qzHH 	CHH4"(4%<"A"AABBHdTk""G^
HHHbgdmm#)C**271:://22tWgx
 
t 
Q//q(*q.99 	 	B//	 	D \A%%%hii($;;;??AA:
1 111$AAG JqMA-qzB B   Ihl3b		 OOE()),<dCCqLb		 	%  1$}}VZ00AwatVXu44rC   c                6    |                      |||||          S )N)rx   rU   rh   rn   )r  )rQ  re   rx   rU   rh   rn   s         r@   __call__zZivotAndrewsUnitRoot.__call__
  s*     xxDJ  
 
 	
rC   )ra   )rn  Nra   rb   )__name__
__module____qualname____doc__rR  rZ  rd  ri  rm  r  r  r6   rC   r@   r  r  	  s         f> f> f>P$ $ $ $L
3 
3 
3  &  (T5 T5 T5 T5n BG
 
 
 
 
 
rC   r  )r6   r6   F)Nra   rb   FF)rU   rc   )FTTr   N)FNFTNTr   )Nr   )re   r   r   rc   rV   r   r   r   )NT)re   r   r   rc   r   r   r   r   )NTF)
re   r   r   rc   r   r   r   r   r   r   )Nr  N)
re   r   r   rc   rV   r  r   r  r   r  )TTT)TT)r   Fr;   )r9  r:  T)TN)ra   r  Nr9   N)rn   r  )r  rr   rD   ra   NN)ra   r  F)rh   r  r   r  rq   r   r   r  )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  rS  r   __all__r   r  rr  r  r  r`   r/   r%   r,   r&   r(   r1   r)   r'   r*   r+   r3   r2   rk  r  r-   r  r.   r   r0   r  r  r5   r  r4   r  r6   rC   r@   <module>r     s    # " " " " " * * * * * * 5 5 5 5 5 5 * * * * * * 2 2 2 2 2 2 ! ! ! ! ! ! ! !      $ $ $ $ $ $           & & & & & & " " " " " " @ @ @ @ @ @ @ @              8 7 7 7 7 7 7 7                % $ $ $ $ $ M M M M M M M M ? ? ? ? ? ? ? ? A A A A A A A A A ABJ	4;67  . "'("(29%%)
*
* V( V( V( V(F 
`F `F `F `F `FF Z((G G G )(GT' ' '^ 


N" N" N" N"d )30 0 0 0 0h >BB B B B BJ Z(( 	V V V V )(Vv  	#T T T T Tn Z((*@ *@ *@ )(*@Z Z((8D 8 8 8 8 )(8zD- D- D- D-N6 6 6 6t @DV# V# V# V#rb b b bP I& I& I& I& I&X   < GKe e e eP" " " &)-3	k4 k4 k4 k4 k4\	 	 	  *H, H, H, H,Va
 a
 a
 a
 a
 a
 a
 a
H %$&&%)1   rC   