Module contents
Lesson 16 of 31Core 110 min

Multivariate time series and VAR models

Several series influence one another. Extend stationarity and cross-covariances to vectors, then study VAR(p), its companion form and stability, equation-by-equation least squares, lag selection, Granger causality, impulse responses and identification of orthogonalized shocks, and forecast-error variance decomposition.

After this lesson you can

  • Write a VAR(p) in companion form, check stability and calculate autocovariances.
  • Estimate a VAR by least squares from scratch and choose the number of lags.
  • Test Granger causality with a Wald test and explain its limitations as a causal notion.
  • Calculate impulse responses and FEVD with bootstrap bands and show their dependence on Cholesky ordering.
  • Forecast using a VAR and compare it with univariate models.

Before you start

When series move together

Inflation can respond to output with delay and interest rates can react to both. Latencies of two services can also share an external cause. Separate forecasts do not describe how a shock propagates between components. A VAR offers an initial joint description, but its predictive arrows do not automatically identify interventions.

Start with the deterministic part of a two-variable system. A stable matrix can produce damped oscillations if its eigenvalues are complex; transient expansion is also insufficient to decide stability when the matrix is non-normal. Move coefficients and compare the field with the unit circle.

InteractiveDynamics and eigenvalues

The matrix defines Xₜ₊₁ = AXₜ + εₜ₊₁. Here deterministic dynamics with ε=0 and no constant are drawn: each point is a discrete iteration. The field shows displacement AX−X, not a differential equation.

Eigenvalues in the complex plane
Path and displacement AX−X
  • Unit circle
  • Eigenvalue 1 and start
  • Eigenvalue 2
  • Iterations

Showing 20 of 20 steps. Arrows indicate direction, not magnitude. Drag the start or use keyboard arrows.

If ρ(A)<1, Aⁿ tends to zero and a weakly stationary causal solution exists for innovations forming finite-second-moment white noise. With ρ(A)>1 some initial conditions grow, although others may lie in a stable subspace. At ρ(A)=1 strict stability fails: dynamics may remain bounded or oscillate, or grow if Jordan blocks exist.

20
Eigenvalue 10.800 + 0.400i
Eigenvalue 20.800 − 0.400i
Spectral radius0.894
Strict stabilityYes
The field and paths correspond to the chosen VAR(1) matrix without innovations. Asymptotic stability depends on spectral radius, not on every component decreasing at every step.

Cross-covariances and joint memory

A vector Yt∈RkY_t\in\mathbb R^k is weakly stationary if it has finite second moment, constant mean μ\mu and cross-covariance matrix

Γ(h)=E[(Yt−μ)(Yt−h−μ)T]\Gamma(h)=\mathbb E[(Y_t-\mu)(Y_{t-h}-\mu)^\mathsf T]

depending only on lag. Under this convention, Γij(h)\Gamma_{ij}(h) compares current component ii with jj from hh steps ago and Γ(−h)=Γ(h)T\Gamma(-h)=\Gamma(h)^\mathsf T. Visible cross-correlation does not imply a direct relationship: autocorrelation, trend and common factors can generate persistent associations. Uncertainty in correlation calculated from dependent observations differs from that of independent pairs.

VAR, companion form and stability

A VAR(pp) is

Yt=c+A1Yt−1+⋯+ApYt−p+ut,E[ut∣Ft−1]=0,E[ututT]=Σu.Y_t=c+A_1Y_{t-1}+\cdots+A_pY_{t-p}+u_t,\qquad \mathbb E[u_t\mid\mathcal F_{t-1}]=0,\quad \mathbb E[u_tu_t^\mathsf T]=\Sigma_u.

Each AjA_j has dimension k×kk\times k; row ii, column jj gives the coefficient of lagged variable jj in equation ii. With St=(YtT,Yt−1T,…,Yt−p+1T)TS_t=(Y_t^\mathsf T,Y_{t-1}^\mathsf T,\ldots,Y_{t-p+1}^\mathsf T)^\mathsf T, companion matrix FF has blocks A1,…,ApA_1,\ldots,A_p in its first row and identity blocks on the subdiagonal. Thus St=d+FSt−1+ηtS_t=d+FS_{t-1}+\eta_t.

Stability requires ρ(F)<1\rho(F)<1, equivalently that finite roots of det⁡(I−A1z−⋯−Apzp)=0\det(I-A_1z-\cdots-A_pz^p)=0 lie outside the unit circle. If the determinant is constant there are no finite roots to check. Under that condition and finite-variance white noise, a stationary causal solution exists,

μ=(I−∑j=1pAj)−1c,Yt−μ=∑h=0∞Ψhut−h,Ψ0=I,Ψh=∑j=1min⁡(p,h)AjΨh−j.\mu=(I-\textstyle\sum_{j=1}^p A_j)^{-1}c,\quad Y_t-\mu=\sum_{h=0}^\infty\Psi_hu_{t-h},\quad \Psi_0=I,\quad \Psi_h=\sum_{j=1}^{\min(p,h)}A_j\Psi_{h-j}.

To see root equivalence, let Fv=λvFv=\lambda v with λ≠0\lambda\ne0 and blocks v1,…,vpv_1,\ldots,v_p. Lower rows imply vj=λ−(j−1)v1v_j=\lambda^{-(j-1)}v_1 and the first reduces to (I−∑jAjλ−j)v1=0(I-\sum_jA_j\lambda^{-j})v_1=0. Therefore z=1/λz=1/\lambda is a root; conversely, a finite root produces an eigenvector of that form. Zero eigenvalues do not correspond to finite roots and have modulus below one.

For VAR(1), Γ(0)=AΓ(0)AT+Σu\Gamma(0)=A\Gamma(0)A^\mathsf T+\Sigma_u and Γ(h)=AhΓ(0)\Gamma(h)=A^h\Gamma(0) if h≥0h\ge0. The first is a discrete Lyapunov equation; scalar division cannot replace it when matrices do not commute. For VAR(pp), multiplying by (Yt−h−μ)T(Y_{t-h}-\mu)^\mathsf T and taking expectations gives, for h≥1h\ge1,

Γ(h)=∑j=1pAjΓ(h−j).\Gamma(h)=\sum_{j=1}^{p}A_j\Gamma(h-j).

When h−j<0h-j<0, use the transpose of the corresponding positive lag. Matrix order matters: Γ12(1)\Gamma_{12}(1) and Γ21(1)\Gamma_{21}(1) describe different questions.

Fitting and lag selection

Least-squares estimation forms a design row with a constant and the pp lagged vectors. If XX has full rank and YY contains observed vectors, B^=(XTX)−1XTY\widehat B=(X^\mathsf TX)^{-1}X^\mathsf TY; numerically use QR or SVD, not an explicit inverse. Equations have the same regressors and can be fitted separately even when contemporaneous innovations are correlated.

Compare orders using AIC or BIC on the same effective sample, so observations do not change when pp changes. With Σ^=ETE/n\widehat\Sigma=E^\mathsf TE/n and d=1+kpd=1+kp regressors per equation, one per-observation form of the criteria is log⁡det⁡Σ^+2kd/n\log\det\widehat\Sigma+2kd/n or log⁡det⁡Σ^+(log⁡n)kd/n\log\det\widehat\Sigma+(\log n)kd/n. The determinant must be positive; constants and corrections can differ between implementations. After selection, fit on training data and inspect residuals and stability. The k2pk^2p dynamic coefficients grow quickly; ridge, lasso and Bayesian VAR introduce regularization with their own choices and validation.

Granger is not an intervention

Granger causality asks whether the past of XX improves prediction of YY after including past observed variables. In a linear VAR, the joint null sets the pp coefficients of lags of XX in the equation for YY to zero. A Wald test uses coefficient covariance; reference χp2\chi^2_p is asymptotic and depends on model and estimation assumptions. A small pp value rejects that predictive restriction; it does not prove a causal intervention or direct physical transmission.

In the figure, a common factor reaches XX before YY. When observing only XX and YY, the past of XX may contain factor information; adding the relevant past of ZZ changes the conditional question. A finite sample can yield a different decision than expected, and including one factor does not automatically solve other omitted variables.

InteractiveA common cause and a predictive arrow

First 80 aligned observations of Yₜ, Xₜ₋₁ and common factor Zₜ₋₂.

  • Yₜ
  • Xₜ₋₁
  • Zₜ₋₂

The simulated model is Xₜ = Zₜ₋₁ + σuₜ and Yₜ = 0.35Yₜ₋₁ + Zₜ₋₂ + σvₜ. Z, u and v are independent standard normal noise and σ controls noise. The first 100 steps are discarded. Lag Xₜ₋₁ contains information about Zₜ₋₂, which also enters Yₜ, although X is absent from Y’s structural equation.

Each test compares two least-squares regressions of Yₜ: both include a constant and Yₜ₋₁; the unrestricted one adds Xₜ₋₁. With Z, both also add Zₜ₋₂. The null is zero coefficient on Xₜ₋₁. F = (restricted RSS − full RSS)/(full RSS/df), with one restriction and df = n − 3 without Z or n − 4 with Z.

P values are tails of the F(1, df) distribution, the usual test reference; finite-sample calibration is not automatic with dynamic regressors. Predictive signal may disappear when including the observed factor, but results vary between samples. Granger measures predictive ability conditional on the information set, not structural causality.

200
0.8
1
p without Z< 0.0001
Test without ZRejects at 5%
p with Z0.8410
Test with ZDoes not reject at 5%
X coefficient without / with Z0.594 / −0.013
F without / with Z105.71 / 0.04
Compare the test with and without the observed factor. Data are generated by the figure's explicit mechanism and the p-value changes across samples.

Impulses and their identification

The reduced-form impulse response to one unit in innovation jj is Ψhej\Psi_he_j. But if Σu\Sigma_u is not diagonal, changing one innovation while fixing the others is not equivalent to an observed independent shock. With Σu=LLT\Sigma_u=LL^\mathsf T, where LL is lower Cholesky, write ut=Lεtu_t=L\varepsilon_t with identity covariance: ΨhLej\Psi_hL e_j responds to one standard deviation of orthogonalized shock jj.

Changing variable order changes Cholesky and its contemporaneous restrictions. The first variable in that order does not respond contemporaneously to later shocks; this is an identifying assumption, not a fact learned from the reduced fit. A structural VAR can impose other restrictions, whose validity requires external arguments.

With Gaussian innovations, the Pesaran-Shin generalized response to a one-standard-deviation shock in innovation jj is ΨhΣuej/(Σu)jj\Psi_h\Sigma_u e_j/\sqrt{(\Sigma_u)_{jj}}. It does not depend on variable order, but includes expected contemporaneous movement of correlated innovations and does not by itself identify an intervention. Without Gaussianity that expression can be interpreted as a linear response, not necessarily an exact conditional expectation.

InteractiveOrder changes interpretation

Response of X to a unit-standard-deviation shock associated with Y. The dashed line always uses reference order X → Y → Z.

Horizon h, with h = 0 at impact
  • Order Z → Y → X
  • Reference X → Y → Z

Cholesky order: drag or use arrows

1. Z
2. Y
3. X

FEVD: fraction by shock at H = 8

X: X 43.9 % · Y 16.0 % · Z 40.1 %
Y: X 1.0 % · Y 56.6 % · Z 42.4 %
Z: X 0.0 % · Y 1.0 % · Z 99.0 %
  • Shock X
  • Shock Y
  • Shock Z

Population model: (Xₜ,Yₜ,Zₜ)ᵀ = A(Xₜ₋₁,Yₜ₋₁,Zₜ₋₁)ᵀ + uₜ, with A rows (0.5, 0.2, 0), (0.1, 0.4, 0.1) and (0, 0.1, 0.3). Innovations have variance 1 and common correlation ρ. A’s spectral radius is approximately 0.6115; the VAR is stable. The covariance matrix is positive definite across the available range.

For the selected order, permuted covariance is factorized as LLᵀ and rows and columns are returned to original labels. If B is that impact matrix, responses are AʰB. FEVD divides the sum of squares of each column for h = 0,…,H−1 by the sum across all columns: each row totals 100% before rounding. If ρ = 0, both orders yield identical responses and attributions.

Reordering changes the contemporaneous restriction and therefore the definition of the shock identified with each variable; it need not represent the same intervention. These are exact calculations for the specified model without estimation bands: Cholesky ordering alone does not establish structural causality.

0.6
Response variable
Shock identified with
8
Current orderZ → Y → X
FEVD X by shock Y16.0 %
Reference FEVD X → Y → Z4.0 %
Maximum IRF change, h = 0 to 160.600
Maximum FEVD change52.0 %
Reorder variables and compare orthogonalized responses and variance decomposition; setting innovation correlation to zero removes order dependence.

From response to forecast error

For a stable VAR with known parameters and horizon HH, forecast error given information through tt is ∑h=0H−1Ψhut+H−h\sum_{h=0}^{H-1}\Psi_hu_{t+H-h}. If orthogonalized shocks are uncorrelated across time and Θh=ΨhL\Theta_h=\Psi_hL, the forecast-error variance decomposition of component ii attributed to shock jj is

FEVD⁡ij(H)=∑h=0H−1(eiTΘhej)2∑h=0H−1∑ℓ=1k(eiTΘheℓ)2.\operatorname{FEVD}_{ij}(H)= \frac{\sum_{h=0}^{H-1}(e_i^\mathsf T\Theta_he_j)^2} {\sum_{h=0}^{H-1}\sum_{\ell=1}^k(e_i^\mathsf T\Theta_he_\ell)^2}.

If the denominator is positive, contributions of the kk shocks sum to one. Total error variance does not depend on ordering, but its allocation among Cholesky shocks does. Residual-bootstrap bands must refit the model in each replication and reflect resampling assumptions; pointwise quantiles are not simultaneous bands.

The companion-form point forecast is obtained by iterating S^t+h∣t=d+FS^t+h−1∣t\widehat S_{t+h|t}=d+F\widehat S_{t+h-1|t} from the last observed state. For the known model, unconditional innovation-error covariance is ∑h=0H−1ΨhΣuΨhT\sum_{h=0}^{H-1}\Psi_h\Sigma_u\Psi_h^\mathsf T and increases in positive-semidefinite matrix order with horizon. To interpret it as conditional covariance, future innovations’ conditional variance must also be controlled. This expression excludes parameter-estimation uncertainty; the lab bands address part of it under their resampling scheme.

Lab: a VAR from scratch

Generate two correlated system metrics. The matrix and innovation covariance are experimental parameters, not observations from real infrastructure. Fit by least squares, calculate eigenvalues and compare with statsmodels VAR. Read the mean and coefficient matrices under the convention above.

[ ]Simulate and fitBrowser
import numpy as np
from scipy.stats import chi2
from scipy.linalg import solve_discrete_lyapunov
from statsmodels.tsa.api import VAR

def sim_var(A, cov, n, burn, rng):
    k = A.shape[0]
    x = np.zeros(k)
    salida = []
    L = np.linalg.cholesky(cov)
    for t in range(n+burn):
        x = A@[email protected](size=k)
        if t >= burn:
            salida.append(x.copy())
    return np.array(salida)

def matriz_retardos(data, p, start=None):
    y = np.asarray(data, dtype=float)
    if start is None:
        start = p
    if not 1 <= p <= start < len(y):
        raise ValueError("retardo o muestra inválidos")
    X = np.column_stack([np.ones(len(y)-start)] +
        [y[start-lag:len(y)-lag] for lag in range(1,p+1)])
    return X, y[start:]

def ajustar_var(data, p, start=None):
    X, Y = matriz_retardos(data, p, start)
    coef, _, rango, _ = np.linalg.lstsq(X,Y,rcond=None)
    if rango < X.shape[1]:
        raise ValueError("diseño sin rango completo")
    resid = Y-X@coef
    return coef, resid, X

A = np.array([[.55,.2],[-.1,.35]])
cov = np.array([[1.,.45],[.45,1.]])
datos = sim_var(A,cov,360,150,np.random.default_rng(26016))
train, test = datos[:300], datos[300:]
coef, resid, X = ajustar_var(train,1)
ref = VAR(train).fit(1,trend="c")
print("radio espectral verdadero:", max(abs(np.linalg.eigvals(A))))
print("A verdadera y estimada:", A, coef[1:].T)
print("máxima diferencia de coeficientes con statsmodels:",
      np.max(abs(coef-ref.params)))
G = solve_discrete_lyapunov(A,cov)
print("error ecuación Lyapunov:", np.max(abs(G-A@[email protected])))

Select lag by comparing Σ^\widehat\Sigma on identical rows. This deliberately small example makes the calculation inspectable; a selected order does not guarantee a correct model.

[ ]AIC and BIC on the same sampleBrowser
def criterios(data, p, start):
    coef, resid, X = ajustar_var(data,p,start)
    n, k = resid.shape
    signo, logdet = np.linalg.slogdet(resid.T@resid/n)
    if signo <= 0:
        raise ValueError("covarianza residual singular")
    parametros = k*X.shape[1]
    return logdet+2*parametros/n, logdet+np.log(n)*parametros/n

for p in (1,2,3,4):
    print("p, AIC, BIC:", p, *criterios(train,p,4))

Lab: testing and propagation

The following test uses a selection matrix on lags of the supposed cause and classical equation covariance σ^2(XTX)−1\widehat\sigma^2(X^\mathsf TX)^{-1}. The Wald reference is asymptotic; with heteroskedasticity, residual dependence or integration, this covariance and its p-value may be inappropriate.

[ ]Wald testBrowser
def granger_test(data, cause, effect, p):
    coef, resid, X = ajustar_var(data,p)
    n, k = resid.shape
    if not 0 <= cause < k or not 0 <= effect < k or cause == effect:
        raise ValueError("índices inválidos")
    if n <= X.shape[1]:
        raise ValueError("grados de libertad insuficientes")
    indices = [1+(lag-1)*k+cause for lag in range(1,p+1)]
    b = coef[indices,effect]
    var = resid[:,effect]@resid[:,effect]/(n-X.shape[1])
    inv_gram = np.linalg.solve(X.T@X,np.eye(X.shape[1]))
    V = var*inv_gram[np.ix_(indices,indices)]
    W = float([email protected](V,b))
    return W, chi2.sf(W,p)

W, valor_p = granger_test(train,1,0,1)
test_ref = VAR(train).fit(1).test_causality(0,[1],kind="wald")
print("Wald propio y statsmodels:", W, test_ref.test_statistic)
print("p propio y statsmodels:", valor_p, test_ref.pvalue)

From the fitted model obtain Ψh\Psi_h, orthogonalized responses and FEVD. When comparing with the library use the same Cholesky and horizon convention: H=1H=1 includes only h=0h=0.

[ ]IRF y FEVDBrowser
def matrices_psi(coef, k, p, horizonte):
    A = [coef[1+j*k:1+(j+1)*k].T for j in range(p)]
    psi = [np.eye(k)]
    for h in range(1,horizonte+1):
        psi.append(sum((A[j-1]@psi[h-j] for j in range(1,min(p,h)+1)),
                       np.zeros((k,k))))
    return np.array(psi)

def fevd(theta, H):
    potencias = np.sum(theta[:H]**2,axis=0)
    return potencias/potencias.sum(axis=1,keepdims=True)

k, H = 2, 8
psi = matrices_psi(coef,k,1,H)
sigma = resid.T@resid/(len(resid)-X.shape[1])
theta = [email protected](sigma)
descomp = fevd(theta,H)
irf_ref = ref.irf(H)
print("error IRF ortogonalizada frente a statsmodels:",
      np.max(abs(theta-irf_ref.orth_irfs)))
print("FEVD propia y suma por fila:", descomp, descomp.sum(axis=1))
print("error FEVD frente a statsmodels:",
      np.max(abs(descomp-ref.fevd(H).decomp[:,H-1,:])))

A centered residual bootstrap generates paths with estimated parameters and re-estimates the VAR in each. Use few replications here so the mechanism is quick to explore; increase BB before using quantiles for analysis. Under regime changes, heteroskedasticity or dependent residuals, resampling iid vectors may be inappropriate.

[ ]Pointwise residual-bootstrap bandsBrowser
def bootstrap_irf(data, B, H, rng):
    coef, resid, X = ajustar_var(data,1)
    n, k = data.shape
    resid = resid-resid.mean(axis=0)
    respuestas = []
    for _ in range(B):
        sim = np.empty_like(data)
        sim[0] = data[0]
        indices = rng.integers(0,len(resid),size=n-1)
        for t in range(1,n):
            sim[t] = coef[0]+coef[1:].T@sim[t-1]+resid[indices[t-1]]
        cb, eb, xb = ajustar_var(sim,1)
        sb = eb.T@eb/(len(eb)-xb.shape[1])
        respuestas.append(matrices_psi(cb,k,1,H)@np.linalg.cholesky(sb))
    return np.quantile(np.array(respuestas),[.025,.975],axis=0)

bandas = bootstrap_irf(train,120,H,np.random.default_rng(2616))
print("banda puntual 95 % para respuesta 1 al choque 2 en h=2:",
      bandas[:,2,0,1])
print("estimación correspondiente:", theta[2,0,1])

For a prediction band, generate future innovations as well as re-estimating parameters. The following interval is pointwise for each component at H=8H=8, conditional on the last observed state; it is not a simultaneous band for the entire path. The same residual-resampling limitations apply.

[ ]Bootstrap prediction intervalsBrowser
def bootstrap_prediccion(data, B, H, rng):
    coef, resid, _ = ajustar_var(data,1)
    resid = resid-resid.mean(axis=0)
    n, k = data.shape
    finales = []
    for _ in range(B):
        sim = np.empty_like(data)
        sim[0] = data[0]
        indices = rng.integers(0,len(resid),size=n-1)
        for t in range(1,n):
            sim[t] = coef[0]+coef[1:].T@sim[t-1]+resid[indices[t-1]]
        cb, _, _ = ajustar_var(sim,1)
        estado = data[-1].copy()
        for _ in range(H):
            estado = cb[0]+cb[1:].T@estado+resid[rng.integers(len(resid))]
        finales.append(estado)
    return np.quantile(np.array(finales),[.05,.95],axis=0)

print("intervalos predictivos puntuales del 90 % para H=8:",
      bootstrap_prediccion(train,120,8,np.random.default_rng(1616)))

Out-of-sample forecasting and macroeconomic data

First compare one-step forecasts with parameters fixed at the end of training. At each step the actual previous observation is seen; this is not a 60-step forecast from one origin. The univariate reference uses one AR(1) regression per component and the same evaluation interval. One split may favor either model.

[ ]Joint and separate forecastingBrowser
def comparar_un_paso(train, test):
    k = train.shape[1]
    cv, _, _ = ajustar_var(train,1)
    ar = []
    for j in range(k):
        z = np.column_stack([np.ones(len(train)-1), train[:-1,j]])
        ar.append(np.linalg.lstsq(z,train[1:,j],rcond=None)[0])
    anterior = train[-1]
    pred_var, pred_ar = [], []
    for obs in test:
        pred_var.append(cv[0]+cv[1:].T@anterior)
        pred_ar.append([ar[j][0]+ar[j][1]*anterior[j] for j in range(k)])
        anterior = obs
    return (np.mean((test-np.array(pred_var))**2,axis=0),
            np.mean((test-np.array(pred_ar))**2,axis=0))

print("MSE a un paso, VAR y AR separados:", comparar_un_paso(train,test))

The public statsmodels macrodata collection contains 203 quarterly observations from 1959-Q1 to 2009-Q3. Real GDP, consumption and investment are expressed in billions of chained 2005 dollars at a seasonally adjusted annual rate. Apply 100Δlog⁡100\Delta\log to those levels: the transformation approximates quarterly percentage change and is not an annualized growth rate. Differencing does not prove stationarity or rule out structural changes. Reserve the final segment for evaluation and do not interpret responses as economic causality.

[ ]VAR on public macro dataBrowser
from statsmodels.datasets import macrodata

macro = macrodata.load_pandas().data
niveles = macro[["realgdp","realcons","realinv"]].to_numpy()
crecimiento = 100*np.diff(np.log(niveles),axis=0)
macro_train, macro_test = crecimiento[:160], crecimiento[160:]
mc, me, mx = ajustar_var(macro_train,1)
macro_ref = VAR(macro_train).fit(1)
print("observaciones y división:", len(niveles), len(macro_train), len(macro_test))
print("desacuerdo con statsmodels:", np.max(abs(mc-macro_ref.params)))
print("MSE a un paso, VAR y AR:", comparar_un_paso(macro_train,macro_test))
print("raíz espectral estimada:", max(abs(np.linalg.eigvals(mc[1:].T))))

As a size check under the null, simulate independent AR pairs and measure Wald rejection frequency. A result near nominal level in this configuration does not guarantee calibration on nonstationary, heteroskedastic or small data.

[ ]Empirical size under the nullBrowser
rng = np.random.default_rng(1626)
nulos = 160
rechazos = 0
for _ in range(nulos):
    par = sim_var(np.diag([.45,.35]),np.eye(2),180,80,rng)
    rechazos += granger_test(par,1,0,1)[1] < .05
print("réplicas, rechazos y proporción:", nulos, rechazos, rechazos/nulos)
respuestas = set()
for a in (.3,.5,.7):
    for d in (.3,.5,.7):
        mat = np.array([[a,.4],[0.,d]])
        respuestas.add(round(float((mat@mat)[0,1]),2))
print("posibles respuestas h=2 con b=0.4 y a,d en 0.3,0.5,0.7:",
      sorted(respuestas))

Exercises

ProofRoots and companion matrix
Prove: For a VAR(p), relate eigenvalues of companion matrix F to finite roots of det(I−A₁z−⋯−Aₚzᵖ), and prove stability equivalence.
0
The determinant of I−zF reduces blockwise to the VAR matrix polynomial.

Step 1 of 3. What determinant equality follows by eliminating lagged blocks?

NumericAn unorthogonalized impulse
In a two-variable VAR(1), A=[[0.5,0.4],[−0.2,0.3]]. What is the response of the first variable at h=2 to one unit in the second reduced-form innovation?
QuizWhat rejection establishes
In a correctly specified VAR, you reject the null that all X lags are zero in the Y equation. What conclusion is legitimate within the model?
ProofDecomposing the error
Prove: Derive the H-step FEVD of a stable VAR and explain why contributions sum to one.
0
Assume orthogonalized innovations with identity covariance and no temporal correlation.

Step 1 of 3. Which terms form the H-step forecast error?

CodeGranger through nested regressions
Implement granger_f(data, cause, effect, p). Fit by least squares the full equation for effect with constant and p lags of all variables, and the restricted equation omitting every lag of cause. Use identical rows and return (F, p-value) with F(p,n−d) reference, where n is row count and d the full regressor count. Reject equal or out-of-range indices, rank-deficient designs and insufficient degrees of freedom. Compare its simulated size with the lab’s Wald test.
import numpy as np
from scipy.stats import f

def granger_f(data, cause, effect, p):
  pass
Shift+Enter to run
Key idea

A VAR organizes lagged dependencies in matrices. Stability belongs to the companion form; least squares and tests describe conditional prediction; impulse responses and FEVD require stating which shocks have been identified.