ó
áp7]c           @   s0  d  Z  d d l m Z d d l m Z m Z m Z m Z m Z m	 Z	 m
 Z
 d d l m Z d d l m Z d d l Z d d l Z d d l m Z d d l m Z d d	 l m Z m Z d d
 l m Z m Z m Z d d l m Z m  Z  d d l! m" Z" d d l# m$ Z$ m% Z% d d l& m' Z' d d l( m) Z) m* Z* m+ Z+ d d d d d d d d d d d d d d d d d  d! d" g Z, e j- e j. e j/ ƒ j0 ƒ Z1 d# e2 f d$ „  ƒ  YZ3 dJ dK e4 d% „ Z5 d d& d' e4 e4 d( „ Z7 e4 e8 d d) d d* „ Z9 d+ d, „ Z: e4 d- e4 d d d) d. „ Z; d- d/ d0 „ Z< d e8 d1 „ Z= d- e8 e4 d2 „ Z> d- d3 d d4 „ Z? e8 e8 d5 „ Z@ e8 d6 „ ZA d7 „  ZB d8 e4 d9 „ ZC d d: „ ZD d d d; „ ZE d< „  ZF e8 e8 d= „ ZG d& d> d d? d d@ „ ZH d dA „ ZI dB dC dD d& d d dE „ ZJ dF „  ZK d& d e4 dG „ ZL dH „  ZM dI „  ZN d S(L   s,   
Statistical tools for time series analysis
iÿÿÿÿ(   t   division(   t	   iteritemst   ranget   lranget   string_typest   lzipt   zipt   long(   t   lstsq(   t   _next_regularN(   t   LinAlgError(   t   stats(   t   OLSt   yule_walker(   t   InterpolationWarningt   MissingDataErrort   CollinearityWarning(   t   add_constantt   Bunch(   t   bds(   t
   mackinnonpt   mackinnoncrit(   t   ARMA(   t   lagmatt	   lagmat2dst	   add_trendt   acovft   acft   pacft   pacf_ywt   pacf_olst   ccovft   ccft   periodogramt   q_statt   cointt   arma_order_select_ict   adfullert   kpssR   t	   pacf_burgt   innovations_algot   innovations_filtert   levinson_durbin_pacft   levinson_durbint   ResultsStorec           B   s   e  Z d  „  Z RS(   c         C   s   |  j  S(   N(   t   _str(   t   self(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyt   __str__$   s    (   t   __name__t
   __module__R/   (    (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR,   #   s   c	         C   sx  i  }	 | j  ƒ  } xW t | | | d ƒ D]> }
 |  | | d d … d |
 … f | Œ } | j ƒ  |	 |
 <q* W| d k r t d „  t |	 ƒ Dƒ ƒ \ } } nº | d k rÎ t d „  t |	 ƒ Dƒ ƒ \ } } n‰ | d k rGd } xt t | | | d d	 ƒ D]E }
 t j |	 |
 j d	 ƒ } t j | ƒ | k rû |
 } | } Pqû qû Wn t d
 ƒ | ‚ | sg| | f S| | |	 f Sd S(   s•  
    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.
    i   Nt   aicc         s   s$   |  ] \ } } | j  | f Vq d  S(   N(   R2   (   t   .0t   kt   v(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pys	   <genexpr>`   s    t   bicc         s   s$   |  ] \ } } | j  | f Vq d  S(   N(   R6   (   R3   R4   R5   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pys	   <genexpr>b   s    s   t-statg»jg	RQú?iÿÿÿÿs(   Information Criterion %s not understood.(	   t   lowerR   t   fitt   minR   t   npt   abst   tvaluest
   ValueError(   t   modt   endogt   exogt   startlagt   maxlagt   methodt   modargst   fitargst
   regresultst   resultst   lagt   mod_instancet   icbestt   bestlagt   stop(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyt   _autolag(   s*    1(%%!
t   ct   AICc      	   C   sŒ  | r t  } n  i d d 6d d 6d d 6d d 6} | d k sR t | t t f ƒ r_ | | } n  | j ƒ  } | d k rŠ t d ƒ | ‚ n  t j |  ƒ }  |  j	 d } | d k r¾ t
 | ƒ n d } | d k r2t t j d	 t j | d
 d  ƒ ƒ ƒ } t | d | d | ƒ } | d k  rYt d ƒ ‚ qYn' | | d | d k rYt d ƒ ‚ n  t j |  ƒ }	 t |	 d d … d f | d d d d ƒ}
 |
 j	 d } |  | d d !|
 d d … d f <|	 | } | rßt ƒ  } n  | r | d k r	t |
 | d t  ƒ} n |
 } | j	 d |
 j	 d d } | sUt t | | | | | ƒ \ } } n3 t t | | | | | d | ƒ\ } } } | | _ | | 8} t |	 d d … d f | d d d d ƒ}
 |
 j	 d } |  | d d !|
 d d … d f <|	 | } | } n | } d } | d k rSt | t |
 d d … d | d … f | ƒ ƒ j ƒ  } n/ t | |
 d d … d | d … f ƒ j ƒ  } | j d } t | d | d d ƒ} t d d d | d | ƒ } i | d d 6| d d 6| d d 6} | rY| | _ | | _ | | _ | | _ | | _ | | _ d | _ d | _  | | _! d | _" | | | | f S| sr| | | | | f S| | | | | | f Sd S(!   s0  
    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
        data series
    maxlag : int
        Maximum lag which is included in test, default 12*(nobs/100)^{1/4}
    regression : {'c','ct','ctt','nc'}
        Constant and trend order to include in regression

        * 'c' : constant only (default)
        * 'ct' : constant and trend
        * 'ctt' : constant, and linear and quadratic trend
        * 'nc' : no constant, no trend
    autolag : {'AIC', 'BIC', 't-stat', None}
        * 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
    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
        Test statistic
    pvalue : float
        MacKinnon's approximate p-value based on MacKinnon (1994, 2010)
    usedlag : int
        Number of lags used
    nobs : int
        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.

    Examples
    --------
    See example notebook

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

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

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

    .. [*] 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
    t   ncRN   i    t   cti   t   ctti   s#   regression option %s not understoodg      (@g      Y@g      @s=   sample size is too short to use selected regression componentso   maxlag must be less than (nobs/2 - 1 - ntrend) where n trend is the number of included deterministic regressorsNt   trimt   botht   originalt   iniÿÿÿÿt   prependRF   t
   regressiont   Nt   nobss   1%s   5%s   10%s8   The coefficient on the lagged level equals 1 - unit roots4   The coefficient on the lagged level < 1 - stationarys$   Augmented Dickey-Fuller Test Results(   RN   RP   RQ   RR   g      Ð?(#   t   Truet   Nonet
   isinstancet   intR   R7   R=   R:   t   asarrayt   shapet   lent   ceilt   powerR9   t   diffR   R,   R   RM   R   t   autolag_resultsR8   R<   R   R   t   resolsRB   t   usedlagt   adfstatt
   critvaluesRZ   t   H0t   HARJ   R-   (   t   xRB   RX   t   autolagt   storeRF   t	   trenddictRZ   t   ntrendt   xdifft   xdallt   xdshortt   resstoret   fullRHSRA   RJ   RK   t   alresRg   Rf   Rh   t   pvalueRi   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR%   }   sŠ    U	"!)+"		
+"	&/										t   nonec         C   sË  | d k r7 d d l } d } | j | t ƒ t } n  t j t j |  ƒ ƒ }  |  j d k rt t	 d |  j ƒ ‚ n  | j
 ƒ  } | d k rŸ t	 d
 | ƒ ‚ n  | d k r´ t } n t |  ƒ } | r3| d k rá t d ƒ ‚ n  t j |  ƒ }	 | d k r|  j ƒ  }  d |  |	 <n
 |  |	 }  |	 j t ƒ }
 n  | rv| rv|  |  j ƒ  |
 j ƒ  } | d k r•d | |	 <q•n | r|  |  j ƒ  } n |  } t |  ƒ } | } | d k rÀ| d } n | | d k rßt	 d ƒ ‚ n  | r=| d k	 r=t j | d ƒ } | j | ƒ | d <x< t | ƒ D]. } | | d j | | d  ƒ | | d <q%W| sj| d	 k r›| rŽ| | t j | d ƒ } q9| | } nž | r)t j | d d t j ƒ} |
 j ƒ  | d <x< t | ƒ D]. } |
 | d j |
 | d  ƒ | | d <qÚWd | | d k <| | } n | |
 j ƒ  } | S| r}| r}| d k r}t j |
 |
 d ƒ } d | | d k <nŠ | rÂt j d | d ƒ } t j | | d  d d d … f ƒ } nE | rì|
 j ƒ  t j d | d ƒ } n | t j d | d ƒ } | r€t | ƒ } t d | d ƒ } t j j | d | ƒ} t j j | t j | ƒ ƒ |  | | d } | j  } n) t j | | d ƒ | d | | d } | d k	 rÇ| | d  j ƒ  S| S(   s²  
    Autocovariance for 1D

    Parameters
    ----------
    x : array
        Time series data. Must be 1d.
    unbiased : bool
        If True, then denominators is n-k, otherwise n
    demean : bool
        If True, then subtract the mean x from each element of x
    fft : bool
        If True, use FFT convolution.  This method should be preferred
        for long time series.
    missing : str
        A string in ['none', 'raise', 'conservative', 'drop'] specifying how
        the NaNs are to be treated.
    nlag : {int, 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
    -------
    acovf : array
        autocovariance function

    References
    -----------
    .. [*] Parzen, E., 1963. On spectral analysis with missing observations
           and amplitude modulation. Sankhya: The Indian Journal of
           Statistics, Series A, pp.383-392.
    iÿÿÿÿNsx   fft=True will become the default in a future version of statsmodels. To suppress this warning, explicitly set fft=False.i   s   x must be 1d. Got %d dims.Rx   t   raiset   conservativet   drops    missing option %s not understoods!   NaNs were encountered in the datai    s"   nlag must be smaller than nobs - 1t   dtypet   fulli   t   n(   Rx   Ry   Rz   R{   (!   R\   t   warningst   warnt   FutureWarningt   FalseR:   t   squeezeR_   t   ndimR=   R7   t   has_missingR   t   isnant   copyt   astypeR^   t   sumt   meanRa   t   emptyt   dotR   t   aranget   int64t	   correlatet   hstackt   onesR	   t   fftt   ifftt	   conjugatet   real(   Rl   t   unbiasedt   demeanR’   t   missingt   nlagR   t   msgt   deal_with_maskedt   notmask_boolt   notmask_intt   xoR~   t   lag_lent   acovt   it   divisort   dt   xiRZ   t   Frf(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR   9  s’    $		
,,)$/)t   ljungboxc         C   s”   t  j |  ƒ }  | d k r_ | | d t  j d | t  j d t |  ƒ d ƒ |  d ƒ } n  t j j | t  j d t |  ƒ d ƒ ƒ } | | f S(   sê  
    Return's Ljung-Box Q Statistic

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

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

    Notes
    -----
    Written to be used with acf.
    R¦   i   g      ð?i   (   R:   R_   t   cumsumR   Ra   R   t   chi2t   sf(   Rl   RZ   t   typet   retR¨   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR"   ½  s    9+i(   c      
   C   s   | d k r7 d d l } d } | j | t ƒ t } n  t |  ƒ }	 t |  d | d t d | d | ƒ}
 |
 | d  |
 d	 } | p† | s | S| d k	 rNt j	 | d ƒ |	 } d	 | d	 <d
 |	 | d <| d c d d t j
 | d d !d ƒ 9)t j j d | d ƒ t j | ƒ } t j t | | | | ƒ ƒ } | sN| | f Sn  | rœt | d d |	 ƒ\ } } | d k	 rŒ| | | | f S| | | f Sn  d S(   s  
    Autocorrelation function for 1d arrays.

    Parameters
    ----------
    x : array
       Time series data
    unbiased : bool
       If True, then denominators for autocovariance are n-k, otherwise n
    nlags: int, optional
        Number of lags to return autocorrelation for.
    qstat : bool, optional
        If True, returns the Ljung-Box q statistic for each autocorrelation
        coefficient.  See q_stat for more information.
    fft : bool, optional
        If True, computes the ACF via FFT.
    alpha : scalar, 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
        Bartlett's formula.
    missing : str, optional
        A string in ['none', 'raise', 'conservative', 'drop'] specifying how the NaNs
        are to be treated.

    Returns
    -------
    acf : array
        autocorrelation function
    confint : array, optional
        Confidence intervals for the ACF. Returned if alpha is not None.
    qstat : array, optional
        The Ljung-Box Q-Statistic.  Returned if q_stat is True.
    pvalues : array, optional
        The p-values associated with the Q-statistics.  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 unbiased is true, the denominator for the autocovariance is adjusted
    but the autocorrelation is not an unbiased estimator.

    References
    ----------
    .. [*] Parzen, E., 1963. On spectral analysis with missing observations
       and amplitude modulation. Sankhya: The Indian Journal of
       Statistics, Series A, pp.383-392.

    iÿÿÿÿNsx   fft=True will become the default in a future version of statsmodels. To suppress this warning, explicitly set fft=False.R–   R—   R’   R˜   i   i    g      ð?i   g       @RZ   (   R\   R   R€   R   R‚   Ra   R   R[   R:   R‘   R§   R   t   normt   ppft   sqrtt   arrayR   R"   (   Rl   R–   t   nlagst   qstatR’   t   alphaR˜   R   Rš   RZ   t   avfR   t   varacft   intervalt   confintRw   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR   Ý  s0    ;	$
,' R–   c         C   sX   d g } x? t  d | d ƒ D]* } | j t |  | d | ƒd d ƒ q Wt j | ƒ S(   sÉ  Partial autocorrelation estimated with non-recursive yule_walker

    Parameters
    ----------
    x : 1d array
        observations of time series for which pacf is calculated
    nlags : int
        largest lag for which pacf is returned
    method : 'unbiased' (default) or 'mle'
        method for the autocovariance calculations in yule walker

    Returns
    -------
    pacf : 1d array
        partial autocorrelations, maxlag+1 elements

    See Also
    --------
    statsmodels.tsa.stattools.pacf
    statsmodels.tsa.stattools.pacf_burg
    statsmodels.tsa.stattools.pacf_ols

    Notes
    -----
    This solves yule_walker for each desired lag and contains
    currently duplicate calculations.
    g      ð?i   RC   i    iÿÿÿÿ(   R   t   appendR   R:   R¯   (   Rl   R°   RC   R   R4   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR   6  s    	(c         C   s­  t  j t  j |  ƒ ƒ }  |  j d k r6 t d ƒ ‚ n  | rO |  |  j ƒ  }  n  |  j d } | d k	 rn | n# t t	 d t  j
 | ƒ ƒ | d ƒ } | | d k r³ t d ƒ ‚ n  t  j | d ƒ } d |  j |  ƒ | d <t  j | d ƒ } |  d d d … j ƒ  } |  d d d … j ƒ  } | d  j | d  ƒ | d j | d ƒ | d <d | d | d j | d  ƒ | d <t  j | ƒ }	 t  j | ƒ }
 xÑ t d | ƒ D]À } | |	 (| |
 (|	 d  | | |
 d | d )|
 d | | |	 d  | d )d | | d | | | | d | d d | | d <d | | d | | d j | | d !ƒ | | d <q§Wd | d | d	 | t  j d | d ƒ } d | d <| | f S(
   s}  
    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 compute the partial autocorrelations.  If omitted,
        uses the smaller of 10(log10(nobs)) or nobs - 1
    demean : bool, optional

    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
    statsmodels.tsa.stattools.pacf_yw
    statsmodels.tsa.stattools.pacf_ols

    References
    ----------
    .. [*] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    i   s#   x must be 1-d or squeezable to 1-d.i    i
   s#   nlags must be smaller than nobs - 1i   Niÿÿÿÿg       @(   R:   Rƒ   R_   R„   R=   RŠ   R`   R\   R9   R^   t   log10t   zerosRŒ   R‡   t
   empty_likeR   R   (   Rl   R°   R—   RZ   t   pR£   R   t   uR5   t   last_ut   last_vR¡   t   sigma2(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR'   X  s8     80'::.
c   
      C   s­  t  j | d ƒ } d | d <t  j t  j |  ƒ ƒ }  |  j d k rS t d ƒ ‚ n  | ræ t |  | d d ƒ\ } } t | ƒ } xò t d | d ƒ D]K } t	 | | d … d | d … f | | d d ƒd } | d	 | | <q” Wn |  t  j |  ƒ }  t |  | d d d
 d ƒ\ } } xX t d | d ƒ D]C } t	 | d d … d | … f | d d ƒd } | d	 | | <q.W| r©t |  ƒ }	 | |	 |	 t  j | d ƒ 9} n  | S(   sÐ  
    Calculate partial autocorrelations via OLS

    Parameters
    ----------
    x : 1d array
        observations of time series for which pacf is calculated
    nlags : int
        Number of lags for which pacf is returned.  Lag 0 is not returned.
    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.
    unbiased : bool, optional
        Adjust each partial autocorrelation by n / (n - lag)

    Returns
    -------
    pacf : 1d array
        partial autocorrelations, (maxlag,) array corresponding to lags
        0, 1, ..., maxlag

    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.

    See Also
    --------
    statsmodels.tsa.stattools.pacf
    statsmodels.tsa.stattools.pacf_yw
    statsmodels.tsa.stattools.pacf_burg

    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
    i   g      ð?i    s#   x must be squeezable to a 1-d arrayRU   t   sepNt   rcondiÿÿÿÿRS   RT   (   R:   R‹   Rƒ   R_   R„   R=   R   R   R   R   R\   RŠ   Ra   R   (
   Rl   R°   t	   efficientR–   R   t   xlagst   x0R4   t   paramsR~   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR   —  s(    2
7!/"t
   ywunbiasedc         C   s´  | d  k rE d | k } d | k } t  |  d | d | d | ƒ} nì | d! k rl t |  d | d d ƒ} nÅ | d" k r“ t |  d | d d ƒ} nž | d# k rÜ t |  d t d t ƒ} t | d | d t ƒ} | d } nU | d$ k r%t |  d t d t ƒ} t | d | d t ƒ} | d } n t d ƒ ‚ | d k	 r¬d t |  ƒ }	 t	 j
 j d | d ƒ t j |	 ƒ }
 t j t | |
 | |
 ƒ ƒ } | d | d <| | f S| Sd S(%   s  
    Partial autocorrelation estimated

    Parameters
    ----------
    x : 1d array
        observations of time series for which pacf is calculated
    nlags : int
        largest lag for which the pacf is returned
    method : str
        specifies which method for the calculations to use:

        - 'yw' or 'ywunbiased' : Yule-Walker with bias correction in
          denominator for acovf. Default.
        - 'ywm' or 'ywmle' : Yule-Walker without bias correction
        - '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-unbiased' : regression of time series on lags with a bias
          adjustment
        - 'ld' or 'ldunbiased' : Levinson-Durbin recursion with bias correction
        - 'ldb' or 'ldbiased' : Levinson-Durbin recursion without bias
          correction

    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 : 1d array
        partial autocorrelations, nlags elements, including lag zero
    confint : array, optional
        Confidence intervals for the PACF. Returned if confint is not None.

    See Also
    --------
    statsmodels.tsa.stattools.acf
    statsmodels.tsa.stattools.pacf_yw
    statsmodels.tsa.stattools.pacf_burg
    statsmodels.tsa.stattools.pacf_ols

    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-unbiased.

    Yule-Walker (unbiased) and Levinson-Durbin (unbiased) performed
    consistently worse than the other options.
    t   olss   ols-inefficients   ols-unbiasedt   inefficientR–   R°   RÂ   t   ywt   ywuRÆ   t   yw_unbiasedRC   t   ywmt   ywmlet   yw_mlet   mlet   ldt   ldut
   ldunbiasedt   ld_unbiasedR’   t   isacovi   t   ldbt   ldbiasedt	   ld_biaseds   method not availableg      ð?g       @i    N(   RÇ   s   ols-inefficients   ols-unbiased(   RÉ   RÊ   RÆ   RË   (   RÌ   RÍ   RÎ   (   RÐ   RÑ   RÒ   RÓ   (   RÕ   RÖ   R×   (   R   R   R   R[   R‚   R+   R=   R\   Ra   R   R¬   R­   R:   R®   R¯   R   (   Rl   R°   RC   R²   RÂ   R–   R«   t   acvt   ld_R´   Rµ   R¶   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR   ä  s0    8!' 
c   	      C   s“   t  |  ƒ } | r5 |  |  j ƒ  } | | j ƒ  } n |  } | } | rn t j | ƒ } t j | | d ƒ } n | } t j | | d ƒ | | d S(   sš   crosscovariance for 1D

    Parameters
    ----------
    x, y : arrays
       time series data
    unbiased : boolean
       if True, then denominators is n-k, otherwise n

    Returns
    -------
    ccovf : array
        autocovariance function

    Notes
    -----
    This uses np.correlate which does full convolution. For very long time
    series it is recommended to use fft convolution instead.
    R}   i   (   Ra   RŠ   R:   R‘   R   (	   Rl   t   yR–   R—   R~   Rž   t   yoR¤   R£   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR   9  s    c         C   s9   t  |  | d | d t ƒ} | t j |  ƒ t j | ƒ S(   sN  cross-correlation function for 1d

    Parameters
    ----------
    x, y : arrays
       time series data
    unbiased : boolean
       if True, then denominators for autocovariance is n-k, otherwise n

    Returns
    -------
    ccf : array
        cross-correlation function of x and y

    Notes
    -----
    This is based np.correlate which does full convolution. For very long time
    series it is recommended to use fft convolution instead.

    If unbiased is true, the denominator for the autocovariance is adjusted
    but the autocorrelation is not an unbiased estimtor.

    R–   R—   (   R   R[   R:   t   std(   Rl   RÚ   R–   t   cvf(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR    \  s    c         C   sJ   t  j |  ƒ }  d t |  ƒ t  j t  j j |  ƒ ƒ d } d | d <| S(   s  
    Returns the periodogram for the natural frequency of X

    Parameters
    ----------
    X : array-like
        Array for which the periodogram is desired.

    Returns
    -------
    pgram : array
        1./len(X) * np.abs(np.fft.fft(X))**2


    References
    ----------
    .. [*] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    g      ð?i   g        i    (   R:   R_   Ra   R;   R’   (   t   Xt   pergr(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR!   x  s    -
i
   c         C   sñ  t  j |  ƒ }  | } | r$ |  } n t |  d t ƒ| d  } t  j | d | d f d ƒ } t  j | d ƒ } | d | d | d	 <| d | d
 | d | d <x÷ t d | d ƒ D]â } | | t  j | d | … | d f | d | !d d d … ƒ | | d | | | f <xY t d | ƒ D]H } | | | d f | | | f | | | | d f | | | f <q'W| | d d | | | f d | | <q¹ W| d }	 | d d … d f }
 t  j | ƒ j ƒ  } d | d <|	 |
 | | | f S(   s  
    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 : integer
        largest lag to include in recursion or order of the autoregressive
        process
    isacov : boolean
        flag to indicate whether the first argument, s, contains the
        autocovariances or the data series.

    Returns
    -------
    sigma_v : float
        estimate of the error variance ?
    arcoefs : ndarray
        estimate of the autoregressive coefficients for a model including nlags
    pacf : ndarray
        partial autocorrelation function
    sigma : ndarray
        entire sigma array from intermediate result, last value is sigma_v
    phi : ndarray
        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).
    R’   i   R£   i    i   Niÿÿÿÿg      ð?(   i   i   (   i   i   (	   R:   R_   R   R‚   R¹   R   RŒ   t   diagR‡   (   t   sR°   RÔ   t   ordert   sxx_mt   phit   sigR4   t   jt   sigma_vt   arcoefst   pacf_(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR+   —  s(    '	 $4F,

c         C   s   t  j t  j |  ƒ ƒ }  |  j d k r6 t d ƒ ‚ n  |  d d k rU t d ƒ ‚ n  |  d }  |  j d } | d k	 r­ | | k r“ t d ƒ ‚ n  |  |  }  |  j d } n  t  j | d ƒ } |  d | d <t  j d |  d ƒ } |  j	 ƒ  } x˜ t
 d | ƒ D]‡ } | | |  j	 ƒ  } | | | | d d d … | | | *| | | | d | j | d | | !d d d … ƒ | | d <qWd | d <| | f S(	   sú  
    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
        acf computed from the partial autocorrelations. Array returned contains
        the autocorelations corresponding to lags 0, 1, ..., p

    References
    ----------
    .. [*] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    i   s&   pacf must be 1-d or squeezable to 1-d.i    sC   The first entry of the pacf corresponds to lags 0 and so must be 1.sI   Must provide at least as many values from the pacf as the number of lags.i   Niÿÿÿÿ(   R:   Rƒ   R_   R„   R=   R`   R\   R¹   t   cumprodR‡   R   RŒ   (   R   R°   R~   R   t   nuRè   R¡   t   prev(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR*   Ù  s,    

(H
c      	   C   sâ  t  j t  j |  ƒ ƒ }  |  j d k r6 t d ƒ ‚ n  | d
 k rH d n | } t | t ƒ sl t d ƒ ‚ n  | d
 k	 r¥ | t | ƒ k s– | d k  r¥ t d ƒ ‚ n  | d
 k r¾ |  j	 d n	 t | ƒ } t t  j
 t  j |  d k ƒ ƒ ƒ } t  j | d ƒ } |  d | d <t  j | d | d f ƒ } xƒt d | ƒ D]r} x¯ t t
 | | d ƒ | ƒ D]‘ } d }	 xV t t
 | | d ƒ | ƒ D]8 }
 |	 | | | |
 f | | | |
 f | |
 7}	 qˆWd | | |  | | |	 | | | | f <q_W|  d | | <xN t t
 | | d ƒ | ƒ D]0 }
 | | c | | | |
 f d | |
 8<qW| d	 k r<| | d	 | | | d | k  r®| | | | d )| | | | d )Pq®q<q<W| d
 d … d d
 … f } | d  } | | f S(   sI  
    Innovations algorithm to convert autocovariances to MA parameters

    Parameters
    ----------
    acov : array-like
        Array containing autocovariances including lag 0
    nobs : int, optional
        Number of periods to run the algorithm.  If not provided, nobs is
        equal to the length of acovf
    rtol : float, optional
        Tolerance used to check for convergence. Default value is 0 which will
        never prematurely end the algorithm. Checks after 10 iterations and
        stops if sigma2[i] - sigma2[i - 10] < rtol * sigma2[0]. When the
        stopping condition is met, the remaining values in theta and sigma2
        are forward filled using the value of the final iteration.

    Returns
    -------
    theta : ndarray
        Innovation coefficients of MA representation. Array is (nobs, q) where
        q is the largest index of a non-zero autocovariance. theta
        corresponds to the first q columns of the coefficient matrix in the
        common description of the innovation algorithm.
    sigma2 : ndarray
        The prediction error variance (nobs,).

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.macrodata.load_pandas()
    >>> rgdpg = data.data['realgdp'].pct_change().dropna()
    >>> acov = sm.tsa.acovf(rgdpg)
    >>> nobs = activity.shape[0]
    >>> theta, sigma2  = innovations_algo(acov[:4], nobs=nobs)

    See Also
    --------
    innovations_filter

    References
    ----------
    .. [*] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    i   s&   acov must be 1-d or squeezable to 1-d.g        s*   rtol must be a non-negative float or None.s   nobs must be a positive integeri    g      ð?i   i
   Niÿÿÿÿ(   R:   Rƒ   R_   R„   R=   R\   R]   t   floatR^   R`   t   maxt   argwhereR¹   R   (   R    RZ   t   rtolR~   t   max_lagR5   t   thetaR¡   R4   t   subRæ   (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR(     s<    .*%$##60#.$
c         C   s¡  |  } t  j t  j |  ƒ ƒ }  |  j d k r< t d ƒ ‚ n  |  j d } | j \ } } | | k rs t d ƒ ‚ n  t | t j t j	 f ƒ } | rÁ t
 | j ƒ | k rÁ d } t | ƒ ‚ qÁ n  t  j | ƒ } |  d | d <x• t d | ƒ D]„ }	 |	 | k  r4| |	 d |	 … f | |	  d d d … j ƒ  }
 n, | |	 | |	 | |	 !d d d … j ƒ  }
 |  |	 |
 | |	 <qî W| rt j	 | d | j j ƒ  ƒ} n  | S(	   s¸  
    Filter observations using the innovations algorithm

    Parameters
    ----------
    endog : array-like
        The time series to filter (nobs,). Should be demeaned if not mean 0.
    theta : ndarray
        Innovation coefficients of MA representation. Array must be (nobs, q)
        where q order of the MA.

    Returns
    -------
    resid : ndarray
        Array of filtered innovations

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.macrodata.load_pandas()
    >>> rgdpg = data.data['realgdp'].pct_change().dropna()
    >>> acov = sm.tsa.acovf(rgdpg)
    >>> nobs = activity.shape[0]
    >>> theta, sigma2  = innovations_algo(acov[:4], nobs=nobs)
    >>> resid = innovations_filter(rgdpg, theta)

    See Also
    --------
    innovations_algo

    References
    ----------
    .. [*] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    i   s'   endog must be 1-d or squeezable to 1-d.i    s2   theta must be (nobs, q) where q is the moder ordersg   If endog is a Series or DataFrame, the index must correspond to the number of time series observations.Niÿÿÿÿt   index(   R:   Rƒ   R_   R„   R=   R`   R]   t   pdt	   DataFramet   SeriesRa   Rô   R‹   R   R‰   R‡   (   R?   Rò   t
   orig_endogRZ   t   n_thetaR4   t	   is_pandasRš   R¼   R¡   t   hat(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR)   `  s.    $4,!c         C   s²  d d l  m } t j |  ƒ }  |  j d d | t | ƒ k rw t d j t |  j d t | ƒ d ƒ d ƒ ƒ ‚ n  i  } x.t d | d ƒ D]} i  } | r¶ d GHd | f GHn  | } t	 |  | d	 d
 d d ƒ}	 | r4t
 |	 d d … d | d … f d t ƒ}
 t
 |	 d d … d d … f d t ƒ} n t d ƒ ‚ t |	 d d … d f |
 ƒ j ƒ  } t |	 d d … d f | ƒ j ƒ  } | j | j | j | | j } | râd | | j j | | | j ƒ | j | f GHn  | | j j | | | j ƒ | j | f | d <| j | j | j | j } | rXd | | j j | | ƒ | f GHn  | | j j | | ƒ | f | d <d | j | j } | r¸d | | j j | | ƒ | f GHn  | | j j | | ƒ | f | d <t j t j | | f ƒ t j | | ƒ t j | d f ƒ f ƒ } | j | ƒ } | rUd | j | j | j | j f GHn  t j | j ƒ d t j | j ƒ d | j | j f | d <| | | | g f | | <q‘ W| S(   sz  four tests for granger non causality of 2 timeseries

    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, 2d
        data for test whether the time series in the second column Granger
        causes the time series in the first column
    maxlag : integer
        the Granger causality test results are calculated for all lags up to
        maxlag
    verbose : bool
        print results if true

    Returns
    -------
    results : dictionary
        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
        teststatistic, 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
    ----------
    http://en.wikipedia.org/wiki/Granger_causality
    Greene: Econometric Analysis

    iÿÿÿÿ(   R   i    i   s7   Insufficient observations. Maximum allowable lag is {0}i   s   
Granger Causalitys   number of lags (no zero)RS   RT   t   dropexNRW   s   Not ImplementedsD   ssr based F test:         F=%-8.4f, p=%-8.4f, df_denom=%d, df_num=%dt	   ssr_ftests3   ssr based chi2 test:   chi2=%-8.4f, p=%-8.4f, df=%dt   ssr_chi2testiþÿÿÿs3   likelihood ratio test: chi2=%-8.4f, p=%-8.4f, df=%dt   lrtestsD   parameter F test:         F=%-8.4f, p=%-8.4f, df_denom=%d, df_num=%dt   params_ftest(    (    (   t   scipyR   R:   R_   R`   R^   R=   t   formatR   R   R   R‚   t   NotImplementedErrorR   R8   t   ssrt   df_residt   fR©   RZ   R¨   t   llft   column_stackR¹   t   eyet   f_testt   fvalueRw   t   df_denomt   df_numRƒ   (   Rl   RB   t   addconstt   verboseR   t   reslit   mlgt   resultt   mxlgt   dtat   dtaownt   dtajointt   res2downt
   res2djointt   fgc1t   fgc2t   lrt   rconstrt   ftres(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyt   grangercausalitytestsŸ  sj    4!	,+%%	"	!"!"t   aegR2   c         C   s›  | j  ƒ  } | d k r+ t d | ƒ ‚ n  t j |  ƒ }  t j | ƒ } | j d k  rq | d d … d f } n  | j \ } } | d 7} | d k rŸ | }	 n t | d	 | d
 t ƒ}	 t	 |  |	 ƒ j
 ƒ  }
 |
 j d d t k  rt |
 j d | d | d d ƒ} n) d d l } | j d t ƒ t j f } | d k rOt j g d } n t d | d | d | d ƒ } t | d d | d | ƒ} | d | | f S(   s  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
    ----------
    y1 : array_like, 1d
        first element in cointegrating vector
    y2 : array_like
        remaining elements in cointegrating vector
    trend : str {'c', 'ct'}
        trend term included in regression for cointegrating equation

        * 'c' : constant
        * 'ct' : constant and linear trend
        * also available quadratic trend 'ctt', and no constant 'nc'

    method : string
        currently only 'aeg' for augmented Engle-Granger test is available.
        default might change.
    maxlag : None or int
        keyword for `adfuller`, largest or given number of lags
    autolag : string
        keyword 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
        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
    ----------
    MacKinnon, J.G. 1994  "Approximate Asymptotic Distribution Functions for
        Unit-Root and Cointegration Tests." Journal of Business & Economics
        Statistics, 12.2, 167-76.
    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
    RN   RP   RQ   RR   s   trend option %s not understoodi   Ni   t   trendRW   id   RB   Rm   RX   iÿÿÿÿsZ   y0 and y1 are (almost) perfectly colinear.Cointegration test is not reliable in this case.i   RY   RZ   i    (   RN   RP   RQ   RR   (   R7   R=   R:   R_   R„   R\   R`   R   R‚   R   R8   t   rsquaredt   SQRTEPSR%   t   residR   R€   R   t   inft   nanR   R   (   t   y0t   y1R   RC   RB   Rm   t   return_resultsRZ   t   k_varst   xxt   res_cot   res_adfR   t   critt   pval_asy(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR#   '  s2    Y
		c         C   så   y2 t  |  d | | j d d d | d | |  SWn¬ t k
 rF d  St k
 rÙ } | d  k	 re d  Sd | j d k sŠ d t | ƒ k rÒ d g t | ƒ } | d k r¹ d g | } n  t |  | | | | | ƒ Sd  Sn d  SXd  S(	   NRâ   t   dispi    R   t   start_paramst   initialgš™™™™™¹?RN   (	   R   R8   R
   R=   R\   t   argst   strR‰   t   _safe_arma_fit(   RÚ   Râ   t   model_kwR   t   fit_kwR0  t   error(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR4  ¨  s$    $%i   i   R6   c         C   s  d d l  m } t d | d ƒ } t d | d ƒ }	 t | t ƒ rQ | g } n$ t | t t f ƒ su t d ƒ ‚ n  t j	 t
 | ƒ | d | d f ƒ }
 | d k r­ i  n | } | d k rÅ i  n | } t j |  ƒ } xê | D]â } xÙ |	 D]Ñ } | d k r:| d k r:| d k r:t j |
 d d … | | f <qî n  t | | | f | | | ƒ } | d k r†t j |
 d d … | | f <qî n  x6 t | ƒ D]( \ } } t | | ƒ |
 | | | f <q“Wqî Wqá Wg  |
 D] } | | d |	 d	 | ƒ^ qÎ} t t | | ƒ ƒ } i  } xi t | ƒ D][ \ } } t j | j ƒ  j ƒ  | k ƒ } | j i | d d | d d f | d
 6ƒ qW| j | ƒ t |   S(   sU  
    Returns information criteria for many ARMA models

    Parameters
    ----------
    y : array-like
        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
    -------
    obj : Results object
        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``.

    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='nc')
    >>> res.aic_min_order
    >>> res.bic_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.
    iÿÿÿÿ(   Rö   i    i   s.   Need a list or a tuple for ic if not a string.RP   Nt   columnsRô   t
   _min_order(   t   pandasRö   R   R]   R   t   listt   tupleR=   R:   R¹   Ra   R\   R_   R%  R4  t	   enumeratet   getattrt   dictR   R   t   whereR9   t   updateR   (   RÚ   t   max_art   max_mat   icR   R5  R6  Rö   t   ar_ranget   ma_rangeRG   t   y_arrt   art   maR>   R¡   t   criteriat   rest   dfst   min_resR  t   mins(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR$   Â  s<    9&$(+!2c         C   s   t  j t  j |  ƒ ƒ S(   sJ   
    Returns True if 'data' contains missing entries, otherwise False
    (   R:   R†   R‰   (   t   data(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR…   $  s    c         C   s  d d l  m } t |  ƒ } t j |  ƒ }  | j ƒ  } | |  j k ra t d j |  j	 ƒ ƒ ‚ n  | d k r° t
 |  t t j d | d ƒ ƒ ƒ j ƒ  j } d d d d	 g } nF | d
 k rá |  |  j ƒ  } d d d d g } n t d j | ƒ ƒ ‚ | d( k rd } d }	 | |	 t ƒ n  | d k rit t j d t j | d d) ƒ ƒ ƒ } t | | d ƒ } n* | d k r‡t | | ƒ } n t | ƒ } | | k rºt d j | | ƒ ƒ ‚ n  d d d d g }
 t j | j ƒ  d ƒ | d } t | | | ƒ } | | } t j | | |
 ƒ } | |
 d k r>| d t ƒ n  | |
 d k r^| d t ƒ n  i | d d 6| d d  6| d d! 6| d" d# 6} | rýt ƒ  } | | _ | | _ | d
 k rÃd$ n d% } d& j | ƒ | _ d' j | ƒ | _  | | | | f S| | | | f Sd( S(*   sŠ  
    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
        Data series
    regression : str{'c', 'ct'}
        Indicates the null hypothesis for the KPSS test
        * 'c' : The data is stationary around a constant (default)
        * 'ct' : The data is stationary around a trend
    lags : {None, str, int}, optional
        Indicates the number of lags to be used. If None (default), lags is
        calculated using the legacy method. If 'auto', 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 None,
    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.

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

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

    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.

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

    Schwert, G. W. (1989). Tests for unit roots: A Monte Carlo investigation.
    Journal of Business and Economic Statistics, 7 (2): 147-159.
    iÿÿÿÿ(   R€   s   x of shape {0} not understoodRQ   i   gX9´Èv¾?gã¥›Ä °Â?gºI+‡Æ?gÙÎ÷Sã¥Ë?RN   gh‘í|?5Ö?goƒÀÊ¡Ý?g‘í|?5^â?gÙÎ÷Sã¥ç?s   hypothesis '{0}' not understoodt   legacysU  The behavior of using lags=None will change in the next release. Currently lags=None is the same as lags='legacy', and so a sample-size lag length is used. After the next release, the default will change to be the same as lags='auto' which uses an automatic lag length selection method. To silence this warning, either use 'auto' or 'legacy'g      (@g      Y@g      @t   autos/   lags ({}) must be < number of observations ({})gš™™™™™¹?gš™™™™™©?gš™™™™™™?g{®Gáz„?i   s-   p-value is smaller than the indicated p-valuei    s-   p-value is greater than the indicated p-values   10%s   5%s   2.5%i   s   1%t   levelR   s   The series is {0} stationarys    The series is not {0} stationaryNg      Ð?(!   R   R€   Ra   R:   R_   R7   t   sizeR=   R  R`   R   R   R   R8   R#  RŠ   R\   R   R^   Rb   Rc   R9   t   _kpss_autolagR‰   R§   t   _sigma_est_kpsst   interpR   R,   t   lagsRZ   Rj   Rk   (   Rl   RX   RW  Rn   R€   RZ   t   hypot   residsR-  Rš   t   pvalst   etat   s_hatt	   kpss_statt   p_valuet	   crit_dictt   rstoret   stationary_type(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyR&   +  sZ    I.)	!
2			c         C   su   t  j |  d ƒ } xW t d | d ƒ D]B } t  j |  | |  | |  ƒ } | d | d | | d 7} q' W| | S(   s{   
    Computes equation 10, p. 164 of Kwiatkowski et al. (1992). This is the
    consistent estimator for the variance.
    i   i   g      ð?(   R:   R‰   R   RŒ   (   RY  RZ   RW  R\  R¡   t   resids_prod(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyRU  À  s
    "c         C   sð   t  t j | d	 ƒ ƒ } t j |  d ƒ | } d } x_ t d | d ƒ D]J } t j |  | |  | |  ƒ } | | d } | | 7} | | | 7} qI W| | } d
 } d t j | | | ƒ }	 t j | t  |	 t j | | ƒ ƒ g ƒ }
 |
 S(   sè   
    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       @g      "@i   i    i   g      ð?g      @gÿ²{ò°Pò?gÇqÇqÌ?gUUUUUUÕ?(   R^   R:   Rc   R‰   R   RŒ   t   amin(   RY  RZ   t   covlagst   s0t   s1R¡   Rb  R\  t   pwrt	   gamma_hatt   autolags(    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyRT  Ì  s    

+(    (    (O   t   __doc__t
   __future__R    t   statsmodels.compat.pythonR   R   R   R   R   R   R   t   statsmodels.compat.numpyR   t   statsmodels.compat.scipyR	   t   numpyR:   R:  Rõ   t   numpy.linalgR
   R  R   t#   statsmodels.regression.linear_modelR   R   t   statsmodels.tools.sm_exceptionsR   R   R   t   statsmodels.tools.toolsR   R   t   statsmodels.tsa._bdsR   t   statsmodels.tsa.adfvaluesR   R   t   statsmodels.tsa.arima_modelR   t   statsmodels.tsa.tsatoolsR   R   R   t   __all__R®   t   finfot   doublet   epsR"  t   objectR,   R‚   RM   R\   R%   R[   R   R"   R   R   R'   R   R   R   R    R!   R+   R*   R(   R)   R  R#   R4  R$   R…   R&   RU  RT  (    (    (    s8   lib/python2.7/site-packages/statsmodels/tsa/stattools.pyt   <module>   sd   4T	»„ X"?MU#	B4S	?ˆ€a	•	