
p7]c           @  s4  d  Z  d d l m Z d d l Z d d l Z d d l Z d d l Z d d l m Z d d l	 Z
 d d l m Z d d l m Z d d l m Z m Z m Z m Z d d	 g Z d. a d d/ d     YZ e   Z i d d 6d d 6Z i d e 6d e 6d d 6Z d   Z d e d  Z d d  Z d   Z d e e d  Z  d   Z! d   Z" d   Z# d   Z$ d    Z% d!   Z& d"   Z' d# e( f d$     YZ) d% e) f d&     YZ* d'   Z+ d0 d1 d d d e e d e e d d e d e d*  Z, d2 d3 d d d e e d d d e d e d+  Z- d, e( f d-     YZ. d S(4   s   
Run x12/x13-arima specs in a subprocess from Python and curry results back
into python.

Notes
-----
Many of the functions are called x12. However, they are also intended to work
for x13. If this is not the case, it's a bug.
i(   t   print_functionN(   t   warn(   t	   iteritems(   t   Bunch(   t   X13NotFoundErrort	   IOWarningt   X13Errort
   X13Warningt   x13_arima_select_ordert   x13_arima_analysiss	   x13as.exet   x13ass   x12a.exet   x12at   _freq_to_periodc           B  s   e  Z d    Z RS(   c         C  s=   | j  d  r d S| j  d  r& d S| j  d  r9 d Sd  S(   Nt   Mi   t   Qi   t   Wi4   (   t
   startswith(   t   selft   key(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   __getitem__   s    (   t   __name__t
   __module__R   (    (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR      s   R   i   R   i   t   logt   nonet   autoc         C  s   |  r
 d Sd S(   Nt   yest   no(    (   t   x(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   <lambda>,   t    c         C  s-  |  d k	 r0 |  j t  r0 t j j |   }  n  | s t d d d  a |  d k rj t j d d  }  n  |  s t j d d  }  q n< |  d k r t j d d  }  |  s t j d d  }  q n  xb t D]V } t j j |  |  } y' t j	 | d t j
 d t j
 | SWq t k
 r q Xq Wt Sd S(   s  
    If x12path is not given, then either x13as[.exe] or x12a[.exe] must
    be found on the PATH. Otherwise, the environmental variable X12PATH or
    X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched
    for. If it is false, only X12PATH is searched for.
    Nit   X12PATHR   t   X13PATHt   stdoutt   stderr(   t   Nonet   endswitht   _binary_namest   ost   patht   dirnamet   getenvt   joint
   subprocesst
   check_callt   PIPEt   OSErrort   False(   t   x12patht
   prefer_x13t   binaryt   x12(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt	   _find_x12/   s*    
c         C  s%   t  |   }  |  s! t d   n  |  S(   Nsx   x12a and x13as not found on path. Give the path, put them on PATH, or set the X12PATH or X13PATH environmental variable.(   R3   R   (   R/   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt
   _check_x12S   s    c         C  se   t  j d |   }  d   } t |   d k rE t | |   \ }  } n | |  d  }  d } |  | f S(   s   
    Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma
    order tuple. Also accepts (1 1 0) and return arma order and (0, 0, 0)
    s   \([0-9 ]*?\)c         S  s+   t  t t t j d d |   j d    S(   Ns   [()]R   t    (   t   tuplet   mapt   intt   ret   subt   split(   R   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   cleanc   s    i   i    (   i    i    i    (   R9   t   findallt   lenR7   (   t   orderR<   t   sorder(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _clean_order\   s    	c         C  s   | r | r t  d   n  | r4 |  d | g } n% | rM |  d | g } n |  | g } | ro | | g 7} n  t j | d t j d t j S(   Ns&   Cannot specify both meta and datameta.s   -m s   -d R    R!   (   t
   ValueErrorR*   t   PopenR,   t   STDOUT(   R/   t   specpatht   outnamet   metat   datametat   args(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   run_speco   s    c         C  ss   d } | d j  |  d |  d  7} | d  k	 rQ | d j  | d | d  7} n | d j  | d | d  7} | S(   Ns   
s   maxorder = ({0} {1})
i    i   s   maxdiff = ({0} {1})
s   diff = ({0} {1})
(   t   formatR"   (   t   maxordert   maxdifft   difft   options(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _make_automdl_options   s    !c         C  s   t  |  d  r |  j } n' t  |  d  r6 |  j } n t d   y d j |  } WnN t k
 r d d l m } |  j d k r d } q d j | |    } n X| S(	   Nt   namet   columnss0   exog is not a Series or DataFrame or is unnamed.R5   i(   t   _make_exog_namesi   t   x1(	   t   hasattrRQ   RR   RB   R)   t	   TypeErrort   statsmodels.base.dataRS   t   ndim(   t   exogt	   var_namesRS   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _make_var_names   s    	c         C  s   |  r | d  k r d Sd } |  r0 | d 7} n  | d  k	 r t |  } | d j |  7} | d j d j t t | j j   j      7} n  | d 7} | S(   NR   s   regression{
s       variables = (td)
s       user = ({0})
s       data = ({0})
s   
s   }
(	   R"   R[   RK   R)   R7   t   strt   valuest   ravelt   tolist(   t   tradingRY   t   reg_specRZ   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _make_regression_options   s    "
c         C  s-   |  d  k r d Sd } | d j |   7} | S(   NR   s
   forecast{
s   maxlead = ({0})
}}
(   R"   RK   (   t   forecast_yearst   forecast_spec(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _make_forecast_options   s
    c         C  sd   |  |  j  d  d j   }  |  r> d |  k r> t |    n" |  r` d |  k r` t |  t  n  d  S(   Ns   spc:i   t   ERRORt   WARNING(   t   findt   stripR   R   R   (   t   errors(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _check_errors   s
    c      
   C  sn   d d l  m } d d l m } | | |   d d d d d d d	 d
 } | j |  j d i | d 6 | S(   si   
    Convert x to a DataFrame where x is a string in the format given by
    x-13arima-seats output.
    i(   t   StringIO(   t   read_csvt   skiprowsi   t   headert   seps   	t   enginet   pythonRR   i   N(   t   statsmodels.compatRl   t   pandasRm   R"   t	   set_indext   rename(   R   t   datesRQ   Rl   Rm   t   out(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _convert_out_to_series   s
    c         C  s(   t  |  d   } | j   } Wd  QX| S(   Nt   r(   t   opent   read(   t   fnamet   fint   fout(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   _open_and_read   s    t   Specc           B  s)   e  Z e d     Z d   Z d   Z RS(   c         C  s   |  j  j j d d  S(   NR   R   (   t	   __class__R   t   replace(   R   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt	   spec_name   s    c         K  s"   d } | j  d |  j d |  j  S(   Ns/   {name} {{
        {options}
        }}
        RQ   RO   (   RK   R   RO   (   R   t   kwargst   spec(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   create_spec   s    c         K  s]   d } xG t  |  D]9 \ } } | d j | |  7} |  j j i | | 6 q W| |  _ d  S(   NR   s   {0}={1}
(   R   RK   t   __dict__t   updateRO   (   R   R   RO   R   t   value(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   set_options   s
    (   R   R   t   propertyR   R   R   (    (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR      s   	t
   SeriesSpecc           B  sM   e  Z d  Z d e e d	 d d d
 d d g  g  d d d d	 d	 d d d  Z RS(   sh  
    Parameters
    ----------
    data
    appendbcst : bool
    appendfcst : bool
    comptype
    compwt
    decimals
    modelspan
    name
    period
    precision
    to_print
    to_save
    span
    start
    title
    type

    Notes
    -----
    Rarely used arguments

    divpower
    missingcode
    missingval
    saveprecision
    trimzero

    s   Unnamed Seriesi   i    i   R   iayi ʚ;c         C  sy   t  t | | g  \ } } d j | d   } d j | d   } |  j d | d | d | d |	 d | d	 | d
 |  d  S(   Ns   "{0}"i@   iO   t   datat
   appendbcstt
   appendfcstt   periodt   startt   titleRQ   (   R7   t   _bool_to_yes_noRK   R   (   R   R   RQ   R   R   t   comptypet   compwtt   decimalst	   modelspanR   t	   precisiont   to_printt   to_savet   spanR   R   t   series_typet   divpowert   missingcodet
   missingvalt   series_name(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   __init__  s    	N(    (    (   i   i   (   R   R   t   __doc__R.   R"   R   (    (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR      s   c   	      C  s}  t  |  d  rG t |  j  d k r3 t d   n  |  |  j d }  n  d j d j t t |  j j	      } y t
 |  j j } Wn: t t f k
 r d d l m } t
 | |  j  } n X|  j d } | d	 k r | j | j } } n. | d
 k r| j | j } } n t d   t  |  d  r@|  j p:d } n d } t d | d | d | d | d d j | |   } | S(   NRR   i   s3   Does not handle DataFrame with more than one columni    s   ({0})s   
i(   t
   infer_freqi   i   sq   Only monthly and quarterly periods are supported. Please report or send a pull request if you want this extended.RQ   s   Unnamed SeriesR   R   R   R   s   {0}.{1}(   RU   R>   RR   RB   RK   R)   R7   R\   R]   R_   R   t   indext   freqstrt   AttributeErrort   pandas.tseries.apiR   t   yeart   montht   quarterRQ   R   (	   R   R   R   R   t
   start_dateR   t   stperiodRQ   t   series_spec(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   pandas_to_series_spec  s.    *i   i   c         C  s~  t  |  } t |  t j t j f  s | d k s? | d k rN t d   n  t j |  d t j d | d t |   d |  }  n  t	 |   } | j
   } | d j t |  7} | r | d 7} n  t | | |  } | d j |  7} | t | |  7} | t |  7} | d	 7} |
 r"| St j d
 t d d  } t j d
 t  } z | j | j d   | j   | j   t | | j d  | j  } | j   | j j   } | rt | j j    n  t | j d  } t |  t | j d  } t | j d  } t | j d  } t | j d  } Wd y$ t j | j  t j | j  Wns t  k
 rt j! j" | j  rt# d j | j  t$  n  t j! j" | j  rt# d j | j  t$  qn XXt% | |  j& d  } t% | |  j& d  } t% | |  j& d  } |	 sGt' d |  d | d | d | d | d |  } n3 t' d |  d | d | d | d | d | d |  } | S(   s  
    Perform x13-arima analysis for monthly or quarterly data.

    Parameters
    ----------
    endog : array-like, pandas.Series
        The series to model. It is best to use a pandas object with a
        DatetimeIndex or PeriodIndex. However, you can pass an array-like
        object. If your object does not have a dates index then ``start`` and
        ``freq`` are not optional.
    maxorder : tuple
        The maximum order of the regular and seasonal ARMA polynomials to
        examine during the model identification. The order for the regular
        polynomial must be greater than zero and no larger than 4. The
        order for the seaonal polynomial may be 1 or 2.
    maxdiff : tuple
        The maximum orders for regular and seasonal differencing in the
        automatic differencing procedure. Acceptable inputs for regular
        differencing are 1 and 2. The maximum order for seasonal differencing
        is 1. If ``diff`` is specified then ``maxdiff`` should be None.
        Otherwise, ``diff`` will be ignored. See also ``diff``.
    diff : tuple
        Fixes the orders of differencing for the regular and seasonal
        differencing. Regular differencing may be 0, 1, or 2. Seasonal
        differencing may be 0 or 1. ``maxdiff`` must be None, otherwise
        ``diff`` is ignored.
    exog : array-like
        Exogenous variables.
    log : bool or None
        If None, it is automatically determined whether to log the series or
        not. If False, logs are not taken. If True, logs are taken.
    outlier : bool
        Whether or not outliers are tested for and corrected, if detected.
    trading : bool
        Whether or not trading day effects are tested for.
    forecast_years : int
        Number of forecasts produced. The default is one year.
    retspec : bool
        Whether to return the created specification file. Can be useful for
        debugging.
    speconly : bool
        Whether to create the specification file and then return it without
        performing the analysis. Can be useful for debugging.
    start : str, datetime
        Must be given if ``endog`` does not have date information in its index.
        Anything accepted by pandas.DatetimeIndex for the start value.
    freq : str
        Must be givein if ``endog`` does not have date information in its
        index. Anything accapted by pandas.DatetimeIndex for the freq value.
    print_stdout : bool
        The stdout from X12/X13 is suppressed. To print it out, set this
        to True. Default is False.
    x12path : str or None
        The path to x12 or x13 binary. If None, the program will attempt
        to find x13as or x12a on the PATH or by looking at X13PATH or
        X12PATH depending on the value of prefer_x13.
    prefer_x13 : bool
        If True, will look for x13as first and will fallback to the X13PATH
        environmental variable. If False, will look for x12a first and will
        fallback to the X12PATH environmental variable. If x12path points
        to the path for the X12/X13 binary, it does nothing.


    Returns
    -------
    res : Bunch
        A bunch object with the following attributes:

        - results : str
          The full output from the X12/X13 run.
        - seasadj : pandas.Series
          The final seasonally adjusted ``endog``
        - trend : pandas.Series
          The trend-cycle component of ``endog``
        - irregular : pandas.Series
          The final irregular component of ``endog``
        - stdout : str
          The captured stdout produced by x12/x13.
        - spec : str, optional
          Returned if ``retspec`` is True. The only thing returned if
          ``speconly`` is True.

    Notes
    -----
    This works by creating a specification file, writing it to a temporary
    directory, invoking X12/X13 in a subprocess, and reading the output
    directory, invoking exog12/X13 in a subprocess, and reading the output
    back in.
    s=   start and freq cannot be none if endog is not a pandas objectR   R   t   periodst   freqs   transform{{function={0}}}
s
   outlier{}
s   automdl{{{0}}}
s   x11{ save=(d11 d12 d13) }t   deletet   suffixs   .spct   utf8is   .errs   .outs   .d11s   .d12s   .d13Ns   Failed to delete resource {0}t   seasadjt   trendt	   irregulart   observedt   resultsR    R   ((   R4   t
   isinstancet   pdt	   DataFramet   SeriesR"   RB   t   DatetimeIndexR>   R   R   RK   t   _log_to_x12RP   Rb   Re   t   tempfilet   NamedTemporaryFileR.   t   writet   encodet   closeRJ   RQ   t   waitR    R|   t   printR   Rk   R%   t   removeR-   R&   t   existsR   R   Ry   R   t   X13ArimaAnalysisResult(   t   endogRL   RM   RN   RY   R   t   outlierR`   Rc   t   retspect   speconlyR   R   t   print_stdoutR/   R0   t   spec_objR   RO   t   ftempint   ftempoutt   pR    Rj   R   R   R   R   t   res(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR	   @  st    ^





	c         C  s   t  |  d | d | d | d | d | d | d | d | d	 | d
 |	 d |
 d | } t j d | j  } | j   } t j d | j  r t } n$ t j d | j  r t } n t } t |  \ } } t d | d | d | d | j d | j	  } | S(   sy  
    Perform automatic seaonal ARIMA order identification using x12/x13 ARIMA.

    Parameters
    ----------
    endog : array-like, pandas.Series
        The series to model. It is best to use a pandas object with a
        DatetimeIndex or PeriodIndex. However, you can pass an array-like
        object. If your object does not have a dates index then ``start`` and
        ``freq`` are not optional.
    maxorder : tuple
        The maximum order of the regular and seasonal ARMA polynomials to
        examine during the model identification. The order for the regular
        polynomial must be greater than zero and no larger than 4. The
        order for the seaonal polynomial may be 1 or 2.
    maxdiff : tuple
        The maximum orders for regular and seasonal differencing in the
        automatic differencing procedure. Acceptable inputs for regular
        differencing are 1 and 2. The maximum order for seasonal differencing
        is 1. If ``diff`` is specified then ``maxdiff`` should be None.
        Otherwise, ``diff`` will be ignored. See also ``diff``.
    diff : tuple
        Fixes the orders of differencing for the regular and seasonal
        differencing. Regular differencing may be 0, 1, or 2. Seasonal
        differencing may be 0 or 1. ``maxdiff`` must be None, otherwise
        ``diff`` is ignored.
    exog : array-like
        Exogenous variables.
    log : bool or None
        If None, it is automatically determined whether to log the series or
        not. If False, logs are not taken. If True, logs are taken.
    outlier : bool
        Whether or not outliers are tested for and corrected, if detected.
    trading : bool
        Whether or not trading day effects are tested for.
    forecast_years : int
        Number of forecasts produced. The default is one year.
    start : str, datetime
        Must be given if ``endog`` does not have date information in its index.
        Anything accepted by pandas.DatetimeIndex for the start value.
    freq : str
        Must be givein if ``endog`` does not have date information in its
        index. Anything accapted by pandas.DatetimeIndex for the freq value.
    print_stdout : bool
        The stdout from X12/X13 is suppressed. To print it out, set this
        to True. Default is False.
    x12path : str or None
        The path to x12 or x13 binary. If None, the program will attempt
        to find x13as or x12a on the PATH or by looking at X13PATH or X12PATH
        depending on the value of prefer_x13.
    prefer_x13 : bool
        If True, will look for x13as first and will fallback to the X13PATH
        environmental variable. If False, will look for x12a first and will
        fallback to the X12PATH environmental variable. If x12path points
        to the path for the X12/X13 binary, it does nothing.

    Returns
    -------
    results : Bunch
        A bunch object that has the following attributes:

        - order : tuple
          The regular order
        - sorder : tuple
          The seasonal order
        - include_mean : bool
          Whether to include a mean or not
        - results : str
          The full results from the X12/X13 analysis
        - stdout : str
          The captured stdout from the X12/X13 analysis

    Notes
    -----
    This works by creating a specification file, writing it to a temporary
    directory, invoking X12/X13 in a subprocess, and reading the output back
    in.
    R/   RY   R   R   R`   Rc   RL   RM   RN   R   R   R0   s&   (?<=Final automatic model choice : ).*s   Mean is not significantt   ConstantR?   R@   t   include_meanR   R    (
   R	   R9   t   searchR   t   groupR.   t   TrueRA   R   R    (   R   RL   RM   RN   RY   R   R   R`   Rc   R   R   R   R/   R0   R   t   modelR?   R   R@   R   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR     s"    S			R   c           B  s   e  Z d    Z d   Z RS(   c         K  s1   x* t  |  D] \ } } t |  | |  q Wd  S(   N(   R   t   setattr(   R   R   R   R   (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR   Q  s    c         C  s   d d l  m } |   } | j d d d t \ } } |  j j d | d d t  | d j d	  |  j j d | d d t  | d j d
  |  j	 j d | d d t  | d j d  |  j
 j d | d d t  | d j d  | j   | S(   Ni(   t   _import_mpli   i   t   sharext   axi    t   legendt   Observeds   Seas. Adjustedi   t   Trendi   t	   Irregular(   t   statsmodels.graphics.utilsR   t   subplotsR   R   t   plotR.   t
   set_ylabelR   R   R   t   tight_layout(   R   R   t   pltt   figt   axes(    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR   U  s    	
(   R   R   R   R   (    (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyR   P  s   	(   s	   x13as.exeR
   s   x12a.exeR   (    (   i   i   (   i   i   (   i   i   (   i   i   (/   R   t
   __future__R    R%   R*   R   R9   t   warningsR   Rt   R   t   statsmodels.compat.pythonR   t   statsmodels.tools.toolsR   t   statsmodels.tools.sm_exceptionsR   R   R   R   t   __all__R$   R   t   _period_to_freqR   R.   R"   R   R   R3   R4   RA   RJ   RP   R[   Rb   Re   Rk   Ry   R   t   objectR   R   R   R	   R   R   (    (    (    s2   lib/python2.7/site-packages/statsmodels/tsa/x13.pyt   <module>	   sT   "
		$			
						3	'				c