a
    \:b<W                     @   s   d Z ddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZmZ ddlm  m  mZ ddlmZ ddlm  m  mZ ddlmZmZ d	d
 ZG dd dejZG dd deZG dd deeZdS )u   
Vector Autoregression (VAR) processes

References
----------
Lütkepohl (2005) New Introduction to Multiple Time Series Analysis
    N)slogdet)rename_trend)deprecated_alias)approx_fprimeapprox_hess)
IRAnalysis)
VARProcess
VARResultsc                 C   sD   |d u r | dks| dkr t d|d u r@| dks8| dkr@t dd S )NAABz+SVAR of type A or AB but A array not given.Bz+SVAR of type B or AB but B array not given.)
ValueError	svar_typer
   r    r   Clib/python3.9/site-packages/statsmodels/tsa/vector_ar/svar_model.py
svar_ckerr   s    r   c                       s   e Zd ZdZeddddZd% fdd		Zd&ddZdd Zd'ddZ	dd Z
dd Zdd Zd( fdd	Zdd  Zd!d" Zd#d$ Z  ZS ))SVARaJ  
    Fit VAR and then estimate structural components of A and B, defined:

    .. math:: Ay_t = A_1 y_{t-1} + \ldots + A_p y_{t-p} + B\var(\epsilon_t)

    Parameters
    ----------
    endog : array_like
        1-d endogenous response variable. The independent variable.
    dates : array_like
        must match number of rows of endog
    svar_type : str
        "A" - estimate structural parameters of A matrix, B assumed = I
        "B" - estimate structural parameters of B matrix, A assumed = I
        "AB" - estimate structural parameters indicated in both A and B matrix
    A : array_like
        neqs x neqs with unknown parameters marked with 'E' for estimate
    B : array_like
        neqs x neqs with unknown parameters marked with 'E' for estimate

    References
    ----------
    Hamilton (1994) Time Series Analysis
    yendogz0.11.0)Zremove_versionNnonec                    sR  t  j|d |||d | jjd | _g d}||vrDtdt| || _t||| || _	|| _
|d u rt| j}tj|jtd | _}	nt|dk|dk}	|	| _|d u rt| j}tj|jtd | _}
nt|dk|dk}
|
| _tj|jtd}||	  ||	 < tj||	< || _tj|jtd}||
  ||
 < tj||
< || _d S )N)missing   )r
   r   r   z%SVAR type not recognized, must be in )ZdtypeEe)super__init__r   shapeneqsr   strr   r   
A_original
B_originalnpZidentityzerosboolA_maskZ
logical_orB_maskfloatnanr
   r   )selfr   r   datesZfreqr
   r   r   typesr%   r&   ZAnumZBnum	__class__r   r   r   :   s:    

zSVAR.__init__olscFmlebfgs  c              	   C   s   |}t |}|dur\| j||d}||vr>td|t|f || }|rhtd||f  n|du rhd}t| j| | _| ||}| j	||||	|
||dS )uz  
        Fit the SVAR model and solve for structural parameters

        Parameters
        ----------
        A_guess : array_like, optional
            A vector of starting values for all parameters to be estimated
            in A.
        B_guess : array_like, optional
            A vector of starting values for all parameters to be estimated
            in B.
        maxlags : int
            Maximum number of lags to check for order selection, defaults to
            12 * (nobs/100.)**(1./4), see select_order function
        method : {'ols'}
            Estimation method to use
        ic : {'aic', 'fpe', 'hqic', 'bic', None}
            Information criterion to use for VAR order selection.
            aic : Akaike
            fpe : Final prediction error
            hqic : Hannan-Quinn
            bic : Bayesian a.k.a. Schwarz
        verbose : bool, default False
            Print order selection output to the screen
        trend, str {"c", "ct", "ctt", "n"}
            "c" - add constant
            "ct" - constant and trend
            "ctt" - constant, linear and quadratic trend
            "n" - co constant, no trend
            Note that these are prepended to the columns of the dataset.
        s_method : {'mle'}
            Estimation method for structural parameters
        solver : {'nm', 'newton', 'bfgs', 'cg', 'ncg', 'powell'}
            Solution method
            See statsmodels.base for details
        override : bool, default False
            If True, returns estimates of A and B without checking
            order or rank condition
        maxiter : int, default 500
            Number of iterations to perform in solution method
        maxfun : int
            Number of function evaluations to perform

        Notes
        -----
        Lütkepohl pp. 146-153
        Hamilton pp. 324-336

        Returns
        -------
        est : SVARResults
        N)maxlagsverbosez#%s not recognized, must be among %szUsing %d based on %s criterionr   )trendsolveroverridemaxitermaxfun)
r   Zselect_orderr   sortedprintlenr   nobs_get_init_params_estimate_svar)r)   A_guessB_guessr3   methodZicr5   r4   Zs_methodr6   r7   r8   r9   lagsZ
selectionsstart_paramsr   r   r   fitm   s&    7

zSVAR.fitc                 C   s   | j  }| j }|dv r\|du r6tdg| }q`t||kr`d}t|t||f ng }| j }|dv r|du rtdg| }qt||krd}t|t||f ng }tj	||f S )zL
        Returns either the given starting or .1 if none are given.
        )abaNg?z/len(A_guess) = %s, there are %s parameters in A)rF   bz/len(B_guess) = %s, there are %s parameters in B)
r   lowerr%   sumr"   arrayr<   r   r&   Zr_)r)   r@   rA   Zvar_typeZ
n_masked_amsgZ
n_masked_br   r   r   r>      s$    


zSVAR._get_init_paramsnmc                 C   s   t |}| j}	t j|	||dd}
|	|d }tjj|
|ddd }|t|
| }t|}|| j	| |  }t|j
|}|| }|| _| j||||d\}}| j}| j}t|	|
|||| j|| jj| ||||dS )	zQ
        lags : int
        trend : {str, None}
            As per above
        raise)r5   Zhas_constantN)Zrcondr   )r7   r6   r8   )namesr5   r*   modelr
   r   r%   r&   )utilget_trendorderr   Zget_var_endogr"   linalgZlstsqdotr<   r   Tsigma_u	_solve_ABr%   r&   SVARResultsZendog_namesdatar*   )r)   rD   rC   r8   r9   r5   r6   r7   k_trendr   zZy_sampleZ
var_paramsZresidZavobsZdf_residZsseZomegar
   r   r%   r&   r   r   r   r?      s,    


zSVAR._estimate_svarc                 C   s   | j }| j}| j}| j}t|| }t|| }|durH|d| ||< |durd||||  ||< | j}| j}	| j}
t	t
||}t	t	|j||
}t|d \}}|| }| d |	tdtj  tt
|d  | t|  }|S )z
        Loglikelihood for SVAR model

        Notes
        -----
        This method assumes that the autoregressive parameters are
        first estimated, then likelihood with structural parameters
        is estimated
        N   g       @)r
   r   r%   r&   r<   r=   r   rW   r"   rU   nplinvrV   r   logZpiZdetZtrace)r)   paramsr
   r   r%   r&   A_lenZB_lenr=   r   rW   WZtrc_inZsignZb_logdetZ	b_slogdetZliklr   r   r   loglike  s2    zSVAR.loglikec                 C   s   | j }t||ddS )z
        Return the gradient of the loglike at AB_mask.

        Parameters
        ----------
        AB_mask : unknown values of A and B matrix concatenated

        Notes
        -----
        Return numerical gradient
        g:0yE>)epsilon)rd   r   r)   ZAB_maskrd   r   r   r   score-  s    z
SVAR.scorec                 C   s   | j }t||S )z,
        Returns numerical hessian.
        )rd   r   rf   r   r   r   hessian<  s    zSVAR.hessianc                    s   | j }| j}| j}| j}t|| }	|d|	 ||< ||	d ||< |sj| ||}
| |
 | |
 ntd t	 j
|||dddj}|d|	 ||< ||	d ||< ||fS )a  
        Solves for MLE estimate of structural parameters

        Parameters
        ----------

        override : bool, default False
            If True, returns estimates of A and B without checking
            order or rank condition
        solver : str or None, optional
            Solver to be used. The default is 'nm' (Nelder-Mead). Other
            choices are 'bfgs', 'newton' (Newton-Raphson), 'cg'
            conjugate, 'ncg' (non-conjugate gradient), and 'powell'.
        maxiter : int, optional
            The maximum number of iterations. Default is 500.

        Returns
        -------
        A_solve, B_solve: ML solutions for A, B matrices
        Nz+Order/rank conditions have not been checkedg#B;F)rD   rB   r8   ZgtolZdisp)r%   r&   r
   r   r<   
_compute_Jcheck_order
check_rankr;   r   rE   ra   )r)   rD   r8   r7   r6   r%   r&   r
   r   rb   JZretvalsr,   r   r   rX   C  s&    
zSVAR._solve_ABc              	   C   sP  | j }| j}| j}| j}ttd| |d  |d g}t|D ]}|}	||	  kr^|k rBn qBttd| |d  dg}
d|
t|| |	d  d|d  |  d < t||g}d||	|f< d|||	f< |t|
|	dd d d f j
 }|	d }	qJqB|j
}t|}t|d t|| f}t|d t|| f}d}d}t|| dkrtj	|dd}t|d D ]$}|| rzd|||f< |d7 }qzt|| dkrtj	|dd}t|d D ]$}|| rd|||f< |d7 }qt|}tt|t|||}d| }tt|t|||}tj||dd	}|S )
Ng      ?r   r]   Fr   )orderrO   g       Zaxis)r   rW   r%   r&   r"   r#   intrangerU   ZravelrV   r^   Zpinvr<   r_   Zkronappend)r)   A_solveB_solver   rW   r%   r&   ZD_nTjiuZTijZD_nZD_plZS_BZS_DZj_dZA_veckZB_vecZinvAZJ_p1iZJ_p1ZJ_p2rl   r   r   r   ri   r  sN    ",$



zSVAR._compute_Jc                 C   s(   t j|ddt j|ddk r$tdd S )Nr   ro   r   z3Order condition not met: solution may not be unique)r"   sizer   )r)   rl   r   r   r   rj     s    zSVAR.check_orderc                 C   s*   t j|}|t j|ddk r&tdd S )Nr   ro   z3Rank condition not met: solution may not be unique.)r"   rT   Zmatrix_rankry   r   )r)   rl   Zrankr   r   r   rk     s    zSVAR.check_rank)NNNNr   )NNNr.   Nr/   Fr0   r1   Fr2   r2   )r/   rM   F)Fr1   )__name__
__module____qualname____doc__r   r   r   rE   r>   r?   rd   rg   rh   rX   ri   rj   rk   __classcell__r   r   r,   r   r      s&     3   
N  
,'/<r   c                   @   s.   e Zd ZdZd
ddZdddZddd	ZdS )SVARProcessa  
    Class represents a known SVAR(p) process

    Parameters
    ----------
    coefs : ndarray (p x k x k)
    intercept : ndarray (length k)
    sigma_u : ndarray (k x k)
    names : sequence (length k)
    A : neqs x neqs np.ndarray with unknown parameters marked with 'E'
    A_mask : neqs x neqs mask array with known parameters masked
    B : neqs x neqs np.ndarry with unknown parameters marked with 'E'
    B_mask : neqs x neqs mask array with known parameters masked
    Nc                 C   s>   t || _|jd | _|| _|| _|| _|| _|| _|| _	d S )Nr   )
r<   k_arr   r   coefs	interceptrW   rs   rt   rP   )r)   r   r   rW   rs   rt   rP   r   r   r   r     s    
zSVARProcess.__init__
   c                 C   s   t dS )z'

        Unavailable for SVAR
        N)NotImplementedError)r)   maxnPr   r   r   orth_ma_rep  s    zSVARProcess.orth_ma_repc                    sJ    du r&| j }| j}tt|| | j|d}t fdd|D S )zW

        Compute Structural MA coefficient matrices using MLE
        of A, B
        Nr   c                    s   g | ]}t | qS r   )r"   rU   ).0r   r   r   r   
<listcomp>      z+SVARProcess.svar_ma_rep.<locals>.<listcomp>)rs   rt   r"   rU   r^   r_   Zma_reprK   )r)   r   r   rs   rt   Zma_matsr   r   r   svar_ma_rep  s    zSVARProcess.svar_ma_rep)N)r   N)r   N)rz   r{   r|   r}   r   r   r   r   r   r   r   r     s
    

r   c                       s:   e Zd ZdZdZd fdd	Zddd	ZdddZ  ZS )rY   a  
    Estimate VAR(p) process with fixed number of lags

    Parameters
    ----------
    endog : ndarray
    endog_lagged : ndarray
    params : ndarray
    sigma_u : ndarray
    lag_order : int
    model : VAR model instance
    trend : str {'n', 'c', 'ct'}
    names : array_like
        List of names of the endogenous variables in order of appearance in `endog`.
    dates

    Attributes
    ----------
    aic
    bic
    bse
    coefs : ndarray (p x K x K)
        Estimated A_i matrices, A_i = coefs[i-1]
    cov_params
    dates
    detomega
    df_model : int
    df_resid : int
    endog
    endog_lagged
    fittedvalues
    fpe
    intercept
    info_criteria
    k_ar : int
    k_trend : int
    llf
    model
    names
    neqs : int
        Number of variables (equations)
    nobs : int
    n_totobs : int
    params
    k_ar : int
        Order of VAR process
    params : ndarray (Kp + 1) x K
        A_i matrices and intercept in stacked form [int A_1 ... A_p]
    pvalue
    names : list
        variables names
    resid
    sigma_u : ndarray (K x K)
        Estimate of white noise process variance Var[u_t]
    sigma_u_mle
    stderr
    trenorder
    tvalues
    r   Nr/   c                    s   |
| _ || _|| _|| _| jj\| _| _| j| | _t	|}|dkrP|d }nd }|| _
|| _|| _t|||| _|| _|| _| j| j
d  }||| j| jf}| jd }|dd }|| _|| _|| _|	| _t j||||||d d S )Nr   r   r]   )rP   )rQ   r   endog_laggedr*   r   Zn_totobsr   r=   rR   rS   r[   Zk_exog
trendorderZmake_lag_namesZ
exog_namesra   rW   ZreshapeZswapaxescopyr
   r   r%   r&   r   r   )r)   r   r   ra   rW   Z	lag_orderr
   r   r%   r&   rQ   r5   rP   r*   r[   r   Zreshapedr   r   r,   r   r   r   )  s6    


zSVARResults.__init__r   c                 C   s.   | j }| j}tt||}t| ||ddS )z
        Analyze structural impulse responses to shocks in system

        Parameters
        ----------
        periods : int

        Returns
        -------
        irf : IRAnalysis
        T)r   periodsZsvar)r
   r   r"   rU   r^   r_   r   )r)   r   Z	var_orderr
   r   r   r   r   r   irfT  s    zSVARResults.irfF  皙?d   c           &         s  | j }|  }	| j}
| j}| j}| j}| j}| j}t	||d ||f}| j
}| j}| j}| j}| jj}| jj}| jj}g } fdd}|| }|| }t|D ]}tj|||||| d}||d }t||||d}|dkrtj|dd	}t|| } |d|  }|| d }|j|
||d
}!|dk rT|t|!j
|  |!j|   ||!j|d||< qtj|dd	}"tt|d | d ttd|d  | d f}#|"|#d ddddddf }$|"|#d ddddddf }%|$|%fS )u  
        Compute Monte Carlo integrated error bands assuming normally
        distributed for impulse response functions

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse response error bands
        repl : int
            number of Monte Carlo replications to perform
        steps : int, default 10
            number of impulse response periods
        signif : float (0 < signif <1)
            Significance level for error bars, defaults to 95% CI
        seed : int
            np.random.seed for replications
        burn : int
            number of initial observations to discard for simulation
        cum : bool, default False
            produce cumulative irf error bands

        Notes
        -----
        Lütkepohl (2005) Appendix D

        Returns
        -------
        Tuple of lower and upper arrays of ma_rep monte carlo standard errors
        r   c                    s    r| j ddS | S )Nr   ro   )Zcumsum)Zimpulsescumr   r   agg  s    z(SVARResults.sirf_errband_mc.<locals>.agg)seedstepsNr   r   r   ro   )r3   r@   rA   r   r]   )r   meanr   r   rW   r   df_modelr=   r"   r#   r
   r   r%   r&   rQ   r    r!   r   rq   rR   Zvarsimr   r<   rE   rr   tolistr   sortrp   round)&r)   Zorthreplr   Zsignifr   Zburnr   r   r   r   r   rW   r   r   r=   Zma_collr
   r   r%   r&   ZA_passZB_passZs_typeZg_listr   Zopt_AZopt_Brv   ZsimsmodZmean_ABsplitZsresZma_sortindexrI   upperr   r   r   sirf_errband_mcf  sX    

  zSVARResults.sirf_errband_mc)NNNNNr/   NN)r   N)Fr   r   r   Nr   F)	rz   r{   r|   r}   Z_model_typer   r   r   r~   r   r   r,   r   rY     s   <  +
  rY   ) r}   Znumpyr"   Znumpy.linalgrT   r^   r   Zstatsmodels.tsa.tsatoolsr   Zstatsmodels.tools.decoratorsr   Zstatsmodels.tools.numdiffr   r   Zstatsmodels.tsa.base.tsa_modelZtsabaseZ	tsa_modelZtsbaseZstatsmodels.tsa.vector_ar.irfr   Zstatsmodels.tsa.vector_ar.utilZ	vector_arrR   Z#statsmodels.tsa.vector_ar.var_modelr   r	   r   ZTimeSeriesModelr   r   rY   r   r   r   r   <module>   s"      0