
    !gV                         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
mZ ddlmc mc mZ ddlmZ ddlmc mc mZ ddlmZmZ d Z G d	 d
ej4                        Z G d de      Z G d dee      Zy)u   
Vector Autoregression (VAR) processes

References
----------
Lütkepohl (2005) New Introduction to Multiple Time Series Analysis
    N)slogdet)deprecated_alias)approx_fprimeapprox_hess)
IRAnalysis)
VARProcess
VARResultsc                 b    || dk(  s| dk(  rt        d      || dk(  s| dk(  rt        d      y y )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   s      a/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/vector_ar/svar_model.py
svar_ckerrr      sG    yi3&)t*;FGGyi3&)t*;FGG +<y    c                        e Zd ZdZ eddd      Z	 	 d fd	Z	 	 	 ddZd Z	 dd	Z	d
 Z
d Zd Zd fd	Zd Zd Zd Z x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)remove_versionc                    t         |   |d |||       | j                  j                  d   | _        g d}||vrt        dt        |      z         || _        t        |||       || _	        || _
        |Lt        j                  | j                        }t        j                  |j                  t              x| _        }	n#t        j                   |dk(  |dk(        }	|	| _        |Lt        j                  | j                        }t        j                  |j                  t              x| _        }
n#t        j                   |dk(  |dk(        }
|
| _        t        j                  |j                  t$              }||	    ||	 <   t        j&                  ||	<   || _        t        j                  |j                  t$              }||
    ||
 <   t        j&                  ||
<   || _        y )N)missing   )r   r   r   z%SVAR type not recognized, must be in )dtypeEe)super__init__r   shapeneqsr   strr   r   
A_original
B_originalnpidentityzerosboolA_mask
logical_orB_maskfloatnanr   r   )selfr   r   datesfreqr   r   r   typesr*   r,   AnumBnum	__class__s                r   r    zSVAR.__init__8   s   eT7C JJ$$Q'	 E!D"5z* + +"9a# 9DII&A#%88AGG4#@@DK&]]18Q#X6F DK9DII&A#%88AGG4#@@DK&]]18Q#X6F DK
 xxu-6'
fWvvVxxu-6'
fWvvVr   c           	      0   |}|H| j                  ||      }||vrt        |dt        |            ||   }|rt        d||fz         n|d}t	        | j
                        |z
  | _        | j                  ||      }| j                  ||||	|
||      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
        )maxlagsverbosez not recognized, must be among zUsing %d based on %s criterionr   )trendsolveroverridemaxitermaxfun)	select_orderr   sortedprintlenr   nobs_get_init_params_estimate_svar)r/   A_guessB_guessr7   methodicr9   r8   s_methodr:   r;   r<   r=   lags
selectionsstart_paramss                   r   fitzSVAR.fitk   s    n >**7G*LJ# $&z(:"< = =b>D64*DE|

Od*	 ,,Wg>""<U*08+26 # C 	Cr   c                    | j                   j                         }| j                  j                         }|dv rE|t	        j
                  dg|z        }n+t        |      |k7  rd}t        |t        |      |fz        g }| j                  j                         }|dv rE|t	        j
                  dg|z        }n+t        |      |k7  rd}t        |t        |      |fz        g }t        j                  ||f   S )zL
        Returns either the given starting or .1 if none are given.
        )abag?z/len(A_guess) = %s, there are %s parameters in A)rO   bz/len(B_guess) = %s, there are %s parameters in B)
r   lowerr*   sumr&   arrayrA   r   r,   r_)r/   rE   rF   var_type
n_masked_amsg
n_masked_bs          r   rC   zSVAR._get_init_params   s    
 >>'')[[__&
{"((B4
?3w<:-KC$SCL*+E%EFFG[[__&
{"((B4
?3w<:-KC$SCL*+E%EFFGuuWg%&&r   c                 `   t        j                  |      }| j                  }	t        j                  |	||d      }
|	|d }t        j
                  j                  |
|d      d   }|t	        j                  |
|      z
  }t        |      }|| j                  |z  |z   z
  }t	        j                  |j                  |      }||z  }|| _        | j                  ||||      \  }}| j                  }| j                  }t        |	|
|||| j                   || j"                  j$                  | ||||      S )	zQ
        lags : int
        trend : {str, None}
            As per above
        raise)r9   has_constantN)rcondr   )r;   r:   r<   )namesr9   r0   modelr   r   r*   r,   )utilget_trendorderr   get_var_endogr&   linalglstsqdotrA   r"   Tsigma_u	_solve_ABr*   r,   SVARResultsendog_namesdatar0   )r/   rL   rJ   r<   r=   r9   r:   r;   k_trendr   zy_sample
var_paramsresidavobsdf_residsseomegar   r   r*   r,   s                         r   rD   zSVAR._estimate_svar   s(    %%e,JJq$e'JTU8 YY__Q_;A>
266!Z00 HDII,w67ffUWWe$h~~lX%+&-  /1 1aUD!%!1!1!%!F6C 	Cr   c                    | j                   }| j                  }| j                  }| j                  }t	        ||         }t	        ||         }||d| ||<   |||||z    ||<   | j
                  }| j                  }	| j                  }
t        j                  t        j                  |      |      }t        j                  t        j                  |j                  |      |
      }t        |dz        \  }}||z  }| dz  |	t        j                  dt        j                  z        z  t        j                  t        j                   |      dz        z
  |z   t        j"                  |      z   z  }|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,   rA   rB   r"   rh   r&   rf   nplinvrg   r   logpidettrace)r/   paramsr   r   r*   r,   A_lenB_lenrB   r"   rh   Wtrc_insignb_logdet	b_slogdetlikls                    r   loglikezSVAR.loglike  s?    FFFFAfIAfI=vAfI=uU5[1AfIyyyy,,FF3771:a qss1g. Ah8O	uRx4"&&RUU"3366#''!*a-013<=88F+, - r   c                 6    | j                   }t        ||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)r   r   r/   AB_maskr   s      r   scorez
SVAR.score*  s     ,,Wgt<<r   c                 2    | j                   }t        ||      S )z,
        Returns numerical hessian.
        )r   r   r   s      r   hessianzSVAR.hessian9  s     ,,7G,,r   c                    | j                   }| j                  }| j                  }| j                  }t	        ||         }	|d|	 ||<   ||	d ||<   |s5| j                  ||      }
| j                  |
       | j                  |
       nt        d       t        | )  |||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)rL   rG   r<   gtoldisp)r*   r,   r   r   rA   
_compute_Jcheck_order
check_rankr@   r   rM   r~   )r/   rL   r<   r;   r:   r*   r,   r   r   r   Jretvalsr5   s               r   ri   zSVAR._solve_AB@  s    , FFFFAfI %(&	 (&	1%AQOOA?@'+<%+W#(u  66<f 	 FUO&	EFO&	!tr   c           	         | j                   }| j                  }| j                  }| j                  }t	        j
                  t        d|z  |dz   z        |dz  g      }t        |      D ]  }|}	||	cxk  r|k  sn t	        j
                  t        d|z  |dz   z        dg      }
d|
t        ||z  |	dz   z   d|dz   z  |z  z
  dz
        <   t	        j
                  ||g      }d||	|f<   d|||	f<   |t	        j                  |
|j                  d      d d d f   j                        z   }|	dz   }	||	cxk  r|k  r  |j                  }t        j                  |      }t	        j
                  |dz  t        ||         f      }t	        j
                  |dz  t        ||         f      }d}d}t        ||         dk7  r<t	        j                  |d      }t        |dz        D ]  }||   s	d|||f<   |dz  } t        ||         dk7  r<t	        j                  |d      }t        |dz        D ]  }||   s	d|||f<   |dz  } t        j                  |      }t	        j                  t	        j                  |t	        j                  ||            |      }d|z  }t	        j                  t	        j                  |t	        j                  ||            |      }t	        j                   ||d	      }|S )
Ng      ?r   rw   Fr   )orderr]   g       axis)r"   rh   r*   r,   r&   r(   intrangerf   ravelrg   rx   pinvrA   ry   kronappend)r/   A_solveB_solver"   rh   r*   r,   D_nTjiuTijD_nD_plS_BS_Dj_dA_veckB_vecinvAJ_p1iJ_p1J_p2r   s                            r   r   zSVAR._compute_Jo  s    yy,, xxg$/4!8<=tQwGHt 		AAq-4-((Cd1f 56:;KL#a$h!a%(GA+>+BBQFGHHHd4[)AaCAaC"&&CIIcN1T6$:#=#=>>A# q-4-		 FFXXc] hhaWV_!567hhaWV_!567wv1$HHV3/E47^ 8!C!HFA wv1$HHV3/E47^ 8!"C#J!GC wwwrvvdBGGGT$:;SAe|vvbffT2774#67=IIdDq)r   c                 x    t        j                  |d      t        j                  |d      k  rt        d      y )Nr   r   r   z3Order condition not met: solution may not be unique)r&   sizer   )r/   r   s     r   r   zSVAR.check_order  s7    7711 22 : ; ; 3r   c                     t         j                  j                  |      }|t        j                  |d      k  rt	        d      y )Nr   r   z3Rank condition not met: solution may not be unique.)r&   rd   matrix_rankr   r   )r/   r   ranks      r   r   zSVAR.check_rank  s@    yy$$Q'"''!!$$ ; < < %r   )NNNNnone)NNNolsNcFmlebfgsF  r   )r   nmF)Fr   )__name__
__module____qualname____doc__r   r   r    rM   rC   rD   r   r   r   ri   r   r   r   __classcell__r5   s   @r   r   r      sq    2 	gh?A/34:-f DI8=?BKCZ'@ 9>*CX%N=--^:x;
<r   r   c                   *    e Zd ZdZ	 ddZddZddZy)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                     t        |      | _        |j                  d   | _        || _        || _        || _        || _        || _        || _	        y )Nr   )
rA   k_arr!   r"   coefs	interceptrh   r   r   r_   )r/   r   r   rh   r   r   r_   s          r   r    zSVARProcess.__init__  sF    J	KKN	
"
r   c                     t         )z'

        Unavailable for SVAR
        )NotImplementedError)r/   maxnPs      r   orth_ma_repzSVARProcess.orth_ma_rep  s
    
 "!r   c           	      $   |A| j                   }| j                  }t        j                  t	        j
                  |      |      }| j                  |      }t        j                  |D cg c]  }t        j                  ||       c}      S c c}w )zW

        Compute Structural MA coefficient matrices using MLE
        of A, B
        r   )r   r   r&   rf   rx   ry   ma_reprT   )r/   r   r   r   r   ma_matsr   s          r   svar_ma_repzSVARProcess.svar_ma_rep  sl     9llGllGswww'1A++4+(xxw?eq)?@@?s   )B)N
   N)r   r   r   r   r    r   r    r   r   r   r     s     	"Ar   r   c                   @     e Zd ZdZdZ	 	 d fd	ZddZ	 	 ddZ xZS )	rj   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   c                    |
| _         || _        || _        || _        | j                  j                  \  | _        | _        | j
                  |z
  | _        t        j                  |      }|dkD  r|dz
  }nd }|| _
        || _        || _        t        j                  |||      | _        || _        || _        | j                  | j                  d  }|j#                  || j                  | j                  f      }| j                  d   }|j%                  dd      j'                         }|| _        || _        || _        |	| _        t0        | e  ||||||       y )Nr   r   rw   )r_   )r`   r   endog_laggedr0   r!   n_totobsr"   rB   ra   rb   rm   k_exog
trendordermake_lag_names
exog_namesr~   rh   reshapeswapaxescopyr   r   r*   r,   r   r    )r/   r   r   r~   rh   	lag_orderr   r   r*   r,   r`   r9   r_   r0   rm   r   reshapedr   r   r5   s                      r   r    zSVARResults.__init__&  sD    

(
#'::#3#3 tyMMI-	%%e,Q; 1JJ$--eYH ;;t||}-##Y		499$EF KKN	!!!Q',,.
 	7Aq05 	 	7r   c                     | j                   }| j                  }t        j                  t	        j
                  |      |      }t        | ||d      S )z
        Analyze structural impulse responses to shocks in system

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

        Returns
        -------
        irf : IRAnalysis
        T)r   periodssvar)r   r   r&   rf   rx   ry   r   )r/   r   	var_orderr   r   r   s         r   irfzSVARResults.irfQ  s?     FF66FF3771:q!$!W4@@r   c           	      
   | j                   }| j                         }	| j                  }
| j                  }| j                  }| j
                  }| j                  }| j                  }t        j                  ||dz   ||f      }| j                  }| j                  }| j                  }| j                  }| j                  j                  }| j                  j                   }| j                  j"                  }g }fd}||   }||   }t%        |      D ]  }t'        j(                  ||||||z         }||d }t+        ||||      }|dk(  r/t        j                  |d      }t-        ||         } |d|  }|| d }|j/                  |
||	      }!|dk  r[|j1                  t        j0                  |!j                  |   j3                         |!j                  |   j3                                       ||!j5                  |
            ||<    t        j6                  |d      }"t9        t;        |dz  |z        dz
        t9        t;        d|dz  z
  |z        dz
        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                 0    r| j                  d      S | S )Nr   r   )cumsum)impulsescums    r   aggz(SVARResults.sirf_errband_mc.<locals>.agg  s    A..Or   )seedstepsNr   r   r   r   )r7   rE   rF   r   rw   )r"   meanr   r   rh   r   df_modelrB   r&   r(   r   r   r*   r,   r`   r$   r%   r   r   ra   varsimr   rA   rM   r   tolistr   sortr   round)&r/   orthreplr   signifr   burnr   r"   r   r   r   rh   r   r   rB   ma_collr   r   r*   r,   A_passB_passs_typeg_listr   opt_Aopt_Br   simsmodmean_ABsplitsresma_sortindexrR   uppers&          `                              r   sirf_errband_mczSVARResults.sirf_errband_mcc  s`   > yyyy{yy

,,NN	==yy((D%!)T489FFFF&&&&%%	
 &	&	t 	;A++eYd$(4K1Cde*Cv6BDBw''&q1AfI88D%8GD2vbiiv(=(=(?(,v(=(=(?A BT--5-9:GAJ)	;, '''*U6A:,-12UA
Nd23a78:a!Q)*a!Q)*e|r   )NNNNNr   NNr   )Fi  r   g?Nd   F)	r   r   r   r   _model_typer    r   r  r   r   s   @r   rj   rj     s4    :x K BF.2)7VA$ <>>CUr   rj   )r   numpyr&   numpy.linalgrd   rx   r   statsmodels.tools.decoratorsr   statsmodels.tools.numdiffr   r   statsmodels.tsa.base.tsa_modeltsabase	tsa_modeltsbasestatsmodels.tsa.vector_ar.irfr   statsmodels.tsa.vector_ar.util	vector_arra   #statsmodels.tsa.vector_ar.var_modelr   r	   r   TimeSeriesModelr   r   rj   r   r   r   <module>r     sg        9 @ / / 4 - - FHX<6!! X<v-A* -A`Q+z Qr   