Module contents
Lesson 17 of 31Advanced 110 min

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

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 tt 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.

InteractiveRegression between independent walks

Displayed pair: observed points and OLS line with intercept.

Distribution of t in 1200 new pairs, compared with the conventional t reference.

  • Simulated statistic
  • t reference(198)

Both walks start at zero and add independent standard normal innovations. The differences view uses exactly those innovations, with the same number of rows. The histogram simulation uses another reproducible stream, independent of the displayed pair.

The two-sided test rejects if |t| exceeds 1.972, the 97.5% quantile of t with n−2 degrees of freedom. Under independence, every rejection is a false alarm. Rates use valid replicates; the error shown measures approximate Monte Carlo variation. The histogram shows only t between −12 y 12, but the false alarm count also includes omitted tails.

In levels, the conventional t reference and its p value are invalid: temporal dependence of residuals changes inference. For differences, under this iid Gaussian model, the conventional test has size 5%; this allows false alarms and does not guarantee the same result in every sample. Differencing alone does not solve every time-series problem.

Regression
200
1
R² of displayed pair0.463
Slope t−13.068
Durbin-Watson0.084
Conventional two-sided p< 0.0001
Simulated false alarms989/1200 (82.4 %)
Estimated MC error, one standard deviation1.1 %
Values outside histogram253 / 1200
Compare the scatter, line and simulated rejection frequency. High R² can appear without any relationship between innovations.

In a spurious regression between independent walks, R2R^2 and the usual statistic tt do not behave as in a stationary regression. Residuals often show persistence; the Durbin-Watson statistic, ∑t=2n(et−et−1)2/∑t=1net2\sum_{t=2}^n(e_t-e_{t-1})^2/\sum_{t=1}^ne_t^2, may be small but is not itself a cointegration test. The classic analysis of Granger and Newbold studies this problem.

Two series Xt,YtX_t,Y_t are cointegrated of order (1,1)(1,1) if they are I(1)I(1) and a nontrivial linear combination exists, for example st=Yt−a−βXts_t=Y_t-a-\beta X_t, that is I(0)I(0). The common stochastic trend cancels in the spread. Vector (1,−β)(1,-\beta) 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 nn instead of n\sqrt n. This does not automatically validate ordinary tt 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 Yt∈RkY_t\in\mathbb R^k, rewrite a VAR(pp) as a vector error-correction model:

ΔYt=c+ΠYt−1+∑j=1p−1ΓjΔYt−j+ut,Π=∑j=1pAj−I,Γj=−∑i=j+1pAi.\Delta Y_t=c+\Pi Y_{t-1}+\sum_{j=1}^{p-1}\Gamma_j\Delta Y_{t-j}+u_t, \quad \Pi=\sum_{j=1}^{p}A_j-I,\quad \Gamma_j=-\sum_{i=j+1}^{p}A_i.

If Π=αβT\Pi=\alpha\beta^\mathsf T has rank rr, the rr columns of β\beta describe equilibrium relationships and those of α\alpha indicate how each equation responds to deviations. Factorization is not unique: for an invertible matrix HH, αH\alpha H and βH−T\beta H^{-\mathsf T} represent the same Π\Pi. 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 ΠYt−1\Pi Y_{t-1} when modeling only differences loses equilibrium information. Engle and Granger develop representation and estimation.

In the illustrated case, st=Xt−Yts_t=X_t-Y_t and Δ(Xt,Yt)T=αst−1+ut\Delta(X_t,Y_t)^\mathsf T=\alpha s_{t-1}+u_t. Then

st=(1+α1−α2)st−1+u1t−u2t.s_t=(1+\alpha_1-\alpha_2)s_{t-1}+u_{1t}-u_{2t}.

Spread stability requires ∣1+α1−α2∣<1|1+\alpha_1-\alpha_2|<1, not merely a favorable sign in one equation. A common unit root can remain even when the spread is stationary. With α1=α2=0\alpha_1=\alpha_2=0, the difference is a random walk if innovations have positive variance: its dispersion grows even though one path does not move away monotonically.

InteractiveWho corrects disequilibrium?

The equilibrium relationship is X=Y. With zₜ=Xₜ−Yₜ, the model is ΔXₜ₊₁=α₁zₜ+ε₁ₜ₊₁ and ΔYₜ₊₁=α₂zₜ+ε₂ₜ₊₁. Innovations are independent standard normal variables; the sample starts at X₀=3, Y₀=0 and uses seed 2617. Both expected adjustments are calculated without future shocks.

XY
Step 36: X=−0.13, Y=0.71. Length is rescaled at each step; the exact separation appears in the readouts.

Two levels with a common trend

  • X
  • Y

Spread X−Y

  • Spread
  • Equilibrium
  • X
  • Y
  • Spread
  • Equilibrium

Subtracting the equations gives zₜ₊₁=φzₜ+ε₁ₜ₊₁−ε₂ₜ₊₁. Spread correction is stable exactly when −2<α₁−α₂<0; if φ<0, the expected deviation alternates in sign. The half-life describes the amplitude of expected deviation without new shocks, not the noisy path.

In the stable regime, theoretical spread variance is 2/(1−φ²), but the sample starts outside the regime. The levels retain a common unit-root trend. If both adjustments are zero, the spread is also a random walk: its variance grows by 2 per step, though a path need not move monotonically away. If α₁=α₂, adjustments cancel in the difference even if nonzero.

-0.15
0.10
Step 36 of 36
Persistence φ = 1 + α₁ − α₂0.75
Spread dynamicsStable
Half-life of expected deviation2.41 steps
Spread at step−0.83
Expected X and Y adjustments0.13; −0.08
Change adjustment speeds and jointly observe the series and spread. Stability corresponds to the parameter combination stated in the equation.

Johansen: how many equilibria?

The Johansen test studies the rank of Π\Pi in a system. In the lab’s unrestricted-constant specification, first remove lagged differences and that constant from ΔYt\Delta Y_t and Yt−1Y_{t-1}. 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 λ^1≥⋯≥λ^k\hat\lambda_1\ge\cdots\ge\hat\lambda_k. With TT effective rows, the statistics are

Traza⁡(r)=−T∑i=r+1klog⁡(1−λ^i),Maˊx⁡(r)=−Tlog⁡(1−λ^r+1).\operatorname{Traza}(r)=-T\sum_{i=r+1}^{k}\log(1-\hat\lambda_i),\qquad \operatorname{Máx}(r)=-T\log(1-\hat\lambda_{r+1}).

The trace test compares rank at most rr against higher rank; the maximum-eigenvalue test compares rr with r+1r+1. Critical values are not ordinary χ2\chi^2 and depend on dimension and deterministic terms. Common practice starts at r=0r=0 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 I(1)I(1) system whose only roots on the unit circle are at +1+1 and whose other roots are stable, zero rank means no cointegration relations, intermediate rank rr means rr relations, and full rank means stationarity around deterministic terms. Condition I(1)I(1) excludes higher-order integration chains. Rank of Π\Pi alone does not rule out explosive or seasonal unit roots. Short samples, incorrect lags and breaks can obscure rank.

InteractiveRank and canonical correlations

Eigenvalues λ: squared canonical correlations

λ10.243
λ20.172
λ30.026
λ40.000
Bars share the scale from 0 to 1.

Trace versus 5% asymptotic critical value

H₀: rank ≤ 097.67 / 40.17
H₀: rank ≤ 142.52 / 24.28
H₀: rank ≤ 25.13 / 12.32
H₀: rank ≤ 3 · out of sequence0.00 / 4.13
Bar: statistic. Marker: critical value. Numbers are statistic / critical value.

Start at rank 0 and reject when the bar exceeds the marker. Estimated rank is the first value not rejected; if all four are rejected, it is 4. Tests after the first non-rejection are shown only for information. With true rank 2, there are 2 unit-root modes.

Generated model: in four independent modes, Δzₜ = −0.3 D zₜ₋₁ + 0.2 Δzₜ₋₁ + εₜ, with diagonal D and ones in its first r positions, standard normal εₜ and z₀ = z₁ = 0. Observed series are Yₜ = Qzₜ, where Q is the Hadamard matrix of order four divided by 2, with rows (++++) , (+−+−), (++−−), (+−−+). Each sample is reproducible by seed.

Projections on ΔYₜ₋₁ are removed from ΔYₜ and Yₜ₋₁, without constant or trend. Eigenvalues come from canonical correlations between both residuals and τ(r) = −T Σᵢ₌ᵣ₊₁⁴ log(1 − λᵢ), with T = n − 2. Rank 4 corresponds to a stationary system; lower rank yields stochastic trends. Initial conditions create a transient.

Critical values are asymptotic, for four variables, no deterministic terms and one lag in differences. In finite samples the actual size may differ from 5%, and the selected rank may be wrong; changing deterministic specification requires different critical values. Source: statsmodels Johansen tables (c_sjt, det_order = −1).

2
200
True rank2
Rank estimated by trace2
Effective rows T198
Seed2617
Generate systems with different ranks and compare trace statistics with critical values for the indicated specification. The decision is random in finite samples.

A spread does not guarantee arbitrage

If a stationary spread follows st=ϕst−1+ηts_t=\phi s_{t-1}+\eta_t with 0<∣ϕ∣<10<|\phi|<1, expected amplitude of an initial deviation halves after h1/2=log⁡(1/2)/log⁡∣ϕ∣h_{1/2}=\log(1/2)/\log|\phi| steps. If ϕ<0\phi<0, sign alternates and this is an amplitude half-life; if ϕ=0\phi=0, the previous state’s contribution disappears in one step. Near one, a small estimated change in ϕ\phi 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.

[ ]Two stages of Engle-GrangerBrowser
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.

[ ]Critical value by simulation under the nullBrowser
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 β\beta, estimate α\alpha by least squares in differences. To compare with statsmodels VECM, use vector β\beta estimated by the library and the same specification without constant or additional differenced lags.

[ ]Estimate speeds with known βBrowser
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; p=2p=2 in levels corresponds to one lag in differences. Alignment uses ΔYt\Delta Y_t, ΔYt−1\Delta Y_{t-1} and Yt−1Y_{t-1} 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.

[ ]Johansen trace from canonical correlationsBrowser
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 r=0,1,2r=0,1,2 relations. In each system the first rr coordinates have a stable root and the others are independent random walks; matrix Π\Pi is diagonal with known rank. A decision from one simulation may be wrong. Sequential selection uses library trace critical values with the same specification.

[ ]Three known ranksBrowser
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 tt, we apply exposure to the change in logarithms between tt and t+1t+1, 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.

[ ]Pairs with a break in βBrowser
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

ProofFrom relationship to adjustment
Prove: Let X and Y be two I(1) series with stationary spread Yₜ−a−βXₜ. Under the assumptions of Granger's representation theorem for a bivariate system, justify the variables in an error-correction representation.
0
Distinguish what follows from the definition of cointegration from what requires the theorem.

Step 1 of 3. Which properties follow from the definition?

NumericPersistence of a deviation
The spread satisfies sₜ=0.95sₜ₋₁+ηₜ with centered innovations. How many steps does it take for the expected contribution of s₀ to halve? Give your answer to two decimal places.
QuizInterpreting rank
For a regular I(1) system of k variables whose only unit roots are at +1 and whose other roots are stable, which association is correct?
QuizThe best test out of many
You search all pairs of 500 series and choose the smallest cointegration p-value in the same sample. What is the problem and a reasonable response?
CodeCanonical correlations and trace
Implement johansen_trace(data, p) for a VAR in levels of order p≥2. Use a constant and q=p−1 lagged differences; remove those controls from ΔYₜ and Yₜ₋₁ on the same rows. Return (descending eigenvalues, trace statistics for r=0,…,k−1). Use a symmetric generalized problem and reject samples that are too short or invalid p. The lab checks known ranks in simulation.
import numpy as np
from scipy.linalg import eigh

def johansen_trace(data, p):
  pass
Shift+Enter to run
Key idea

A 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.