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
- 26Autoregressive modelCausality and invertibilityOrder selection with information criteriaWeak (second-order) stationarityWhite noise and its variantsLinear process
- 02Eigenvalues and eigenvectorsKronecker productCholesky decompositionLeast squares
- 05Wald testParametric bootstrap
- 27Structural causal modelLadder of causation
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.
Cross-covariances and joint memory
A vector is weakly stationary if it has finite second moment, constant mean and cross-covariance matrix
depending only on lag. Under this convention, compares current component with from steps ago and . 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() is
Each has dimension ; row , column gives the coefficient of lagged variable in equation . With , companion matrix has blocks in its first row and identity blocks on the subdiagonal. Thus .
Stability requires , equivalently that finite roots of 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,
To see root equivalence, let with and blocks . Lower rows imply and the first reduces to . Therefore 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), and if . The first is a discrete Lyapunov equation; scalar division cannot replace it when matrices do not commute. For VAR(), multiplying by and taking expectations gives, for ,
When , use the transpose of the corresponding positive lag. Matrix order matters: and describe different questions.
Fitting and lag selection
Least-squares estimation forms a design row with a constant and the lagged vectors. If has full rank and contains observed vectors, ; 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 changes. With and regressors per equation, one per-observation form of the criteria is or . The determinant must be positive; constants and corrections can differ between implementations. After selection, fit on training data and inspect residuals and stability. The 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 improves prediction of after including past observed variables. In a linear VAR, the joint null sets the coefficients of lags of in the equation for to zero. A Wald test uses coefficient covariance; reference is asymptotic and depends on model and estimation assumptions. A small value rejects that predictive restriction; it does not prove a causal intervention or direct physical transmission.
In the figure, a common factor reaches before . When observing only and , the past of may contain factor information; adding the relevant past of 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.
Impulses and their identification
The reduced-form impulse response to one unit in innovation is . But if is not diagonal, changing one innovation while fixing the others is not equivalent to an observed independent shock. With , where is lower Cholesky, write with identity covariance: responds to one standard deviation of orthogonalized shock .
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 is . 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.
From response to forecast error
For a stable VAR with known parameters and horizon , forecast error given information through is . If orthogonalized shocks are uncorrelated across time and , the forecast-error variance decomposition of component attributed to shock is
If the denominator is positive, contributions of the 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 from the last observed state. For the known model, unconditional innovation-error covariance is 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.
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@x+L@rng.normal(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@G@A.T-cov)))Select lag by comparing on identical rows. This deliberately small example makes the calculation inspectable; a selected order does not guarantee a correct model.
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 . The Wald reference is asymptotic; with heteroskedasticity, residual dependence or integration, this covariance and its p-value may be inappropriate.
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(b@np.linalg.solve(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 , orthogonalized responses and FEVD. When comparing with the library use the same Cholesky and horizon convention: includes only .
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 = psi@np.linalg.cholesky(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 before using quantiles for analysis. Under regime changes, heteroskedasticity or dependent residuals, resampling iid vectors may be inappropriate.
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 , conditional on the last observed state; it is not a simultaneous band for the entire path. The same residual-resampling limitations apply.
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.
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 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.
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.
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
Step 1 of 3. What determinant equality follows by eliminating lagged blocks?
Step 1 of 3. Which terms form the H-step forecast error?
import numpy as np
from scipy.stats import f
def granger_f(data, cause, effect, p):
passA 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.