
p7]c           @  s{  d  Z  d d l m Z d d l m Z m Z m 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 d d	 d
 e d  Z d e f d     YZ d e f d     YZ e   Z e j  e _  d e f d     YZ e   Z e j  e _  d e d  Z d d
 e e d  Z d d e e d	 d  Z d e d  Z d   Z e d  Z  d e d  Z! d e f d     YZ" e"   Z# e# j$ j  e# _  d   Z% d d  Z& d d  Z' d   Z( d    Z) d!   Z* d d" d# d$  Z+ d%   Z, d	 d&  Z- d'   Z. e/ d( k rwd) g Z0 d) e0 k re j1 j2 d*  Z3 e4 e e3 d+   e4 e e3   d, Z5 d, Z6 e j7 e5  Z8 xW e9 e5 d-  D]E Z: d. e j1 j2 e6  j;   Z3 e e3 d/ d0 d	 d1 d d	 e8 e: <qWe4 e8 d2 k  j<    e4 e j= e8   e j> e8  Z? x5 d3 d4 d5 d6 g D]! Z@ e4 e@ e? eA e5 e@   q$We4 d7  e4 d8  e4 d9  e4 d:  e4 d;  eB g  d: jC d<  D] ZD e eE eD jC d=   ^ q ZF eB g  d; jC d<  D] ZD e eE eD jC d=   ^ q ZG d> d? e6 d@ e6 d/ ZH e4 eH  e e3 d/ d0 d	 d1 d dA d- \ ZI ZJ ZJ ZK e4 e8 eH k j<    e4 eK jL jM jN dB  e4 e3 dB  e4 e j= e8 dC e jO dD dE dF dG dH e jO g  e4 e? e5 e jP d3 d4 d5 d6 dI g  jQ eA   n  d, Z6 e jR e6 d/ f  Z3 e jS e6  dJ e3 d d  d- f <e3 j< d-  dK d- dL e3 d d  d- f dM k e j1 jT e6  ZU e4 e# eU e3 d-   e3 j< d-  dK d- d e3 d d  d- f dM k e j1 jT e6  ZU e4 e# eU e3 d-   e3 j< d-  dK d- d e3 d d  d- f dM k e j1 jT e6  ZU e4 e# eU e3 d-   e4 e eU e3   e4 e  eU e3   e# eU e3 d-  \ ZV ZW ZX e4 eV eW  e# eU e3 d- dN eY ZZ e4 eZ  e4 e) eU e3   e eU e3  j[   Z\ e4 e) e\ j] e3   e4 e\ j^    e4 e\ j_  e4 e\ j`  e3 j< d-  dO d- d e3 d d  d- f dM k e j1 jT e6  ZU e4 e"   j$ eU e3 d- dP dQ  n  d S(R   s  Various Statistical Tests


Author: josef-pktd
License: BSD-3

Notes
-----
Almost fully verified against R or Gretl, not all options are the same.
In many cases of Lagrange multiplier tests both the LM test and the F test is
returned. In some but not all cases, R has the option to choose the test
statistic. Some alternative test statistic results have not been verified.


TODO
* refactor to store intermediate results
* how easy is it to attach a test that is a class to a result instance,
  for example CompareCox as a method compare_cox(self, other) ?

missing:

* pvalues for breaks_hansen
* additional options, compare with R, check where ddof is appropriate
* new tests:
  - breaks_ap, more recent breaks tests
  - specification tests against nonparametric alternatives


i(   t   print_function(   t	   iteritemst   mapt   longN(   t   stats(   t   OLS(   t   acft   adfuller(   t   lagmati    t   AICc         C  s(   t  |  d | d | d | d | d t S(   Nt   maxlagt
   regressiont   autolagt   storet
   regresults(   R   t   False(   t   xR
   t
   trendorderR   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   unitroot_adf)   s    t   ResultsStorec           B  s   e  Z d    Z RS(   c         C  s   |  j  S(   N(   t   _str(   t   self(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   __str__0   s    (   t   __name__t
   __module__R   (    (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR   /   s   t
   CompareCoxc           B  s#   e  Z d  Z e d  Z d   Z RS(   sX  Cox Test for non-nested models

    Parameters
    ----------
    results_x : Result instance
        result instance of first model
    results_z : Result instance
        result instance of second model
    attach : bool


    Formulas from Greene, section 8.3.4 translated to code

    produces correct results for Example 8.3, Greene


    c         C  s  t  j | j j | j j  s- t d   n  | j j j d } | j j } | j j } | j | } | j | } | j }	 | j }
 t	 |	 |  j
   } | j } t	 | |  j
   } | j } | t  j | j |  | } | d t  j |  t  j |  } | t  j | j |  | d } | t  j |  } d t j j t  j |   } | r| |  _ | |  _ | |  _ | |  _ | |  _ | |  _ t j |  _ n  | | f S(   s  run Cox test for non-nested models

        Parameters
        ----------
        results_x : Result instance
            result instance of first model
        results_z : Result instance
            result instance of second model
        attach : bool
            If true, then the intermediate results are attached to the instance.

        Returns
        -------
        tstat : float
            t statistic for the test that including the fitted values of the
            first model in the second model has no effect.
        pvalue : float
            two-sided pvalue for the t statistic

        Notes
        -----
        Tests of non-nested hypothesis might not provide unambiguous answers.
        The test should be performed in both directions and it is possible
        that both or neither test rejects. see ??? for more information.

        References
        ----------
        ???

        s/   endogenous variables in models are not the samei    g       @i   (   t   npt   allcloset   modelt   endogt
   ValueErrort   shapet   exogt   ssrt   fittedvaluesR   t   fitt   residt   dott   Tt   logt   sqrtR   t   normt   sft   abst   res_dxt   res_xzxt   c01t   v01t   qt   pvaluet   dist(   R   t	   results_xt	   results_zt   attacht   nobsR   t   zt   sigma2_xt   sigma2_zt   yhat_xt   yhat_zR,   t   err_zxR-   t   err_xzxt	   sigma2_zxR.   R/   R0   t   pval(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   runI   s6     				$!						c         C  s   |  j  | | d t S(   NR5   (   R@   R   (   R   R3   R4   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   __call__   s    (   R   R   t   __doc__t   TrueR@   RA   (    (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR   5   s   ?t   CompareJc           B  s#   e  Z d  Z e d  Z d   Z RS(   s  J-Test for comparing non-nested models

    Parameters
    ----------
    results_x : Result instance
        result instance of first model
    results_z : Result instance
        result instance of second model
    attach : bool


    From description in Greene, section 8.3.3

    produces correct results for Example 8.3, Greene - not checked yet
    #currently an exception, but I don't have clean reload in python session

    check what results should be attached

    c         C  s   t  j | j j | j j  s- t d   n  | j j j d } | j j } | j j } | j j } | j } t | t  j	 | | f   j
   }	 |	 |  _ |	 j d }
 |	 j d } | r |	 |  _ t j |	 j  |  _ |
 |  _ | |  _ n  |
 | f S(   s  run J-test for non-nested models

        Parameters
        ----------
        results_x : Result instance
            result instance of first model
        results_z : Result instance
            result instance of second model
        attach : bool
            If true, then the intermediate results are attached to the instance.

        Returns
        -------
        tstat : float
            t statistic for the test that including the fitted values of the
            first model in the second model has no effect.
        pvalue : float
            two-sided pvalue for the t statistic

        Notes
        -----
        Tests of non-nested hypothesis might not provide unambiguous answers.
        The test should be performed in both directions and it is possible
        that both or neither test rejects. see ??? for more information.

        References
        ----------
        ???

        s/   endogenous variables in models are not the samei    (   R   R   R   R   R   R   R    R"   R   t   column_stackR#   t   res_zxt   tvaluest   pvaluesR   t   tt   df_residR2   t   teststatR1   (   R   R3   R4   R5   R6   t   yR   R7   R:   RF   t   tstatR?   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR@      s"    	$			c         C  s   |  j  | | d t S(   NR5   (   R@   R   (   R   R3   R4   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyRA      s    (   R   R   RB   RC   R@   RA   (    (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyRD      s   5c         C  s{  t  j |   }  |  j d } | d k rR t  j d t | d d d  d  } n. t | t t f  r t  j d | d  } n  t  j |  } t	 |  } t
 |  d | d t } | d | d !d | t  j d | d  } | | d t  j |  | d } t j j | |  } | s(| | f S| t  j | d | d !d  | d }	 t j j |	 |  }
 | | |	 |
 f Sd S(   sk  
    Ljung-Box test for no autocorrelation

    Parameters
    ----------
    x : array_like, 1d
        data series, regression residuals when used as diagnostic test
    lags : None, int or array_like
        If lags is an integer then this is taken to be the largest lag
        that is included, the test result is reported for all smaller lag length.
        If lags is a list or array, then all lags are included up to the largest
        lag in the list, however only the tests for the lags in the list are
        reported.
        If lags is None, then the default maxlag is 'min((nobs // 2 - 2), 40)'
    boxpierce : {False, True}
        If true, then additional to the results of the Ljung-Box test also the
        Box-Pierce test results are returned

    Returns
    -------
    lbvalue : float or array
        test statistic
    pvalue : float or array
        p-value based on chi-square distribution
    bpvalue : (optional), float or array
        test statistic for Box-Pierce test
    bppvalue : (optional), float or array
        p-value based for Box-Pierce test on chi-square distribution

    Notes
    -----
    Ljung-Box and Box-Pierce statistic differ in their scaling of the
    autocorrelation function. Ljung-Box test is reported to have better
    small sample properties.

    TODO: could be extended to work with more than one series
    1d or nd ? axis ? ravel ?
    needs more testing

    *Verification*

    Looks correctly sized in Monte Carlo studies.
    not yet compared to verified values

    Examples
    --------
    see example script

    References
    ----------
    Greene
    Wikipedia
    i    i   i   i(   t   nlagst   fftN(   R   t   asarrayR   t   Nonet   aranget   mint
   isinstancet   intR   t   maxR   R   t   cumsumR   t   chi2R*   (   R   t   lagst	   boxpierceR6   R
   t   acfxt   acf2normt	   qljungboxR?   t
   qboxpiercet   pvalbp(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   acorr_ljungbox   s"    6*-#
*c         C  s  | r t  } n  t j |   }  |  j d } | d k rg t t j d t j | d d d    } n  t j |   } t	 |  d d  d f | d d } | j d } t j
 t j | d f  | f } |  | } | r t   }	 n  | r8i  }
 xN t d | d  D]9 } t | | d d  d | d  f  j   |
 | <qW| j   d	 k r{t d
   t |
  D  \ } } nC | j   d k rt d   t |
  D  \ } } n t d   t	 |  d d  d f | d d } | j d } t j
 t j | d f  | f } |  | } | } | r>|
 |	 _ q>n | } t | | d d  d | d  f  j   } | j } | j } | | j } t j j | |  } | r| |	 _ | |	 _ | | | | |	 f S| | | | f Sd S(   s  Lagrange Multiplier tests for autocorrelation

    This is a generic Lagrange Multiplier test for autocorrelation. I don't
    have a reference for it, but it returns Engle's ARCH test if x is the
    squared residual array. A variation on it with additional exogenous
    variables is the Breusch-Godfrey autocorrelation test.

    Parameters
    ----------
    resid : ndarray, (nobs,)
        residuals from an estimation, or time series
    maxlag : int
        highest lag to use
    autolag : None or string
        If None, then a fixed number of lags given by maxlag is used.
    store : bool
        If true then the intermediate results are also returned

    Returns
    -------
    lm : float
        Lagrange multiplier test statistic
    lmpval : float
        p-value for Lagrange multiplier test
    fval : float
        fstatistic for F test, alternative version of the same test based on
        F test for the parameter restriction
    fpval : float
        pvalue for F test
    resstore : instance (optional)
        a class instance that holds intermediate results. Only returned if
        store=True

    See Also
    --------
    het_arch
    acorr_breusch_godfrey
    acorr_ljung_box

    i    g      (@g      Y@i   g      @Nt   trimt   botht   aicc         s  s$   |  ] \ } } | j  | f Vq d  S(   N(   Rc   (   t   .0t   kt   v(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pys	   <genexpr>t  s    t   bicc         s  s$   |  ] \ } } | j  | f Vq d  S(   N(   Rg   (   Rd   Re   Rf   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pys	   <genexpr>v  s    s(   autolag can only be None, 'AIC' or 'BIC'(   RC   R   RP   R   RQ   RU   t   ceilt   powert   diffR   t   c_t   onesR   t   rangeR   R#   t   lowerRS   R   R   t   resultst   fvaluet   f_pvaluet   rsquaredR   RX   R*   t   resolst   usedlag(   R   R
   R   R   R   R6   t   xdifft   xdallt   xshortt   resstoreRo   t   mlagt   bestict	   icbestlagt   icbestRt   Rs   t   fvalt   fpvalt   lmt   lmpval(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   acorr_lm/  sP    *	0%" 7%%%"/				c      
   C  s&   t  |  d d | d | d | d | S(   s  Engle's Test for Autoregressive Conditional Heteroscedasticity (ARCH)

    Parameters
    ----------
    resid : ndarray
        residuals from an estimation, or time series
    maxlag : int
        highest lag to use
    autolag : None or string
        If None, then a fixed number of lags given by maxlag is used.
    store : bool
        If true then the intermediate results are also returned
    ddof : int
        Not Implemented Yet
        If the residuals are from a regression, or ARMA estimation, then there
        are recommendations to correct the degrees of freedom by the number
        of parameters that have been estimated, for example ddof=p+a for an
        ARMA(p,q) (need reference, based on discussion on R finance mailinglist)

    Returns
    -------
    lm : float
        Lagrange multiplier test statistic
    lmpval : float
        p-value for Lagrange multiplier test
    fval : float
        fstatistic for F test, alternative version of the same test based on
        F test for the parameter restriction
    fpval : float
        pvalue for F test
    resstore : instance (optional)
        a class instance that holds intermediate results. Only returned if
        store=True

    Notes
    -----
    verified agains R:FinTS::ArchTest

    i   R
   R   R   R   (   R   (   R$   R
   R   R   R   t   ddof(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   het_arch  s    *c         C  s  t  j |  j  } |  j j } | j d } | d k rm t  j d t  j | d d d   } t	 |  } n  t  j
 t  j |  | f  } t | d d  d f | d d } | j d } t  j t  j | d f  | f } | | } t  j | | f  } | j d }	 | rt   }
 n  t | |  j   } | j t  j | |	 |	 |   } | j } | j } t  j |  d	 } t  j |  d
 } | | j } t j j | |  } | r| |
 _ | |
 _ | | | | |
 f S| | | | f Sd S(   s  Breusch Godfrey Lagrange Multiplier tests for residual autocorrelation

    Parameters
    ----------
    results : Result instance
        Estimation results for which the residuals are tested for serial
        correlation
    nlags : int
        Number of lags to include in the auxiliary regression. (nlags is
        highest lag)
    store : bool
        If store is true, then an additional class instance that contains
        intermediate results is returned.

    Returns
    -------
    lm : float
        Lagrange multiplier test statistic
    lmpval : float
        p-value for Lagrange multiplier test
    fval : float
        fstatistic for F test, alternative version of the same test based on
        F test for the parameter restriction
    fpval : float
        pvalue for F test
    resstore : instance (optional)
        a class instance that holds intermediate results. Only returned if
        store=True

    Notes
    -----
    BG adds lags of residual to exog in the design matrix for the auxiliary
    regression with residuals as endog,
    see Greene 12.7.1.

    References
    ----------
    Greene Econometrics, 5th edition

    i    g      (@g      Y@i   g      @NRa   Rb   (    (    (   R   RP   R$   R   R    R   RQ   t   truncRi   RU   t   concatenatet   zerosR   Rk   Rl   RE   R   R   R#   t   f_testt   eyeRp   R1   t   squeezeRr   R   RX   R*   Rs   Rt   (   Ro   RN   R   R   t   exog_oldR6   Rv   Rw   R    t   k_varsRx   Rs   t   ftR}   R~   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   acorr_breusch_godfrey  s8    *'%" "				c   
      C  s   t  j |  } t  j |   d } | j \ } } t | |  j   } | j } | j } | | j }	 |	 t j	 j
 |	 | d  | | f S(   s  Breusch-Pagan Lagrange Multiplier test for heteroscedasticity

    The tests the hypothesis that the residual variance does not depend on
    the variables in x in the form

    :math: \sigma_i = \sigma * f(\alpha_0 + \alpha z_i)

    Homoscedasticity implies that $\alpha=0$


    Parameters
    ----------
    resid : array-like
        For the Breusch-Pagan test, this should be the residual of a regression.
        If an array is given in exog, then the residuals are calculated by
        the an OLS regression or resid on exog. In this case resid should
        contain the dependent variable. Exog can be the same as x.
        TODO: I dropped the exog option, should I add it back?
    exog_het : array_like
        This contains variables that might create data dependent
        heteroscedasticity.

    Returns
    -------
    lm : float
        lagrange multiplier statistic
    lm_pvalue :float
        p-value of lagrange multiplier test
    fvalue : float
        f-statistic of the hypothesis that the error variance does not depend
        on x
    f_pvalue : float
        p-value for the f-statistic

    Notes
    -----
    Assumes x contains constant (for counting dof and calculation of R^2).
    In the general description of LM test, Greene mentions that this test
    exaggerates the significance of results in small or moderately large
    samples. In this case the F-statistic is preferrable.

    *Verification*

    Chisquare test statistic is exactly (<1e-13) the same result as bptest
    in R-stats with defaults (studentize=True).

    Implementation
    This is calculated using the generic formula for LM test using $R^2$
    (Greene, section 17.6) and not with the explicit formula
    (Greene, section 11.4.3).
    The degrees of freedom for the p-value assume x is full rank.

    References
    ----------
    http://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test
    Greene 5th edition
    Breusch, Pagan article

    i   i   (   R   RP   R   R   R#   Rp   Rq   Rr   R   RX   R*   (
   R$   t   exog_hetR   RL   R6   t   nvarsRs   R}   R~   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   het_breuschpagan  s    =		c         C  s@  t  j |  } t  j |   } | j d k r< t d   n  | j \ } } t  j |  \ } } | d d  | f | d d  | f } | j \ } }	 |	 | | d d | k s t  t | d |  j   }
 |
 j	 } |
 j
 } | |
 j } |
 j t  j j |  d k st  t j j | |
 j  } | | | | f S(   sJ  White's Lagrange Multiplier Test for Heteroscedasticity

    Parameters
    ----------
    resid : array_like
        residuals, square of it is used as endogenous variable
    exog : array_like
        possible explanatory variables for variance, squares and interaction
        terms are included in the auxilliary regression.
    resstore : instance (optional)
        a class instance that holds intermediate results. Only returned if
        store=True

    Returns
    -------
    lm : float
        lagrange multiplier statistic
    lm_pvalue :float
        p-value of lagrange multiplier test
    fvalue : float
        f-statistic of the hypothesis that the error variance does not depend
        on x. This is an alternative test variant not the original LM test.
    f_pvalue : float
        p-value for the f-statistic

    Notes
    -----
    assumes x contains constant (for counting dof)

    question: does f-statistic make sense? constant ?

    References
    ----------
    Greene section 11.4.1 5th edition p. 222
    now test statistic reproduces Greene 5th, example 11.3

    i   s5   x should have constant and at least one more variableNg       @i   (   R   RP   t   ndimR   R   t   triu_indicest   AssertionErrorR   R#   Rp   Rq   Rr   t   df_modelt   linalgt   matrix_rankR   RX   R*   (   R$   R    t   retresR   RL   R6   t   nvars0t   i0t   i1R   Rs   R}   R~   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt	   het_white\  s     &*"		%c         C  s  t  j |  } t  j |   }  | j \ } } | d k rF | d } n+ d | k  rq | d k  rq t | |  } n  t  j | d d  | f  } |  | }  | | d d  f } t |  |  | |   j   } t |  | | |  j   }	 | j |	 j }
 |
 d k r-t	 j
 j |
 | j |	 j  } d } n. d |
 }
 t	 j
 j |
 |	 j | j  } d } | rt   } d | _ |
 | _ | | _ |	 j | j f | _ | | _ |	 | _ | | _ | | _ d	 | |
 | f | _ | S|
 | f Sd S(
   sU  test whether variance is the same in 2 subsamples

    Parameters
    ----------
    y : array_like
        endogenous variable
    x : array_like
        exogenous variable, regressors
    idx : integer
        column index of variable according to which observations are
        sorted for the split
    split : None or integer or float in intervall (0,1)
        index at which sample is split.
        If 0<split<1 then split is interpreted as fraction of the observations
        in the first sample
    retres : boolean
        if true, then an instance of a result class is returned,
        otherwise 2 numbers, fvalue and p-value, are returned

    Returns
    -------
    (fval, pval) or res
    fval : float
        value of the F-statistic
    pval : float
        p-value of the hypothesis that the variance in one subsample is larger
        than in the other subsample
    res : instance of result class
        The class instance is just a storage for the intermediate and final
        results that are calculated

    Notes
    -----

    TODO:
    add resultinstance - DONE
    maybe add drop-middle as option
    maybe allow for several breaks

    recommendation for users: use this function as pattern for more flexible
        split in tests, e.g. drop middle.

    can do Chow test for structural break in same way

    ran sanity check
    i   i    i   Nt   largerg      ?t   smallers6   Test Results for Goldfeld-Quandt test of heterogeneitys   The Goldfeld-Quandt test for null hypothesis that the
variance in the second subsample is %s than in the first subsample:
    F-statistic =%8.4f and p-value =%8.4f(   R   RP   R   RQ   RU   t   argsortR   R#   t	   mse_residR   t   fR*   RJ   R   RB   R}   R~   t   df_fvalt   resols1t   resols2t   orderingt   splitR   (   RL   R   t   idxR   R   R6   R   t   xsortindR   R   R}   R~   R   t   res(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   _het_goldfeldquandt2_old  s@    /
	
								t   HetGoldfeldQuandtc           B  sD   e  Z d  Z d d d d e d  Z d   Z d d d d d  Z RS(   sz  test whether variance is the same in 2 subsamples

    Parameters
    ----------
    y : array_like
        endogenous variable
    x : array_like
        exogenous variable, regressors
    idx : integer
        column index of variable according to which observations are
        sorted for the split
    split : None or integer or float in intervall (0,1)
        index at which sample is split.
        If 0<split<1 then split is interpreted as fraction of the observations
        in the first sample
    drop : None, float or int
        If this is not None, then observation are dropped from the middle part
        of the sorted series. If 0<split<1 then split is interpreted as fraction
        of the number of observations to be dropped.
        Note: Currently, observations are dropped between split and
        split+drop, where split and drop are the indices (given by rounding if
        specified as fraction). The first sample is [0:split], the second
        sample is [split+drop:]
    alternative : string, 'increasing', 'decreasing' or 'two-sided'
        default is increasing. This specifies the alternative for the p-value
        calculation.

    Returns
    -------
    (fval, pval) or res
    fval : float
        value of the F-statistic
    pval : float
        p-value of the hypothesis that the variance in one subsample is larger
        than in the other subsample
    res : instance of result class
        The class instance is just a storage for the intermediate and final
        results that are calculated

    Notes
    -----
    The Null hypothesis is that the variance in the two sub-samples are the
    same. The alternative hypothesis, can be increasing, i.e. the variance in
    the second sample is larger than in the first, or decreasing or two-sided.

    Results are identical R, but the drop option is defined differently.
    (sorting by idx not tested yet)
    t
   increasingc         C  s  t  j |  } t  j |  } | j \ } }	 | d k rF | d } n+ d | k  rq | d k  rq t | |  } n  | d k r | }
 n9 d | k  r | d k  r | t | |  }
 n
 | | }
 | d k	 rt  j | d d  | f  } | | } | | d d  f } n  t | |  | |   j   } t | |
 | |
  j   } | j | j } | j	   d k rt
 j j | | j | j  } d } n | j	   d k r| } t
 j j d | | j | j  } d
 } nv | j	   d k r=t
 j j | | j | j  } t
 j j | | j | j  } d t | |  } d } n t d   | r|  } d | _ | | _ | | _ | j | j f | _ | | _ | | _ | | _ | | _ d | | | f | _ n  | | | f S(   s   see class docstringi   i    i   Nt   it   incR   t   dt   dect
   decreasingg      ?t   2s   2-sideds	   two-sideds   invalid alternatives6   Test Results for Goldfeld-Quandt test of heterogeneitys   The Goldfeld-Quandt test for null hypothesis that the
    variance in the second subsample is %s than in the first subsample:
        F-statistic =%8.4f and p-value =%8.4f(   R   R   R   (   R   R   R   (   R   s   2-sideds	   two-sided(   R   RP   R   RQ   RU   R   R   R#   R   Rn   R   R   R*   RJ   t   cdfRS   R   RB   R}   R~   R   R   R   R   R   R   (   R   RL   R   R   R   t   dropt   alternativeR5   R6   R   t   start2R   R   R   R}   R~   R   t   fpval_smt   fpval_laR   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR@   "  sX    	

	"									c         C  s*   y |  j  SWn t k
 r% t |   SXd  S(   N(   R   t   AttributeErrort   repr(   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR   _  s    c         C  s.   |  j  | | d | d | d | d t d | S(   NR   R   R   R5   R   (   R@   R   (   R   RL   R   R   R   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyRA   f  s    'N(   R   R   RB   RQ   RC   R@   R   RA   (    (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR     s   0	<		c         C  s@   t  |  d d d d } d d l m } | j | d d d  S(   s  Harvey Collier test for linearity

    The Null hypothesis is that the regression is correctly modeled as linear.

    Parameters
    ----------
    res : Result instance

    Returns
    -------
    tvalue : float
        test statistic, based on ttest_1sample
    pvalue : float
        pvalue of the test

    Notes
    -----
    TODO: add sort_by option

    This test is a t-test that the mean of the recursive ols residuals is zero.
    Calculating the recursive residuals might take some time for large samples.

    t   skipi   t   alphagffffff?i(   R   i    (   t   recursive_olsresidualst   scipyR   t   ttest_1samp(   R   t   rrR   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   linear_harvey_colliern  s    g      ?c         C  s  |  j  } |  j j } |  j j } t j d d | |  j t  } t j | | |  j t  } t	 | |  } t
 | | | |  j   } | j j j d }	 | j }
 |  j } | |
 | |	 |
 | j } d d l m } | j j | | |	 | j  } | | f S(   ss  Rainbow test for linearity

    The Null hypothesis is that the regression is correctly modelled as linear.
    The alternative for which the power might be large are convex, check

    Parameters
    ----------
    res : Result instance

    Returns
    -------
    fstat : float
        test statistic based of F test
    pvalue : float
        pvalue of the test

    g      ?i   i    i(   R   (   R6   R   R   R    R   Rh   t   astypeRU   t   floort   sliceR   R#   R   R!   RJ   R   R   R   R*   (   R   t   fracR6   R   R    t   lowidxt   uppidxt   mi_slt   res_mit   nobs_mit   ss_mit   sst   fstatR   R?   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   linear_rainbow  s    	$ 		c         C  s   d d l  m } | d k r( d   } n  t j | | | d d  d d  f  f  } | j \ } } t |  |  j   } | j t j	 | d | d d |   } | | j
 }	 | j j |	 | d  }
 |	 |
 | f S(   s0  Lagrange multiplier test for linearity against functional alternative

    limitations: Assumes currently that the first column is integer.
    Currently it doesn't check whether the transformed variables contain NaNs,
    for example log of negative number.

    Parameters
    ----------
    resid : ndarray
        residuals of a regression
    exog : ndarray
        exogenous variables for which linearity is tested
    func : callable
        If func is None, then squares are used. func needs to take an array
        of exog and return an array of transformed variables.

    Returns
    -------
    lm : float
       Lagrange multiplier test statistic
    lm_pval : float
       p-value of Lagrange multiplier tes
    ftest : ContrastResult instance
       the results from the F test variant of this test

    Notes
    -----
    written to match Gretl's linearity test.
    The test runs an auxilliary regression of the residuals on the combined
    original and transformed regressors.
    The Null hypothesis is that the linear specification is correct.

    i(   R   c         S  s   t  j |  d  S(   Ni   (   R   Ri   (   R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   <lambda>  t    Ni   i   (   R   R   RQ   R   RE   R   R   R#   R   R   Rr   RX   R*   (   R$   R    t   funcR   t   exog_auxR6   R   t   lst   ftestR   t   lm_pval(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt	   linear_lm  s    "1*c         C  s  t  j |  } t  j |   } | j d k r< t d   n  t  j | j d  \ } } t  j | d d  | f | d d  | f d d  } d } d } | | | j d  } t  j j	 | d d }	 t  j
 |	 j    t  j |  k  }
 | d d  t  j |
  d f } | | } | t  j |  } t  j | j |  } | t  j | d	 d } | | d d  d f 9} | j j |  } | j t  j j | |   } | j d } t j j | |  } | | | f S(
   s6  
    White's Two-Moment Specification Test

    Parameters
    ----------
    resid : array_like
        OLS residuals
    exog : array_like
        OLS design matrix

    Returns
    -------
    stat : float
        test statistic
    pval : float
        chi-square p-value for test statistic
    dof : int
        degrees of freedom

    Notes
    -----
    Implements the two-moment specification test described by White's
    Theorem 2 (1980, p. 823) which compares the standard OLS covariance
    estimator with White's heteroscedasticity-consistent estimator. The
    test statistic is shown to be chi-square distributed.

    Null hypothesis is homoscedastic and correctly specified.

    Assumes the OLS design matrix contains an intercept term and at least
    one variable. The intercept is removed to calculate the test statistic.

    Interaction terms (squares and crosses of OLS regressors) are added to
    the design matrix to calculate the test statistic.

    Degrees-of-freedom (full rank) = nvar + nvar * (nvar + 1) / 2

    Linearly dependent columns are removed to avoid singular matrix error.

    Reference
    ---------
    White, H. (1980). A heteroskedasticity-consistent covariance matrix
    estimator and a direct test for heteroscedasticity. Econometrica,
    48: 817-838.

    See also het_white.
    i   s2   X should have a constant and at least one variableNi    g+=gvIh%<=t   modet   rt   axis(   R   RP   R   R   R   R   t   deletet   varR   t   qrR+   t   diagonalR(   t   wheret   meanR%   R&   RQ   t   solveR   RX   R*   (   R$   R    R   t   eR   R   t   atolt   rtolt   tolR   t   maskt   sqet   sqmndevsR   t   devxt   bt   statt   dofR?   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt
   spec_white  s,    /9$$
c         C  s  |  j  d } t t d | d d d   } |  | j } t j | | j  } x t |  D]z } t j | d d  | |  f | d d  d | |  f j  } d | | d } | t j | | | j  } q^ Wt j j t j | j |   }	 t j |	 t j | |	   }
 |
 S(	   s  
    Did not run yet

    from regstats2 ::

        if idx(29) % HAC (Newey West)
        L = round(4*(nobs/100)^(2/9));
        % L = nobs^.25; % as an alternative
        hhat = repmat(residuals',p,1).*X';
        xuux = hhat*hhat';
        for l = 1:L;
            za = hhat(:,(l+1):nobs)*hhat(:,1:nobs-l)';
            w = 1 - l/(L+1);
            xuux = xuux + w*(za+za');
        end
        d = struct;
        d.covb = xtxi*xuux*xtxi;
    i    i   g      Y@i   g      "@Ni   g      ?(	   R   RU   t   roundR&   R   R%   Rm   R   t   inv(   R$   R   R6   RN   t   hhatt   xuuxt   lagt   zat   wt   xtxit   covbNW(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   _neweywestcov0  s    "E!!c         C  s  |  j  j } |  j  j } | j \ } } t j t j | | f  } t j t j |  } t j t j |  } t j t j |  }	 | |  }
 | |  } t j |
 j |
  } t j |
 j |  } t j	 j
 | |  } | | | d <t j | | d |  } | | | d <| | d | | | d <d t j | | d t j t j	 j |  | | d   |	 | d <x#t | |  D]} | | | d  d d  f } | | } t j | j |  } | | j   } t | j | j  t |  t |  t j	 j
 | |  } | | | d <t j | |  } | | | <| | | | <d t j | t j t j	 j |  | j   |	 | <| | 7} | | 7} q~W| } t j	 j
 | |  } | | | d <| t j |	  } | | } | | d j d d  } | t j |  } | | d j   } d } | t j |  } | t j |  | t j d | |  t j |  t j d g d 
g g  } | | | | | | | f S(   sq   this is my original version based on Greene and references

    keep for now for comparison and benchmarking
    i   NR   g}?5^I?i    g      g      ?(   R   R   R    R   R   t   nanR   R%   R&   R   R   R   Rm   t   ravelt   printR(   R   RW   RR   t   array(   t
   olsresultsR   RL   R   R6   R   t   rparamst   rresidt   rypredt   rvarrawt   x0t   y0t   XTXt   XTYt   betat   yipredR   t   xit   yit   xxTt   xyt   rresid_scaledt   nrrt   sigma2t   rresid_standardizedt   rcusumt   at   critt   rcusumci(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   _recursive_olsresiduals2R  s^    

F 



5

5g        gffffff?c   !      C  s  |  j  j } |  j  j } | j \ } } | d k r< | } n  t j t j | | f  } t j t j |  }	 t j t j |  }
 t j t j |  } | |  } | |  } t j j	 t j
 | j |  | t j |   } t j
 | j |  } t j
 | |  } | | | d <t j
 | | d |  } | |
 | d <| | d | |	 | d <d t j
 | | d t j
 | | | d   | | d <x t | |  D] } | | | d  d d  f } | | } | | j   } t j
 | |  } | |
 | <| | } | |	 | <t j
 | | j  } d t j
 | |  } | t j
 | | j  | } | | | | j   } | | | <| | | <qW| } |	 t j |  } | | } | | j d d  } | t j |  } | | d j   } | d k rd } n6 | d k rd } n! | d k r(d	 } n t d
   | t j |  } | t j |  d | t j d | |  t j |  t j d g d 
g g  }  |	 | |
 | | | |  f S(   s  calculate recursive ols with residuals and cusum test statistic

    Parameters
    ----------
    olsresults : instance of RegressionResults
        uses only endog and exog
    skip : int or None
        number of observations to use for initial OLS, if None then skip is
        set equal to the number of regressors (columns in exog)
    lamda : float
        weight for Ridge correction to initial (X'X)^{-1}
    alpha : {0.95, 0.99}
        confidence level of test, currently only two values supported,
        used for confidence interval in cusum graph

    Returns
    -------
    rresid : array
        recursive ols residuals
    rparams : array
        recursive ols parameter estimates
    rypred : array
        recursive prediction of endogenous variable
    rresid_standardized : array
        recursive residuals standardized so that N(0,sigma2) distributed, where
        sigma2 is the error variance
    rresid_scaled : array
        recursive residuals normalize so that N(0,1) distributed
    rcusum : array
        cumulative residuals for cusum test
    rcusumci : array
        confidence interval for cusum test, currently hard coded for alpha=0.95


    Notes
    -----
    It produces same recursive residuals as other version. This version updates
    the inverse of the X'X matrix and does not require matrix inversion during
    updating. looks efficient but no timing

    Confidence interval in Greene and Brown, Durbin and Evans is the same as
    in Ploberger after a little bit of algebra.

    References
    ----------
    jplv to check formulas, follows Harvey
    BigJudge 5.5.2b for formula for inverse(X'X) updating
    Greene section 7.5.2

    Brown, R. L., J. Durbin, and J. M. Evans. “Techniques for Testing the
    Constancy of Regression Relationships over Time.”
    Journal of the Royal Statistical Society. Series B (Methodological) 37,
    no. 2 (1975): 149-192.

    i   NR   gffffff?gtV?gGz?g}?5^I?g?g333333?s#   alpha can only be 0.9, 0.95 or 0.99i   i    g      g      ?(   R   R   R    R   RQ   R   R   R   R   R   R%   R&   R   Rm   R   R(   R   RW   R   RR   R   (!   R   R   t   lamdaR   RL   R   R6   R   R   R   R   R   R   R   t   XTXiR  R  R  R   R  R  R  t   residit   tmpR   R	  R
  R  R  R  R  R  R  (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyR     sf    9	

2: 





			9c         C  s  |  j  j } |  j  j } |  j } | j \ } } | d } t j | | d d  d f | | j   f } | j	 d  } t j
 | d  d k  j   s t  | | d d  d d  d f | d d  d d d  f j d  }	 | d d  d d  d f | d d  d d d  f j d  }
 t j t j t j j |	  |
   } t j d d d d g d d t f d t f g } | | | | f S(   s  test for model stability, breaks in parameters for ols, Hansen 1992

    Parameters
    ----------
    olsresults : instance of RegressionResults
        uses only endog and exog

    Returns
    -------
    teststat : float
        Hansen's test statistic
    crit : structured array
        critical values at alpha=0.95 for different nvars
    pvalue Not yet
    ft, s : arrays
        temporary return for debugging, will be removed

    Notes
    -----
    looks good in example, maybe not very powerful for small changes in
    parameters

    According to Greene, distribution of test statistics depends on nvar but
    not on nobs.

    Test statistic is verified against R:strucchange

    References
    ----------
    Greene section 7.5.1, notation follows Greene

    i   Ni    ig    _Bgffffff?i   g      @i   i   gGz@t   dtypeR6   R  (   i   gffffff?(   i   g      @(   i   g      @(   i   gGz@(   R   R   R    R$   R   R   Rk   RQ   R   RW   R+   t   allR   t   sumt   traceR%   R   R   R   RU   t   float(   R   RL   R   R$   R6   R   t   resid2R   t   st   Ft   St   Ht   crit95(    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   breaks_hansen&  s    !	
1%IE'c   	      C  s   |  j    } t |  } | d j   } | d k rI | | | | } n  | j   t j |  } t j |  j   } d	 d
 d g } t j	 j
 |  } | | | f S(   sx  cusum test for parameter stability based on ols residuals

    Parameters
    ----------
    olsresiduals : ndarray
        array of residuals from an OLS estimation
    ddof : int
        number of parameters in the OLS estimation, used as degrees of freedom
        correction for error variance.

    Returns
    -------
    sup_b : float
        test statistic, maximum of absolute value of scaled cumulative OLS
        residuals
    pval : float
        Probability of observing the data under the null hypothesis of no
        structural change, based on asymptotic distribution which is a Brownian
        Bridge
    crit: list
        tabulated critical values, for alpha = 1%, 5% and 10%

    Notes
    -----
    tested agains R:strucchange

    Not clear: Assumption 2 in Ploberger, Kramer assumes that exog x have
    asymptotically zero mean, x.mean(0) = [1, 0, 0, ..., 0]
    Is this really necessary? I don't see how it can affect the test statistic
    under the null. It does make a difference under the alternative.
    Also, the asymptotic distribution of test statistic depends on this.

    From examples it looks like there is little power for standard cusum if
    exog (other than constant) have mean zero.

    References
    ----------
    Ploberger, Werner, and Walter Kramer. “The Cusum Test with Ols Residuals.”
    Econometrica 60, no. 2 (March 1992): 271-285.

    i   i    i   gGz?i   g(\?i
   gQ?(   i   gGz?(   i   g(\?(   i
   gQ?(   R   t   lenR  RW   R   R(   R+   RV   R   t	   kstwobignR*   (	   t   olsresidualR   R$   R6   t
   nobssigma2t   Bt   sup_bR  R?   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   breaks_cusumolsresidW  s    *c         C  s   d S(   sN  supLM, expLM and aveLM by Andrews, and Andrews,Ploberger

    p-values by B Hansen

    just idea for computation of sequence of tests with given change point
    (Chow tests)
    run recursive ols both forward and backward, match the two so they form a
    split of the data, calculate sum of squares for residuals and get test
    statistic for each breakpoint between skip and nobs-skip
    need to put recursive ols (residuals) into separate function

    alternative: B Hansen loops over breakpoints only once and updates
        x'x and xe'xe
    update: Andrews is based on GMM estimation not OLS, LM test statistic is
       easy to compute because it only requires full sample GMM estimate (p.837)
       with GMM the test has much wider applicability than just OLS



    for testing loop over single breakpoint Chow test function

    N(    (   R   R    R   (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt	   breaks_AP  s    t   __main__t   adfi   i   id   i   g-C6?i   R   R   g(\g{Gz?g?g?g?s#   critical values in Green table 20.5s   sample size = 100s   with constantsA   0.01: -19.8,  0.025: -16.3, 0.05: -13.7, 0.01: -11.0, 0.975: 0.47sA   0.01: -3.50,  0.025: -3.17, 0.05: -2.90, 0.01: -2.58, 0.975: 0.26t   ,t   :gE>'gio,gfffff&)R   it   binsg      g\(\	g333333gp=
ףgp=
ף?g333333?g      4@g)\(?g      ?i
   R   g      $@R   R   (a   RB   t
   __future__R    t   statsmodels.compat.pythonR   R   R   t   numpyR   R   R   t#   statsmodels.regression.linear_modelR   t   statsmodels.tsa.stattoolsR   R   t   statsmodels.tsa.tsatoolsR   RQ   R   R   t   objectR   R   t   compare_coxRD   t	   compare_jR`   R   R   R   R   R   R   R   t   het_goldfeldquandtR@   R   R   R   R   R   R  R   R!  R(  R)  R   t   examplest   randomt   randnR   R   t   nreplR6   R   t   mcresRm   t   iiRW   R  t	   histogramt   sortt	   mcressortt   ratioRU   t   dictR   R  R  t   crvdgt   crvdt   crit_5lags0p05t   adfstatt   _Rx   Rs   R   R    t   infR   R   Rl   RR   t   randRL   R   t   fpt   foRC   t   resgqR#   R   R$   t
   cov_paramst   HC0_set   cov_HC0(    (    (    sC   lib/python2.7/site-packages/statsmodels/sandbox/stats/diagnostic.pyt   <module>   s   W	O	Le-R	H;Y{		 "1	O	"	@	1Y		'




::	
-56#EEE
E