
    M/Phs7                   j   d dl mZ d dlmZmZmZmZ d dlmZ d dl	Z	d dl	Z
d dlmZ d dlmZmZmZ d dlmZ d dlZd dlZd dlZd dlmZmZ d dlmc mZ d d	lmZ d d
l m!Z! d dl"m#Z# d dl$m%Z%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z>m?Z?m@Z@mAZA d dlBmCZCmDZD ddgZEdZFdZGd:d;d ZHd<d#ZI G d$ de:jJ                  ZK G d% d          ZL G d& d'          ZM e(eKjN        jO                  ZPePQ                    g d(d)          ZR G d* d+e:jS                  ZT G d, d-ejU                  ZV ejW        eVeT            e(eKjO                  ZPePQ                    g d.d/          ZX eeX0          	 	 	 	 	 	 	 	 	 d=d>d7            ZY G d8 d9          ZZdS )?    )annotations)AppenderSubstitutioncall_cached_functo_numpy)IterableN)SimpleNamespace)AnyLiteralcast)Sequence)gaussian_kdenorm)Summary)OLS)eval_measures)cache_readonlycache_writable)	Docstringremove_parameters)SpecificationWarning)	ArrayLikeArrayLike1DArrayLike2DFloat64ArrayNDArray)
array_like	bool_likeint_likestring_like)arma2ma)	tsa_model)PredictionResults)DeterministicProcessDeterministicTermSeasonality	TimeTrend)freq_to_periodlagmatARAutoRegaU  
statsmodels.tsa.AR has been deprecated in favor of statsmodels.tsa.AutoReg and
statsmodels.tsa.SARIMAX.

AutoReg adds the ability to specify exogenous variables, include time trends,
and add seasonal dummies. The AutoReg API differs from AR since the model is
treated as immutable, and so the entire specification including the lag
length must be specified when creating the model. This change is too
substantial to incorporate into the existing AR api. The function
ar_select_order performs lag length selection for AutoReg models.

AutoReg only estimates parameters using conditional MLE (OLS). Use SARIMAX to
estimate ARX and related models using full MLE via the Kalman Filter.

To silence this warning and continue using AR until it is removed, use:

import warnings
warnings.filterwarnings('ignore', 'statsmodels.tsa.ar_model.AR', FutureWarning)
z
Model has been fit using maxlag={0}, method={1}, ic={2}, trend={3}. These
cannot be changed in subsequent calls to `fit`. Instead, use a new instance of
AR.
x
np.ndarrayaxisintreturnfloat | np.ndarrayc                4    t          j        | dz  |          S )z<Helper function to calculate sum of squares along first axis   r.   )npsum)r,   r.   s     X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/ar_model.pysumofsqr8   R   s    6!Q$T""""    data!pd.DatetimeIndex | pd.PeriodIndexc                L    | j         rt          |          S t          d          )z2Shared helper to get period from frequenc or raisezfreq cannot be inferred from endog and model includes seasonal terms.  The number of periods must be explicitly set when the endog's index does not contain a frequency.)freqr(   
ValueError)r:   
index_freqs     r7   _get_periodr@   W   s1    y *j)))
	6  r9   c                      e Zd ZU dZded<   	 	 	 	 	 	 dTddddU fdZedVd            ZedWd            ZedXd!            Z	edYd"            Z
edZd#            ZedWd$            Zed[d&            Zed\d(            Zd]d*Zd^d,Zd]d-Z	 	 	 d_d`d4Zdad8Zdbd:Zdad;Zdad<Zdad=ZdcdAZdddGZdedKZdfdLZdgdMZdhdPZdQ Z	 	 	 	 	 didjdSZ xZ S )kr+   a  
    Autoregressive AR-X(p) model

    Estimate an AR-X model using Conditional Maximum Likelihood (OLS).

    Parameters
    ----------
    endog : array_like
        A 1-d endogenous response variable. The dependent variable.
    lags : {None, int, list[int]}
        The number of lags to include in the model if an integer or the
        list of lag indices to include.  For example, [1, 4] will only
        include lags 1 and 4 while lags=4 will include lags 1, 2, 3, and 4.
        None excludes all AR lags, and behave identically to 0.
    trend : {'n', 'c', 't', 'ct'}
        The trend to include in the model:

        * 'n' - No trend.
        * 'c' - Constant only.
        * 't' - Time trend only.
        * 'ct' - Constant and time trend.

    seasonal : bool
        Flag indicating whether to include seasonal dummies in the model. If
        seasonal is True and trend includes 'c', then the first period
        is excluded from the seasonal terms.
    exog : array_like, optional
        Exogenous variables to include in the model. Must have the same number
        of observations as endog and should be aligned so that endog[i] is
        regressed on exog[i].
    hold_back : {None, int}
        Initial observations to exclude from the estimation sample.  If None,
        then hold_back is equal to the maximum lag in the model.  Set to a
        non-zero value to produce comparable models with different lag
        length.  For example, to compare the fit of a model with lags=3 and
        lags=1, set hold_back=3 which ensures that both models are estimated
        using observations 3,...,nobs. hold_back must be >= the maximum lag in
        the model.
    period : {None, int}
        The period of the data. Only used if seasonal is True. This parameter
        can be omitted if using a pandas object for endog that contains a
        recognized frequency.
    missing : str
        Available options are 'none', 'drop', and 'raise'. If 'none', no nan
        checking is done. If 'drop', any observations with nans are dropped.
        If 'raise', an error is raised. Default is 'none'.
    deterministic : DeterministicProcess
        A deterministic process.  If provided, trend and seasonal are ignored.
        A warning is raised if trend is not "n" or seasonal is not False.
    old_names : bool
        Flag indicating whether to use the v0.11 names or the v0.12+ names.

        .. deprecated:: 0.13.0

           old_names is deprecated and will be removed after 0.14 is
           released. You must update any code reliant on the old variable
           names to use the new names.

    See Also
    --------
    statsmodels.tsa.statespace.sarimax.SARIMAX
        Estimation of SARIMAX models using exact likelihood and the
        Kalman Filter.

    Notes
    -----
    See the notebook `Autoregressions
    <../examples/notebooks/generated/autoregressions.html>`__ for an overview.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> from statsmodels.tsa.ar_model import AutoReg
    >>> data = sm.datasets.sunspots.load_pandas().data['SUNACTIVITY']
    >>> out = 'AIC: {0:0.3f}, HQIC: {1:0.3f}, BIC: {2:0.3f}'

    Start by fitting an unrestricted Seasonal AR model

    >>> res = AutoReg(data, lags = [1, 11, 12]).fit()
    >>> print(out.format(res.aic, res.hqic, res.bic))
    AIC: 5.945, HQIC: 5.970, BIC: 6.007

    An alternative used seasonal dummies

    >>> res = AutoReg(data, lags=1, seasonal=True, period=11).fit()
    >>> print(out.format(res.aic, res.hqic, res.bic))
    AIC: 6.017, HQIC: 6.080, BIC: 6.175

    Finally, both the seasonal AR structure and dummies can be included

    >>> res = AutoReg(data, lags=[1, 11, 12], seasonal=True, period=11).fit()
    >>> print(out.format(res.aic, res.hqic, res.bic))
    AIC: 5.884, HQIC: 5.959, BIC: 6.071
    r   _ycFNnone)deterministic	old_namesendogr   lagsint | Sequence[int] | NonetrendLiteral['n', 'c', 't', 'ct']seasonalboolexogArrayLike2D | None	hold_back
int | NoneperiodmissingstrrE   DeterministicProcess | NonerF   c	          	     B   t                                          ||d d |           t          t          d         t	          |ddd                    | _        t          |d          | _        t          |dd	          | _	        | j	        &| j        rt          | j        | j                  | _	        t          j        | j                  g}|rCt          | j	        t                     sJ |                    t%          | j	                             t'          | j        j        d
          r| j        j        j        }n)t-          j        | j        j        j        d                   }d| _        |	3t          |	t6                    st9          d          |	| _        d| _        nt7          ||          | _        g | _        d| _        t          |
dd	          | _         |	.| j        dk    s| j        rtC          j"        dtF          d           | j         rtC          j"        dtH          d           | %                    |t          |dd	                    \  | _&        | _'        | (                                 | j)        j        d         | _*        | j+        | j        _,        d S )N)rS   )nrC   tctrJ   F)optionsoptionalrL   rR   Tr[   indexr   z,deterministic must be a DeterministicProcess)additional_termsrF   rW   zGWhen using deterministic, trend must be "n" and seasonal must be False.r3   )
stacklevelzoold_names will be removed after the 0.14 release. You should stop setting this parameter and use the new names.rP   )-super__init__r   r   r    _trendr   	_seasonalr   _periodr@   r:   _index_freqr'   from_string
isinstancer/   appendr&   hasattr
orig_endogr]   r5   arangerG   shape_user_deterministicr$   	TypeError_deterministics_exog_names_k_ar
_old_nameswarningswarnr   FutureWarning_check_lags_lags
_hold_back_setup_regressorsrB   nobs
exog_namesxnames)selfrG   rH   rJ   rL   rN   rP   rR   rS   rE   rF   termsr]   	__class__s                r7   ra   zAutoReg.__init__   s    	dD'BBB'(w(=  
 
 #8Z884@@@<DN&ty$2BCCDL*3*?*L*L)M 	4dlC00000LLT\2233349'11 	8I(.EEIdio3A677E#( $m-ABB P NOOO#0D '+D$$#7$ $ $D  ')
#I{UKKK$K3$.M*$	    ? 	ME	    '+&6&6(9kDAAA'
 '
#
DO 	   GM!$	?	r9   r0   list[int] | Nonec                6    t          | j                  }|sdn|S )-The autoregressive lags included in the modelN)listrw   )r}   rH   s     r7   ar_lagszAutoReg.ar_lags	  s"     DJ)ttT)r9   c                    | j         S )z?The number of initial obs. excluded from the estimation sample.)rx   r}   s    r7   rP   zAutoReg.hold_back  s     r9   Literal['n', 'c', 'ct', 'ctt']c                    | j         S )zThe trend used in the model.rb   r   s    r7   rJ   zAutoReg.trend       {r9   c                    | j         S )z=Flag indicating that the model contains a seasonal component.rc   r   s    r7   rL   zAutoReg.seasonal       ~r9   c                "    | j         r| j        ndS )z-The deterministic used to construct the modelN)rm   ro   r   s    r7   rE   zAutoReg.deterministic  s     (,'?It##TIr9   c                    | j         S z%The period of the seasonal component.rd   r   s    r7   rR   zAutoReg.period#       |r9   r/   c                &    | j         j        d         S )zThe model degrees of freedom.   )_xrl   r   s    r7   df_modelzAutoReg.df_model(  s     w}Qr9   list[str] | Nonec                    | j         S )z.Names of exogenous variables included in model)rp   r   s    r7   r{   zAutoReg.exog_names-  s     r9   Nonec                    dS )zInitialize the model (no-op).N r   s    r7   
initializezAutoReg.initialize2  s    r9   tuple[list[int], int]c                N   |g }d| _         net          |t                    rg }|D ]>}t          |d          }t          |t                    sJ |                    |           ?t          j        t          |                    }t          j	        |dk               s.t          j
        |          j        d         |j        d         k    rt          d          t          j        |          | _         d |D             }nqt          |d          }t          |t                    sJ || _         | j         dk     rt          d          t          j        d| j         dz             }d |D             }|| j         }|| j         k     rt          d          |t	          |          fS )	Nr   rH   r   z1All values in lags must be positive and distinct.c                ,    g | ]}t          |          S r   r/   .0vs     r7   
<listcomp>z'AutoReg._check_lags.<locals>.<listcomp>K      ///SVV///r9   z#lags must be a non-negative scalar.c                ,    g | ]}t          |          S r   r   r   s     r7   r   z'AutoReg._check_lags.<locals>.<listcomp>S  r   r9   zNhold_back must be >= lags if lags is an int ormax(lags) if lags is array_like.)_maxlagrg   r   r   r/   rh   r5   arraysortedanyuniquerl   r>   maxrk   )r}   rH   rP   rw   lagval	_lags_arrs          r7   rv   zAutoReg._check_lags6  s    <!EDLLh'' 	0E " "sF++!#s+++++S!!!!!#&--!8!8Iy1}%%9Y''-a0IOA4FFF G   6),,DL//Y///EE4((Cc3'''''DL|a !FGGG	!T\A%566I//Y///EIt|##3   c)nn$$r9   c                   | j         }| j        }g }| j        t          | j        |d          \  }}|                    fd| j        D                        t          | j                  |k     r&|d d t          j	        | j                  dz
  f         }|j
        d         | _        | j                                        }|j
        d         rt          j        t          |          |f         }| j        rg }d| j        v r|                    d           d| j        v r|                    d           | j        r_| j        }t+          |t,                    sJ d	 t/          |          D             }	d| j        v r
|	dd          }	|                    |	           nt1          |j                  }||z   }| j        8t          j        || j        f         }|                    | j        j                   ||d          }||d          }|j
        d
         |j
        d         k     r|j
        d         }
| j        }| j        dk    rd
nt          | j                  }| j        r1t+          |t,                    sJ |t-          d| j        v           z
  }nd
}t          | j                  }|j
        d
         }t;          d|
 d| d| d| d| d          ||c| _        | _        || _         d S )Nsep)originalc                     g | ]
}d | z   S )z.Lr   )r   r   endog_namess     r7   r   z-AutoReg._setup_regressors.<locals>.<listcomp>e  s$    <<<#[:::%<<<r9   r   rC   	interceptrX   rJ   c                    g | ]}d | S )z	seasonal.r   r   is     r7   r   z-AutoReg._setup_regressors.<locals>.<listcomp>v  s    DDD___DDDr9   r   rW   z@The model specification cannot be estimated. The model contains z regressors (z trend, z seasonal, zS lags) but after adjustment for hold_back and creation of the lags, there are only z. data points available to estimate parameters.)!r   rx   r   r)   rG   extendrw   lenr5   asarrayrl   rq   ro   	in_samplec_r   rr   rb   rh   rc   rd   rg   r/   ranger   columnsrN   r:   param_namesr>   rB   r   rp   )r}   maxlagrP   r{   r,   yrE   deterministic_namesrR   namesregrJ   seasrH   rz   r   s                  @r7   ry   zAutoReg._setup_regressors^  s5   O	
&dj&59991<<<<<<<	
 	
 	
 tz??V##!!!RZ
++a//0AWQZ
,6688q! 	:h}--q01A B&(#$+%%'..{;;;$+%%'..w777> 6!\F%fc22222DDeFmmDDDEdk)) %abb	'..u555&*=+@&A&A#,z9J9 al#Adi3444ijjMijjM71:
""'!*C\F++AAT[1A1AE~ !&#.....C4;$6 7 77tz??D71:D&) 8=  $(  !	     a%r9   	nonrobustcov_typecov_kwdsdict[str, Any] | Noneuse_tAutoRegResultsWrapperc           	        | j         j        d         dk    rBt          t          | t	          j        d          t	          j        d                              S t          | j        | j                   }|                    |||          }|	                                }|j
        }|dk    r3|s1| j        j        d         }| j         j        d         }|||z
  z  }	||	z  }t          | |j        ||j        |          }
t          |
          S )a  
        Estimate the model parameters.

        Parameters
        ----------
        cov_type : str
            The covariance estimator to use. The most common choices are listed
            below.  Supports all covariance estimators that are available
            in ``OLS.fit``.

            * 'nonrobust' - The class OLS covariance estimator that assumes
              homoskedasticity.
            * 'HC0', 'HC1', 'HC2', 'HC3' - Variants of White's
              (or Eiker-Huber-White) covariance estimator. `HC0` is the
              standard implementation.  The other make corrections to improve
              the finite sample performance of the heteroskedasticity robust
              covariance estimator.
            * 'HAC' - Heteroskedasticity-autocorrelation robust covariance
              estimation. Supports cov_kwds.

              - `maxlags` integer (required) : number of lags to use.
              - `kernel` callable or str (optional) : kernel
                  currently available kernels are ['bartlett', 'uniform'],
                  default is Bartlett.
              - `use_correction` bool (optional) : If true, use small sample
                  correction.
        cov_kwds : dict, optional
            A dictionary of keyword arguments to pass to the covariance
            estimator. `nonrobust` and `HC#` do not support cov_kwds.
        use_t : bool, optional
            A flag indicating that inference should use the Student's t
            distribution that accounts for model degree of freedom.  If False,
            uses the normal distribution. If None, defers the choice to
            the cov_type. It also removes degree of freedom corrections from
            the covariance estimator when cov_type is 'nonrobust'.

        Returns
        -------
        AutoRegResults
            Estimation results.

        See Also
        --------
        statsmodels.regression.linear_model.OLS
            Ordinary Least Squares estimation.
        statsmodels.regression.linear_model.RegressionResults
            See ``get_robustcov_results`` for a detailed list of available
            covariance estimators and options.

        Notes
        -----
        Use ``OLS`` to estimate model parameters and to estimate parameter
        covariance.
        r   r   )r   r   )r   r   r   r   )r   )r   rl   r   AutoRegResultsr5   emptyr   rB   fit
cov_paramsr   paramsnormalized_cov_params)r}   r   r   r   ols_modols_resr   rz   kscaleress              r7   r   zAutoReg.fit  s   | 7=q  (tRXa[["(62B2BCC   dgtw''++  
 
 ''))
{""5"7=#Da AD1H%E%JN)
 
 
 %S)))r9   r   r   r-   c                    t          |dd          }| j                                        | j        |z                                  z
  S )Nr   r3   )ndim)r   rB   squeezer   r}   r   s     r7   _residzAutoReg._resid  s@    FH1555w  DGf$4#=#=#?#???r9   floatc                    | j         }|                     |          }||z  }|dz   t          j        dt          j        z            t          j        ||z            z   dz   z  }|S )a  
        Log-likelihood of model.

        Parameters
        ----------
        params : ndarray
            The model parameters used to compute the log-likelihood.

        Returns
        -------
        float
            The log-likelihood value.
        r3   r   )rz   r   r5   logpi)r}   r   rz   residssrllfs         r7   loglikezAutoReg.loglike  sb     yF##emqkRVAI..d
1C1CCaGH
r9   c                J    |                      |          }| j        j        |z  S )aP  
        Score vector of model.

        The gradient of logL with respect to each parameter.

        Parameters
        ----------
        params : ndarray
            The parameters to use when evaluating the Hessian.

        Returns
        -------
        ndarray
            The score vector evaluated at the parameters.
        )r   r   T)r}   r   r   s      r7   scorezAutoReg.score  s$      F##wy5  r9   c                z    |                      |          }||z  | j        z  }| j        j        | j        z  d|z  z  S )a5  
        Fisher information matrix of model.

        Returns -1 * Hessian of the log-likelihood evaluated at params.

        Parameters
        ----------
        params : ndarray
            The model parameters.

        Returns
        -------
        ndarray
            The information matrix.
        r   )r   rz   r   r   )r}   r   r   sigma2s       r7   informationzAutoReg.information  s?      F##*	DG#F
33r9   c                .    |                      |           S )a  
        The Hessian matrix of the model.

        Parameters
        ----------
        params : ndarray
            The parameters to use when evaluating the Hessian.

        Returns
        -------
        ndarray
            The hessian evaluated at the parameters.
        )r   r   s     r7   hessianzAutoReg.hessian/  s       ((((r9   add_forecastsexog_oosr   c                \   t          j        || j        j        d         f          }| j                            |          }|j        d         }t          |          |d d d |f<   |t          | j                  z   }| j	        't          j
        |          }|d |         |d d |d f<   |S )Nr   )steps)r5   zerosr   rl   ro   out_of_sampler   r   rw   rN   r   )r}   r   r   r,   oos_exogn_deterministicloc
exog_oos_as           r7   _setup_oos_forecastzAutoReg._setup_oos_forecast?  s     HmTW]1%5677'55M5JJ".+!)(!3!3!!!o
DJ/9 H--J#N]N3AaaagJr9   
predictionstartendpad	pd.Seriesc                ~   t          j        t          j        |t           j                  |g          }||z
  |z   }t	          | j        j        t          j        t          j	        f          s|| d          S | j
        }|| j        j        d         k    r}t          |dd           }|rVt	          |t          j                  rt          j        |d         ||          }n2t          j        |d         ||          }nt          j        |          }|||z
  |         }|| d          }t          j        ||          S )Nr   r=   )r=   periodsr]   )r5   hstackfullnanrg   r:   rj   pdSeries	DataFrame_indexrG   rl   getattrPeriodIndexperiod_range
date_range
RangeIndex)r}   r   r   r   r   n_valuesr]   r=   s           r7   _wrap_predictionzAutoReg._wrap_predictionM  s.    YRV 4 4jABB
;$$).BL0IJJ 	*xijj))!!$$$5&$//D +eR^44 LOE!H4MMMEEM%(sKKKEEc**eckC'(	

+
y51111r9   dynamicnum_oosFloat64Array | Nonec                $   g }| j         }	d}
||	k     r|	|z
  }
||
z  }t          ||
z
  d          }||	z
  | j        k    rst          ||	z
  |dz   |	z
            }| j        |         }|6|                                }|||dz            |dd|j        d          df<   |                    |           |dk    r)|                    |                     ||                     t          j
        |          }| j        j        d         t          | j                  z
  }|| j        dn| j        j        d         z  }t          j        |j        d                   }|d|         |z  |d|<   t          ||j        d                   D ]o}t!          | j                  D ]3\  }}||z
  }||k    r	||         }n| j        ||z            }|||||z   f<   4t          j        |||dz            |z            ||<   p|                     |||dz   |z   |
          S )z

        :param params:
        :param start:
        :param end:
        :param dynamic:
        :param num_oos:
        :param exog:
        :param exog_oos:
        :return:
        r   r   N)rx   r   rz   slicer   copyrl   rh   r   r5   vstackr   rw   rN   r   r   	enumeraterG   r   r  )r}   r   r   r   r  r  rN   r   r   rP   adjis_locr,   _regdet_col_idx	forecastshjr   	fcast_locr   s                        r7   _dynamic_predictzAutoReg._dynamic_predictb  sC   * O	9e#CgmQ''I$)++ 59,cAg	.ABBFAFFHH)-ecAgo)>!!!djm^%%%&JJqMMMQ;;JJt//BBCCCy~~gmA&TZ8DI-qq49?13EEHTZ]++	"8G8nv5	(7(w
1.. 
	@ 
	@A#DJ// / /3G	''#I.CC *Y%67C+.Qa'((:d1q1u9o&>??IaLL$$YsQw7H#NNNr9   c                   |                      ||          }| j        dk    r||z  S t          j        |          }| j        dn| j        j        d         }| j        j        d         |z
  t          | j                  z
  }t          |          D ]}}t          | j                  D ]A\  }	}
||
z
  }|dk     r| j        |         n||         }t          j        |          ||||	z   f<   Bt          j        |||dz            |z            ||<   ~|S )Nr   r   )r   r   r5   r   rN   rl   r   r   rw   r   r  rB   r   )r}   r   r  r   new_xr  nexog	ar_offsetr   r  r   r   r   s                r7   _static_oos_predictzAutoReg._static_oos_predict  s    (((;;<16>!HW%%	Y&DIOA,>GM!$u,s4:>	w 	A 	AA#DJ// : :3#g&)Aggdgcll9S>*,*S//aQ&'':eAAI&6&?@@IaLLr9   c                   | j         }| j        j        d         }t          j        d| j        j        d         f          }	t          d||z
            }
||
z  }||k    rrt          ||z
  |dz   |z
            }| j        |         }	|Jt          j        |          }|		                                }	|||dz            |	dd|j        d          df<   |	|z  }|dk    r| 
                    |||dz   |
          S |                     |||          }t          j        ||f          }| 
                    |||dz   |z   |
          S )a  
        Path for static predictions

        Parameters
        ----------
        params : ndarray
            The model parameters
        start : int
            Index of first observation
        end : int
            Index of last in-sample observation. Inclusive, so start:end+1
            in slice notation.
        num_oos : int
            Number of out-of-sample observations, so that the returned size is
            num_oos + (end - start + 1).
        exog : {ndarray, DataFrame}
            Array containing replacement exog values
        exog_oos :  {ndarray, DataFrame}
            Containing forecast exog values
        r   r   N)rx   rG   rl   r5   r   r   r   r  r   r  r  r$  r  )r}   r   r   r   r  rN   r   rP   rz   r,   r  r  exog_ar   r   r   s                   r7   _static_predictzAutoReg._static_predict  sV   : O	z"Haq)*++ !Y&''D==59,cAg	.ABBFAD))FFHH+1%#'/+B!!!fl1o%'''(J	a<<((E37CHHH00(KKY	=9::
$$Za'8I3OOOr9   3int | str | datetime.datetime | pd.Timestamp | Nonedtuple[np.ndarray, np.ndarray | pd.DataFrame | None, np.ndarray | pd.DataFrame | None, int, int, int]c                   t          |d          }t          |t          j                  sJ t          |t          j                  r|}nt          |ddd          }t          |t          j                  r|}nt          |ddd          }|dn|}|| j        d         n|}|                     ||          \  }}}}	||||||fS )	Nr   rN   r3   T)r   r[   r   r   )r   rg   r5   ndarrayr  r  r  _get_prediction_index)
r}   r   rN   r   r   r   _exog	_exog_oosr  _s
             r7   _prepare_predictionzAutoReg._prepare_prediction  s     FH--&"*-----dBL)) 	DEEtV!dCCCEh-- 	P II"8Za$OOOI]!$dk"oo#!%!;!;E3!G!GsGQuiW<<r9   c                   t          |t          t          t          j        t
          j        t          j        f          r|                     |          \  }}}||z  }n|du rd}nt          |          }|dk     rt          d          |S )NTr   zMDynamic prediction cannot begin prior to the first observation in the sample.)rg   rT   bytesr  	TimestampdtdatetimePeriod_get_index_locr/   r>   )r}   r  r   dynamic_locr0  s        r7   _parse_dynamiczAutoReg._parse_dynamic  s    c5",RYG
 
 
	' !% 3 3G < <KA5 KK__KKg,,K ??3   r9   
bool | intc           	     p   |                      |||||          \  }}}}}}| j        ||t          d          | j        |I|j        | j        j        k    r4d}t          |                    |j        | j        j                            |a|j        d         | j        j        d         k    r@d}t          |                    |j        d         | j        j        d                             |dk    r|t          d          |A||j        d         k    r0d}t          |                    ||j        d                             t          |t                    r|r| j        dk    r|                     ||||||          S | 	                    ||          }| 
                    |||||||          S )	a  
        In-sample prediction and out-of-sample forecasting.

        Parameters
        ----------
        params : array_like
            The fitted model parameters.
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out-of-sample prediction. Default is the last observation in
            the sample. Unlike standard python slices, end is inclusive so
            that all the predictions [start, start+1, ..., end-1, end] are
            returned.
        dynamic : {bool, int, str, datetime, Timestamp}, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Prior to this observation, true endogenous values
            will be used for prediction; starting with this observation and
            continuing through the end of prediction, forecasted endogenous
            values will be used instead. Datetime-like objects are not
            interpreted as offsets. They are instead used to find the index
            location of `dynamic` which is then used to to compute the offset.
        exog : array_like
            A replacement exogenous array.  Must have the same shape as the
            exogenous data array used when the model was created.
        exog_oos : array_like
            An array containing out-of-sample values of the exogenous variable.
            Must has the same number of columns as the exog used when the
            model was created, and at least as many rows as the number of
            out-of-sample forecasts.

        Returns
        -------
        predictions : {ndarray, Series}
            Array of out of in-sample predictions and / or out-of-sample
            forecasts.
        NzWexog and exog_oos cannot be used when the model does not contains exogenous regressors.z]The shape of exog {0} must match the shape of the exog variable used to create the model {1}.r   z~The number of columns in exog_oos ({0}) must match the number of columns  in the exog variable used to create the model ({1}).r   zAexog_oos must be provided when producing out-of-sample forecasts.z}start and end indicate that {0} out-of-sample predictions must be computed. exog_oos has {1} rows but must have at least {0}.)r1  rN   r>   rl   formatrg   rM   r   r'  r:  r  )	r}   r   r   r   r  rN   r   r  msgs	            r7   predictzAutoReg.predict  s   j 7;6N6ND(E37
 7
3hsG 9$"2h6J:   Y"DJ$)/$A$AB  !DJ	!H!HIII$N1%);;;. 
 !JJx~a0$)/!2DEE   {{x/ /   %'HN14E*E*E2 
 !GX^A5F!G!GHHHw%% 	g 	$,!:K:K''sGT8   %%gu55$$E3$
 
 	
r9   )rC   FNNNrD   )rG   r   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rQ   rS   rT   rE   rU   rF   rM   r0   r   r0   rQ   r0   r   r0   rM   )r0   rU   )r0   r/   )r0   r   )r0   r   )rH   rI   rP   rQ   r0   r   )r   NF)r   rT   r   r   r   rM   r0   r   )r   r   r0   r-   )r   r   r0   r   )r   r/   r   r   r0   r-   )
r   r-   r   r/   r   r/   r   r/   r0   r   )r   r   r   r/   r   r/   r  r/   r  r/   rN   r  r   r  r0   r   )r   r   r  r/   r   r   r0   r-   )r   r   r   r/   r   r/   r  r/   rN   r  r   r  r0   r   )r   r   rN   r   r   r   r   r(  r   r(  r0   r)  NNFNN)r   r   r   r(  r   r(  r  r;  rN   rO   r   rO   r0   r   )!__name__
__module____qualname____doc____annotations__ra   propertyr   rP   rJ   rL   rE   rR   r   r{   r   rv   ry   r   r   r   r   r   r   r   r  r  r$  r'  r1  r:  r?  __classcell__r   s   @r7   r+   r+   b   s)        ] ]~  /2#' $!C+ 6:C+ C+ C+ C+ C+ C+ C+ C+J * * * X*
    X    X    X J J J XJ    X       X        X    &% &% &% &%P8& 8& 8& 8&x $*.	V* V* V* V* V*p@ @ @ @   (! ! ! !&4 4 4 4() ) ) )    2 2 2 2*<O <O <O <O|   "4P 4P 4P 4Pl= = = =<  0 FJCG##''+f
 f
 f
 f
 f
 f
 f
 f
 f
r9   c                      e Zd ZdZd ZdS )r*   z
    The AR class has been removed and replaced with AutoReg

    See Also
    --------
    AutoReg
        The replacement for AR that improved deterministic modeling
    c                     t          d          )NzXAR has been removed from statsmodels and replaced with statsmodels.tsa.ar_model.AutoReg.NotImplementedErrorr}   argskwargss      r7   ra   zAR.__init__  s    !0
 
 	
r9   NrE  rF  rG  rH  ra   r   r9   r7   r*   r*     s-         
 
 
 
 
r9   c                      e Zd ZdZd ZdS )	ARResultszX
    Removed and replaced by AutoRegResults.

    See Also
    --------
    AutoReg
    c                     t          d          )NzNAR and ARResults have been removed and replaced by AutoReg And AutoRegResults.rO  rQ  s      r7   ra   zARResults.__init__  s    !*
 
 	
r9   NrT  r   r9   r7   rV  rV    s-         
 
 
 
 
r9   rV  r   r   r  rN   r      c                      e Zd ZU dZi Zded<   	 	 	 	 d/ fd	Zd	 Zed
             Z	ed             Z
ed             Zed             Zed             Z e            d             Z e            d             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zd Zed             Zed             Zed             Zd0dZd Zd1dZd Z  e! e"e#j$        j        d                     	 d2d!            Z$	 d2d"Z%d3d$Z&d% Z' e(e)&          	 	 	 	 	 	 	 	 	 d4d)            Z*d5d+Z+d6d,Z,d7d-Z-d7d.Z. xZ/S )8r   a  
    Class to hold results from fitting an AutoReg model.

    Parameters
    ----------
    model : AutoReg
        Reference to the model that is fit.
    params : ndarray
        The fitted parameters from the AR Model.
    cov_params : ndarray
        The estimated covariance matrix of the model parameters.
    normalized_cov_params : ndarray
        The array inv(dot(x.T,x)) where x contains the regressors in the
        model.
    scale : float, optional
        An estimate of the scale of the model.
    use_t : bool, optional
        Whether use_t was set in fit
    summary_text : str, optional
        Additional text to append to results summary
    zdict[str, Any]_cacheN      ?F c                ~   t                                          ||||           i | _        || _        |j        | _        |j        j        d         | _        |j	        | _
        |j        | _        || _        | j        t          | j                  | _        nd| _        | j        j        | _        || _        || _        d S )Nr   )r`   ra   r[  _paramsrz   _nobsrG   rl   	_n_totobsr   	_df_modelr   _ar_lags_use_tr   _max_lagmodelrP   rx   cov_params_default_summary_text)	r}   rf  r   r   r   r   r   summary_textr   s	           r7   ra   zAutoRegResults.__init__  s     	(=uEEEZ
*1-=$..DMMDM*.",)r9   c                "    || _         || _        dS )aA  
        Initialize (possibly re-initialize) a Results instance.

        Parameters
        ----------
        model : Model
            The model instance.
        params : ndarray
            The model parameters.
        **kwargs
            Any additional keyword arguments required to initialize the model.
        N)r_  rf  )r}   rf  r   rS  s       r7   r   zAutoRegResults.initialize  s     


r9   c                    | j         S )r   )rc  r   s    r7   r   zAutoRegResults.ar_lags  s     }r9   c                    | j         S )zThe estimated parameters.)r_  r   s    r7   r   zAutoRegResults.params  r   r9   c                    | j         S )z-The degrees of freedom consumed by the model.)rb  r   s    r7   r   zAutoRegResults.df_model  r   r9   c                     | j         | j        z
  S )z2The remaining degrees of freedom in the residuals.)rz   rb  r   s    r7   df_residzAutoRegResults.df_resid  s     y4>))r9   c                    | j         S )zT
        The number of observations after adjusting for losses due to lags.
        )r`  r   s    r7   rz   zAutoRegResults.nobs  s    
 zr9   c                @    d| j         z  t          | j                  z  S )Nr\  )rz   r8   r   r   s    r7   r   zAutoRegResults.sigma2  s    TY!4!444r9   c                    | j         S N)r   r   s    r7   r   zAutoRegResults.scale  s
    {r9   c                r    t          j        t          j        |                                                     S )a  
        The standard errors of the estimated parameters.

        If `method` is 'cmle', then the standard errors that are returned are
        the OLS standard errors of the coefficients. If the `method` is 'mle'
        then they are computed using the numerical Hessian.
        )r5   sqrtdiagr   r   s    r7   bsezAutoRegResults.bse  s(     wrwt0011222r9   c                R    t          j        | j        | j        | j        dz             S )z
        Akaike Information Criterion using Lutkepohl's definition.

        :math:`-2 llf + \ln(nobs) (1 + df_{model})`
        r   )r   aicr   rz   r   r   s    r7   ry  zAutoRegResults.aic  s$      49dma6GHHHr9   c                R    t          j        | j        | j        | j        dz             S )z
        Hannan-Quinn Information Criterion using Lutkepohl's definition.

        :math:`-2 llf + 2 \ln(\ln(nobs)) (1 + df_{model})`
        r   )r   hqicr   rz   r   r   s    r7   r{  zAutoRegResults.hqic+  s$     !$(DIt}q7HIIIr9   c                D    | j         }| j        }| j        ||z   ||z
  z  z  S )u   
        Final prediction error using Lütkepohl's definition.

        :math:`((nobs+df_{model})/(nobs-df_{model})) \sigma^2`
        )rz   r   r   )r}   rz   r   s      r7   fpezAutoRegResults.fpe;  s,     y={th4(?CDDr9   c                R    t          j        | j        | j        | j        dz             S )z
        Akaike Information Criterion with small sample correction

        :math:`2.0 * df_{model} * nobs / (nobs - df_{model} - 1.0)`
        r   )r   aiccr   rz   r   r   s    r7   r  zAutoRegResults.aiccG  s$     !$(DIt}q7HIIIr9   c                R    t          j        | j        | j        | j        dz             S )zb
        Bayes Information Criterion

        :math:`-2 llf + \ln(nobs) (1 + df_{model})`
        r   )r   bicr   rz   r   r   s    r7   r  zAutoRegResults.bicP  s$      49dma6GHHHr9   c                p    | j         }|j                                        }|| j        d         | j        z
  S )z-
        The residuals of the model.
        N)rf  rG   r   rx   fittedvalues)r}   rf  rG   s      r7   r   zAutoRegResults.resid^  s9    
 
##%%T_&&'$*;;;r9   c                @   | j         | j         ng }t          |          }t          j        | j        dz             }d|d<   | j        }| j        j        }||j        d         nd}| j	        ||z
  |z
  ||z
           }t          |          D ]\  }}	||          ||	<   |S )z6Returns poly repr of an AR, (1  -phi1 L -phi2 L^2-...)Nr   r   )rc  r   r5   r   re  rb  rf  rN   rl   r_  r  )
r}   r   k_ar	ar_paramsr   rN   k_exogr   r   r   s
             r7   	_lag_reprzAutoRegResults._lag_reprg  s    #'=#<$--"7||HT]Q.//		!>z"&"2Aho6F9JJK(( 	( 	(FAs$QiZIcNNr9   c                    |                                  }|j        d         dk    rt          j        d          S t          j        |          dz  S )z
        The roots of the AR process.

        The roots are the solution to
        (1 - arparams[0]*z - arparams[1]*z**2 -...- arparams[p-1]*z**k_ar) = 0.
        Stability requires that the roots in modulus lie outside the unit
        circle.
        r   r   r+  )r  rl   r5   r   roots)r}   lag_reprs     r7   r  zAutoRegResults.rootsu  sH     >>##>!!!8A;;x!!R''r9   c                n    | j         }t          j        |j        |j                  dt          j        z  z  S )z
        Returns the frequency of the AR roots.

        This is the solution, x, to z = abs(z)*exp(2j*np.pi*x) where z are the
        roots.
        r3   )r  r5   arctan2imagrealr   )r}   zs     r7   arfreqzAutoRegResults.arfreq  s,     Jz!&!&))QY77r9   c                Z    | j                             | j                  | j        d         S )z
        The in-sample predicted values of the fitted AR model.

        The `k_ar` initial values are computed via the Kalman Filter if the
        model is fit by `mle`.
        N)rf  r?  r   rx   r   s    r7   r  zAutoRegResults.fittedvalues  s)     z!!$+..t/@/@AAr9   c                0   ddl m} t          |dd          }t          |dd          }|| j        n|}| j        j        d         }|t          |dz  d	          } || j        |d
|          }g d}|dk    rt          dd|z
            }nSt          j	        t          j
        d|dz             |z
  dt          j                  }|                    t                    }||d<   t          j        d|dz   d          }t          j        |||          S )at  
        Ljung-Box test for residual serial correlation

        Parameters
        ----------
        lags : int
            The maximum number of lags to use in the test. Jointly tests that
            all autocorrelations up to and including lag j are zero for
            j = 1, 2, ..., lags. If None, uses min(10, nobs // 5).
        model_df : int
            The model degree of freedom to use when adjusting computing the
            test statistic to account for parameter estimation. If None, uses
            the number of AR lags included in the model.

        Returns
        -------
        output : DataFrame
            DataFrame containing three columns: the test statistic, the
            p-value of the test, and the degree of freedom used in the test.

        Notes
        -----
        Null hypothesis is no serial correlation.

        The the test degree-of-freedom is 0 or negative once accounting for
        model_df, then the test statistic's p-value is missing.

        See Also
        --------
        statsmodels.stats.diagnostic.acorr_ljungbox
            Ljung-Box test for serial correlation.
        r   )acorr_ljungboxrH   Tr\   r   N   
   F)rH   	boxpiercemodel_df)z	Ljung-Boxz
LB P-valueDFr   dfLagnamer   r]   )statsmodels.stats.diagnosticr  r   r   r   rl   minr   r5   cliprk   infastyper/   r  r  r  )	r}   rH   r  r  nobs_effective
test_statscolsr  r]   s	            r7   test_serial_correlationz&AutoRegResults.test_serial_correlation  s;   D 	@?????ft444Hj4@@@$,$44==()!,<~*B//D#^J	
 
 

 100199QH%%BB1dQh//(:ArvFFB3B
4a666|JEBBBBr9   c                ^    ddl m} g d}t          j         || j                  |          S )a  
        Test for normality of standardized residuals.

        Returns
        -------
        Series
            Series containing four values, the test statistic and its p-value,
            the skewness and the kurtosis.

        Notes
        -----
        Null hypothesis is normality.

        See Also
        --------
        statsmodels.stats.stattools.jarque_bera
            The Jarque-Bera test of normality.
        r   )jarque_bera)zJarque-BeraP-valueSkewnessKurtosisr   )statsmodels.stats.stattoolsr  r  r  r   )r}   r  r]   s      r7   test_normalityzAutoRegResults.test_normality  sB    ( 	<;;;;;BBByTZ00>>>>r9   c                   ddl m} t          |dd          }| j        j        d         }|t          |dz  d          }g }t          d	|d	z             D ]8} || j        |
          }|                    |d         |d	         |g           9t          j	        d	|d	z   d          }g d}t          j
        |||          S )a  
        ARCH-LM test of residual heteroskedasticity

        Parameters
        ----------
        lags : int
            The maximum number of lags to use in the test. Jointly tests that
            all squared autocorrelations up to and including lag j are zero for
            j = 1, 2, ..., lags. If None, uses lag=12*(nobs/100)^{1/4}.

        Returns
        -------
        Series
            Series containing the test statistic and its p-values.

        See Also
        --------
        statsmodels.stats.diagnostic.het_arch
            ARCH-LM test.
        statsmodels.stats.diagnostic.acorr_lm
            LM test for autocorrelation.
        r   )het_archrH   Tr\   Nr  r  r   )nlagsr  r  )zARCH-LMr  r  r  )r  r  r   r   rl   r  r   rh   r  r  r  )	r}   rH   r  r  outr   r   r]   r  s	            r7   test_heteroskedasticityz&AutoRegResults.test_heteroskedasticity  s    . 	:99999ft444)!,<~*B//DD1H%% 	. 	.C(4:S111CJJAA,----a666+++|CU;;;;r9   c                   ddl m}  |dg          }t                      }|                                 }|j        |j        dk             }d t          |j                                                  D             }d}|j	        d         rZ ||dgt          |j                  z   dd|	          }|j                            |           |j                            |           |                                 }d
} ||j        gt          |j                  dd|	          }|j                            |           |j                            |           |                                 }	d t          |	j                                                  D             }d} ||dgt          |	j                  z   dd|	          }|j                            |           |S )a=  
        Returns a summary containing standard model diagnostic tests

        Returns
        -------
        Summary
            A summary instance with panels for serial correlation tests,
            normality tests and heteroskedasticity tests.

        See Also
        --------
        test_serial_correlation
            Test models residuals for serial correlation.
        test_normality
            Test models residuals for deviations from normality.
        test_heteroskedasticity
            Test models residuals for conditional heteroskedasticity.
        r   SimpleTabler]  c                &    g | ]\  }}|d z   g|z   S r   r   r   r   rows      r7   r   z5AutoRegResults.diagnostic_summary.<locals>.<listcomp>-  s&    LLLFAs1q5'C-LLLr9   )%10d%10.3fr  r  r  zTest of No Serial Correlationr)headerstitleheader_align	data_fmts)r  r  r  r  zTest of Normalityc                &    g | ]\  }}|d z   g|z   S r  r   r  s      r7   r   z5AutoRegResults.diagnostic_summary.<locals>.<listcomp>E  s3     
 
 
$aQUGcM
 
 
r9   z$Test of Conditional Homoskedasticity)statsmodels.iolib.tabler  r   r  r   r  r  valuestolistrl   r   r   tablesrh   r  r]   r  )
r}   r  spacersmryscr  r  tabjbarch_lms
             r7   diagnostic_summaryz!AutoRegResults.diagnostic_summary  s   & 	877777bT""yy))++VBEAILLi	8H8H8J8J.K.KLLL8	8A; 		'+$rz"2"225 #  C Ks###Kv&&&  ""<	kYKNN%
 
 
 	36"""..00
 
(1'.2G2G2I2I(J(J
 
 
 9	kGd7?3338
 
 
 	3r9   r   c                L    | j                             | j        |||||          S )NrX  )rf  r?  r_  )r}   r   r   r  rN   r   s         r7   r?  zAutoRegResults.predictS  s7     z!!L " 
 
 	
r9   c                t   |                      |||||          }t          j        || j                  }t          j        |t          j        |          <   |dn|}|| j        j        d         n|}| j                            ||          \  }}}	}|	dk    r]| 	                                }
t          |
t          j        d          |	          }| j        t          j        |dz            z  ||	 d<   t          |t          j                  rt          j        ||j                  }t#          ||          S )	aY  
        Predictions and prediction intervals

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out-of-sample prediction. Default is the last observation in
            the sample. Unlike standard python slices, end is inclusive so
            that all the predictions [start, start+1, ..., end-1, end] are
            returned.
        dynamic : {bool, int, str, datetime, Timestamp}, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Prior to this observation, true endogenous values
            will be used for prediction; starting with this observation and
            continuing through the end of prediction, forecasted endogenous
            values will be used instead. Datetime-like objects are not
            interpreted as offsets. They are instead used to find the index
            location of `dynamic` which is then used to to compute the offset.
        exog : array_like
            A replacement exogenous array.  Must have the same shape as the
            exogenous data array used when the model was created.
        exog_oos : array_like
            An array containing out-of-sample values of the exogenous variable.
            Must has the same number of columns as the exog used when the
            model was created, and at least as many rows as the number of
            out-of-sample forecasts.

        Returns
        -------
        PredictionResults
            Prediction results with mean and prediction intervals
        rX  Nr   r+  r   )rH   r3   r   )r?  r5   	full_liker   r  isnanrf  r  r-  r  r!   onescumsumrg   r  r  r]   r#   )r}   r   r   r  rN   r   meanmean_varr0  oosr  mas               r7   get_predictionzAutoRegResults.get_prediction`  s'   V ||S'x  
 
 <dk22#%6$ ]'*{dj##z77sCC1c177((IBGAJJS999B"kBIb!e,<,<<HcTUUOdBI&& 	=y<<<H x000r9   r   c                    | j         j        j        j        d         }t	          |t
          t          j        f          r	||z   dz
  }n|}|                     ||d|          S )a  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : {int, str, datetime}, default 1
            If an integer, the number of steps to forecast from the end of the
            sample. Can also be a date string to parse or a datetime type.
            However, if the dates index does not have a fixed frequency,
            steps must be an integer.
        exog : {ndarray, DataFrame}
            Exogenous values to use out-of-sample. Must have same number of
            columns as original exog data and at least `steps` rows

        Returns
        -------
        array_like
            Array of out of in-sample predictions and / or out-of-sample
            forecasts.

        See Also
        --------
        AutoRegResults.predict
            In- and out-of-sample predictions
        AutoRegResults.get_prediction
            In- and out-of-sample predictions and confidence intervals
        r   r   F)r   r   r  r   )	rf  r:   rj   rl   rg   r/   r5   integerr?  )r}   r   rN   r   r   s        r7   forecastzAutoRegResults.forecast  s`    8 
*03ec2:.// 	%-!#CCC||%S%$|OOOr9   c           	        ddl m}m}	  |              |	||          }|dn|}|| j        j        d         n|}| j                            ||          \  }
}
}}
|                    d          }|j        }|s-|r+t          |t          j
                  r|j        | d         }n|st          d          |                    |dd	           |r|t          j        |                    |                    }|| ddf         || dd
f         }}d
|z
  dd}|                                d                                         }|                    || d         ||dd|d
           |                    d           |S )z&Shared helper for plotting predictionsr   _import_mplcreate_mpl_figNr+  o   zCin_sample is False but there are noout-of-sample forecasts to plot.r3   Forecast)zorderlabelr   z.0%z confidence intervalgray      ?)coloralphar  r  best)r   )statsmodels.graphics.utilsr  r  rf  r  r-  add_subplotpredicted_meanrg   r  r  ilocr>   plotr5   r   conf_int	get_lines	get_xdatafill_betweenlegend)r}   predictionsr   r   r  r   figfigsizer  r  r0  r  axr  cilowerupperr  r,   s                      r7   _plot_predictionsz AutoRegResults._plot_predictions  s    	KJJJJJJJnS'**]'*{dj##z77sCC1c1__S!!) 	S 	$	** (y#' 	3   	Qj111 	5$K007788BsdeeQh<SDEE1H5E5y::::Er",,..AOO3$%%     			f	
r9   )predict_params皙?Tc
           	     l    |                      |||||          }
|                     |
||||||	          S )a1  
        Plot in- and out-of-sample predictions

        Parameters
        ----------
%(predict_params)s
        alpha : {float, None}
            The tail probability not covered by the confidence interval. Must
            be in (0, 1). Confidence interval is constructed assuming normally
            distributed shocks. If None, figure will not show the confidence
            interval.
        in_sample : bool
            Flag indicating whether to include the in-sample period in the
            plot.
        fig : Figure
            An existing figure handle. If not provided, a new figure is
            created.
        figsize: tuple[float, float]
            Tuple containing the figure size values.

        Returns
        -------
        Figure
            Figure handle containing the plot.
        rX  )r  r  )r}   r   r   r  rN   r   r  r   r  r  r  s              r7   plot_predictzAutoRegResults.plot_predict  sS    J ))S'x * 
 
 %%UIsG
 
 	
r9   r  c                   ddl m}m}  |              |||          }| j        }|                    d          }t          | j        j        d          rD| j        j        8| j        j        j        	                                }|| j        j
        d         }n3| j        j
        }	|	t          j        | j        j        d                   z   }|t          j        | j                  z  }
|                    ||
           |                    d|d         |d         d           |                    |d         |d                    |                    d	           |
t          j        |                    }|                    d
          }|                    |dd           t-          |
          }d}t          j        |d         |d                   }|                    | ||          d           |                    |t1          j        |          d           |                    |           |                                 |                    d           |                    d          }ddlm}  ||
d|           |                    d           |                    d          }ddlm}  ||||           |                    d           |                    dd           |S )aO  
        Diagnostic plots for standardized residuals

        Parameters
        ----------
        lags : int, optional
            Number of lags to include in the correlogram. Default is 10.
        fig : Figure, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the 2x2 grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        Produces a 2x2 plot grid with the following plots (ordered clockwise
        from top left):

        1. Standardized residuals over time
        2. Histogram plus estimated density of standardized residuals, along
           with a Normal(0,1) density plotted for reference.
        3. Normal Q-Q plot, with Normal reference line.
        4. Correlogram

        See Also
        --------
        statsmodels.graphics.gofplots.qqplot
        statsmodels.graphics.tsaplots.plot_acf
        r   r     datesNr+  r  )r  zStandardized residual   THist)densityr  )g\(\g\(\@r   KDE)r  zN(0,1)z Histogram plus estimated density   )qqplots)liner  z
Normal Q-Q   )plot_acf)r  rH   Correlogram) r  r  r  r   r  ri   rf  r:   r  	_mpl_reprrP   r5   rk   rl   ru  r   r  hlinesset_xlim	set_titler  histr   linspacer   pdfr  statsmodels.graphics.gofplotsr  statsmodels.graphics.tsaplotsr  set_ylim)r}   rH   r  r  r  r  r   r  r,   rP   	std_residstd_resid_nonmissingkdexlimr  r  s                   r7   plot_diagnosticszAutoRegResults.plot_diagnostics  s   @ 	KJJJJJJJnS'**
 __S!!4:?G,, 	;1L
%//11A$*&(()AA
,IBIdj&6q&9:::ABGDK000	
9
		!QqT1R5	,,,
AaD!B%   
,---
  )28E??);<__S!!
$d&AAA9%%$KQa))
33q66'''
48A;;h///
D
		
7888 __S!!888888ysr****
\""" __S!!::::::2D))))
]###
B
r9   c           	        | j         }|j        j        dz   }d}| j        }| j        j        K| j        j        }||                             d          g}|d|d                             d          z   gz  }n5t          |          t          t          | j        j	                            g}|j        j        }| j         j
        rd|z   }| j        "t          | j                  | j        k     rd|z   }| j         j        |d	z  }d
| j         d}t          | j         j                  }	d|	gfd||z   gfd|gfddd|d         gfd|d         gfg}
dt          t          | j         j                            gfdd| j        z  gfdd| j        dz  z  gfdd| j        z  gfdd| j        z  gfdd| j        z  gfg}t+                      }|                    | |
||           |                    | |d           dd lm} | j        rd! t5          d| j        dz             D             }|}| j        }| j        }t;          j        |          }t;          j        |j         |j!        ||f          } |d" |D             g d#d$|%          }|j"        #                    |           | j$        r.|j%        |j%        ng }|&                    || j$        gz              |S )&a  
        Summarize the Model

        Parameters
        ----------
        alpha : float, optional
            Significance level for the confidence intervals.

        Returns
        -------
        smry : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        z Model ResultszConditional MLENz%m-%d-%Yz- r+  zSeas. zRestr. z-X()zDep. Variable:zModel:zMethod:)zDate:N)zTime:NzSample:r   r]  r   zNo. Observations:zLog Likelihoodz%#5.3fzS.D. of innovationsr  AICBICHQIC)gleftgrightr  F)r  r   r  c                    g | ]}d |z  S )zAR.%dr   r   s     r7   r   z*AutoRegResults.summary.<locals>.<listcomp>  s    HHHqw{HHHr9   c                b    g | ],}d |d         z  d|d         z  d |d         z  d |d         z  f-S )z%17.4fr   z%+17.4fjr   r3      r   )r   r  s     r7   r   z*AutoRegResults.summary.<locals>.<listcomp>  s\         !3q6)"SV+ 3q6) 3q6)	  r9   )z            Realz         Imaginaryz         Modulusz        FrequencyRoots)r  r  stubs)'rf  r   rE  rx   r:   r  strftimerT   r   rj   rL   r   re  rN   r   rG   r   r   ry  r  r{  r   add_table_2colsadd_table_paramsr  r  r   r  r  r5   abscolumn_stackr  r  r  rh   rh  	extra_txtadd_extra_txt)r}   r  rf  r  methodr   r  sampleorderdep_nametop_left	top_rightr  r  arstubsr(  r  r=   modulusr:   roots_tabler.  s                         r7   summaryzAutoRegResults.summaryt  sc   & 
(+;;"9?&IOEEl++J778FteBi00<<<==FF%jj#c$)*>&?&?"@"@AF(: 	%u$E<#DL(9(9DM(I(I%E:?&TME$DM$$$tz-..z*'!$&)
 !3s4:+;'<'<#=#=">?48 345"XS0@%@$ABX()*X()*h*+,
	 yy% 	 	
 	
 	
 	d%u=== 	877777= 	,HHE!T]Q5F,G,GHHHGEJE;DfUmmG?EJ
GT#JKKD%+   $     #  K( K{+++ 	A*..*D"IyD,>+??@@@r9   c                x   | j         }	 |j        }|bt          |t          j        t          j        f          r|j        }nt          j        |j	        d                   }|
                    |          }t          ||j        |j        |j        ||j        |j        |d	  	        }n># t"          $ r1}	d}
|
f|	j        z   |	_        |	                    |	j                  d}	~	ww xY w|j        du |j        du k    r%|j        t-          d          t-          d          |j        I|j        j	        d         |j        j	        d         k    r#t-          d	|j        j	        d          d
          |r|i n|} |j        di |S d}t1          || j        | j        | j        | j        |          }t;          |          S )a'  
        Apply the fitted parameters to new data unrelated to the original data

        Creates a new result object using the current fitted parameters,
        applied to a completely new dataset that is assumed to be unrelated to
        the model's original data. The new results can then be used for
        analysis or forecasting.

        Parameters
        ----------
        endog : array_like
            New observations from the modeled time-series process.
        exog : array_like, optional
            New observations of exogenous regressors, if applicable.
        refit : bool, optional
            Whether to re-fit the parameters, using the new dataset.
            Default is False (so parameters from the current results object
            are used to create the new results object).
        fit_kwargs : dict, optional
            Keyword arguments to pass to `fit` (if `refit=True`).

        Returns
        -------
        AutoRegResults
            Updated results object containing results for the new dataset.

        See Also
        --------
        AutoRegResults.append
        statsmodels.tsa.statespace.mlemodel.MLEResults.apply

        Notes
        -----
        The `endog` argument to this method should consist of new observations
        that are not necessarily related to the original model's `endog`
        dataset.

        Care is needed when using deterministic processes with cyclical
        components such as seasonal dummies or Fourier series. These
        deterministic components will align to the first observation
        in the data and so it is essential that any new data have the
        same initial period.

        Examples
        --------
        >>> import pandas as pd
        >>> from statsmodels.tsa.ar_model import AutoReg
        >>> index = pd.period_range(start='2000', periods=3, freq='Y')
        >>> original_observations = pd.Series([1.2, 1.5, 1.8], index=index)
        >>> mod = AutoReg(original_observations, lags=1, trend="n")
        >>> res = mod.fit()
        >>> print(res.params)
        y.L1    1.219512
        dtype: float64
        >>> print(res.fittedvalues)
        2001    1.463415
        2002    1.829268
        Freq: A-DEC, dtype: float64
        >>> print(res.forecast(1))
        2003    2.195122
        Freq: A-DEC, dtype: float64

        >>> new_index = pd.period_range(start='1980', periods=3, freq='Y')
        >>> new_observations = pd.Series([1.4, 0.3, 1.2], index=new_index)
        >>> new_res = res.apply(new_observations)
        >>> print(new_res.params)
        y.L1    1.219512
        dtype: float64
        >>> print(new_res.fittedvalues)
        1981    1.707317
        1982    0.365854
        Freq: A-DEC, dtype: float64
        >>> print(new_res.forecast(1))
        1983    1.463415
        Freq: A-DEC, dtype: float64
        Nr   F)rH   rJ   rL   rN   rP   rR   rE   rF   zAn exception occured during the creation of the cloned AutoReg instance when applying the existing model specification to the new data. The original traceback appears below.zFexog must be provided when the original model contained exog variableszHexog must be None when the original model did not contain exog variablesr   zSThe number of exog variables passed must match the original number of exog values (r  znParameters and standard errors were estimated using a different dataset and were then applied to this dataset.)r   ri  r   )rf  rE   rg   r  r  r  r]   r5   rk   rl   applyr+   r   rJ   rL   rP   rR   	ExceptionrR  with_traceback__traceback__rN   r>   r   r   r   rg  r   r   r   )r}   rG   rN   refit
fit_kwargsexistingrE   r]   modexcerrorsmry_txtr   s                r7   r;  zAutoRegResults.apply  s+   Z :	8$2M(ebi%>?? 6!KEEIek!n55E - 3 3E : :%n!*",+
 
 
CC  	8 	8 	8!  x#(*CH$$S%6777	8 H(-4"788}( %   !  
 M%#A&#(.*;;;D*2-*=a*@D D D    	))1zJ37((Z(((= 	 K#&*!
 
 
 %S)))s   BB& &
C!0,CC!c                Z    d fd	} j         }|j        du }||du k    r|rd}nd}t          |          t          |j        j        t          j        t          j        f          r ||j        j        |d          }n& ||j	        t          j        |          dd          }t          |j        j        t          j        t          j        f          r ||j        j        |d	          }n(|& ||j        t          j        |          dd          }                     ||||
          S )a.  
        Append observations to the ones used to fit the model

        Creates a new result object using the current fitted parameters
        where additional observations are appended to the data used
        to fit the model. The new results can then be used for
        analysis or forecasting.

        Parameters
        ----------
        endog : array_like
            New observations from the modeled time-series process.
        exog : array_like, optional
            New observations of exogenous regressors, if applicable.
        refit : bool, optional
            Whether to re-fit the parameters, using the new dataset.
            Default is False (so parameters from the current results object
            are used to create the new results object).
        fit_kwargs : dict, optional
            Keyword arguments to pass to `fit` (if `refit=True`).

        Returns
        -------
        AutoRegResults
            Updated results object containing results for the new dataset.

        See Also
        --------
        AutoRegResults.apply
        statsmodels.tsa.statespace.mlemodel.MLEResults.append

        Notes
        -----
        The endog and exog arguments to this method must be formatted in the
        same way (e.g. Pandas Series versus Numpy array) as were the endog
        and exog arrays passed to the original model.

        The endog argument to this method should consist of new observations
        that occurred directly after the last element of endog. For any other
        kind of dataset, see the apply method.

        Examples
        --------
        >>> import pandas as pd
        >>> from statsmodels.tsa.ar_model import AutoReg
        >>> index = pd.period_range(start='2000', periods=3, freq='Y')
        >>> original_observations = pd.Series([1.2, 1.4, 1.8], index=index)
        >>> mod = AutoReg(original_observations, lags=1, trend="n")
        >>> res = mod.fit()
        >>> print(res.params)
        y.L1    1.235294
        dtype: float64
        >>> print(res.fittedvalues)
        2001    1.482353
        2002    1.729412
        Freq: A-DEC, dtype: float64
        >>> print(res.forecast(1))
        2003    2.223529
        Freq: A-DEC, dtype: float64

        >>> new_index = pd.period_range(start='2003', periods=3, freq='Y')
        >>> new_observations = pd.Series([2.1, 2.4, 2.7], index=new_index)
        >>> updated_res = res.append(new_observations)
        >>> print(updated_res.params)
        y.L1    1.235294
        dtype: float64
        >>> print(updated_res.fittedvalues)
        dtype: float64
        2001    1.482353
        2002    1.729412
        2003    2.223529
        2004    2.594118
        2005    2.964706
        Freq: A-DEC, dtype: float64
        >>> print(updated_res.forecast(1))
        2006    3.335294
        Freq: A-DEC, dtype: float64
        Tc                   ddl m} t          |           }t          ||          st	          | d| d|j         d          |st          j        | |g          S t          |           }|t          |          z   dz
  }
j	        
                    ||          \  }}}}	 ||	||           t          j        | |gd          S )	Nr   )_check_indexz  must have the same type as the z& used to originally create the model (z).r   )r  r4   )#statsmodels.tsa.statespace.mlemodelrH  typerg   rn   rE  r5   concatenater   rf  r-  r  concat)orignewr  
use_pandasrH  typr   r   r0  	append_ixr}   s             r7   _checkz%AutoRegResults.append.<locals>._check  s   HHHHHHt**Cc3''  E ET E E47LE E E    3~tSk222IIE#c(("Q&C!%!A!A%!M!MAq!YLCt44449dC[q1111r9   Nz>Original model does not contain exog data but exog data passedz5Original model has exog data but not exog data passedrG   F)rO  rN   )r?  r@  )T)rf  rN   r>   rg   r:   rj   r  r  r  rG   r5   r   	orig_exogr;  )	r}   rG   rN   r?  r@  rR  rA  no_exogerrs	   `        r7   rh   zAutoRegResults.appendi  s]   `	2 	2 	2 	2 	2 	2" :-4'tt|$$ N 
 NS//!hm.BL0IJJ 	F8=3UGDDEEF
5 1 17u  E hm-	2</HII 	6(-14@@DD6rz$//U  D zz%UzzJJJr9   )Nr\  Fr]  )NNrs  rD  )r   N)	NNFNNr  TNN)r  NN)r  )NFN)0rE  rF  rG  rH  r[  rI  ra   r   rJ  r   r   r   ro  rz   r   r   r   r   rw  ry  r{  r}  r  r  r   r  r  r  r  r  r  r  r  r   r   r+   r?  r  r  r  r   _predict_paramsr  r  r9  r;  rh   rK  rL  s   @r7   r   r     s         ,  F #* * * * * *4      X   X   X * * X*   X ^5 5 5 ^   3 3 ^3 I I ^I J J ^J 	E 	E ^	E J J ^J I I ^I < < ^<   ( ( ^(  	8 	8 ^	8 B B ^B8C 8C 8C 8Ct? ? ?2#< #< #< #<J= = =~ X 7BBCCGK

 

 

 DC

 HL:1 :1 :1 :1x!P !P !P !PF/ / /b \111 )
 )
 )
 21)
VV V V Vpd d d dLM* M* M* M*^xK xK xK xK xK xK xK xKr9   r   c                      e Zd Zi Z ej        ej        j        e          Zi Z	 ej        ej        j
        e	          Z
dS )r   N)rE  rF  rG  _attrswrapunion_dictsr"   TimeSeriesResultsWrapper_wrap_attrs_methods_wrap_methodsr   r9   r7   r   r     sX        F"$"*6 K H$D$*8( MMMr9   r   rJ   rL   rN   rP   rR   rS   rF      )auto_reg_paramsr  FrC   rD   rJ   r   c                   t          | |||||||	|
	  	        }|j        |j        j        d         nd}|j        |j        c}|j        d         |z
  |z
  }t          j        |j        d         t                    }g }d fd}|sd||||z   <   t          |dz             D ]}d	||||z   <   t          j	        |          s |
                    d |            f           @t          |dd|f                                                   }t          d
 t          d|dz             D                       }|sdn|}|
                    | |          f           nt          j        d|z  t
          j                  dddf         }|                    t
          j                  }t          j        |                              dd          }t          d          D ]8}|ddd|z  d|dz   z  f         dddddf         |ddd|z  d|dz   z  f<   9|ddd|f         }|D ]}|||||z   <   t          j	        |          s |
                    d |            f           @t          |dd|f                                                   }t          t          j        |          d         dz             }|sdn|}|
                    | |          f           dddd|         t+          |fd          }|d         d         }t          | |||||||	|
	  	        }t-          |||||          S )a  
    Autoregressive AR-X(p) model order selection.

    Parameters
    ----------
    endog : array_like
         A 1-d endogenous response variable. The independent variable.
    maxlag : int
        The maximum lag to consider.
    ic : {'aic', 'hqic', 'bic'}
        The information criterion to use in the selection.
    glob : bool
        Flag indicating where to use a global search  across all combinations
        of lags.  In practice, this option is not computational feasible when
        maxlag is larger than 15 (or perhaps 20) since the global search
        requires fitting 2**maxlag models.
%(auto_reg_params)s

    Returns
    -------
    AROrderSelectionResults
        A results holder containing the model and the complete set of
        information criteria for all models fit.

    Examples
    --------
    >>> from statsmodels.tsa.ar_model import ar_select_order
    >>> data = sm.datasets.sunspots.load_pandas().data['SUNACTIVITY']

    Determine the optimal lag structure

    >>> mod = ar_select_order(data, maxlag=13)
    >>> mod.ar_lags
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])

    Determine the optimal lag structure with seasonal terms

    >>> mod = ar_select_order(data, maxlag=13, seasonal=True, period=12)
    >>> mod.ar_lags
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])

    Globally determine the optimal lag structure

    >>> mod = ar_select_order(data, maxlag=13, glob=True)
    >>> mod.ar_lags
    array([1, 2, 9])
    r_  Nr   r   )dtypec                z   | j         }| j        }d|z  t          | j                  z  }| t	          j        dt          j        z  |z            dz   z  dz  }t          ||||          } t          t          j
        |           }t          t          j        |           }t          t          j        |           }|||fS )Nr\  r3   r   )rz   r   r   r   )rz   r   r8   r   r5   r   r   r	   r   r   ry  r  r{  )r   rz   r   r   r   ry  r  r{  s           r7   compute_icsz$ar_select_order.<locals>.compute_icsM  s    x<tgci000erva"%i&011A56:S
 
 
 ~1377~1377 3S99C~r9   c                    t          j        d         t          j        j        d         df                    } t	          j        | t          j        d                    }t          j        d         |dd          } |          S )z0Fake mod and results to handle no regressor caser   )rz   rG   rN   )r   rz   r   r   
k_constant)r	   rl   r5   r   r   r   )rB  r   r   re  r   s      r7   
ic_no_dataz#ar_select_order.<locals>.ic_no_data\  s    128QWQZO+D+D
 
 
 k#rx{{++!'!*#a
 
 
 {3r9   FTc              3     K   | ]}|V  d S rs  r   )r   r  s     r7   	<genexpr>z"ar_select_order.<locals>.<genexpr>p  s"      44q444444r9   r3   r+      r`  rY  )ry  r  r{  c                     | d                  S Nr   r   )r,   key_locs    r7   <lambda>z!ar_select_order.<locals>.<lambda>  s    AaDM r9   key)r+   rN   rl   rB   r   r5   r  rM   r   r   rh   r   r   tuplerk   int32viewuint8
unpackbitsreshapewherer   AROrderSelectionResults)rG   r   icglobrJ   rL   rN   rP   rR   rS   rF   full_modr"  r,   base_colselicsrh  r   r   rH   bitsmasksmaskselected_modelrB  re  rn  r   s                             @@@r7   ar_select_orderr     s   x 
 
 
H '/m&?HM""QE;DAqwqzE!F*H
'!'!*D
)
)
)CJLC  
  
  
  
  
  
   1,1Hx&(()vz"" 	1 	1A+/C8a<'(6#;; 

Azz||,---a111c6##''))C44E!QUOO44444D *11dDJJkk#../0000	1 yF"(333AAAtG<yy""}T""**2r22q 	 	A+/1q51A;3F0F+G44R4,DAEAQK''(( QQQZ  	1 	1D04C8f,,-6#;; 

Azz||,---a111c6##''))C$*Q.//D *11dDJJkk#../00001--b1G
1111
2
2
2CVAYN

 
 
C #3UHfEEEr9   c                      e Zd ZdZddZedd            Zedd            Zedd            Zedd            Z	edd            Z
edd            Zedd            Zedd            ZdS ) ry  zp
    Results from an AR order selection

    Contains the information criteria for all fitted model orders.
    rf  r+   r  >list[tuple[int | tuple[int, ...], tuple[float, float, float]]]rJ   r   rL   rM   rR   rQ   c                   || _         || _        || _        || _        || _        t          |d           }d |D             | _        t          |d           }d |D             | _        t          |d           }d |D             | _        d S )Nc                    | d         d         S )Nr   r   r   r  s    r7   ro  z2AROrderSelectionResults.__init__.<locals>.<lambda>      !Q r9   rp  c                &    i | ]\  }}||d          S r   r   r   rq  r   s      r7   
<dictcomp>z4AROrderSelectionResults.__init__.<locals>.<dictcomp>  "    555XS#S#a&555r9   c                    | d         d         S rm  r   r  s    r7   ro  z2AROrderSelectionResults.__init__.<locals>.<lambda>  r  r9   c                &    i | ]\  }}||d          S r  r   r  s      r7   r  z4AROrderSelectionResults.__init__.<locals>.<dictcomp>  r  r9   c                    | d         d         S )Nr   r3   r   r  s    r7   ro  z2AROrderSelectionResults.__init__.<locals>.<lambda>  s    1a r9   c                &    i | ]\  }}||d          S )r3   r   r  s      r7   r  z4AROrderSelectionResults.__init__.<locals>.<dictcomp>  s"    777hc3c3q6777r9   )	_model_icsrb   rc   rd   r   _aic_bic_hqic)	r}   rf  r  rJ   rL   rR   ry  r  r{  s	            r7   ra   z AROrderSelectionResults.__init__  s     	!S//00055555	S//00055555	c0011177$777


r9   r0   c                    | j         S )z:The model selected using the chosen information criterion.)r  r   s    r7   rf  zAROrderSelectionResults.model  r   r9   c                    | j         S )z4Flag indicating if a seasonal component is included.r   r   s    r7   rL   z AROrderSelectionResults.seasonal  r   r9   c                    | j         S )z*The trend included in the model selection.r   r   s    r7   rJ   zAROrderSelectionResults.trend  r   r9   c                    | j         S r   r   r   s    r7   rR   zAROrderSelectionResults.period  r   r9   "dict[int | tuple[int, ...], float]c                    | j         S )z
        The Akaike information criterion for the models fit.

        Returns
        -------
        dict[tuple, float]
        )r  r   s    r7   ry  zAROrderSelectionResults.aic       yr9   c                    | j         S )z
        The Bayesian (Schwarz) information criteria for the models fit.

        Returns
        -------
        dict[tuple, float]
        )r  r   s    r7   r  zAROrderSelectionResults.bic  r  r9   c                    | j         S )z
        The Hannan-Quinn information criteria for the models fit.

        Returns
        -------
        dict[tuple, float]
        )r  r   s    r7   r{  zAROrderSelectionResults.hqic  s     zr9   r   c                    | j         j        S )z(The lags included in the selected model.)r  r   r   s    r7   r   zAROrderSelectionResults.ar_lags  s     {""r9   N)
rf  r+   r  r  rJ   r   rL   rM   rR   rQ   )r0   r+   rC  rB  rA  )r0   r  r@  )rE  rF  rG  rH  ra   rJ  rf  rL   rJ   rR   ry  r  r{  r   r   r9   r7   ry  ry    s2        8 8 8 8(    X    X    X    X    X    X    X # # # X# # #r9   ry  r  )r,   r-   r.   r/   r0   r1   )r:   r;   r0   r/   )	r  FrC   FNNNrD   F)rJ   r   )[
__future__r   statsmodels.compat.pandasr   r   r   r   collections.abcr   r6  r5  typesr	   typingr
   r   r   r   rs   numpyr5   pandasr  scipy.statsr   r   statsmodels.base.wrapperbasewrapperrY  statsmodels.iolib.summaryr   #statsmodels.regression.linear_modelr   statsmodels.toolsr   statsmodels.tools.decoratorsr   r   statsmodels.tools.docstringr   r   statsmodels.tools.sm_exceptionsr   statsmodels.tools.typingr   r   r   r   r   statsmodels.tools.validationr   r   r   r    statsmodels.tsa.arima_processr!   statsmodels.tsa.baser"   statsmodels.tsa.base.predictionr#   statsmodels.tsa.deterministicr$   r%   r&   r'   statsmodels.tsa.tsatoolsr(   r)   __all__AR_DEPRECATION_WARNREPEATED_FIT_ERRORr8   r@   TimeSeriesModelr+   r*   rV  r?  rH  docextract_parametersrV  TimeSeriesModelResultsr   ResultsWrapperr   populate_wrapper_auto_reg_paramsr  ry  r   r9   r7   <module>r     s   " " " " " "            % $ $ $ $ $      ! ! ! ! ! ! % % % % % % % % % % $ $ $ $ $ $          * * * * * * * * ' ' ' ' ' ' ' ' ' - - - - - - 3 3 3 3 3 3 + + + + + + G G G G G G G G D D D D D D D D @ @ @ @ @ @                         2 1 1 1 1 1 * * * * * * = = = = = =            < ; ; ; ; ; ; ;
 ( # # # # #
   ^
 ^
 ^
 ^
 ^
i' ^
 ^
 ^
B
 
 
 
 
 
 
 
"
 
 
 
 
 
 
 
  i'((((333Q 
wK wK wK wK wKY5 wK wK wKt!    D/     +^ < < <i  ))      ./// 	,/	SF SF SF SF 0/SFlS# S# S# S# S# S# S# S# S# S#r9   