
    M/Ph3Z                        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mZmZmZ ddgZd	a G d
 d          Z e            ZdddZddddZd Zd-dZd.dZd Zd/dZd Zd Zd Zd Zd Z d Z!d  Z" G d! d"          Z# G d# d$e#          Z$d% Z% ed&d'          	 	 	 	 	 	 d0d)            Z& ed&d'          	 	 	 	 	 d1d*            Z' G d+ d,          Z(dS )2z
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.
    )deprecate_kwargN)warn)Bunch)X13NotFoundError	IOWarningX13Error
X13Warningx13_arima_select_orderx13_arima_analysis)z	x13as.exex13aszx12a.exex12ax13as_ascii
x13as_htmlc                       e Zd Zd ZdS )_freq_to_periodc                     |                     d          rdS |                     d          rdS |                     d          rdS d S )NM   Q   W4   )
startswith)selfkeys     S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/x13.py__getitem__z_freq_to_period.__getitem__    sW    >># 	2^^C   	1^^C   	2	 	    N)__name__
__module____qualname__r    r   r   r   r      s#            r   r   r   r   )r   r   lognoneauto)TFNc                     | rdndS )Nyesnor"   xs    r   <lambda>r+   -   s    Q0EED r   Tc                 j   | X|                      t                    r>t          j                            |           st          j                            |           } |s?t          ddd         a| t          j        dd          } | st          j        dd          } n.| ,t          j        dd          } | st          j        dd          } t          D ]a}t          j                            | |          }	 t          j	        |t          j
        t          j
                   |c S # t          $ r Y ^w xY wdS )a  
    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.
    NX12PATH X13PATHstdoutstderrF)endswith_binary_namesospathisdirdirnamegetenvjoin
subprocess
check_callPIPEOSError)x12path
prefer_x13binaryx12s       r   	_find_x12rD   0   s;    w//>>w}}W%% 	/goog..G 	/%ddd+?i	2..G 	/i	2..G	)Ir** 	/i	2..G 
 
gll7F++	!#jo)3: : : :JJJ 	 	 	D	 us   4,D##
D0/D0c                 F    t          |           } | st          d          | S )Nzxx12a and x13as not found on path. Give the path, put them on PATH, or set the X12PATH or X13PATH environmental variable.)rD   r   )r@   s    r   
_check_x12rF   U   s:      G M  L M M 	M Nr   c                     t          j        d|           } d }t          |           dk    rt          ||           \  } }n || d                   } d}| |fS )z
    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)
    z\([0-9 ]*?\)c           
          t          t          t          t          j        dd|                               d                              S )Nz[()]r/    )tuplemapintresubsplitr)   s    r   cleanz_clean_order.<locals>.cleane   s6    SbfVR3399#>>??@@@r      r   )r   r   r   )rM   findalllenrK   )orderrP   sorders      r   _clean_orderrV   ^   sm    
 J..EA A A 5zzA~~E5))vveAh&=r   Fc                     |r|rt          d          |r| d|z   g}n|r| d|z   g}n| |g}|r||gz  }t          j        |t          j        t          j                  S )Nz&Cannot specify both meta and datameta.z-m z-d r1   )
ValueErrorr<   Popenr>   STDOUT)r@   specpathoutnamemetadatametaargss         r   run_specr`   q   s     C CABBB #)*	 #)*" 	D#-#46 6 6 6r   c                     d}|d| d          d| d          dz  }||d|d          d|d          dz  }n|d|d          d|d          dz  }|S )	N
zmaxorder = (r   rI   rQ   )
zmaxdiff = (zdiff = (r"   )maxordermaxdiffdiffoptionss       r   _make_automdl_optionsrh      s    G<hqk<<HQK<<<<G===gaj====4d1g44Q4444Nr   c                 8   t          | d          r	| j        g}n't          | d          r| j        }nt          d          	 d                    |          }nB# t
          $ r5 ddlm} | j        dk    rd}nd                     ||                     }Y nw xY w|S )	Nnamecolumnsz0exog is not a Series or DataFrame or is unnamed.rI   r   )_make_exog_namesrQ   x1)	hasattrrj   rk   rX   r;   	TypeErrorstatsmodels.base.datarl   ndim)exog	var_namesrl   s      r   _make_var_namesrt      s    tV MYK			y	!	! ML		KLLL9HHY''		 9 9 9::::::9>>II!1!1$!7!788I9 s   A <BBc           
      0   | s|dS d}| r|dz  }|t          |          }|d| dz  }|d                    d                    t          t          |j                                                                                                      z  }|dz  }|S )	Nr/   zregression{
z    variables = (td)
z    user = (rc   z    data = ({})
rb   }
)rt   formatr;   rK   strvaluesraveltolist)tradingrr   reg_specrs   s       r   _make_regression_optionsr~      s     t|rH -,,#D))	191111'..IIC**,,335566 
 
 	
 HOr   c                 $    | dS d}|d|  dz  }|S )Nr/   z
forecast{
zmaxlead = (z)
}
r"   )forecast_periodsforecast_specs     r   _make_forecast_optionsr      s/    r!M<#3<<<<Mr   c                     | |                      d          dz   d                                          } | rd| v rt          |           | rd| v rt          | t                     d S d S d S )Nzspc:r   ERRORWARNING)findstripr   r   r	   )errorss    r   _check_errorsr      s    FKK'')**+1133F !'V##v	 !I''VZ     ! !''r   c                     ddl m} ddlm}  | ||           dddd          }|                    |                              d	|i
          |         S )zi
    Convert x to a DataFrame where x is a string in the format given by
    x-13arima-seats output.
    r   )StringIO)read_csv   N	python)skiprowsheadersepenginerQ   )rk   )ior   pandasr   	set_indexrename)r*   datesrj   r   r   outs         r   _convert_out_to_seriesr      s}    
 
(88A;;D; ; ;C==&&4y&99$??r   c                     t          | d          5 }|                                }d d d            n# 1 swxY w Y   |S )Nzutf-8)encoding)openread)fnamefinfouts      r   _open_and_readr      sy    	eg	&	&	& #xxzz              Ks   377c                   0    e Zd Zed             Zd Zd ZdS )Specc                 B    | j         j                            dd          S )Nr   r/   )	__class__r   replace)r   s    r   	spec_namezSpec.spec_name   s    ~&..vr:::r   c                 H    d}|                     | j        | j                  S )Nz/{name} {{
        {options}
        }}
        )rj   rg   )rw   r   rg   )r   kwargsspecs      r   create_speczSpec.create_spec   s/     {{#'<  1 1 	1r   c                     d}|                                 D ],\  }}|| d| dz  }| j                            ||i           -|| _        d S )Nr/   =rb   )items__dict__updaterg   )r   r   rg   r   values        r   set_optionszSpec.set_options   se     ,,.. 	/ 	/JC#))))))GM  #u....r   N)r   r    r!   propertyr   r   r   r"   r   r   r   r      sK        ; ; X;1 1 1    r   r   c                   >    e Zd ZdZdddddddddg g dd	d
ddddfdZdS )
SeriesSpecag  
    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
    Unnamed SeriesFNrQ   r   r"   r   )rQ   rQ   r/   iayi ʚ;c           	          t          t          ||g          \  }}d|d d          d}d|d d          d}|                     ||||	|||           d S )N"@   O   )data
appendbcst
appendfcstperiodstarttitlerj   )rK   _bool_to_yes_nor   )r   r   rj   r   r   comptypecompwtdecimals	modelspanr   	precisionto_printto_savespanr   r   series_typedivpowermissingcode
missingvalseries_names                        r   __init__zSeriesSpec.__init__
  s     "%_z7A79 ": ":
J )49(((#U3B3Z###dz$.vU$; 	 	 	 	 	 	r   )r   r    r!   __doc__r   r"   r   r   r   r      s^         < #3u!q1a"brRTD#
     r   r   c           	         t          | d          r:t          | j                  dk    rt          d          | | j        d                  } d                    d                    t          t          | j        	                                                              }	 t          | j        j                 }n8# t          t          f$ r$ ddlm} t           || j                           }Y nw xY w| 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|           }|S )Nrk   rQ   z3Does not handle DataFrame with more than one columnr   z({})rb   )
infer_freqr   r   zqOnly monthly and quarterly periods are supported. Please report or send a pull request if you want this extended.rj   r   .)r   rj   r   r   r   )rn   rS   rk   rX   rw   r;   rK   rx   ry   r{   r   indexfreqstrAttributeErrorpandas.tseries.apir   yearmonthquarterrj   r   )	r*   r   r   r   
start_dater   stperiodrj   series_specs	            r   pandas_to_series_specr     s    q) qy>>A & ' ' 'ailO==3sAHOO,=,=#>#>??@@D
6 1J' 6 6 6111111 AG!4!456 J||#**:h	1#**<h * + + 	+ q&  v))""""  K s   B6 62C+*C+forecast_yearsr   r   rQ   c           	      	   t          |          }t          | t          j        t          j        f          sK||t          d          t          j        | t          j        |t          |           |                    } t          |           }|	                                }|dt          |          dz  }|r|dz  }t          |||          }|d| dz  }|t          ||          z  }|t          |          z  }|d	z  }|
r|S t          j        d
d|          }t          j        d
|          }	 |                    |                    d                     |                                 |                                 t'          ||j        dd         |j                  }|                                 |j                                        }|r&t1          |j                                                   t3          |j        dz             }t5          |           t3          |j        dz             }t3          |j        dz             }t3          |j        dz             }t3          |j        dz             }	 t7          j        |j                   t7          j        |j                   n^# t:          $ r t6          j                            |j                  rtA          d|j         tB                     t6          j                            |j                  rtA          d|j         tB                     Y nw xY w# 	 t7          j        |j                   t7          j        |j                   w # t:          $ r t6          j                            |j                  rtA          d|j         tB                     t6          j                            |j                  rtA          d|j         tB                     Y w Y w w xY wxY wtE          || j#        d          }tE          || j#        d          }tE          || j#        d          }|	stI          | |||||          }ntI          | ||||||          }|S )a%  
    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 seasonal 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_periods : int
        Number of forecasts produced. The default is None.
    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 accepted 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.
    tempdir : str
        The path to where temporary files are created by the function.
        If None, files are created in the default temporary file location.

    Returns
    -------
    Bunch
        A bunch object containing the listed 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.
    Nz=start and freq cannot be none if endog is not a pandas object)r   periodsfreq)r   ztransform{function=rv   z
outlier{}
zautomdl{zx11{ save=(d11 d12 d13) }Fz.spc)deletesuffixdir)r   r   utf8z.errz.outz.d11z.d12z.d13zFailed to delete resource seasadjtrend	irregular)observedresultsr   r   r   r2   )r   r   r   r   r   r2   r   )%rF   
isinstancepd	DataFrameSeriesrX   DatetimeIndexrS   r   r   _log_to_x12rh   r~   r   tempfileNamedTemporaryFilewriteencodecloser`   rj   waitr2   r   printr   r   r6   remover?   r7   existsr   r   r   r   X13ArimaAnalysisResult)endogrd   re   rf   rr   r#   outlierr|   r   retspecspeconlyr   r   print_stdoutr@   rA   tempdirspec_objr   rg   ftempinftempoutpr2   r   r   r   r   r   ress                                 r   r   r   H  s   D !!GeblBI677 D=DL / 0 0 0	%r'7e@CE

=A(C (C (C D D D %U++H!!D9;s#39999D #Hgt<<G%%%%%D$Wd333D"#3444D''D  )17.57 7 7G *%WEEEH dkk&))***Wgl3B3/??	 	#!(--//""" 677f !!788 !788x}v566"8=6#9::	
	 Igl###Ihm$$$$ 	  	  	 w~~gl++  @',@@     w~~hm,,  A(-AA     	 	
	 Igl###Ihm$$$$ 	  	  	 w~~gl++  @',@@     w~~hm,,  A(-AA            		  %Wek9EEG"5%+w??E&y%+{KKI  0$eW-4E/8I I I %eW-4E/8*.0 0 0 JsE   5E
M  2J4 4BMMP2M;:P;BPPPPc                 t   t          | ||||||||||	|
||          }t          j        d|j                  }|                                }t          j        d|j                  rd}nt          j        d|j                  rd}nd}t          |          \  }}t          ||||j        |j                  }|S )a  
    Perform automatic seasonal 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 seasonal 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_periods : int
        Number of forecasts produced. The default is None.
    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 accepted 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.
    tempdir : str
        The path to where temporary files are created by the function.
        If None, files are created in the default temporary file location.

    Returns
    -------
    Bunch
        A bunch object containing the listed 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@   rr   r#   r   r|   r   rd   re   rf   r   r   rA   r  z&(?<=Final automatic model choice : ).*zMean is not significantFConstantT)rT   rU   include_meanr   r2   )r   rM   searchr   grouprV   r   r2   )r   rd   re   rf   rr   r#   r   r|   r   r   r   r  r@   rA   r  r   modelrT   r  rU   r	  s                        r   r
   r
     s    n !d)0'2B*2G$',4J)02 2 2G I>o' 'EKKMME	y*GO<< 	:w	/	/  ''ME6
eF@ @ @CJr   c                       e Zd Zd Zd ZdS )r   c                 \    |                                 D ]\  }}t          | ||           d S N)r   setattr)r   r   r   r   s       r   r   zX13ArimaAnalysisResult.__init__d  s<     ,,.. 	& 	&JCD#u%%%%	& 	&r   c                 l   ddl m}  |            }|                    ddd          \  }}| j                            |d         d           |d                             d	           | j                            |d         d           |d                             d
           | j                            |d         d           |d                             d           | j                            |d         d           |d                             d           |	                                 |S )Nr   )_import_mplr   rQ   T)sharexF)axlegendObservedzSeas. Adjustedr   Trend   	Irregular)
statsmodels.graphics.utilsr  subplotsr   plot
set_ylabelr   r   r   tight_layout)r   r  pltfigaxess        r   r  zX13ArimaAnalysisResult.ploth  s+   ::::::kmmLLAdL33	Td1ge444Q:&&&T!WU333Q+,,,
475111Q7###tAwu555Q;'''
r   N)r   r    r!   r   r  r"   r   r   r   r   c  s2        & & &    r   r   )NTr  )NFF)r   r   NNNTFNFFNNFNTN)r   r   NNNTFNNNFNTN))r   statsmodels.compat.pandasr   r6   r<   r   rM   warningsr   r   r   statsmodels.tools.toolsr   statsmodels.tools.sm_exceptionsr   r   r   r	   __all__r5   r   _period_to_freqr   r   rD   rF   rV   r`   rh   rt   r~   r   r   r   r   r   r   r   r   r
   r   r"   r   r   <module>r+     s    6 5 5 5 5 5 				      				           ) ) ) ) ) )9 9 9 9 9 9 9 9 9 9 9 9 $%9
:.        "/##s##68800" " " "J     &6 6 6 6$    $  (  ! ! !	@ 	@ 	@         */ / / / / / / /d( ( (V !#566DHBG6;8<DH#k k k 76k\ !#566HLFK,0?DBF	h h h 76hV         r   