ó
áp7]c           @  s   d  Z  d d l m Z d d l Z d d l m Z d d l m Z d „  Z	 d d „ Z
 d d	 „ Z d
 d
 d
 d
 d „ Z d
 d
 d
 d „ Z d „  Z d „  Z d e f d „  ƒ  YZ d e f d „  ƒ  YZ e d k rœe j d d g d d g g d d g d d g g g ƒ Z e j d d g d d g g d d g d d g g g ƒ Z e j d d g d d g g d d g d d g g g ƒ Z e j d d g d d g g d d g d d g g d d g d d g g g ƒ Z e j e j d ƒ d d d … d d … f d e j d ƒ d d d … d d … f f Z e j d d d g d d d g d d d g g d d d g d d d g d d d g g g ƒ Z e j j d d  ƒ Z  e e e  ƒ Z! e j" j# e e! d ƒ e! d! d ƒZ$ e$ d
 j% d d  d  ƒ Z& e e& ƒ Z' e e! ƒ Z( e( j) d ƒ e( j* ƒ  e( j* d" ƒ d# e j d d g d d g g d d g d d g g d d g d d g g g ƒ Z+ e j d d g d d g g d$ d g d d% g g g ƒ Z, e j d d g d d g g d& d g d$ d g g d% d g d d g g g ƒ Z- e e+ e, ƒ Z. e/ e0 e. ƒ ƒ e/ e. j1 ƒ  ƒ e/ e. j1 e ƒ ƒ e/ e. j2 ƒ  ƒ e/ e. j3 ƒ  ƒ e/ e. j4 ƒ  ƒ e e- ƒ Z5 e/ e5 j3 ƒ  ƒ e/ e5 j4 ƒ  ƒ n  d S('   s8   Helper and filter functions for VAR and VARMA, and basic VAR class

Created on Mon Jan 11 11:04:23 2010
Author: josef-pktd
License: BSD

This is a new version, I didn't look at the old version again, but similar
ideas.

not copied/cleaned yet:
 * fftn based filtering, creating samples with fft
 * Tests: I ran examples but did not convert them to tests
   examples look good for parameter estimate and forecast, and filter functions

main TODOs:
* result statistics
* see whether Bayesian dummy observation can be included without changing
  the single call to linalg.lstsq
* impulse response function does not treat correlation, see Hamilton and jplv

Extensions
* constraints, Bayesian priors/penalization
* Error Correction Form and Cointegration
* Factor Models Stock-Watson,  ???


see also VAR section in Notes.txt

iÿÿÿÿ(   t   print_functionN(   t   signal(   t   lagmatc   	      C  së  t  j |  ƒ }  t  j | ƒ } |  j d k rF |  d d … d f }  n  |  j d k rd t d ƒ ‚ n  |  j d } | j d } | d } | j d k r½ t j |  | d d … d f d d ƒS| j d k r~t | j ƒ d k r÷ t j |  | d d ƒSt  j	 |  j d | d | f ƒ } x\ t
 | ƒ D]N } t j |  d d … | f | d d … | f d d ƒ| d d … | f <q(W| S| j d k rçt j |  d d … d d … d f | ƒ } | | | … | j d d d d … f } | Sd S(	   s¶  apply an autoregressive filter to a series x

    Warning: I just found out that convolve doesn't work as I
       thought, this likely doesn't work correctly for
       nvars>3


    x can be 2d, a can be 1d, 2d, or 3d

    Parameters
    ----------
    x : array_like
        data array, 1d or 2d, if 2d then observations in rows
    a : array_like
        autoregressive filter coefficients, ar lag polynomial
        see Notes

    Returns
    -------
    y : ndarray, 2d
        filtered array, number of columns determined by x and a

    Notes
    -----

    In general form this uses the linear filter ::

        y = a(L)x

    where
    x : nobs, nvars
    a : nlags, nvars, npoly

    Depending on the shape and dimension of a this uses different
    Lag polynomial arrays

    case 1 : a is 1d or (nlags,1)
        one lag polynomial is applied to all variables (columns of x)
    case 2 : a is 2d, (nlags, nvars)
        each series is independently filtered with its own
        lag polynomial, uses loop over nvar
    case 3 : a is 3d, (nlags, nvars, npoly)
        the ith column of the output array is given by the linear filter
        defined by the 2d array a[:,:,i], i.e. ::

            y[:,i] = a(.,.,i)(L) * x
            y[t,i] = sum_p sum_j a(p,j,i)*x(t-p,j)
                     for p = 0,...nlags-1, j = 0,...nvars-1,
                     for all t >= nlags


    Note: maybe convert to axis=1, Not

    TODO: initial conditions

    i   Ni   s   x array has to be 1d or 2di    t   modet   validi   (   t   npt   asarrayt   ndimt   Nonet
   ValueErrort   shapeR   t   convolvet   mint   zerost   range(	   t   xt   at   nvart   nlagst   ntrimt   resultt   it   yft   yvalid(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt	   varfilter&   s,    9
&$L++i   c   
   
   C  sÉ  |  j  \ } } } | | k r+ t d ƒ n  t j | d | | f ƒ } |  d | d d d … d d … f <|  d | d | … d d … d d … f <| d k rGx¤ t d | d ƒ D]Œ } t j | | f ƒ } xO t d | ƒ D]> }	 | t j |  |	 | | |	 d d … d d … f ƒ 7} qß W| | | d d … d d … f <q´ Wn  | d k rÅxo t | d | d ƒ D]S } t |  d j  | | d | | d … d d … d d … f j  ƒ t d ƒ ‚ qkWn  | S(   sù  creates inverse ar filter (MA representation) recursively

    The VAR lag polynomial is defined by ::

        ar(L) y_t = u_t  or
        y_t = -ar_{-1}(L) y_{t-1} + u_t

    the returned lagpolynomial is arinv(L)=ar^{-1}(L) in ::

        y_t = arinv(L) u_t



    Parameters
    ----------
    ar : array, (nlags,nvars,nvars)
        matrix lagpolynomial, currently no exog
        first row should be identity

    Returns
    -------
    arinv : array, (nobs,nvars,nvars)


    Notes
    -----

    s.   exogenous variables not implemented not testedi   i    Ni   iÿÿÿÿs+   waiting for generalized ufuncs or something(   R
   t   printR   R   R   t   dott   NotImplementedError(
   t   art   nobst   versionR   t   nvarst   nvarsext   arinvR   t   tmpt   p(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   varinversefilter…   s"    #*<&Ac      
   C  sT  |  j  \ } } } | d } | j  d } | | k rB t d ƒ n  | j  d | k rd t d ƒ ‚ n  | d k r’ t j | | | f ƒ } | }	 nG t | | j  d ƒ }	 t j | |	 | f ƒ } | | |	 | j  d |	 +| | |	 )xj t |	 |	 | ƒ D]U }
 xL t d | ƒ D]; } | |
 c t j | |
 | d d … f |  | ƒ 7<qWq÷ W| S(   sE  generate an VAR process with errors u

    similar to gauss
    uses loop

    Parameters
    ----------
    ar : array (nlags,nvars,nvars)
        matrix lagpolynomial
    u : array (nobs,nvars)
        exogenous variable, error term for VAR

    Returns
    -------
    sar : array (1+nobs,nvars)
        sample of var process, inverse filtered u
        does not trim initial condition y_0 = 0

    Examples
    --------
    # generate random sample of VAR
    nobs, nvars = 10, 2
    u = numpy.random.randn(nobs,nvars)
    a21 = np.array([[[ 1. ,  0. ],
                     [ 0. ,  1. ]],

                    [[-0.8,  0. ],
                     [ 0.,  -0.6]]])
    vargenerate(a21,u)

    # Impulse Response to an initial shock to the first variable
    imp = np.zeros((nobs, nvars))
    imp[0,0] = 1
    vargenerate(a21,imp)

    i   i    s.   exogenous variables not implemented not testeds   u needs to have nvars columnsN(	   R
   R   R	   R   R   R   t   maxR   R   (   R   t   ut
   initvaluesR   R   R    t   nlagsm1R   t   sart   startR   R#   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   vargenerate¹   s$    %
	
=i    c         C  sÄ   t  j |  j ƒ } | | c | | 7<t  j |  j ƒ } t  j | ƒ } | j | ƒ t  j |  j ƒ } | | | <| | }	 g  t t |	 ƒ ƒ D] }
 t	 | |
 |	 |
 ƒ ^ q } |  | t
 | ƒ <| S(   sÅ  pad with zeros along one axis, currently only axis=0


    can be used sequentially to pad several axis

    Examples
    --------
    >>> padone(np.ones((2,3)),1,3,axis=1)
    array([[ 0.,  1.,  1.,  1.,  0.,  0.,  0.],
           [ 0.,  1.,  1.,  1.,  0.,  0.,  0.]])

    >>> padone(np.ones((2,3)),1,1, fillvalue=np.nan)
    array([[ NaN,  NaN,  NaN],
           [  1.,   1.,   1.],
           [  1.,   1.,   1.],
           [ NaN,  NaN,  NaN]])
    (   R   t   arrayR
   t   emptyt   fillR   R   R   t   lent   slicet   tuple(   R   t   frontt   backt   axist	   fillvalueR
   t   shapearrt   outt   startindt   endindt   kt   myslice(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   padoneö   s    

6c   
      C  s¢   t  j |  j ƒ } | | c | | 8<t  j |  j ƒ } t  j |  j ƒ } | | | <| | } g  t t | ƒ ƒ D] } t | | | | ƒ ^ qq }	 |  t |	 ƒ S(   s;  trim number of array elements along one axis


    Examples
    --------
    >>> xp = padone(np.ones((2,3)),1,3,axis=1)
    >>> xp
    array([[ 0.,  1.,  1.,  1.,  0.,  0.,  0.],
           [ 0.,  1.,  1.,  1.,  0.,  0.,  0.]])
    >>> trimone(xp,1,3,1)
    array([[ 1.,  1.,  1.],
           [ 1.,  1.,  1.]])
    (	   R   R,   R
   R   R   R   R/   R0   R1   (
   R   R2   R3   R4   R
   R6   R8   R9   R:   R;   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   trimone  s    

6c         C  sI   |  j  \ } } } t j t j | | ƒ d d d … d d … f |  f S(   s?   make reduced lagpolynomial into a right side lagpoly array
    N(   R
   R   t   r_t   eyeR   (   R   R   R   t   nvarex(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   ar2full5  s    c         C  s	   |  d S(   s   convert full (rhs) lagpolynomial into a reduced, left side lagpoly array

    this is mainly a reminder about the definition
    i   (    (   R   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   ar2lhs<  s    t   _Varc           B  sA   e  Z d  Z d „  Z d „  Z d „  Z d „  Z d d d „ Z RS(   s<  obsolete VAR class, use tsa.VAR instead, for internal use only


    Examples
    --------

    >>> v = Var(ar2s)
    >>> v.fit(1)
    >>> v.arhat
    array([[[ 1.        ,  0.        ],
            [ 0.        ,  1.        ]],

           [[-0.77784898,  0.01726193],
            [ 0.10733009, -0.78665335]]])

    c         C  s"   | |  _  | j \ |  _ |  _ d  S(   N(   t   yR
   R   R   (   t   selfRD   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   __init__V  s    	c         C  sä   | |  _  |  j } t |  j | d d d d ƒ} | d d … d | … f |  _ | d d … | d … f |  _ t j j |  j |  j d d ƒ} | |  _	 | d j
 | | | ƒ |  _ t |  j ƒ |  _ | d	 |  _ | d
 |  _ d S(   s¯  estimate parameters using ols

        Parameters
        ----------
        nlags : integer
            number of lags to include in regression, same for all variables

        Returns
        -------
        None, but attaches

        arhat : array (nlags, nvar, nvar)
            full lag polynomial array
        arlhs : array (nlags-1, nvar, nvar)
            reduced lag polynomial for left hand side
        other statistics as returned by linalg.lstsq : need to be completed



        This currently assumes all parameters are estimated without restrictions.
        In this case SUR is identical to OLS

        estimation results are attached to the class instance


        t   trimt   botht   originalt   inNt   rcondiÿÿÿÿi    i   i   (   R   R   R   RD   t   yredt   xredR   t   linalgt   lstsqt
   estresultst   reshapet   arlhsRA   t   arhatt   rsst   xredrank(   RE   R   R   t   lmatt   res(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   fitZ  s    		!	c         C  s1   t  |  d ƒ s* t |  j |  j ƒ |  _ n  |  j S(   s:   calculate estimated timeseries (yhat) for sample

        t   yhat(   t   hasattrR   RD   RS   RY   (   RE   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   predictƒ  s    c         C  sa   |  j  d d d d … f t j j t j |  j j |  j ƒ ƒ d d … d d … d f |  _ d S(   sÔ   covariance matrix of estimate
        # not sure it's correct, need to check orientation everywhere
        # looks ok, display needs getting used to
        >>> v.rss[None,None,:]*np.linalg.inv(np.dot(v.xred.T,v.xred))[:,:,None]
        array([[[ 0.37247445,  0.32210609],
                [ 0.1002642 ,  0.08670584]],

               [[ 0.1002642 ,  0.08670584],
                [ 0.45903637,  0.39696255]]])
        >>>
        >>> v.rss[0]*np.linalg.inv(np.dot(v.xred.T,v.xred))
        array([[ 0.37247445,  0.1002642 ],
               [ 0.1002642 ,  0.45903637]])
        >>> v.rss[1]*np.linalg.inv(np.dot(v.xred.T,v.xred))
        array([[ 0.32210609,  0.08670584],
               [ 0.08670584,  0.39696255]])
       N(	   RT   R   R   RN   t   invR   RM   t   Tt   paramcov(   RE   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   covmatŒ  s    i   c         C  s@   | d k r' t j | |  j f ƒ } n  t |  j | d |  j ƒS(   s£  calculates forcast for horiz number of periods at end of sample

        Parameters
        ----------
        horiz : int (optional, default=1)
            forecast horizon
        u : array (horiz, nvars)
            error term for forecast periods. If None, then u is zero.

        Returns
        -------
        yforecast : array (nobs+horiz, nvars)
            this includes the sample and the forecasts
        R'   N(   R   R   R   R   R+   RS   RD   (   RE   t   horizR&   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   forecast£  s    N(	   t   __name__t
   __module__t   __doc__RF   RX   R[   R_   R   Ra   (    (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyRC   D  s   		)			t	   VarmaPolyc           B  s}   e  Z d  Z d d „ Z d d d „ Z d d d „ Z d d d d „ Z d „  Z d „  Z	 d d	 „ Z
 d d
 „ Z d „  Z RS(   s¼  class to keep track of Varma polynomial format


    Examples
    --------

    ar23 = np.array([[[ 1. ,  0. ],
                     [ 0. ,  1. ]],

                    [[-0.6,  0. ],
                     [ 0.2, -0.6]],

                    [[-0.1,  0. ],
                     [ 0.1, -0.1]]])

    ma22 = np.array([[[ 1. ,  0. ],
                     [ 0. ,  1. ]],

                    [[ 0.4,  0. ],
                     [ 0.2, 0.3]]])


    c         C  sõ   | |  _  | |  _ | j \ } } } | | | |  _ |  _ |  _ | d d  | … f t j | ƒ k j ƒ  |  _	 |  j d  k r¡ t j | ƒ d |  _ t |  _ n# | d t j | ƒ k j ƒ  |  _ | j d |  _ | | k |  _ | d |  _ d  S(   Ni    .i   (   N.(   R   t   maR
   R   t   nvarallR   R   R?   t   allt   isstructuredR   t   Truet   isindependentt   malagst   hasexogt   arm1(   RE   R   Rf   R   Rg   R   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyRF   Ï  s    		/#R   c         C  sd   | d k	 r | } n< | d k r- |  j } n$ | d k rE |  j } n t d ƒ ‚ | j d |  j ƒ S(   s4   stack lagpolynomial vertically in 2d array

        R   Rf   s   no array or name giveniÿÿÿÿN(   R   R   Rf   R	   RQ   Rg   (   RE   R   t   name(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   vstackß  s    	c         C  ss   | d k	 r | } n< | d k r- |  j } n$ | d k rE |  j } n t d ƒ ‚ | j d d ƒ j d |  j ƒ j S(   s6   stack lagpolynomial horizontally in 2d array

        R   Rf   s   no array or name giveni   i   iÿÿÿÿN(   R   R   Rf   R	   t   swapaxesRQ   Rg   R]   (   RE   R   Ro   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   hstackî  s    	t   verticalc         C  sª   | d k	 r | } n< | d k r- |  j } n$ | d k rE |  j } n t d ƒ ‚ | j d |  j ƒ } | j \ } } t j | d | ƒ} | | d d … d | … f <| S(   sD   stack lagpolynomial vertically in 2d square array with eye

        R   Rf   s   no array or name giveniÿÿÿÿR:   N(	   R   R   Rf   R	   RQ   Rg   R
   R   R?   (   RE   R   Ro   t   orientationt   astackedt   lenpkR   t   amat(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   stacksquareý  s    	c         C  s9   t  j |  j d |  j d f d ƒ } | j d |  j ƒ S(   s;   stack ar and lagpolynomial vertically in 2d array

        i   i    iÿÿÿÿ(   R   t   concatenateR   Rf   RQ   Rg   (   RE   R   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   vstackarma_minus1  s    &c         C  sE   t  j |  j d |  j d f d ƒ } | j d d ƒ j d |  j ƒ S(   su   stack ar and lagpolynomial vertically in 2d array

        this is the Kalman Filter representation, I think
        i   i    i   iÿÿÿÿ(   R   Ry   R   Rf   Rq   RQ   Rg   (   RE   R   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   hstackarma_minus1  s    &c         C  sŸ   | d k	 r | } n1 |  j r8 |  j |  j ƒ d } n |  j d } |  j | ƒ } t j t j j | ƒ ƒ d d d … } | |  _	 t j
 | ƒ d k  j ƒ  S(   sA  check whether the auto-regressive lag-polynomial is stationary

        Returns
        -------
        isstationary : boolean

        *attaches*

        areigenvalues : complex array
            eigenvalues sorted by absolute value

        References
        ----------
        formula taken from NAG manual

        i   Niÿÿÿÿ(   R   Ri   t
   reduceformR   Rx   R   t   sortRN   t   eigvalst   areigenvaluest   absRh   (   RE   R   Rw   t   ev(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   getisstationary   s    		(	c         C  sÌ   | d k	 r | } n/ |  j r7 |  j |  j ƒ d } n |  j d } | j d d k rs t j g  t j ƒ |  _ t	 S|  j
 | ƒ } t j t j j | ƒ ƒ d d d … } | |  _ t j | ƒ d k  j ƒ  S(   sA  check whether the auto-regressive lag-polynomial is stationary

        Returns
        -------
        isinvertible : boolean

        *attaches*

        maeigenvalues : complex array
            eigenvalues sorted by absolute value

        References
        ----------
        formula taken from NAG manual

        i   i    Niÿÿÿÿ(   R   Rk   R|   Rf   R
   R   R,   t   complext   maeigenvaluesRj   Rx   R}   RN   R~   R€   Rh   (   RE   R   Rw   R   (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   getisinvertible=  s    		(	c         C  sÌ   | j  d k r t d ƒ ‚ n  | j \ } } } t j | ƒ } y/ t j j | d d | … d d … f ƒ } Wn& t j j k
 r– t d d ƒ ‚ n Xx. t | ƒ D]  } t j	 | | | ƒ | | <q¤ W| S(   s.   

        this assumes no exog, todo

        i   s   apoly needs to be 3di    Ns   matrix not invertibles   ask for implementation of pinv(
   R   R	   R
   R   t
   empty_likeRN   R\   t   LinAlgErrorR   R   (   RE   t   apolyR   R    R   R   t   a0invt   lag(    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyR|   _  s    /N(   Rb   Rc   Rd   R   RF   Rp   Rr   Rx   Rz   R{   R‚   R…   R|   (    (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyRe   ·  s   		"t   __main__g      ð?g        gš™™™™™é¿g333333ã¿gš™™™™™¹?gš™™™™™É?gš™™™™™¹¿i   gš™™™™™é?g333333ã?gÍÌÌÌÌÌì?iè  i   RK   i   iâÿÿÿgš™™™™™Ù?g333333Ó?gffffffþ¿(6   Rd   t
   __future__R    t   numpyR   t   scipyR   t   statsmodels.tsa.tsatoolsR   R   R$   R   R+   R<   R=   RA   RB   t   objectRC   Re   Rb   R,   t   a21t   a22t   a23t   a24R>   R?   t   a31t   a32t   randomt   randnt   utt   ar2sRN   RO   RW   RQ   t   bhatRS   t   vRX   Ra   t   ar23t   ma22t   ar23nst   vpR   t   varsRp   R{   R‚   R…   t   vp2(    (    (    s<   lib/python2.7/site-packages/statsmodels/tsa/varma_process.pyt   <module>   s”   	_4=#		s¿					[$
					