
    M/Phy                      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
mZmZ d dlZd dlmZ d dlmZmZmZmZmZmZ d dlmZmZmZ d dlZd dlZd dlZd d	l m!Z! d d
l"m#Z# d dl$m%c m&Z' d dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6m7Z7m8Z8m9Z9 d dl:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZG d dlHmIZI d dlJmKZK d dlLmMZM d dlNmOZO erd dlPZQg dZR G d de          ZSedeTeUeeeT         f         f         ZVedeTeVeeT         eUeeeTeeT         df         f         f         ZWeTejX        fZYdnd!ZZdod&Z[ G d' d(eA          Z\ e0e\j]        j^                  Z_e_`                    g d)d*          Za G d+ d,eB          Zb G d- d.e'jc                  Zd e'je        edeb            G d/ d0e@          Zf	 dpdd2d3d2d2dddd4d5	dqdKZg ej'        dLdM          Zh e1dNd9ehO          Zi ej'        dPdM          Zj e1ddQejO          Zk e0e\jl        j^                  Zmemn                    dRdS           em2                    dN           em2                    d           emo                    dTei           emo                    dNek            e0e\jp        j^                  Zqeqn                    dU e1dVdWdXg          g           eqjr        =eqjr        dY         Zsest                    d dZgd[gf           eqn                    dYes            G d\ d]e\          Zu G d^ dWeb          ZvdrddZwdsdkZx G dl dme'jc                  Zy e'je        eyev           dS )t    )annotations)AppenderSubstitutioncall_cached_func)defaultdictN)combinationsproduct)SimpleNamespace)TYPE_CHECKINGAnyLiteral
NamedTupleOptionalUnion)HashableMappingSequence)stats)
PandasData)Summarysummary_params)OLS)cache_readonly)	Docstring	Parameterremove_parameters)SpecificationWarning)ArrayLike1DArrayLike2DFloat64ArrayNDArray)
array_like	bool_like
float_likeint_like)AROrderSelectionResultsAutoRegAutoRegResultssumofsq)pss_critical_values)arma2ma)	tsa_model)PredictionResults)DeterministicProcess)lagmat)ARDLARDLResultsardl_select_orderARDLOrderSelectionResultsUECMUECMResultsBoundsTestResultc                  H    e Zd ZU ded<   ded<   ded<   ded<   ded	<   d
 ZdS )r6   floatstatpd.DataFrame	crit_valsz	pd.Seriesp_valuesstrnullalternativec                    | j         j         d| j        dd| j        d         dd| j        d         dd| j         d	| j         d
S )Nz
Stat: z0.5fz
Upper P-value: upperz0.3gz
Lower P-value: lowerz
Null: z
Alternative: 
)	__class____name__r9   r<   r>   r?   selfs    Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/ardl/model.py__repr__zBoundsTestResult.__repr__N   s     y   g&   g&	  
 y     	    N)rE   
__module____qualname____annotations__rI    rJ   rH   r6   r6   G   s[         KKKIII    rJ   r6   orderint | Sequence[int] | Nonecausalboolreturnc                \   | dS t          | t          t          j        f          rEt          |           t          |          k     r#t	          dt          |           d| d          dS | D ]2}t          |t          t          j        f          st          d          3d | D             } t          t          |                     t          |           k    st          |           dk     rt	          d          t          |          r"t          |           d	k     rt	          d
          dS )NTz integer orders must be at least z when causal is .z8sequence orders must contain non-negative integer valuesc                ,    g | ]}t          |          S rN   int.0vs     rH   
<listcomp>z _check_order.<locals>.<listcomp>u   s    ###SVV###rJ   r   z9sequence orders must contain distinct non-negative values   z=sequence orders must be strictly positive when causal is True)	
isinstancerX   npinteger
ValueError	TypeErrorlensetmin)rO   rQ   r[   s      rH   _check_orderrf   f   sO   }t%#rz*++ u::F## 3v;;            t  !c2:.// 	J  	 $#U###E
3u::#e**$$E

QG
 
 	
 6{{ 
s5zzA~~K
 
 	
 4rJ   exogr   
_ARDLOrderdict[Hashable, list[int]]c           	        | dv ri S t          | t          j                  s;t          | ddd          } t	          t          | j        d                             }nd | j        D             }d |D             }nt          t                    r"}t          |          
                                                              }t                                                    
                    |          }|rUd}|d	z  }|d
                    t	          t          d |D                                           dz   z  }t          |          |rCd}|d
                    d |D                       dz   z  }t          j        |t"          d           |D ]}t%          ||         |           nRt          t&                    rt%          |           fd|D             }nt%          |           fd|D             }i }	|D ]f}||         }
|
|
J t          |
t(                    r1t	          t          t)          |          |
dz                       |	|<   Wd |
D             |	|<   g|	S )N)r   Nrg      ndimmaxdimr]   c                    g | ]}|S rN   rN   )rZ   cols     rH   r\   z!_format_order.<locals>.<listcomp>   s    ,,,,,,rJ   c                    i | ]}|d S NrN   rZ   ks     rH   
<dictcomp>z!_format_order.<locals>.<dictcomp>   s    ,,,!a,,,rJ   zWorder dictionary contains keys for exogenous variable(s) that are not contained in exogz Extra keys: z, c                ,    g | ]}t          |          S rN   r=   rY   s     rH   r\   z!_format_order.<locals>.<listcomp>   s    )@)@)@Q#a&&)@)@)@rJ   rU   zSexog contains variables that are missing from the order dictionary.  Missing keys: c                ,    g | ]}t          |          S rN   rw   rs   s     rH   r\   z!_format_order.<locals>.<listcomp>   s    666c!ff666rJ   )
stacklevelc                0    i | ]}|t                    S rN   rW   rZ   rt   rO   s     rH   ru   z!_format_order.<locals>.<dictcomp>   s!    222aU222rJ   c                0    i | ]}|t                    S rN   )listr{   s     rH   ru   z!_format_order.<locals>.<dictcomp>   s!    333ae333rJ   c                ,    g | ]}t          |          S rN   rW   rZ   lags     rH   r\   z!_format_order.<locals>.<listcomp>   s    :::SC:::rJ   )r^   pd	DataFramer"   r}   rangeshapecolumnsr   rd   
differencekeysjoinsortedra   warningswarnr   rf   
_INT_TYPESrX   )rg   rO   rQ   r   
exog_ordermissingextramsgkeyfinal_ordervalues    `         rH   _format_orderr      s   
 |**	dBL)) -$Qq999E$*Q-(()),,t|,,,},,t,,,

	E7	#	# 4
d))&&uzz||44EJJLL!!,,T22 	"=  ?"C499T&)@)@%)@)@)@"A"ABBCCcIICS//! 	C.  49966g66677#==CM#3BBBB 	2 	2CC&1111	2	E:	&	& 4UF###2222T222

UF###3333d333
-/K ; ;3=   eS!! 	;#E#f++uqy$A$ABBK::E:::KrJ   c            	      ^    e Zd ZdZ	 	 	 dRdddddddddS fdZedTd!            ZedUd"            ZedVd$            ZedWd&            Z	edXd(            Z
dYd)ZedZd,            Zd[d-Z	 	 	 d\d]d6Zd.dd/d7d^d9Zd_d;Zd< Zd`dDZ	 	 	 	 	 	 	 dadbdIZe	 	 	 dcdddddddKdddQ            Z xZS )er0   a  
    Autoregressive Distributed Lag (ARDL) Model

    Parameters
    ----------
    endog : array_like
        A 1-d endogenous response variable. The dependent variable.
    lags : {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.
    exog : array_like
        Exogenous variables to include in the model. Either a DataFrame or
        an 2-d array-like structure that can be converted to a NumPy array.
    order : {int, sequence[int], dict}
        If int, uses lags 0, 1, ..., order  for all exog variables. If
        sequence[int], uses the ``order`` for all variables. If a dict,
        applies the lags series by series. If ``exog`` is anything other
        than a DataFrame, the keys are the column index of exog (e.g., 0,
        1, ...). If a DataFrame, keys are column names.
    fixed : array_like
        Additional fixed regressors that are not lagged.
    causal : bool, optional
        Whether to include lag 0 of exog variables.  If True, only includes
        lags 1, 2, ...
    trend : {'n', 'c', 't', 'ct'}, optional
        The trend to include in the model:

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

        The default is 'c'.

    seasonal : bool, optional
        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.
    deterministic : DeterministicProcess, optional
        A deterministic process.  If provided, trend and seasonal are ignored.
        A warning is raised if trend is not "n" and seasonal is not False.
    hold_back : {None, int}, optional
        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}, optional
        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 : {"none", "drop", "raise"}, optional
        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'.

    Notes
    -----
    The full specification of an ARDL is

    .. math ::

       Y_t = \delta_0 + \delta_1 t + \delta_2 t^2
             + \sum_{i=1}^{s-1} \gamma_i I_{[(\mod(t,s) + 1) = i]}
             + \sum_{j=1}^p \phi_j Y_{t-j}
             + \sum_{l=1}^k \sum_{m=0}^{o_l} \beta_{l,m} X_{l, t-m}
             + Z_t \lambda
             + \epsilon_t

    where :math:`\delta_\bullet` capture trends, :math:`\gamma_\bullet`
    capture seasonal shifts, s is the period of the seasonality, p is the
    lag length of the endogenous variable, k is the number of exogenous
    variables :math:`X_{l}`, :math:`o_l` is included the lag length of
    :math:`X_{l}`, :math:`Z_t` are ``r`` included fixed regressors and
    :math:`\epsilon_t` is a white noise shock. If ``causal`` is ``True``,
    then the 0-th lag of the exogenous variables is not included and the
    sum starts at ``m=1``.

    See the notebook `Autoregressive Distributed Lag Models
    <../examples/notebooks/generated/autoregressive_distributed_lag.html>`__
    for an overview.

    See Also
    --------
    statsmodels.tsa.ar_model.AutoReg
        Autoregressive model estimation with optional exogenous regressors
    statsmodels.tsa.ardl.UECM
        Unconstrained Error Correction Model estimation
    statsmodels.tsa.statespace.sarimax.SARIMAX
        Seasonal ARIMA model estimation with optional exogenous regressors
    statsmodels.tsa.arima.model.ARIMA
        ARIMA model estimation

    Examples
    --------
    >>> from statsmodels.tsa.api import ARDL
    >>> from statsmodels.datasets import danish_data
    >>> data = danish_data.load_pandas().data
    >>> lrm = data.lrm
    >>> exog = data[["lry", "ibo", "ide"]]

    A basic model where all variables have 3 lags included

    >>> ARDL(data.lrm, 3, data[["lry", "ibo", "ide"]], 3)

    A dictionary can be used to pass custom lag orders

    >>> ARDL(data.lrm, [1, 3], exog, {"lry": 1, "ibo": 3, "ide": 2})

    Setting causal removes the 0-th lag from the exogenous variables

    >>> exog_lags = {"lry": 1, "ibo": 3, "ide": 2}
    >>> ARDL(data.lrm, [1, 3], exog, exog_lags, causal=True)

    A dictionary can also be used to pass specific lags to include.
    Sequences hold the specific lags to include, while integers are expanded
    to include [0, 1, ..., lag]. If causal is False, then the 0-th lag is
    excluded.

    >>> ARDL(lrm, [1, 3], exog, {"lry": [0, 1], "ibo": [0, 1, 3], "ide": 2})

    When using NumPy arrays, the dictionary keys are the column index.

    >>> import numpy as np
    >>> lrma = np.asarray(lrm)
    >>> exoga = np.asarray(exog)
    >>> ARDL(lrma, 3, exoga, {0: [0, 1], 1: [0, 1, 3], 2: 2})
    Nr   cFnonefixedrQ   seasonaldeterministic	hold_backperiodr   endog)Sequence[float] | pd.Series | ArrayLike2DlagsrP   rg   ArrayLike2D | NonerO   rh   trendLiteral['n', 'c', 'ct', 'ctt']r   rQ   rR   r   r   DeterministicProcess | Noner   
int | Noner   r    Literal['none', 'drop', 'raise']rS   Nonec                  t          j        d          | _        t          j        d          | _        t	                                          ||||||
|||	d
  
         t          |dd          | _        || j        _	        |t          |dd	d	
          }|j        d         | j        j        j        d         k    s&t          j        t          j        |                    st          d          t!          |t"          j                  rt'          |j                  | _        n)d t-          |j        d                   D             | _        || _        n7t          j        | j        j        j        d         df          | _        g | _        i | _        i | _        |                     |          | _        |                     |
          \  | _        | _        |                                 \  | _        | _        | j        x| j        _         | j        _!        | j        | j        _"        d| _        | j        r;d | j        #                                D             }tI          |          dk    | _        tJ          | _&        tN          | _(        d S )Nr   r   r   F)r   r   rg   r   r   r   r   	old_namesrQ   T)strictr   rk   rl   r   zfixed must be an (nobs, m) array where nobs matches the number of observations in the endog variable, and allvalues must be finitec                    g | ]}d | S )zz.rN   rZ   is     rH   r\   z!ARDL.__init__.<locals>.<listcomp>m  s+     % % %!"HHH% % %rJ   r]   c                ,    g | ]}t          |          S rN   re   )rZ   vals     rH   r\   z!ARDL.__init__.<locals>.<listcomp>  s    AAASCAAArJ   ))r_   empty_x_ysuper__init__r#   _causaldata
orig_fixedr"   r   r   allisfinitera   r^   r   r   r}   r   _fixed_namesr   _fixed_blocks_namesrf   _order_construct_regressors_construct_variable_names_endog_name_exog_namesparam_namesxnamesynamesvaluesre   r1   _results_classARDLResultsWrapper_results_wrapper)rG   r   r   rg   rO   r   r   rQ   r   r   r   r   r   	fixed_arrmin_lagsrD   s                  rH   r   zARDL.__init__>  sd     (6""(4..' 	 	
 	
 	
 !$???$	"5'!DDDIq!TY_%:1%===RVI&&F F= !,  
 %.. $($7$7!!% %&+IOA,>&?&?% % %! $DKK(DIO$9!$<a#@AADK "D.002 ''..55i@@-1-K-K-M-M*$*373CC		 0+	; 	-AADK,>,>,@,@AAAHx==1,DL) 2rJ   NDArray | pd.DataFrame | Nonec                    | j         j        S )z*The fixed data used to construct the model)r   r   rF   s    rH   r   z
ARDL.fixed  s     y##rJ   c                    | j         S )z'Flag indicating that the ARDL is causal)r   rF   s    rH   rQ   zARDL.causal  s     |rJ   list[int] | Nonec                "    | j         sdn| j         S )z-The autoregressive lags included in the modelN)_lagsrF   s    rH   ar_lagszARDL.ar_lags  s      :5tt4:5rJ   ri   c                    | j         S )z5The lags of exogenous variables included in the model)r   rF   s    rH   dl_lagszARDL.dl_lags  s     {rJ   tuple[int, ...]c                   | j         sdn t          t          | j                             }|g}| j                                        D ]3}|/|                    t          t          |                               4t          |          S )zThe order of the ARDL(p,q)r   )r   rX   maxr   r   appendtuple)rG   ar_order
ardl_orderr   s       rH   r   zARDL.ardl_order  s}     !J@11CDJ,@,@Z
K&&(( 	2 	2D!!#c$ii..111Z   rJ   c                l    t          j        | j        j        d         | j        z
  df          | _        dS )z)Place holder to let AutoReg init completer   N)r_   r   r   r   
_hold_backr   rF   s    rH   _setup_regressorszARDL._setup_regressors  s-    (DJ,Q/$/A1EFFrJ   r   dict[Hashable, np.ndarray]c                   |si S d}|                                 D ]!}|t          t          |          |          }"t          | t          j                  st          | ddd          } i }|D ]z}||         t          | t          j                  r$t          |t                    sJ | dd|f         }n| |         }t          ||d          }||         }|dd|f         ||<   {|S )z6Transform exogenous variables and orders to regressorsr   Nrg   rk   rl   inoriginal)
r   r   r^   r   r   r"   r_   ndarrayrX   r/   )	rg   rO   	max_orderr   	exog_lagsr   rp   
lagged_colr   s	            rH   _format_exogzARDL._format_exog  s   
  	I	<<>> 	5 	5CC)44	$-- 	>dF1===D	 
	1 
	1CSz!$
++  !#s+++++111c6l3iY>>>J:D'40IcNNrJ   c                B    t          | j        j        || j                  S )z(Validate and standardize the model order)r   r   	orig_exogr   )rG   rO   s     rH   rf   zARDL._check_order  s    TY0%FFFrJ   	nonrobustTcov_typer=   cov_kwdsdict[str, Any]use_t)tuple[np.ndarray, np.ndarray, np.ndarray]c                   | j         j        d         dk    r;t          j        d          t          j        d          t          j        d          fS t	          | j        | j                   }|                    |||          }|                                }|j        }|dk    r3|s1| j        j        d         }| j         j        d         }|||z
  z  }	||	z  }|j	        ||j
        fS )Nr]   r   r   r   r   r   r   r   )r   r   r_   r   r   r   fit
cov_paramsr   paramsnormalized_cov_params)
rG   r   r   r   ols_modols_resr   nobsrt   scales
             rH   _fitz	ARDL._fit  s     7=q  8D>>28F#3#3RXf5E5EEEdgtw''++  
 
 ''))
{""5"7=#Da AD1H%E%J~z7+HHHrJ   r   r1   c                   |                      |||          \  }}}t          | ||||          }t          |          S )aQ	  
        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
        -------
        ARDLResults
            Estimation results.

        See Also
        --------
        statsmodels.tsa.ar_model.AutoReg
            Ordinary Least Squares estimation.
        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   r1   r   rG   r   r   r   r   r   norm_cov_paramsress           rH   r   zARDL.fit  s\    ~ /3ii /8 /
 /
+
O &*oU
 
 
 "#&&&rJ   tuple[np.ndarray, np.ndarray]c                :   | j         rt          | j                   nd| _        t          | j        j        | j        d          \  }}t          |t          j                  sJ t          |t          j                  sJ ||c| _	        | _
        | j	        j        d         t          | j                   k    r'd | j         D             }| j	        dd|f         | _	        | j        j        }|                     || j                  | _        d}| j                                        D ]#}t          ||t          |          nd          }$t          | j        |          | _        | j                                        | _        | j	        | j        | j        | j        d| _        | j        | j	        g}|d | j                                        D             | j        gz   z  }t          j        |          }	|t1          | j                  | _        | j        | j        k     rt5          d	          |	| j        d         }	|	j        d         |	j        d         k    r,t5          d
|	j        d          d|	j        d          d          | j        j        | j        d         |	fS )%Construct and format model regressorsr   sepr   r]   c                    g | ]}|d z
  S r]   rN   r   s     rH   r\   z.ARDL._construct_regressors.<locals>.<listcomp>3  s    666Ca666rJ   Nr   rg   r   r   c                    g | ]}|S rN   rN   )rZ   exs     rH   r\   z.ARDL._construct_regressors.<locals>.<listcomp>F  s    ///Rb///rJ   Dhold_back must be >= the maximum lag of the endog and exog variablesThe number of regressors () including deterministics, lags of the endog, lags of the exogenous, and fixed regressors is larger than the sample available for estimation ().)r   r   _maxlagr/   r   r   r^   r_   r   
_endog_reg_endogr   rc   r   r   r   _exogr   _deterministics	in_sample_deterministic_regr   r   column_stackrX   r   ra   )
rG   r   r  r  lag_locsr   exog_maxlagr   xregs
             rH   r   zARDL._construct_regressors&  s   
 +/*;s4:!#IOT\E
 
 

F &"*-----*bj11111'16$? #s4:66664:666H"oaaak:DOI'	&&y$+>>
;%%'' 	O 	OCks3s888ANNKK4<55"&"6"@"@"B"B_J!4[	
 
 $do6	//4:,,..///4;-??oa  !$,//DO?T\))   $/##$9Q<#)A,&&4SYq\ 4 4 $'9Q<4 4 4   yt001366rJ   c                   | j         j        fd| j        D             }| j         j        }i }| j        D ]O}t          |t          j                  rd| nt          |          | j        |         }fd|D             ||<   P||| j	        j
        | j        d| _        t          | j	        j
                  }||z  }|D ]}|||         z  }|| j        z  }|fS )Construct model variables namesc                    g | ]	} d | 
S z.LrN   )rZ   r   y_names     rH   r\   z2ARDL._construct_variable_names.<locals>.<listcomp>\  s'    @@@f++++@@@rJ   r  c                    g | ]	} d | 
S r   rN   )rZ   r   bases     rH   r\   z2ARDL._construct_variable_names.<locals>.<listcomp>f  s'    @@@C$//#//@@@rJ   r
  )r   r   r   r   r   r^   r_   r   r=   r  r   r   r   r}   )	rG   endog_lag_namesrg   
exog_namesr   r   x_namesr#  r!  s	          @@rH   r   zARDL._construct_variable_namesY  s   !@@@@TZ@@@y"
; 	A 	AC$
++   3yy3xx;s#D@@@@4@@@JsOO %!4<&	
 
 t.677?" 	' 	'Cz#&GG4$$wrJ   startrX   endnum_oosexog_oos	fixed_oos
np.ndarrayc                    dd}|| j         k    rdn	| j         |z
  }	|dz   | j        j        d         k     r@|>|<t          || j         z
  d          }
 || j        |
|dz   | j         z
           |	          S || j        j        nt          j        |          }|0t          j	        |t          j        |          d	|         g          }|| j
        nt          j        |          }|0t          j	        |t          j        |          d	|         g          }| j                                        }|r2| j                            |          }t          j        ||gd
          }| j        j        }|r3t          j        |t          j        |t          j                  g          }|g}| j        rRt)          |t          | j                  d          }|                    |d	d	d | j        D             f                    | j        dd	         rt/          | j        j        t          j                  r%t          j        || j        j        j                  }|                     || j                  }|                    d |                                D                        |j        d         dk    r|                    |           t          j        |          }t          j        |d	| j         <   ||d	         S )z#Construct exog matrix for forecastsr  r,  padrX   rS   c                    |dk    r| S | j         d         }t          j        t          j        ||ft          j                  | g          S Nr   r]   )r   r_   vstackfullnan)r  r.  rt   s      rH   pad_xz"ARDL._forecasting_x.<locals>.pad_x  sB    axx
A9bgsAh77;<<<rJ   r   r]   Naxisr  r   c                    g | ]}|d z
  S r	  rN   r   s     rH   r\   z'ARDL._forecasting_x.<locals>.<listcomp>  s    "A"A"As37"A"A"ArJ   r   c                6    g | ]}t          j        |          S rN   )r_   asarray)rZ   arrs     rH   r\   z'ARDL._forecasting_x.<locals>.<listcomp>  s     ???#bjoo???rJ   )r  r,  r.  rX   rS   r,  ) r   r   r   r   r   r   rg   r_   r:  r1  r   r  r  out_of_sampler   concathstackr2  r3  r   r/   r   r   r^   r   r   r   r   r   extendr   r  )rG   r'  r(  r)  rg   r*  r   r+  r4  r.  adjusted_startdetoos_detr   r  	endog_regr   s                    rH   _forecasting_xzARDL._forecasting_xu  s   	= 	= 	= 	= DO++aa51H !Gtz'***t| !8!<<N5q4?)BBCS  
 "&ty~~2:d3C3C9dBJx$8$8'$BCDDD$}"*U2C2C Iubj&;&;HWH&EFGGE",,.. 	4*88AAG)S'N333C	 	AIubggrv&>&>?@@EE: 	Duc$*ooEEEIHHYqqq"A"Adj"A"A"AABCCC?122 	A$)-r|<< O|D$)2E2MNNN$$T4;77DHH?????@@@;q>AHHUOOO_Q "T_%&&zrJ   r   r   -int | str | dt.datetime | pd.Timestamp | Nonedynamicc	           	     `                          |||||          \  }}}}}}	 fd}
 j        j        j        d         | |
|d j        j        d          }| |
|d j        j        d          }| |
|d j        d          }|% |
t          j        |          d	 j        d          } j        j        d
         s j        sd}nn j	        st          j
        nt           j	                  } j        r@t          d  j                                        D                       }t          ||          }|	|k    r j        r|t          d           j        r-|j        d         |z   |	k     rt          d|	|z
   d|	 d           j        j        d
         r|t          d           j        j        d
         r'|j        d         |	k     rt          d|	 d|	 d           j        ~|||	rzt          j        |	 j        j        d
         ft          j                  }t%           j        j        t&          j                  r%t'          j        | j        j        j                  }                     |||	||||          }|du r	|d
z   |z
  }n;                     ||          }|}| j        k     rt3          | j        |z
            }t          j        |j        d         t          j                  }|d|         |z  |d|<    j        j        d
         }t7          ||j        d                   D ]X}t9           j	                  D ]3\  }}||z
  }||k    r	||         }n j        ||z            }|||||z   f<   4||         |z  ||<   Y                     |||d
z   |	z   d          S )
  
        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
            variables. Must have 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.
        fixed : array_like
            A replacement fixed array.  Must have the same shape as the
            fixed data array used when the model was created.
        fixed_oos : array_like
            An array containing out-of-sample values of the fixed variables.
            Must have the same number of columns as the fixed 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.
        c                :   t          |t          j                  rst          | t          j                  st          | d          t	          | j                  t	          j        j        j                  k    rt          | d          nt          | |dd          } | j
        dk    s| j        d         |j        d         k    rt          | d|j        d                    |r1| j        d         |j        d         k    rt          | d	 d
          | S )Nz; must be a DataFrame when the original exog was a DataFramez0 must have the same columns as the original exogrk   F)rm   optionalr]   z< must have the same number of columns as the original data, r   z9 must have the same number of rows as the original data (r  )r^   r   r   rb   r   r   r   r   ra   r"   rm   r   )r;  nameorigexactnrG   s       rH   
check_exogz ARDL.predict.<locals>.check_exog  sd   $-- D!#r|44 # * * *   #+&&&1D1L*M*MMM$      N !dUCCCx1}}	!
1 = =  6 6&*jm6 6    1A66  , ,&', , ,   JrJ   r   Nrg   Tr*  Fr   r+  r]   c                ,    g | ]}t          |          S rN   r   rY   s     rH   r\   z ARDL.predict.<locals>.<listcomp>  s    EEE1AEEErJ   zoexog_oos must be provided when out-of-sample observations require values of the exog not in the original samplezexog_oos must have at least z observations to produce z, forecasts based on the model specification.zEfixed_oos must be provided when predicting out-of-sample observationszfixed_oos must have at least z forecasts.r8  )_prepare_predictionr   r   r   r   r   r_   r:  r   r   infre   r   r   ra   rg   r2  r3  r^   r   r   r   rD  _parse_dynamicr   r   r  r   	enumerate_wrap_prediction)rG   r   r'  r(  rF  rg   r*  r   r+  r)  rO  	max_1stepmin_exogr  dynamic_startdynamic_stepfcastsoffsetr   jr   locr   rN  s   `                      @rH   predictzARDL.predict  sz   | 7;6N6ND(E37
 7
3hsG	 	 	 	 	 	4 IO!!$:dFDI,?FFD!z*di&95 H Jugt{DAAE "

9%%{DK I
 ;Q 	5t| 	5II&*jEc$*ooI{ 5EE0B0B0D0DEEEFF	844	Y{ x/ &  
  (."3i"?7!J!J /7Y3F / //6/ / /   { # 		(9 1   "1% )/!*<w*F*F 7G 7 7")7 7 7  
 9 X%5'%5w);<bfEEH$)-r|<< <di&9&A   3x	
 
 e!GeOMM..w>>L(Mt&& #M4?U3J K KRV,,!">M>!2V!;~~(.q1}fl1o66 		& 		&A#DJ// ' '3#g-'' +CC *US[1C#&!VaZ-  !vF1II$$VUC!Gg4EqIIIrJ   rN  rQ   r   r   r   r   r   formular   r:   Literal['none', 'raise']ARDL | UECMc                  |j         }d}d|v r,|                    d          \  }}|                                }t          j        |dz   |          }|j        j        }||_         |j        j        }||_         |^|                    d          d                                         }| d| d}t          j        ||          }|j        j        }||_         nd} | ||||||||||	|
|          S )	aM  
        Construct an ARDL from a formula

        Parameters
        ----------
        formula : str
            Formula with form dependent ~ independent | fixed. See Examples
            below.
        data : DataFrame
            DataFrame containing the variables in the formula.
        lags : {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.
        order : {int, sequence[int], dict}
            If int, uses lags 0, 1, ..., order  for all exog variables. If
            sequence[int], uses the ``order`` for all variables. If a dict,
            applies the lags series by series. If ``exog`` is anything other
            than a DataFrame, the keys are the column index of exog (e.g., 0,
            1, ...). If a DataFrame, keys are column names.
        causal : bool, optional
            Whether to include lag 0 of exog variables.  If True, only
            includes lags 1, 2, ...
        trend : {'n', 'c', 't', 'ct'}, optional
            The trend to include in the model:

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

            The default is 'c'.

        seasonal : bool, optional
            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.
        deterministic : DeterministicProcess, optional
            A deterministic process.  If provided, trend and seasonal are
            ignored. A warning is raised if trend is not "n" and seasonal
            is not False.
        hold_back : {None, int}, optional
            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}, optional
            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 : {"none", "drop", "raise"}, optional
            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'.

        Returns
        -------
        ARDL
            The ARDL model instance

        Examples
        --------
        A simple ARDL using the Danish data

        >>> from statsmodels.datasets.danish_data import load
        >>> from statsmodels.tsa.api import ARDL
        >>> data = load().data
        >>> mod = ARDL.from_formula("lrm ~ ibo", data, 2, 2)

        Fixed regressors can be specified using a |

        >>> mod = ARDL.from_formula("lrm ~ ibo | ide", data, 2, 2)
        N|z -1~r   z ~ z - 1)r   r   rQ   r   r   r   r   r   )indexsplitstripr   from_formular   r   
orig_endog)clsr`  r   r   rO   r   rQ   r   r   r   r   r   rf  fixed_formulamodrg   r   
endog_namer   s                      rH   ri  zARDL.from_formulaX  s   z 
'>>%,]]3%7%7"G])//11Mw55x!
#$ s++A.4466J)AAmAAAM"=$77C),);EEKKEs'
 
 
 	
rJ   Nr   r   )r   r   r   rP   rg   r   rO   rh   r   r   r   r   rQ   rR   r   rR   r   r   r   r   r   r   r   r   rS   r   )rS   r   )rS   rR   )rS   r   rS   ri   )rS   r   )rS   r   )rg   r   rO   ri   rS   r   )rO   rh   rS   ri   )r   NT)r   r=   r   r   r   rR   rS   r   )r   r=   r   r   r   rR   rS   r1   r   r   rS   r  )r'  rX   r(  rX   r)  rX   rg   r   r*  r   r   r   r+  r   rS   r,  NNFNNNN)r   r   r'  rE  r(  rE  rF  rR   rg   r   r*  r   r   r   r+  r   r   r   rN  )r`  r=   r   r:   r   rP   rO   rh   r   r   rQ   rR   r   rR   r   r   r   r   r   r   r   ra  rS   rb  )rE   rK   rL   __doc__r   propertyr   rQ   r   r   r   r   staticmethodr   rf   r   r   r   r   rD  r^  classmethodri  __classcell__rD   s   @rH   r0   r0      s       B BP $(03H3 %)59 $!4:H3 H3 H3 H3 H3 H3 H3 H3T $ $ $ X$    X 6 6 6 X6    X ! ! ! X!G G G G    \4G G G G $#'	I I I I I2 $#'E' E' E' E' E' E'N17 17 17 17f  86 6 6 6v @D=A.226/337iJ iJ iJ iJ iJV 
 ,-03{
 59 $!,2{
 {
 {
 {
 {
 [{
 {
 {
 {
 {
rJ   r0   r'  r(  rF  rg   r*  r   r+     c                      e Zd ZdZi Z	 	 	 d/d0 fdZ e eej	        j        d                    	 	 	 	 	 	 	 d1d2d            Z		 	 	 d3d4d Z
d5d!Z	 	 	 	 	 	 	 d1d6d"Z ee#          	 	 	 	 	 	 	 	 	 	 	 d7d8d,            Zd9d:d.Z xZS );r1   a4  
    Class to hold results from fitting an ARDL model.

    Parameters
    ----------
    model : ARDL
        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
        Whether use_t was set in fit
    N      ?Fmodelr0   r   r,  r   r   Float64Array | Noner   r8   r   rR   c                d   t                                          |||||           i | _        || _        |j        | _        |j        j        d         | _        |j	        | _
        |j        | _        d| _        | j        rt          | j                  | _        | j        j        | _        || _        d S )Nr   r   )r   r   _cache_paramsr   _nobsr   r   	_n_totobsdf_model	_df_modelr   _ar_lags_max_lagr   r~  r   r   cov_params_default)rG   r~  r   r   r   r   r   rD   s          rH   r   zARDLResults.__init__  s     	60%u 	 	
 	
 	
 Z
*1-= 	/..DM*.",rJ   r'  rE  r(  rF  rg   r   r*  r   r+  c           
     P    | j                             | j        |||||||          S )Nrz  )r~  r^  r  )rG   r'  r(  rF  rg   r*  r   r+  s           rH   r^  zARDLResults.predict  s=     z!!L " 	
 	
 		
rJ   r]   stepsrX   rS   np.ndarray | pd.Seriesc                    | j         j        j        j        d         }t	          |t
          t          j        f          r	||z   dz
  }n|}|                     ||d||          S )aZ  
        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 : array_like, optional
            Exogenous values to use out-of-sample. Must have same number of
            columns as original exog data and at least `steps` rows
        fixed : array_like, optional
            Fixed values to use out-of-sample. Must have same number of
            columns as original fixed data and at least `steps` rows

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

        See Also
        --------
        ARDLResults.predict
            In- and out-of-sample predictions
        ARDLResults.get_prediction
            In- and out-of-sample predictions and confidence intervals
        r   r]   F)r'  r(  rF  r*  r+  )	r~  r   rj  r   r^   rX   r_   r`   r^  )rG   r  rg   r   r'  r(  s         rH   forecastzARDLResults.forecast"  sm    H 
*03ec2:.// 	%-!#CCC||S%$%  
 
 	
rJ   c                   | j         | j         ng }t          |          }t          j        | j        dz             }d|d<   | j        j        j        d         }| j        |||z            }t          |          D ]\  }}||          ||<   |S )6Returns poly repr of an AR, (1  -phi1 L -phi2 L^2-...)Nr]   r   )
r  rc   r_   zerosr  r~  r  r   r  rT  )rG   r   k_ar	ar_paramsr[  r   r   r   s           rH   	_lag_reprzARDLResults._lag_reprO  s    #'=#<$--"7||HT]Q.//		!.4Q7fv}45(( 	( 	(FAs$QiZIcNNrJ   c           	     z   |                      |||||||          }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 )
a!
  
        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.
        fixed : array_like
            A replacement fixed array.  Must have the same shape as the
            fixed data array used when the model was created.
        fixed_oos : array_like
            An array containing out-of-sample values of the fixed variables.
            Must have the same number of columns as the fixed 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
        rz  )
fill_valueNr   r]   )r   rk   rf  )r^  r_   	full_likesigma2r3  isnanr~  _index_get_prediction_indexr  r+   onescumsumr^   r   Seriesrf  r-   )rG   r'  r(  rF  rg   r*  r   r+  meanmean_var_oosr  mas                 rH   get_predictionzARDLResults.get_prediction[  s4   t ||  
 
 <===#%6$ ]'*{dj##z77sCC1c177((IBGAJJS999B"kBIb!e,<,<<HcTUUOdBI&& 	=y<<<H x000rJ   )predict_params皙?Talphar  figmatplotlib.figure.Figurefigsizetuple[int, int] | Nonec           	     p    |                      |||||||          }|                     |||||	|
|          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.
        rz  )r  _plot_predictions)rG   r'  r(  rF  rg   r*  r   r+  r  r  r  r  predictionss                rH   plot_predictzARDLResults.plot_predict  s]    N )) * 
 
 %%UIsG
 
 	
rJ   r   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        t          | j         j
                  z   }| j         j        rd|z   }t          | j         j                  }d|gfd	|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           |S )a  
        Summarize the Model

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

        Returns
        -------
        Summary
            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Dep. Variable:zModel:zMethod:)zDate:N)zTime:NzSample:r    r]   zNo. Observations:zLog Likelihoodz%#5.3fzS.D. of innovationsg      ?AICBICHQIC)gleftgrighttitleF)r  r   )r~  rD   rE   r   r   datesstrftimer=   rc   rj  r   r   endog_namesr   llfr  aicbichqicr   add_table_2colsadd_table_params)rG   r  r~  r  methodr'  r  sampledep_nametop_left	top_rightsmrys               rH   summaryzARDLResults.summary  s	   & 
(+;;"9?&IOEEl++J778FteBi00<<<==FF%jj#c$)*>&?&?"@"@AF
$-DJ4I0J0JJ: 	%u$Etz-..z*w!$&)
 !3s4:+;'<'<#=#=">?48 345"XS0@%@$ABX()*X()*h*+,
	 yy% 	 	
 	
 	
 	d%u===rJ   )Nr}  F)r~  r0   r   r,  r   r,  r   r  r   r8   r   rR   rr  )r'  rE  r(  rE  rF  rR   rg   r   r*  r   r   r   r+  r   )r]   NN)r  rX   rg   r   r   r   rS   r  )rS   r,  )r'  rE  r(  rE  rF  rR   rg   r   r*  r   r   r   r+  r   rS   r  )NNFNNNNr  TNN)r'  rE  r(  rE  rF  rR   rg   r   r*  r   r   r   r+  r   r  r8   r  rR   r  r  r  r  rS   r  r  r  r8   rS   r   )rE   rK   rL   rt  r  r   r   r   r0   r^  r  r  r  r   _predict_paramsr  r  rx  ry  s   @rH   r1   r1     s        ( F 6:- - - - - - -0 X 4h??@@ @D=A.226/337
 
 
 
 A@
. .2/3	+
 +
 +
 +
 +
Z
 
 
 
 @D=A.226/337O1 O1 O1 O1 O1b \111 @D=A.226/337(,*.1
 1
 1
 1
 211
f= = = = = = = = =rJ   r1   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   rK   rL   _attrswrapunion_dictsr,   TimeSeriesResultsWrapper_wrap_attrs_methods_wrap_methodsrN   rJ   rH   r   r      X        F"$"*6 K H$D$*8( MMMrJ   r   c                  :     e Zd ZdZ fdZedd            Z xZS )r3   zr
    Results from an ARDL order selection

    Contains the information criteria for all fitted model orders.
    c                4   d}t                                          |||||           d t          j        fd|                                D             t
                    | _        dx| j        j        _        | j        _        | j        	                                | _        t          j        fd|                                D             t
                    | _
        dx| j
        j        _        | j
        _        | j
        	                                | _
        t          j        fd|                                D             t
                    | _        d	x| j        j        _        | j        _        | j        	                                | _        d S )
N))r   )r   r   r   c                @    | d         t          | dd                    fS r0  )dict)ds    rH   _to_dictz4ARDLOrderSelectionResults.__init__.<locals>._to_dict9  s    Q4ae$$rJ   c                :    i | ]\  }}|d           |          S r   rN   rZ   rt   r[   r  s      rH   ru   z6ARDLOrderSelectionResults.__init__.<locals>.<dictcomp>=  +    77741aQqT88A;;777rJ   dtyper  c                :    i | ]\  }}|d           |          S r	  rN   r  s      rH   ru   z6ARDLOrderSelectionResults.__init__.<locals>.<dictcomp>C  r  rJ   r  c                :    i | ]\  }}|d           |          S )rk   rN   r  s      rH   ru   z6ARDLOrderSelectionResults.__init__.<locals>.<dictcomp>I  r  rJ   r  )r   r   r   r  itemsobject_aicrf  rK  
sort_index_bic_hqic)	rG   r~  icsr   r   r   _icsr  rD   s	          @rH   r   z"ARDLOrderSelectionResults.__init__5  sn   #eXv>>>	% 	% 	% I7777399;;777v
 
 
	 165	ty~I((**	I7777399;;777v
 
 
	 165	ty~I((**	Y7777399;;777v
 
 

 398

Z**,,


rJ   rS   ri   c                    | j         j        S )z5The lags of exogenous variables in the selected model)_modelr   rF   s    rH   r   z!ARDLOrderSelectionResults.dl_lagsN  s     {""rJ   rp  )rE   rK   rL   rt  r   ru  r   rx  ry  s   @rH   r3   r3   .  sb         - - - - -2 # # # X# # # # #rJ   r3   r   Fr  r   )	r   rQ   icglobr   r   r   r   r   r   ArrayLike1D | ArrayLike2DmaxlagrX   maxorderint | dict[Hashable, int]r   r   r   r   r  Literal['aic', 'bic']r  r   r   r   r   r   r   r   ra  c       	        H  ,- t          |dd          }d }t          | |||||||	|
|||          }|j        }|j        }t	          j        |d         |d         g          }||d         }g }g }|                    |d	         |d                    |                    t          t          |d	         j	        d
         d
z                                  g }|d         D ]}|d         |         |d         }|                    |           |                    t          t          |j	        d
         d
z                                  |                    |           |j
        }|j	        d
         r_t          j                            |          }t          t          |                    D ]}||         }||||z  z  z
  ||<   ||||z  z  z
  }d }|j	        d
         }i }|r|j        |j        ng }d |D             } |j                                        D ]\  -}!| -fd|!D             z  } t	          j        d |D                       }t          t          |j	        d
                             }"t          |j	        d
                   D ];}t#          |"|          D ](}# || |#          }$ |||dd|#f         |          ||$<   )<nt%          | D ]͊,t	          j        ,fdt'          |          D                       },d         r,d         ndg}$t'          ,d
d                   D ]T\  }%}&||%         }|r |$                    ||&dk    rdn|&f           /|$                    ||&d
z
  dk    r|&d
z
  ndf           Ut)          |$          }$ ||||          ||$<   dd
dd|         }'t          j        }(|D ]}$||$         |'         }&|&|(k     r|&}(|$})d |)d
d         D             }*t          | |)d         ||*||||	|
|||          }+t-          |+|||	|          S )a  
    ARDL order selection

    Parameters
    ----------
    endog : array_like
        A 1-d endogenous response variable. The dependent variable.
    maxlag : int
        The maximum lag to consider for the endogenous variable.
    exog : array_like
        Exogenous variables to include in the model. Either a DataFrame or
        an 2-d array-like structure that can be converted to a NumPy array.
    maxorder : {int, dict}
        If int, sets a common max lag length for all exog variables. If
        a dict, then sets individual lag length. They keys are column names
        if exog is a DataFrame or column indices otherwise.
    trend : {'n', 'c', 't', 'ct'}, optional
        The trend to include in the model:

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

        The default is 'c'.
    fixed : array_like
        Additional fixed regressors that are not lagged.
    causal : bool, optional
        Whether to include lag 0 of exog variables.  If True, only includes
        lags 1, 2, ...
    ic : {"aic", "bic", "hqic"}
        The information criterion to use in model selection.
    glob : bool
        Whether to consider all possible submodels of the largest model
        or only if smaller order lags must be included if larger order
        lags are.  If ``True``, the number of model considered is of the
        order 2**(maxlag + k * maxorder) assuming maxorder is an int. This
        can be very large unless k and maxorder are bot relatively small.
        If False, the number of model considered is of the order
        maxlag*maxorder**k which may also be substantial when k and maxorder
        are large.
    seasonal : bool, optional
        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.
    deterministic : DeterministicProcess, optional
        A deterministic process.  If provided, trend and seasonal are ignored.
        A warning is raised if trend is not "n" and seasonal is not False.
    hold_back : {None, int}, optional
        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}, optional
        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 : {"none", "drop", "raise"}, optional
        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'.

    Returns
    -------
    ARDLSelectionResults
        A results holder containing the selected model and the complete set
        of information criteria for all models fit.
    r   T)rJ  c                   |j         d         r/| |t          j                            || d           d         z  z
  }n| }|j         d         }d|z  t	          |          z  }| t          j        dt          j        z  |z            dz   z  dz  }t          |||j         d         z   ||          }t          t          j
        |          }t          t          j        |          }	t          t          j        |          }
||	|
fS )Nr]   )rcondr   r}  rk   )r   r  r  r  )r   r_   linalglstsqr)   logpir
   r   r1   r  r  r  )yr  dfresidr   r  r  r  r  r  r  s              rH   compute_icsz&ardl_select_order.<locals>.compute_ics  s    71: 	BIOOAqO==a@@@EEE{1~tgenn,erva"%i&011A56:QWQZC
 
 
 {44{44 0#66C~rJ   r   r   r   Nr   r]   rg   c                   |dk    r:d | D             }dt          d |                                D                       z   S t          t                    }g }|D ]U}| |         }|d         |                    |d                    .||d                                      |d                    Vt          |          }|r|dgk    rd}nt          |          }| D ]}|d         |vr|d         d ||d         <    |D ]"}||         t          ||                   ||<   #|ft          d |                                D                       z   S )NrN   c                    i | ]
\  }}||dS )Nr   rN   )rZ   rt   r  s      rH   ru   z<ardl_select_order.<locals>.perm_to_tuple.<locals>.<dictcomp>  s    888$!Q!-A---rJ   r   c              3  $   K   | ]\  }}||fV  d S rr   rN   rZ   rt   r[   s      rH   	<genexpr>z;ardl_select_order.<locals>.perm_to_tuple.<locals>.<genexpr>  s*      ==41aA======rJ   r   r]   c              3  $   K   | ]\  }}||fV  d S rr   rN   r  s      rH   r  z;ardl_select_order.<locals>.perm_to_tuple.<locals>.<genexpr>  s*       > >DAq!Q > > > > > >rJ   )r   r  r   r}   r   r  )r   permr  y_lagsr[   r   s         rH   perm_to_tuplez(ardl_select_order.<locals>.perm_to_tuple  sr   2::88$888A%==17799======= 	) 	)Aq'C1v~c!f%%%%#a&	  Q((((GG 	#A3FF6]]F 	! 	!C1vQ3q6#5 #a&	 	' 	'Cv!qv#y5 > >AGGII > > >>>>>rJ   c                    g | ]}d |fS rr   rN   r   s     rH   r\   z%ardl_select_order.<locals>.<listcomp>  s    +++aq	+++rJ   c                    g | ]}|fS rN   rN   )rZ   r   rt   s     rH   r\   z%ardl_select_order.<locals>.<listcomp>  s    '''aV'''rJ   c                    g | ]}|S rN   rN   )rZ   as     rH   r\   z%ardl_select_order.<locals>.<listcomp>  s    ///1Q///rJ   c                >    g | ]\  }}|d d d |         f         S rr   rN   )rZ   r   r  ios      rH   r\   z%ardl_select_order.<locals>.<listcomp>  s1     M M M41a111g1g: M M MrJ   r   rk   )r  r  r  c                    i | ]\  }}||	S rN   rN   r  s      rH   ru   z%ardl_select_order.<locals>.<dictcomp>  s    66641a!Q666rJ   )r%   r0   r   r   r_   r  r   r}   r   r   r   r  pinvrc   r   r   r  r   r	   rT  r   rR  r3   ).r   r  rg   r  r   r   rQ   r  r  r   r   r   r   r   orig_hold_backr  r#  blocksalwaysselectiter_orders	var_namesvarblockr  pinv_alwaysr   r  r  	always_dfr  r   r   r[   all_columnsr  r   r\  r   rf  lowestselected_orderr   r~  r  rt   s.                                               @@rH   r2   r2   T  s	   p itDDDN  $ #  D I\F_f_5vgGHHFIJJFFK
MM&/)**-...tE&/"7":Q">??@@AAAIf~  vs#IJJ/e4ek!nq&8 9 9::;;;A|A +innV,,s6{{## 	7 	7Aq	AFkAo66F1II+/**? ? ?2 QI
C 4"&,":$,,++7+++K%%'' 	( 	(DAq''''Q''''DDO/////005,,--qwqz"" 	A 	AA$[!44 A A#mD$//&;q!AAAtG*i@@CA	A
 ;' 
	4 
	4B M M M M9V;L;L M M MNNAqE+2a55t,C#BqrrF++ I I3l IJJSAXXTT3?@@@@JJa1S1WW$GHHHH**C"{1a33CHHa++B/EVF ! !#huo<<F N66>!""#5666Jq#   E %UC&IIIrJ   zZThe number of lags of the endogenous variable to include in the model. Must be at least 1.G   r   )rK  typedesczIf int, uses lags 0, 1, ..., order  for all exog variables. If a dict, applies the lags series by series. If ``exog`` is anything other than a DataFrame, the keys are the column index of exog (e.g., 0, 1, ...). If a DataFrame, keys are column names.z	int, dictr   z Construct an UECM from a formular   Returnsr  r5   zEstimation results.zSee Also)zstatsmodels.tsa.ardl.ARDLNz/Autoregressive distributed lag model estimationc            
          e Zd ZdZ	 	 	 dFdddddddddG fdZdH fd!ZdI fd#Zd$ ZdJd&Z e	 e
e                    d'dd(d)dKd0            Ze	 dLdMd3            Z	 	 	 	 	 	 	 dNdOd>Ze e	e                                                    d2d                     	 	 	 dPddddddd@dQ fdE                        Z xZS )Rr4   a  
    Unconstrained Error Correlation Model(UECM)

    Parameters
    ----------
    endog : array_like
        A 1-d endogenous response variable. The dependent variable.
    lags : {int, list[int]}
        The number of lags of the endogenous variable to include in the
        model. Must be at least 1.
    exog : array_like
        Exogenous variables to include in the model. Either a DataFrame or
        an 2-d array-like structure that can be converted to a NumPy array.
    order : {int, sequence[int], dict}
        If int, uses lags 0, 1, ..., order  for all exog variables. If a
        dict, applies the lags series by series. If ``exog`` is anything
        other than a DataFrame, the keys are the column index of exog
        (e.g., 0, 1, ...). If a DataFrame, keys are column names.
    fixed : array_like
        Additional fixed regressors that are not lagged.
    causal : bool, optional
        Whether to include lag 0 of exog variables.  If True, only includes
        lags 1, 2, ...
    trend : {'n', 'c', 't', 'ct'}, optional
        The trend to include in the model:

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

        The default is 'c'.

    seasonal : bool, optional
        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.
    deterministic : DeterministicProcess, optional
        A deterministic process.  If provided, trend and seasonal are ignored.
        A warning is raised if trend is not "n" and seasonal is not False.
    hold_back : {None, int}, optional
        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}, optional
        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 : {"none", "drop", "raise"}, optional
        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'.

    Notes
    -----
    The full specification of an UECM is

    .. math ::

       \Delta Y_t = \delta_0 + \delta_1 t + \delta_2 t^2
             + \sum_{i=1}^{s-1} \gamma_i I_{[(\mod(t,s) + 1) = i]}
             + \lambda_0 Y_{t-1} + \lambda_1 X_{1,t-1} + \ldots
             + \lambda_{k} X_{k,t-1}
             + \sum_{j=1}^{p-1} \phi_j \Delta Y_{t-j}
             + \sum_{l=1}^k \sum_{m=0}^{o_l-1} \beta_{l,m} \Delta X_{l, t-m}
             + Z_t \lambda
             + \epsilon_t

    where :math:`\delta_\bullet` capture trends, :math:`\gamma_\bullet`
    capture seasonal shifts, s is the period of the seasonality, p is the
    lag length of the endogenous variable, k is the number of exogenous
    variables :math:`X_{l}`, :math:`o_l` is included the lag length of
    :math:`X_{l}`, :math:`Z_t` are ``r`` included fixed regressors and
    :math:`\epsilon_t` is a white noise shock. If ``causal`` is ``True``,
    then the 0-th lag of the exogenous variables is not included and the
    sum starts at ``m=1``.

    See Also
    --------
    statsmodels.tsa.ardl.ARDL
        Autoregressive distributed lag model estimation
    statsmodels.tsa.ar_model.AutoReg
        Autoregressive model estimation with optional exogenous regressors
    statsmodels.tsa.statespace.sarimax.SARIMAX
        Seasonal ARIMA model estimation with optional exogenous regressors
    statsmodels.tsa.arima.model.ARIMA
        ARIMA model estimation

    Examples
    --------
    >>> from statsmodels.tsa.api import UECM
    >>> from statsmodels.datasets import danish_data
    >>> data = danish_data.load_pandas().data
    >>> lrm = data.lrm
    >>> exog = data[["lry", "ibo", "ide"]]

    A basic model where all variables have 3 lags included

    >>> UECM(data.lrm, 3, data[["lry", "ibo", "ide"]], 3)

    A dictionary can be used to pass custom lag orders

    >>> UECM(data.lrm, [1, 3], exog, {"lry": 1, "ibo": 3, "ide": 2})

    Setting causal removes the 0-th lag from the exogenous variables

    >>> exog_lags = {"lry": 1, "ibo": 3, "ide": 2}
    >>> UECM(data.lrm, 3, exog, exog_lags, causal=True)

    When using NumPy arrays, the dictionary keys are the column index.

    >>> import numpy as np
    >>> lrma = np.asarray(lrm)
    >>> exoga = np.asarray(exog)
    >>> UECM(lrma, 3, exoga, {0: 1, 1: 3, 2: 2})
    Nr   r   Fr   r   r   r  r   r   rg   r   rO   
_UECMOrderr   r   r   rQ   rR   r   r   r   r   r   r   r   rS   r   c                   t                                          |||||||||
|||	           t          | _        t          | _        d S )N)r   r   r   rQ   r   r   r   r   )r   r   r5   r   UECMResultsWrapperr   )rG   r   r   rg   rO   r   r   rQ   r   r   r   r   r   rD   s                rH   r   zUECM.__init__  sb      	' 	 	
 	
 	
 * 2rJ   rP   tuple[list[int], int]c                    t          |t                    s|t          d          t                                          ||          S )z(Check lags value conforms to requirementNzlags must be an integer or None)r^   r   rb   r   _check_lags)rG   r   r   rD   s      rH   r(  zUECM._check_lags  sD     4,, 	?=>>>ww""4333rJ   rh   c                   t          |t                    rA|                                D ]+\  }}t          |t                    s|t	          d          ,n&t          |t                    s|t	          d          t                                          |          }|st          d          |                                D ]\  }}|dgk    rt          d          |S )z#Check order conforms to requirementNz.order values must be positive integers or NonezVorder must be None, a positive integer, or a dict containing positive integers or Nonez2Model must contain at least one exogenous variabler   z7All included exog variables must have a lag length >= 1)r^   r   r  r   rb   r   rf   ra   )rG   rO   rt   r[   r   r   rD   s         rH   rf   zUECM._check_order  s   eW%% 
	  1!!Z00 Q]#H  
 UJ// 	5=7  
 $$U++ 	D    	 	HCqczz M    rJ   c                |   | j         j        }t          |t          j                  r
|j        pd}n8t          |t          j                  r|                                j        pd}nd}d| t          | j	        j
                  }|                    | d           | j         j        }t          |t          j                  }g }| j                                        D ][\  }}|T|r| d}	nd| d}	|                    |	           |	dd         }
|dd         D ]}|                    d|
 |            \| j        rt!          | j                  nd}fdt#          d	|          D             }|                    |           |                    |           |                    | j                   |fS )
r  r  zD..L1Nr  r  r   c                    g | ]	} d | 
S r   rN   )rZ   r   r!  s     rH   r\   z2UECM._construct_variable_names.<locals>.<listcomp>2  s'    GGGs6**S**GGGrJ   r]   )r   rj  r^   r   r  rK  r   squeezer}   r  r   r   r   r   r  r   r   r   r?  r   )rG   r   y_baser&  r   exog_pandasdexog_namesr   r   x_namelag_baser   r  dendog_namesr!  s                 @rH   r   zUECM._construct_variable_names  s   	$eRY'' 	Z&3FFr|,, 	]]__)0SFFFft.677&~~~&&&I'	 BL99))++ 		= 		=HC * #[[[FF)\\\Fv&&&!#2#;ss8 = =C&&';H';c';';<<<<$(J5TZAGGGGeAv6F6FGGG|$$${###t()))wrJ   r  c                &	   | j         rt          | j                   nd| _        t          j        | j        j        t          j                  }t          j        | j        j        d          |dd<   t          d| j        dz
            }t          ||d          \  | _
        | _        | j                                        | _        | j        j        }t!          |t"          j                  }t          j        | j        j        t          j                  }| j        j        dd         |dd<   |                                g}| j                                        D ]h\  }}	|	a|r|j                            |          }
n|}
| j        j        dd|
f         |dd<   |                    |                                           it          j        |          | _        |r|                                }nDt          j        | j        j        t          j                  }t          j        |d          |dd<   i }| j                                        D ]\  }}	|	|	dgk    rdn	|	dd         }	|	||<    |                     ||          | _        | j        | j        | j
        | j        | j        d| _        | j        g}| j                                        D ]q\  }}	|d	k    r(|                    t          j         |	                     3|	!                                D ])}|                    t          j         |                     *r|d         }t          j        |dd                   }d}| j        !                                D ]#}	t          ||	t          |	          nd          }$t          | j        |          | _        t          | j        d          | _        |tE          | j                  | _#        | j#        | j        k     rtI          d
          || j#        d         }|j%        d         |j%        d         k    r,tI          d|j%        d          d|j%        d          d          t          j&        |          | j#        d         |fS )r  r   r5  r]   Nr  r   r  )r   levelsr   rg   r   rg   r  r  r  r  )'r   r   r  r_   r  r   r   r3  diffr/   r  r  r  r  r  r   r^   r   r   copyr   r  r   get_locrg   r   r  _levelsr   r  r   r   r:  r   rX   r   ra   r   r-  )rG   r   dendogdlagr   r/  lvllvlsr   r   r]  dexog	adj_orderr  subvalr  r  r  s                     rH   r   zUECM._construct_regressors8  sQ   
 +/*;s4:!diorv66WTY_1555qrr
1dlQ&'''-fdU'K'K'K$"&"6"@"@"B"BI'	 BL99l49?BF33)/#2#&ABB

|))++ 	( 	(HC #+33C88CCC)."c2ABBCHHJJ'''t,,  	3NN$$EEL88E	222E!""I	))++ 	! 	!HC;#!**$$3ss8C IcNN&&ui88
 "4l_J[
 
 +**,, 	6 	6HCf}}bjoo....!jjll 6 6FMM"*V"4"4555561IofQRRj));%%'' 	O 	OCks3s888ANNKK4<554<++!$,//DO?T\))   $/##$9Q<#)A,&&4SYq\ 4 4 $'9Q<4 4 4   z!}}T_../44rJ   r   Tr   r   r=   r   r   r   r5   c                   |                      |||          \  }}}t          | ||||          }t          |          S )Nr   r   )r   r5   r%  r  s           rH   r   zUECM.fit  s[     /3ii /8 /
 /
+
O &*oU
 
 
 "#&&&rJ   ardlr0   c                j   d}i }|j         }|                                D ]k\  }}t          |          }t          ||                   |t	          |j                   z   k     r#t          |                    d                    |||<   l|j        d}	nQt          |j                  }t          |j                  |k    r#t          |                    d                    |}	 | |j	        j
        |	|j	        j        ||j        |j        |j        |j        |j        |j        ||j                  S )a|  
        Construct a UECM from an ARDL model

        Parameters
        ----------
        ardl : ARDL
            The ARDL model instance
        missing : {"none", "drop", "raise"}, default "none"
            How to treat missing observations.

        Returns
        -------
        UECM
            The UECM model instance

        Notes
        -----
        The lag requirements for a UECM are stricter than for an ARDL.
        Any variable that is included in the UECM must have a lag length
        of at least 1. Additionally, the included lags must be contiguous
        starting at 0 if non-causal or 1 if causal.
        zmUECM can only be created from ARDL models that include all {var_typ} lags up to the maximum lag in the model.	exogenous)var_typN
endogenous)r   r   r   r   r   rQ   r   r   )r   r  r   rc   rX   rQ   ra   formatr   r   rj  r   r   r   r   r   r   r   )
rk  rB  r   err	uecm_lagsr   r   r   max_valr   s
             rH   	from_ardlzUECM.from_ardl  s:   6A 	 	, 	% 	%HC#hhG73<  Gcdk/.B.B$BCC K!@!@AAA$IcNN<GG$,''G4<  G++ L!A!ABBBGsI I**]n;;,
 
 
 	
rJ   r   r   r'  rE  r(  rF  r   r*  r+  r,  c	                J   |durt          d          |                     |||||          \  }}}}}}	|	dk    rt          d          t          j        | j        j        d         t          j                  }
| j        |z  |
| j        j        d          d<   |
||dz            S )rH  Fz#dynamic forecasts are not supportedr   z)Out-of-sample forecasts are not supportedNr]   )NotImplementedErrorrQ  r_   r2  r   r   r3  r   )rG   r   r'  r(  rF  rg   r*  r   r+  r)  preds              rH   r^  zUECM.predict  s    | %%&KLLL6:6N6ND(E37
 7
3hsG a<<%;   wtz'*BF33$(Gf$4dgmA  !EC!GO$$rJ   rN  r_  r`  r   r:   ra  c               \    t                                          |||||||||	|
|          S )Nr_  )r   ri  )rk  r`  r   r   rO   r   rQ   r   r   r   r   r   rD   s               rH   ri  zUECM.from_formula  sG    " ww##' $ 
 
 	
rJ   ro  )r   r  r   r   rg   r   rO   r#  r   r   r   r   rQ   rR   r   rR   r   r   r   r   r   r   r   r   rS   r   )r   rP   r   r   rS   r&  )rO   rh   rq  )r   r=   r   r   r   rR   rS   r5   )r   )rB  r0   r   r   rr  )r   r   r'  rE  r(  rE  rF  rR   rg   r   r*  r   r   r   r+  r   rS   r,  rs  )r`  r=   r   r:   r   rP   rO   rh   r   r   rQ   rR   r   rR   r   r   r   r   r   r   r   ra  rS   r4   )rE   rK   rL   rt  r   r(  rf   r   r   r   r=   fit_docr   rw  rK  r^  from_formula_doc__str__replaceri  rx  ry  s   @rH   r4   r4   X  s       w wz $(033 %)59 $!4:3 3 3 3 3 3 3 3B4 4 4 4 4 4     4! ! !FM5 M5 M5 M5^ Xcc'll $#'' ' ' ' ' ' EK9
 9
 9
 9
 [9
| @D=A.226/337I% I% I% I% I%V X&&((00@@AA
 ,-03
 59 $!,2
 
 
 
 
 
 
 BA [
 
 
 
 
rJ   r4   c                      e Zd ZU dZi Zded<   	 d+d,dZed-d            Zed-d            Z	ed-d            Z
ed-d            Zd.d/dZd.d0dZed-d            Zd1dZd Z	 	 	 	 	 	 d2d3d*ZdS )4r5   a  
    Class to hold results from fitting an UECM model.

    Parameters
    ----------
    model : UECM
        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.
    r   r  r  r   r,  rK  r=   rS   "NDArray | pd.Series | pd.DataFramec                   t          | j        j        t                    s|S | j        j        d         j        d         }| j        j        d         j        d         }| j        j        d ||z            }t          |||z             D ],}||         }|                    d          r|d d         ||<   -|j	        dk    rt          j        |||          S t          j        |||          S )	Nr   r]   r5  r+  rk   )r   rf  rf  rK  )r^   r~  r   r   r   r   r%  r   endswithrm   r   r   r  )rG   r   rK  ndetnlvllblsr   lbls           rH   _ci_wrapzUECMResults._ci_wrapS  s     $*/:66 	Jz!/28;z!(+1!4z$_t_5tTD[)) 	# 	#Aq'C||E"" #crc(Q8q==<T>>>>yDt4444rJ   r  c                   | j         j        d         j        d         }| j         j        d         j        d         }t          j        | j                  |         }|                     | j        d||z            |z  d          S )z3Parameters of normalized cointegrating relationshipr   r]   r5  N	ci_params)r~  r   r   r_   r:  r   r^  )rG   rZ  r[  r#  s       rH   r`  zUECMResults.ci_paramsc  sp     z!/28;z!(+1!4z$+&&t,}}T[4$;7$>LLLrJ   c                    t          j        t          j        |                                                     }|                     |d          S )z8Standard Errors of normalized cointegrating relationshipci_bse)r_   sqrtdiagci_cov_paramsr^  )rG   bses     rH   rb  zUECMResults.ci_bsek  s=     gbgd00223344}}S(+++rJ   c                j   | j         j        d         j        d         }t          j                    5  t          j        d           t          j        | j                  t          j        | j	                  z  }t          j
        ||<   ddd           n# 1 swxY w Y   |                     |d          S )z1T-values of normalized cointegrating relationshipr   r]   ignoreN
ci_tvalues)r~  r   r   r   catch_warningssimplefilterr_   r:  r`  rb  r3  r^  )rG   rZ  tvaluess      rH   ri  zUECMResults.ci_tvaluesq  s     z!/28;$&& 	# 	#!(+++j002:dk3J3JJGFGDM	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# }}Wl333s   ABBBc                $   t          j                    5  t          j        d           ddt          j                            t          j        | j                            z
  z  }ddd           n# 1 swxY w Y   | 	                    |d          S )z1P-values of normalized cointegrating relationshiprh  rk   r]   N
ci_pvalues)
r   rj  rk  r   normcdfr_   absri  r^  )rG   pvaluess     rH   rn  zUECMResults.ci_pvalues{  s     $&& 	H 	H!(+++1uz~~bfT_.E.EFFFGG	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H }}Wl333s   AA11A58A5r  r  r8   Float64Array | pd.DataFramec                   t          |d          }| j        r3t          j        | j                                      d|dz  z
            }n,t          j                                        d|dz  z
            }| j        }| j        }|||z  z
  |||z  z   g}t          |t          j                  st          j        |          S t          j        |d          }ddg|_        |S )Nr  r]   rk   r5  rB   rA   )r$   r   r   tdf_residppfro  r`  rb  r^   r   r  r_   r  r=  r   )rG   r  qpseoutr  s          rH   ci_conf_intzUECMResults.ci_conf_int  s    5'**: 	0&&**1uqy=99AA
  UQY//AN[1r6z1q2v:&!RY'' 	(?3'''Ys###w'
	rJ   r   c                    |f fd	}t                      } j        j        d         j        d         } j        j        d         j        d         }t	           j        j                  d ||z            }t           j        j        |          }t           j         j	         j
         j        ||          }t          |          }	d|	_        |j                            |	           |S )Nc                R    t          j                            |                     S rr   )r_   r:  r|  )r  rG   s    rH   _ciz#UECMResults.ci_summary.<locals>._ci  s!    :d..u55666rJ   r   r]   r5  )r  r%  )r   rf  rl  rr  conf_intr~  zCointegrating Vector)r   r~  r   r   r}   r%  r
   r  r`  rb  ri  rn  r   r  tablesr   )
rG   r  r  r  rZ  r[  r%  r~  r   tabs
   `         rH   
ci_summaryzUECMResults.ci_summary  s     	7 	7 	7 	7 	7 	7 yyz!/28;z!(+1!4$*/00D4KA

.:
 
 
 >OO
 
 
 T""*	3rJ   c                   | j         j        d         }| j         j        j        }t	          |t
          j                  }|r|n| j         j        }t          j	        |          | j         j
        g}| j         j                                        D ]V\  }}|O|r.|                    t          j	        ||                              7|                    |d d |f                    Wt          j        |          }|| j        z  }t	          | j         j        t                     s|S | j         j        j        j        }	t          j        ||	d          S )Nr   	ci_residsrX  )r~  r   r   r   r^   r   r   rg   r_   r:  r   r   r  r   r  r`  r   rj  rf  r  )
rG   r  rg   	is_pandascolsr   r   ci_xresidsrf  s
             rH   r  zUECMResults.ci_resids  s'   J/z(tR\22	 5ttdjo
1tz/0*,2244 	. 	.JC  .KK
49 5 56666KKQQQV---t$$&$*/:66 	M
*0yu;????rJ   c                   | j         j        d         j        d         }| j         j        d         j        d         }t          t	          ||z                       }|                                 }t          j        |          }|t          j        ||                   }|j        d         }t          j        | j	                  d||z            }||         }	t          j
        ||f          }
t	          |          D ]'}||k    r	d|	z  |
||f<   ||          |	dz  z  |
||f<   (|
|z  |
j        z  }|                     |          S )z6Covariance of normalized of cointegrating relationshipr   r]   r5  r   Nrk   )r~  r   r   r}   r   r   r_   r:  ix_r   r  Tr^  )rG   rZ  r[  r]  covcov_aci_covmr   r#  r  r   s               rH   re  zUECMResults.ci_cov_params  s2   z!/28;z!(+1!45%%&&oo
3rvc3''(LODK((4$;7d|HaVq 	0 	0ADyy$hAadG )tQw/AagJJVac!}}V$$$rJ   c                    dS )r  NrN   rF   s    rH   r  zUECMResults._lag_repr  s      rJ   r   NT順 caseLiteral[1, 2, 3, 4, 5]r   r   r   rR   
asymptoticnsimrX   seedHint | Sequence[int] | np.random.RandomState | np.random.Generator | Nonec           	        | j         }|dk    rd}	n	|dv rd}	nd}	d |j                                        D             }
t          |j        j        t          |j                  |j        j        |
|j	        |	          }|
                    |||          }|                                }t          |j         j                  }|dk    rt          j        |          }nz|d	k    rt          j        |dz             }n\|d
k    rt          j        d|dz             }n=|dk    rt          j        d|d	z             }n|dk    rt          j        d	|d	z             }t          j        |j        d         |j        d         f          }t%          |          D ]\  }}d|||f<   ||z  |j        z  }||j        z  }|j        t          j                            |          z  |z  |j        d         z  }|}|r|dk    rt.          j        }||f}||dz            }||dz            }t3          j        ||dt.          j                  }d|j        _        t3          j        t?          |||d          t?          |||d          d          }n*|j         j        d         }tC          ||||||          \  }}tE          |||dd          S )ad  
        Cointegration bounds test of Pesaran, Shin, and Smith

        Parameters
        ----------
        case : {1, 2, 3, 4, 5}
            One of the cases covered in the PSS test.
        cov_type : str
            The covariance estimator to use. The asymptotic distribution of
            the PSS test has only been established in the homoskedastic case,
            which is the default.

            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 small-sample corrections should be applied
            to the covariance estimator.
        asymptotic : bool
            Flag indicating whether to use asymptotic critical values which
            were computed by simulation (True, default) or to simulate a
            sample-size specific set of critical values. Tables are only
            available for up to 10 components in the cointegrating
            relationship, so if more variables are included then simulation
            is always used. The simulation computed the test statistic under
            and assumption that the residuals are homoskedastic.
        nsim : int
            Number of simulations to run when computing exact critical values.
            Only used if ``asymptotic`` is ``True``.
        seed : {None, int, sequence[int], RandomState, Generator}, optional
            Seed to use when simulating critical values. Must be provided if
            reproducible critical value and p-values are required when
            ``asymptotic`` is ``False``.

        Returns
        -------
        BoundsTestResult
            Named tuple containing ``stat``, ``crit_vals``, ``p_values``,
            ``null` and ``alternative``. The statistic is the F-type
            test statistic favored in PSS.

        Notes
        -----
        The PSS bounds test has 5 cases which test the coefficients on the
        level terms in the model

        .. math::

           \Delta Y_{t}=\delta_{0} + \delta_{1}t + Z_{t-1}\beta
                        + \sum_{j=0}^{P}\Delta X_{t-j}\Gamma + \epsilon_{t}

        where :math:`Z_{t-1}` contains both :math:`Y_{t-1}` and
        :math:`X_{t-1}`.

        The cases determine which deterministic terms are included in the
        model and which are tested as part of the test.

        Cases:

        1. No deterministic terms
        2. Constant included in both the model and the test
        3. Constant included in the model but not in the test
        4. Constant and trend included in the model, only trend included in
           the test
        5. Constant and trend included in the model, neither included in the
           test

        The test statistic is a Wald-type quadratic form test that all of the
        coefficients in :math:`\beta` are 0 along with any included
        deterministic terms, which depends on the case. The statistic returned
        is an F-type test statistic which is the standard quadratic form test
        statistic divided by the number of restrictions.

        References
        ----------
        .. [*] Pesaran, M. H., Shin, Y., & Smith, R. J. (2001). Bounds testing
           approaches to the analysis of level relationships. Journal of
           applied econometrics, 16(3), 289-326.
        r]   rN  rk      r   ctc                4    i | ]\  }}|t          |          S rN   )r   )rZ   r   r   s      rH   ru   z+UECMResults.bounds_test.<locals>.<dictcomp>S	  s$    DDD83c#hhDDDrJ   )rO   rQ   r   r   rk   r        r   
   )T)FrB   rA   r  
percentileFT)r   r  r  zNo CointegrationzPossible Cointegration)#r~  r   r  r4   r   r   r   r   r   rQ   r   r   rc   r   r_   aranger  r   rT  r  r   r  invr*   r;   r   r   crit_percentilesrf  rK  r  _pss_pvaluer  _pss_simulater6   )rG   r  r   r   r   r  r  r  r~  r   rO   uecmr  r  nvarrestrr   r]  vcvcoefr9   rt   cvr   rA   rB   r;   r<   r   s                                 rH   bounds_testzUECMResults.bounds_test  s   ` 
199EEV^^EEEDDu|/A/A/C/CDDDJJ <
 
 
 hh85hIInn39'((1999T??DDQYY9TAX&&DDQYY9Qq))DDQYY9Qq))DDQYY9Qq))DHdjmSYq\233oo 	 	FAsAafII#gm3:~v	c***T1AGAJ> 	!r''$.Bd)CsW}%EsX~&E%00):  I $0IO y(q$>>(q$==  HH 9?1%D"/aDt$# # #Ix  $
 
 	
rJ   )r  )r   r,  rK  r=   rS   rU  )rS   r  r  )r  r8   rS   rs  r  )rS   rs  )r   NTTr  N)r  r  r   r=   r   r   r   rR   r  rR   r  rX   r  r  )rE   rK   rL   rt  r  rM   r^  r   r`  rb  ri  rn  r|  r  r  re  r  r  rN   rJ   rH   r5   r5   >  s         $  F ,.5 5 5 5 5  M M M ^M , , , ^,
 4 4 4 ^4 4 4 4 ^4    $    4 @ @ @ ^@&% % % %(E E E $#'
 q
 q
 q
 q
 q
 q
 q
rJ   r9   r8   rt   r  i1c                t  
 |||f}t           j        |         }t           j        |         }t           j        |         }t	          j        |           
| |k    r|n|}
fdt          t          |                    D             }	dt          j	        
                    |	t	          j        |          z            z
  S )Nc                    g | ]}|z  S rN   rN   )rZ   r   log_stats     rH   r\   z_pss_pvalue.<locals>.<listcomp>	  s    ,,,1,,,rJ   r]   )r*   large_psmall_p	stat_starr_   r  r   rc   r   ro  rp  array)r9   rt   r  r  r   r  r  	thresholdry  r  r  s             @rH   r  r  	  s    dB-C!)#.G!)#.G#-c2Ivd||H)##A,,,,eCFFmm,,,Auz~~a"(1++o....rJ   r  r   r  r  r  tuple[pd.DataFrame, pd.Series]c                d	   t          |t          j        j                  s t          j                            |          }n#t          |t          j        j                  sJ |}d }dd|z  |z  z  }|}	d}
t          j        |          }t          j        |          }|	dk    rpt          |	|          }|                    ||dz   |f          }t          j        |d d d d d df         d          }t          j        |d d d d dd f         d          }|d d d d dd f         }t          j	        |d          }|dv r't          j        |||dz   f          }d|d d d d df<   ng|d	v rLt          j        |||d
z   f          }t          j
        |t                    |d d d d df<   d|d d d d df<   nt          j        |||f          }|d d d df         |d d d d d df<   |d d d df         |d d d d d|f<    |||          }|j        d         |j        d
         z
  }|d
z                      d          |z  }|dv r|d d d d dd f         }n|dk    r|d d d d dd f         }|dv r( |||          }|j        d         |j        d         z
  }n!t          j        |          }|j        d         }|d
z                      d          |d
z                      d          z
  |z  }||z  }|||
|
|z   <   |d d d df         |d d d d d|f<    |||          }|d
z                      d          |z  }|dv r|d d d d dd f         }n|dk    r|d d d d dd f         }|dv r( |||          }|j        d         |j        d         z
  }n!t          j        |          }|j        d         }|d
z                      d          |d
z                      d          z
  |z  }||z  }|||
|
|z   <   |
|z  }
|	|z  }	|	dk    pt          j        }t#          j        t          j        ||          t          j        ||          d|          }d|j        _        t#          j        | |k                                     | |k                                     d          }||fS )Nc                   t          j        | g d          }t          j        ||           }t          j        ||          }t           j                            ||          }t          j        |t          j        | |          z
            S )N)r   rk   r]   )r_   	transposematmulr  solver-  )rhslhsrhs_txpxxpybs         rH   _vectorized_ols_residz,_pss_simulate.<locals>._vectorized_ols_resid	  so    S))),,is##is##IOOC%%z#	#q 1 11222rJ   i r{  r   r]   r5  r  r  )r  r  rk   r  )r  r  r  )r  r  r  r  r  r  )r^   r_   randomRandomStatedefault_rngr   re   standard_normalr  r6  r  r8   r   sumr-  r*   r  r   r   r  rf  rK  r  r  )r9   rt   r  r   r  r  rsr  
block_size	remainingr]  f_upperf_lowerto_doer  x_upperx_lowerr  r  ur  s2rhs_rurnrestfr  r;   r<   s                                 rH   r  r  	  st    dBI122 Y""4(($	 5666663 3 3 TA.JI
ChtnnGhtnnG
a--Iz**tax344Ia111bqbk***)AaaaABBhKa000AAAqqq!""H+gaa   6>>(E4Q/00CC111bMMV^^(E4Q/00CId%888C111bMC111bMM(E4+,,C!!!SbS&	AAAqqq"1"H CRCAAAqqq!A#I!!#s++Yq\CIaL(dZZ]]R6>>111bcc	NEEQYY111bcc	NE9&&uc22BIbMEKO3EECBIbME!e[[^^q!tjjmm+u4	R%&cEk!" !CRCAAAqqq!A#I!!#s++dZZ]]R6>>111bcc	NEEQYY111bcc	NE9&&uc22BIbMEKO3EECBIbME!e[[^^q!tjjmm+u4	R%&cEk!"uU	y a--| +;]7,<==]7,<==	
 	
   I (IOy'>''))TG^4I4I4K4KLL H hrJ   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%  Nr  rN   rJ   rH   r%  r%  
  r  rJ   r%  )rO   rP   rQ   rR   rS   rR   )rg   r   rO   rh   rQ   rR   rS   ri   )r   )r   r  r  rX   rg   r   r  r  r   r   r   r   rQ   rR   r  r  r  rR   r   rR   r   r   r   r   r   r   r   ra  rS   r3   )
r9   r8   rt   rX   r  rX   r  rR   rS   r8   )r9   r8   rt   rX   r  r  r   rX   r  rX   r  r  rS   r  )z
__future__r   statsmodels.compat.pandasr   r   r   collectionsr   datetimedt	itertoolsr   r	   textwraptypesr
   typingr   r   r   r   r   r   collections.abcr   r   r   r   numpyr_   pandasr   scipyr   statsmodels.base.datar   statsmodels.base.wrapperr#  wrapperr  statsmodels.iolib.summaryr   r   #statsmodels.regression.linear_modelr   statsmodels.tools.decoratorsr   statsmodels.tools.docstringr   r   r   statsmodels.tools.sm_exceptionsr   statsmodels.tools.typingr   r   r    r!   statsmodels.tools.validationr"   r#   r$   r%   statsmodels.tsa.ar_modelr&   r'   r(   r)   statsmodels.tsa.ardlr*   statsmodels.tsa.arima_processr+   statsmodels.tsa.baser,   statsmodels.tsa.base.predictionr-   statsmodels.tsa.deterministicr.   statsmodels.tsa.tsatoolsr/   matplotlib.figure
matplotlib__all__r6   rX   r  r#  rh   r`   r   rf   r   r0   r^  rt  docextract_parametersr  r1   ResultsWrapperr   populate_wrapperr3   r2   
lags_descr
lags_paramorder_descrorder_paramri  rQ  replace_blockinsert_parametersr   rP  _dssee_alsoinsertr4   r5   r  r  r%  rN   rJ   rH   <module>r
     s   " " " " " " N N N N N N N N N N # # # # # #     + + + + + + + +  ! ! ! ! ! !                8 7 7 7 7 7 7 7 7 7                , , , , , , ' ' ' ' ' ' ' ' ' = = = = = = = = 3 3 3 3 3 3 7 7 7 7 7 7 O O O O O O O O O O @ @ @ @ @ @                                  5 4 4 4 4 4 1 1 1 1 1 1 * * * * * * = = = = = = > > > > > > + + + + + +       z   $ 4d8Xc]#:;;<
SM5hsmT12	23	5
 2:
   65 5 5 5p[
 [
 [
 [
 [
7 [
 [
 [
| i$%%((III1 
@ @ @ @ @. @ @ @F
    ,     (+ 6 6 6## ## ## ## ## 7 ## ## ##V -0YJ !% %15 (.YJ YJ YJ YJ YJ YJx X] 

 YFZ@@@
hm*   iW;[III9T.677    y*L M M M  " "6 * * *  " "7 + + +  " "6: 6 6 6  " "6; 7 7 7 )DH$
%
%   		"m.C-DEEF   ;{:&HOO	01>?	
   *h///c
 c
 c
 c
 c
4 c
 c
 c
LN
 N
 N
 N
 N
+ N
 N
 N
b
/ / / /i i i iX    ,     (+ 6 6 6 6 6rJ   