ó
áp7]c           @   sb   d  Z  d d l m Z d d l Z d d l m Z m Z d d l m	 Z	 d e	 f d „  ƒ  YZ
 d S(   s‘   
Created on Sun Oct 10 14:57:50 2010

Author: josef-pktd, Skipper Seabold
License: BSD

TODO: check everywhere initialization of signal.lfilter

iÿÿÿÿ(   t   rangeN(   t   signalt   optimize(   t   GenericLikelihoodModelt   Armac           B   s¿   e  Z d  Z d d „ Z d „  Z d „  Z d „  Z d „  Z d d d d „ Z	 d d d	 d
 d d „ Z
 d d d „ Z d d d d „ Z d d d d d „ Z d d d „ Z e d d „ ƒ Z RS(   sü  
    univariate Autoregressive Moving Average model, conditional on initial values

    The ARMA model is estimated either with conditional Least Squares or with
    conditional Maximum Likelihood. The implementation is
    using scipy.filter.lfilter which makes it faster than the Kalman Filter
    Implementation. The Kalman Filter Implementation however uses the exact
    Maximum Likelihood and will be more accurate, statistically more efficent
    in small samples.

    In large samples conditional LS, conditional MLE and exact MLE should be very
    close to each other, they are equivalent asymptotically.

    Notes
    -----
    this can subclass TSMLEModel

    TODO:

    - CondLS return raw estimation results
    - needs checking that there is no wrong state retained, when running fit
      several times with different options
    - still needs consistent order options.
    - Currently assumes that the mean is zero, no mean or effect of exogenous
      variables are included in the estimation.

    c         C   s/   t  t |  ƒ j | | ƒ d |  _ d |  _ d  S(   Ni   (   t   superR   t   __init__t   nart   nma(   t   selft   endogt   exog(    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyR   0   s    	c         C   s   d  S(   N(    (   R	   (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt
   initialize8   s    c   
      C   s¼   |  j  |  j } } t j d g | |  f ƒ } t j d g | | | | !f ƒ } d t | | ƒ } t j | ƒ } | | | d *t j | ƒ } | | | d *t j | | |  j ƒ }	 |	 S(   Ni   (	   R   R   t   npt   concatenatet   maxt   zerosR   t   lfilterR
   (
   R	   t   paramst   pt   qt   art   mat   maxlagt   armaxt   mamaxt	   errorsest(    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt	   geterrors;   s    #c         C   s†   |  j  | ƒ } t j | d d d ƒ } d } t | ƒ } d | t j | ƒ t j | d | | ƒ | t j d t j ƒ } | S(   sª   
        Loglikelihood for arma model

        Notes
        -----
        The ancillary parameter is assumed to be the last element of
        the params vector
        iÿÿÿÿi   gíµ ÷Æ°>i    g      à¿(   R   R   t   maximumt   lent   logt   sumt   pi(   R	   R   R   t   sigma2t   axist   nobst   llike(    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   loglikeM   s    Dc         C   sr   |  j  | ƒ } t j | d d d ƒ } d } t | ƒ } d t j | ƒ | d | t j d t j ƒ } | S(   sª   
        Loglikelihood for arma model

        Notes
        -----
        The ancillary parameter is assumed to be the last element of
        the params vector
        iÿÿÿÿi   gíµ ÷Æ°>i    g      à?(   R   R   R   R   R   R    (   R	   R   R   R!   R"   R#   R$   (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   nloglikeobsk   s    0i    t   lsc            së  t  | d ƒ s( t d t | ƒ ƒ ‚ n  | \ } } | ˆ  _ | ˆ  _ ˆ  j j ƒ  } | d k r d t j	 | ƒ } d t j	 | ƒ }	 t j
 | |	 f } n  | j ƒ  } | d k rt d d d t ƒ }
 |
 j | ƒ t j ˆ  j | |
  \ } } } } } nv | d k rng ‡  f d	 †  } t d
 d d t ƒ }
 |
 j | ƒ t j | | |
  \ } } } } } } } d \ } } | ˆ  _ t j d g | |  f ƒ ˆ  _ t j d g | | | | !f ƒ ˆ  _ ˆ  j | ƒ ˆ  _ | | | | | f S(   sp  
        Estimate lag coefficients of an ARIMA process.

        Parameters
        ----------
        order : sequence
            p,d,q where p is the number of AR lags, d is the number of
            differences to induce stationarity, and q is the number of
            MA lags to estimate.
        method : str {"ls", "ssm"}
            Method of estimation.  LS is conditional least squares.
            SSM is state-space model and the Kalman filter is used to
            maximize the exact likelihood.
        rhoy0, rhoe0 : array_like (optional)
            starting values for estimation

        Returns
        -------
        (rh, cov_x, infodict, mesg, ier) : output of scipy.optimize.leastsq

        rh :
            estimate of lag parameters, concatenated [rhoy, rhoe]
        cov_x :
            unscaled (!) covariance matrix of coefficient estimates
        t   __iter__s8   order must be an iterable sequence.  Got type %s insteadg      à?R'   t   ftolg»½×Ùß|Û=t   full_outputt   ssmc            s   t  j ˆ  j |  ƒ d ƒ S(   Ni   (   R   R   R   (   t   rho(   R	   (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   <lambda>ä   t    t   maxiteri   i   N(   NN(   t   hasattrt
   ValueErrort   typeR   R   R
   t   squeezet   NoneR   t   onest   r_t   lowert   dictt   Truet   updateR   t   leastsqR   t	   fmin_bfgsR   R   t   ar_estt   ma_estt   error_estimate(   R	   t   ordert   start_paramst   methodt   optkwdsR   R   t   xt   arcoefs0t   macoefs0t
   optim_kwdst   rht   cov_xt   infodictt   mesgt   iert   errfnsumt   foptt   goptt   _(    (   R	   s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   fitœ   s8    		
**	 &t   nmiˆ  g:Œ0âŽyE>c      
   K   sÿ   | \ } } \ }	 }
 | | |  _  |  _ | d k ra t j d t j | | ƒ d g f ƒ } n  t t |  ƒ j d | d | d | d | |  } | j	 } | |  _	 t j d g | |	  f ƒ |  _
 t j d g | |	 |	 |
 !f ƒ |  _ |  j | ƒ |  _ | S(   sY  Estimate an ARMA model with given order using Conditional Maximum Likelihood

        Parameters
        ----------
        order : tuple, 2 elements
            specifies the number of lags(nar, nma) to include, not including lag 0
        start_params : array_like, 1d, (nar+nma+1,)
            start parameters for the optimization, the length needs to be equal to the
            number of ar plus ma coefficients plus 1 for the residual variance
        method : str
            optimization method, as described in LikelihoodModel
        maxiter : int
            maximum number of iteration in the optimization
        tol : float
            tolerance (?) for the optimization

        Returns
        -------
        mlefit : instance of (GenericLikelihood ?)Result class
            contains estimation results and additional statistics

        gš™™™™™©?i   RA   R/   RB   t   tolN(   R   R   R4   R   R   R5   R   R   RQ   R   R=   R>   R   R?   (   R	   R@   RA   RB   R/   RS   t   kwdsR   R   R   R   t   mlefitRH   (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   fit_mleô   s    ,		 &c         C   s   |  j  |  j S(   sQ   past predicted values of time series
        just added, not checked yet
        (   R
   R?   (   R	   R   R   (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt	   predicted  s    i
   c         C   sb   t  j |  j t  j | ƒ f } | d k r7 |  j } n  | d k rO |  j } n  t j | | | ƒ S(   so   nperiod ahead forecast at the end of the data period

        forecast is based on the error estimates
        N(	   R   R6   R?   R   R4   R=   R>   R   R   (   R	   R   R   t   nperiodt   eta(    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   forecast)  s    i   c         C   sò   | d k r t  ‚ n  |  j |  j } } d } |  j } |  j }	 |  j | | | !d d d … }
 |  j | | | | | !d d d … } g  } xR t | | ƒ D]A } | j t |
 |	 | | | !ƒ t | | | | | !ƒ ƒ q  Wt	 j
 | ƒ S(   sî  rolling h-period ahead forecast without reestimation, 1 period ahead only

        in construction: uses loop to go over data and
        not sure how to get (finite) forecast polynomial for h-step

        Notes
        -----
        just the idea:
        To improve performance with expanding arrays, specify total period by endog
        and the conditional forecast period by step_ahead

        This should be used by/with results which should contain predicted error or
        noise. Could be either a recursive loop or lfilter with a h-step ahead
        forecast filter, but then I need to calculate that one. ???

        further extension: allow reestimation option

        question: return h-step ahead or range(h)-step ahead ?
        i   i    Niÿÿÿÿ(   t   NotImplementedErrorR   R   R?   R
   R   R    t   appendR   R   t   asarray(   R	   t
   step_aheadt   startt   endR
   R   R   t   kt   errorst   yt   arcoefs_revt   macoefs_revRW   t   i(    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt	   forecast25  s    			!)?c         C   s’   d d l  m } |  j |  j } } d } |  j | | | !} |  j | | | | | !} | | | | ƒ | d }	 |  j }
 t j |
 |	 ƒ } | S(   s1   another try for h-step ahead forecasting
        i   (   t   arma2mai    (   t   arima_processRh   R   R   R   R?   R   t   convolve(   R	   R^   R_   Rh   R   R   Ra   R   R   t   marepRb   t	   forecasts(    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt	   forecast3\  s    	c         C   s)   | t  j j | ƒ } t j | | | ƒ S(   N(   R   t   randomt   randnR   R   (   t   clsR   R   t   nsamplet   stdRY   (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   generate_samplem  s    N(   i    i    (   i    i    (   t   __name__t
   __module__t   __doc__R4   R   R   R   R%   R&   RQ   RV   RW   RZ   Rg   Rm   t   classmethodRs   (    (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyR      s   				1X''(   Rv   t   statsmodels.compat.pythonR    t   numpyR   t   scipyR   R   t   statsmodels.base.modelR   R   (    (    (    s7   lib/python2.7/site-packages/statsmodels/tsa/arma_mle.pyt   <module>	   s
   