Spurious regression, cointegration and error correction models
Two independent random walks can appear related with high R²: this is spurious regression. When a linear combination of I(1) series is stationary, the series share a stochastic trend and are cointegrated. Study the two-stage Engle-Granger method, Granger's representation theorem, vector error-correction models and Johansen's reduced-rank test, with pairs statistical arbitrage as an application.
After this lesson you can
- Reproduce Granger and Newbold's spurious regression by simulation and explain its cause.
- Test cointegration between two series with Engle-Granger using the correct critical values.
- Write a VECM from a levels VAR and interpret α and β.
- Apply Johansen's test to determine cointegration rank in a multivariate system.
- Build a pairs strategy based on the cointegration residual and evaluate its out-of-sample stability.
Before you start
- 26Unit rootAugmented Dickey-Fuller testIntegrated processVector autoregressionVAR stability and companion formVAR estimation and lag selection
- 02Rank
- 05Generalized likelihood ratio test
- 27Generalized least squaresAR(1) error correction (Cochrane-Orcutt and Prais-Winsten)
- 12Canonical correlation analysis
Two trends can mislead a regression
Two prices or product metrics may rise for years and show a convincing regression line. Do they share equilibrium or merely accumulate independent shocks? A stochastic trend persists: a shock to a random walk does not disappear with time. A levels regression may confuse that persistence with a stable relationship.
Generate pairs of independent walks. The figure compares the same increments in levels and differences. The conventional levels statistic uses a reference invalid under that null; its rejection percentage is not a percentage of genuine discoveries. In differences, for the figure’s iid Gaussian model, the test has usual calibration, although a particular sample can still reject.
Spurious regression and common trends
In a spurious regression between independent walks, and the usual statistic do not behave as in a stationary regression. Residuals often show persistence; the Durbin-Watson statistic, , may be small but is not itself a cointegration test. The classic analysis of Granger and Newbold studies this problem.
Two series are cointegrated of order if they are and a nontrivial linear combination exists, for example , that is . The common stochastic trend cancels in the spread. Vector is identifiable only up to scale: multiplying by a nonzero constant does not change the relation. Cointegration does not require series to move together at every instant or guarantee that the vector remains stable after a break.
Engle-Granger in two stages
The Engle-Granger method first fits the levels relationship, including chosen deterministic terms, then tests residuals for a unit root using an ADF regression. The null is no cointegration. The slope is estimated alongside the residual: critical values differ from ordinary ADF values for an observed series. They depend, among other things, on the number of variables and constant or trend. Use critical values and p-value from a cointegration-test implementation, not ordinary ADF. The coint documentation specifies the null and options.
Under usual cointegration and integrated-regressor assumptions, the levels slope can be superconsistent, with rate instead of . This does not automatically validate ordinary standard errors and tests. Dependent variable, lag and deterministic-term choices affect finite samples; the bivariate method also does not by itself identify all relationships in a larger system.
The error-correction spring
For , rewrite a VAR() as a vector error-correction model:
If has rank , the columns of describe equilibrium relationships and those of indicate how each equation responds to deviations. Factorization is not unique: for an invertible matrix , and represent the same . Interpreting a speed requires stating normalization and considering the whole system.
The Granger representation theorem connects cointegration and error correction under regularity conditions, including appropriate restrictions on unit roots, rank and common trends. Cointegration without those assumptions does not justify inventing a particular finite VECM. In a finite VAR satisfying them, omitting when modeling only differences loses equilibrium information. Engle and Granger develop representation and estimation.
In the illustrated case, and . Then
Spread stability requires , not merely a favorable sign in one equation. A common unit root can remain even when the spread is stationary. With , the difference is a random walk if innovations have positive variance: its dispersion grows even though one path does not move away monotonically.
Johansen: how many equilibria?
The Johansen test studies the rank of in a system. In the lab’s unrestricted-constant specification, first remove lagged differences and that constant from and . A constant restricted to the cointegration relationship instead enters the augmented levels vector; it is not removed the same way. Squared canonical correlations between the residual sets give ordered eigenvalues . With effective rows, the statistics are
The trace test compares rank at most against higher rank; the maximum-eigenvalue test compares with . Critical values are not ordinary and depend on dimension and deterministic terms. Common practice starts at and advances to the first non-rejected null; successive decisions have uncertainty. The statsmodels implementation distinguishes deterministic order and lagged differences.
Under assumptions for a regular system whose only roots on the unit circle are at and whose other roots are stable, zero rank means no cointegration relations, intermediate rank means relations, and full rank means stationarity around deterministic terms. Condition excludes higher-order integration chains. Rank of alone does not rule out explosive or seasonal unit roots. Short samples, incorrect lags and breaks can obscure rank.
A spread does not guarantee arbitrage
If a stationary spread follows with , expected amplitude of an initial deviation halves after steps. If , sign alternates and this is an amplitude half-life; if , the previous state’s contribution disappears in one step. Near one, a small estimated change in greatly changes half-life.
A pairs strategy needs to estimate the relationship on training data, decide positions using information available at each date, include costs and evaluate on a later segment. Searching for the best test among many pairs biases selection: correct for multiple comparisons and reserve data unused for selection. Historical cointegration does not protect against regime changes, costs, liquidity issues or financing losses.
Lab: roots and residuals
First generate a common trend and AR(1) spread. Fit the relationship by least squares and calculate from scratch the Dickey-Fuller statistic without extra lags on residuals. Compare it with adfuller and coint: the statistic may agree even though reference distributions differ.
import numpy as np
from scipy.linalg import eigh
from statsmodels.tsa.stattools import adfuller, coint
from statsmodels.tsa.vector_ar.vecm import VECM, coint_johansen
def ajustar_relacion(x,y):
X = np.column_stack([np.ones(len(x)),x])
coef = np.linalg.lstsq(X,y,rcond=None)[0]
return coef, y-X@coef
def df_residuos(resid):
z = np.asarray(resid,dtype=float)
dy, lag = np.diff(z), z[:-1]
b = lag@dy/(lag@lag)
e = dy-b*lag
var = e@e/(len(e)-1)
return b/np.sqrt(var/(lag@lag))
rng = np.random.default_rng(2617)
n = 350
x = np.cumsum(rng.normal(size=n))
spread = np.zeros(n)
for t in range(1,n):
spread[t] = .7*spread[t-1]+rng.normal(size=1)[0]
y = 1.7*x+spread
coef, resid = ajustar_relacion(x,y)
propio = df_residuos(resid)
adf = adfuller(resid,maxlag=0,regression="n",autolag=None)
eg = coint(y,x,trend="c",maxlag=0,autolag=None)
print("constante y pendiente estimadas:", coef)
print("estadísticos propio, ADF y Engle-Granger:", propio, adf[0], eg[0])
print("p Engle-Granger y críticos 1 %, 5 %, 10 %:", eg[1], eg[2])The following calibration simulates one specific null: two independent Gaussian walks, a constant and no extra lag in the residual test. It obtains a finite empirical critical value at the same length. This is not a universal table for other innovations, deterministic terms or lag selections; with few replications the quantile fluctuates. The library test uses Engle-Granger reference approximations.
rng = np.random.default_rng(2717)
B, longitud = 600, len(x)
estadisticos = np.empty(B)
for b in range(B):
paseos = np.cumsum(rng.normal(size=(longitud,2)),axis=0)
_, errores = ajustar_relacion(paseos[:,0],paseos[:,1])
estadisticos[b] = df_residuos(errores)
critico = np.quantile(estadisticos,.05)
print("réplicas y crítico empírico al 5 %:", B, critico)
print("crítico de coint para la muestra cointegrada:", eg[2][1])
print("rechazo del ejemplo con crítico simulado:", propio < critico)Lab: VECM and rank
Generate a system with one common trend and one equilibrium relationship. Given , estimate by least squares in differences. To compare with statsmodels VECM, use vector estimated by the library and the same specification without constant or additional differenced lags.
def sim_vecm(alpha, beta, n, rng):
k = len(alpha)
datos = np.zeros((n,k))
for t in range(1,n):
datos[t] = datos[t-1]+alpha*(beta@datos[t-1])+rng.normal(size=k)
return datos
alpha = np.array([-.15,.10])
beta = np.array([1.,-1.])
vec = sim_vecm(alpha,beta,500,np.random.default_rng(2817))
vec_ref = VECM(vec,k_ar_diff=0,coint_rank=1,deterministic="n").fit()
beta_ref = vec_ref.beta[:,0]
regresor = (vec[:-1]@beta_ref)[:,None]
alpha_propia = np.linalg.lstsq(regresor,np.diff(vec,axis=0),rcond=None)[0].ravel()
print("β verdadero y estimado:", beta, beta_ref)
print("α propio y statsmodels:", alpha_propia, vec_ref.alpha[:,0])
print("diferencia máxima de α:", np.max(abs(alpha_propia-vec_ref.alpha[:,0])))
print("coeficiente AR del spread verdadero:", 1+beta@alpha)For Johansen, remove a constant and one differenced lag from both matrices; in levels corresponds to one lag in differences. Alignment uses , and on the same dates. Solve the symmetric generalized canonical-correlation problem without explicitly inverting covariance matrices. Compare eigenvalues and statistics with coint_johansen for the specification with constant and one differenced lag; do not extrapolate that verification to other deterministic conventions.
def johansen_traza(data):
y = np.asarray(data,dtype=float)
dy = np.diff(y,axis=0)
cambios, niveles = dy[1:], y[1:-1]
controles = np.column_stack([np.ones(len(cambios)),dy[:-1]])
r0 = [email protected](controles,cambios,rcond=None)[0]
r1 = [email protected](controles,niveles,rcond=None)[0]
T = len(r0)
S00, S11, S10 = r0.T@r0/T, r1.T@r1/T, r1.T@r0/T
simetrica = [email protected](S00,S10.T)
valores = np.sort(eigh(simetrica,S11,eigvals_only=True))[::-1]
if np.any(valores < -1e-10) or np.any(valores >= 1):
raise ValueError("correlaciones canónicas inválidas")
valores = np.maximum(valores,0.)
traza = np.array([-T*np.log1p(-valores[i:]).sum()
for i in range(len(valores))])
maximo = -T*np.log1p(-valores)
return valores, traza, maximo
valores, trazas, maximos = johansen_traza(vec)
jref = coint_johansen(vec,det_order=0,k_ar_diff=1)
print("autovalores propios y statsmodels:", valores, jref.eig)
print("error máximo de traza:", np.max(abs(trazas-jref.lr1)))
print("traza y críticos 5 %:", trazas, jref.cvt[:,1])
print("máximo y críticos 5 %:", maximos, jref.cvm[:,1])Now repeat the test in three-dimensional systems with relations. In each system the first coordinates have a stable root and the others are independent random walks; matrix is diagonal with known rank. A decision from one simulation may be wrong. Sequential selection uses library trace critical values with the same specification.
def sistema_rango(r, n, rng):
k = 3
datos = np.zeros((n,k))
phi = np.array([.55 if j < r else 1. for j in range(k)])
for t in range(1,n):
datos[t] = phi*datos[t-1]+rng.normal(size=k)
return datos
def rango_secuencial(trazas, criticos):
r = 0
while r < len(trazas) and trazas[r] > criticos[r]:
r += 1
return r
for r in (0,1,2):
muestra = sistema_rango(r,600,np.random.default_rng(2900+r))
propios = johansen_traza(muestra)
referencia = coint_johansen(muestra,0,1)
elegido = rango_secuencial(propios[1],referencia.cvt[:,1])
print("rango verdadero, elegido y error de traza:",
r, elegido, np.max(abs(propios[1]-referencia.lr1)))Lab: an unstable out-of-sample relationship
We simulate the logarithms of two prices with an AR(1) spread and a deliberate change in the equilibrium slope. We estimate the intercept, slope and scale in an initial calibration window; we then evaluate periods before and after the break without refitting the parameters. With the signal calculated at the close , we apply exposure to the change in logarithms between and , deducting a cost proportional to the change in exposure. The result is a PnL indicator in units of logarithmic exposure, not a funded portfolio or a return on capital. The data, break and cost are explicit assumptions, not market measurements.
rng = np.random.default_rng(3017)
n, corte, calibracion = 800, 400, 200
x = np.cumsum(rng.normal(scale=.3,size=n))
ruido = np.zeros(n)
for t in range(1,n):
ruido[t] = .8*ruido[t-1]+rng.normal(scale=.35)
beta_t = np.where(np.arange(n)<corte, 1.5, .6)
y = beta_t*x+ruido
cb, spread_train = ajustar_relacion(x[:calibracion],y[:calibracion])
escala = spread_train.std(ddof=1)
spread_todo = y-cb[0]-cb[1]*x
def pnl_exposicion(x,y,spread,escala,inicio,fin,beta,coste):
posicion = 0.
pnl = []
cambios = 0.
for t in range(inicio,fin-1):
z = spread[t]/escala
nueva = -np.sign(z) if abs(z)>1 else (0. if abs(z)<.2 else posicion)
giro = abs(nueva-posicion)*(1+abs(beta))
cambios += giro
pnl.append(nueva*((y[t+1]-y[t])-beta*(x[t+1]-x[t]))-coste*giro)
posicion = nueva
return np.sum(pnl), cambios
entreno = pnl_exposicion(x,y,spread_todo,escala,calibracion,corte,cb[1],.002)
prueba = pnl_exposicion(x,y,spread_todo,escala,corte,n,cb[1],.002)
print("β calibrado, β después de la ruptura:", cb[1], beta_t[corte])
print("desviación del spread, antes y después:",
spread_todo[calibracion:corte].std(ddof=1), spread_todo[corte:].std(ddof=1))
print("PnL indicativo y giro, antes y después:", entreno, prueba)
print("PnL indicativo por paso, antes y después:",
entreno[0]/(corte-calibracion-1), prueba[0]/(n-corte-1))
print("semividas de amplitud para una rejilla de φ entre 0.8 y 0.99:",
[np.log(.5)/np.log(p) for p in np.linspace(.8,.99,20)])
print("pares distintos entre 500 series:", 500*499//2)The change in slope induces a discontinuity in the synthetic model and can produce a large loss or gain on the break date. Each evaluated period starts with zero position; the second does not include the jump as a previous trade. Since the periods have different lengths, also compare PnL per step. A single seed does not prove that a strategy always deteriorates.
Exercises
Step 1 of 3. Which properties follow from the definition?
import numpy as np
from scipy.linalg import eigh
def johansen_trace(data, p):
passA stationary combination can reveal an equilibrium between individually integrated series. Engle-Granger tests a residual relationship; Johansen estimates the rank of a system; the VECM retains correction of deviations alongside short-run dynamics.