Algorithm Search⌘K

Algorithmadvanced

Engle-Granger test

Also called Engle-Granger two-step method.

Tests for cointegration by regressing one series on the others and applying a unit root test to the residuals.

Time
Θ(n (m + p)^2) worst · best
Space
Θ(n (m + p)) extra
Where
m = the number of regressors; n = the length of the series; p = the number of lagged differences
Properties
deterministicnot exactofflineiterative
Origin
Robert F. Engle, Clive W. J. Granger, 1987

The Engle-Granger test asks whether two or more nonstationary series are cointegrated, that is, whether some linear combination of them is stationary. It runs in two steps. First it regresses one series on the others in levels by ordinary least squares, which estimates the candidate combination. Then it applies a Dickey-Fuller unit root test to the residuals. If the residuals have a unit root, the series are not cointegrated; if the test rejects the unit root, the combination is stationary. Because the residuals come from a fitted regression, which makes them look more stationary than they are, the critical values are more negative than those of the augmented Dickey-Fuller test, and they depend on the number of series. The same two steps also give the "two-step method": the residual, lagged once, is the error correction term in a regression of the differences.

In plain words

Two series can each wander without limit and still stay close together, like a dog on a leash and its owner. The test first finds the best straight-line rule that links one series to the others, for example "the price in market A is about twice the price in market B plus one". It then looks at how far each point is from that rule. If the gaps keep coming back toward zero, the series are tied together. If the gaps wander as freely as the series themselves, the link was an accident of two trends. The usual unit root table is too generous here, because the rule was chosen to make the gaps small, so a stricter table is used.

The problem

Model and hypotheses. Let yty_t and xt=(x1t,…,xmt)x_t = (x_{1t}, \dots, x_{mt}) be integrated of order one, I(1), as on the ARIMA model page, t=1,…,nt = 1, \dots, n. Consider the levels regression

yt=δ⊤dt+β⊤xt+ut,y_t = \delta^\top d_t + \beta^\top x_t + u_t,

with dt=1d_t = 1 (case "c") or dt=(1,t)d_t = (1, t) (case "ct"). The null hypothesis is H0H_0: utu_t is I(1) for every β\beta, so (yt,xt)(y_t, x_t) is not cointegrated. The alternative is H1H_1: for the true β\beta, utu_t is stationary, so (1,−β⊤)(1, -\beta^\top) is a cointegrating vector. The test assumes at most one cointegrating relation, and that yty_t enters it with a nonzero coefficient.

Statistic. Let u^t\hat u_t be the least squares residuals. Fit the Dickey-Fuller regression with no deterministic terms, because the residuals already have mean zero (and no trend in case "ct"),

∇u^t=ρu^t−1+∑i=1pγi∇u^t−i+et,t=p+2,…,n,\nabla\hat u_t = \rho\hat u_{t-1} + \sum_{i=1}^{p}\gamma_i\nabla\hat u_{t-i} + e_t, \qquad t = p + 2, \dots, n,

and take the t ratio τ=ρ^/se⁡(ρ^)\tau = \hat\rho/\operatorname{se}(\hat\rho).

Null distribution. Asymptotic and nonstandard. Under H0H_0, τ\tau converges to a functional of an NN-dimensional Brownian motion, N=m+1N = m + 1, which depends on NN and on the case but not on the covariance of the increments (Phillips and Ouliaris 1990). This limit is cited, not proved here. Its quantiles are tabulated by simulation.

Rejection rule and size. Reject H0H_0 when τ<cα(N,T)\tau < c_\alpha(N, T), with the response surface of MacKinnon (2010), where T=n−p−1T = n - p - 1:

case NN 1% 5% 10% 5% at T=100T = 100
"c" 2 −3.896-3.896 −3.336-3.336 −3.044-3.044 −3.398-3.398
"c" 3 −4.294-4.294 −3.741-3.741 −3.452-3.452 −3.827-3.827
"c" 4 −4.643-4.643 −4.096-4.096 −3.810-3.810 −4.209-4.209
"ct" 2 −4.328-4.328 −3.781-3.781 −3.496-3.496 −3.877-3.877
"ct" 3 −4.663-4.663 −4.119-4.119 −3.835-3.835 −4.240-4.240

The first three columns are the limits T→∞T \to \infty. For N=2N = 2 in case "c" the 5% point −3.34-3.34 is far below the ADF value −2.86-2.86. The size is asymptotically α\alpha.

p-value. MacKinnon (1996) gives response surface p-values for τ\tau by NN and case. A Monte Carlo p-value from independent random walks is also valid asymptotically, since the limit does not depend on nuisance parameters.

Sensitivity and power. The test detects a stationary combination. Its power falls as the residual becomes more persistent and as NN grows, because the critical values move to the left. When there is more than one cointegrating relation, the regression estimates some combination of them, and the test says nothing about how many there are. For that, use the Johansen test.

The algorithm

  1. ENGLE-GRANGER(y, x₁..x_m, case, p)
  2. 1(δ̂, β̂) ← OLS of y_t on d_t and x_t; û_t ← y_t − δ̂ᵀd_t − β̂ᵀx_t
  3. 2Δû_t ← û_t − û_{t−1}, t = 2..n
  4. 3fit Δû_t = ρ û_{t−1} + Σ_{i=1..p} γ_i Δû_{t−i} + e_t by OLS, t = p+2..n
  5. 4τ ← ρ̂ / se(ρ̂)
  6. 5c ← MacKinnon(N = m + 1, case, T = n − p − 1, α)
  7. 6return (τ, β̂, reject ⇔ τ < c)

The two-step method continues after a rejection. With u^t−1\hat u_{t-1} from line L1, fit the error correction model

∇yt=μ+αu^t−1+θ⊤∇xt+∑i=1q(ai∇yt−i+bi⊤∇xt−i)+εt\nabla y_t = \mu + \alpha\hat u_{t-1} + \theta^\top\nabla x_t + \sum_{i=1}^{q}\left(a_i\nabla y_{t-i} + b_i^\top\nabla x_{t-i}\right) + \varepsilon_t

by OLS. All regressors are stationary under cointegration, so the usual t and F tests apply to this regression, and α<0\alpha < 0 measures how fast yy returns to the long-run relation. The number of lags pp in line L3 is chosen as for the ADF test, by AIC or BIC on common rows.

Example

By hand. Take n=10n = 10, x=(0,1,3,2,4,5,7,6,8,9)x = (0, 1, 3, 2, 4, 5, 7, 6, 8, 9) and y=(2,2,7,6,8,12,15,12,18,18)y = (2, 2, 7, 6, 8, 12, 15, 12, 18, 18), case "c" and p=0p = 0.

step value
L1: xˉ\bar x, yˉ\bar y, SxxS_{xx}, SxyS_{xy} 9/29/2, 1010, 165/2165/2, 160160
L1: β^=Sxy/Sxx\hat\beta = S_{xy}/S_{xx}, δ^=yˉ−β^xˉ\hat\delta = \bar y - \hat\beta\bar x 64/33=1.939464/33 = 1.9394, 14/11=1.272714/11 = 1.2727
L1: u^t\hat u_t 0.727,−1.212,−0.091,0.848,−1.030,1.030,0.152,−0.909,1.212,−0.7270.727, -1.212, -0.091, 0.848, -1.030, 1.030, 0.152, -0.909, 1.212, -0.727
L3: ρ^=∑u^t−1∇u^t/∑u^t−12\hat\rho = \sum\hat u_{t-1}\nabla\hat u_t/\sum\hat u_{t-1}^2 (−1442/121)/(2602/363)=−2163/1301=−1.6626(-1442/121)/(2602/363) = -2163/1301 = -1.6626
L3: s2=RSS/(9−1)s^2 = \mathrm{RSS}/(9 - 1) 0.50266
L4: se⁡(ρ^)=s2/∑u^t−12\operatorname{se}(\hat\rho) = \sqrt{s^2/\sum\hat u_{t-1}^2}, τ\tau 0.26481, −6.278-6.278
L5: c0.05(N=2,T=9)c_{0.05}(N = 2, T = 9) −4.099-4.099

Since −6.28<−4.10-6.28 < -4.10, the test rejects "no cointegration". The residuals change sign almost every step, which is the opposite of a random walk. With only 10 points the response surface is an extrapolation, so this is an illustration of the steps, not a reliable decision.

A cointegrated pair and a spurious pair. With seed 2026, let xtx_t be a Gaussian random walk of length 200, ut=0.5ut−1+εtu_t = 0.5u_{t-1} + \varepsilon_t, and yt=1+2xt+uty_t = 1 + 2x_t + u_t. Then a second, independent random walk wtw_t is regressed on xtx_t.

pair β^\hat\beta slope t ratio lags τ\tau c0.05c_{0.05} decision
yy on xx 1.968 2 −7.20-7.20 −3.367-3.367 cointegrated
ww on xx −0.795-0.795 −9.53-9.53 0 −0.76-0.76 −3.367-3.367 not cointegrated

The spurious regression of ww on xx has R2=0.31R^2 = 0.31 and a slope t ratio of −9.5-9.5, which a t table would call overwhelming. The residual test shows that the residuals are a random walk. For the cointegrated pair the second step gives α^=−0.533\hat\alpha = -0.533 (standard error 0.064) on u^t−1\hat u_{t-1} and 1.9511.951 on ∇xt\nabla x_t, close to the true values −0.5-0.5 and 22.

Superconsistency. For yt=2xt+uty_t = 2x_t + u_t with xtx_t a random walk and utu_t iid N(0,1)N(0, 1), the interquartile range of β^\hat\beta over 400 samples was 0.07520.0752 at n=50n = 50, 0.01790.0179 at n=200n = 200 and 0.00490.0049 at n=800n = 800. So nn times the range stayed near 3.6 to 3.9: the error shrinks like 1/n1/n, not like 1/n1/\sqrt n. With two independent random walks of length 100, the 5% rejection rate against c0.05(2,99)c_{0.05}(2, 99) was 0.054 in 2000 samples.

Correctness

The correctness proof shows four facts. Line L1 computes the least squares fit, and the residual vector is the projection of yy onto the orthogonal complement of the regressors, so τ\tau depends on yy only through that projection. Hence τ\tau is unchanged when yy is replaced by a+cy+d⊤xa + cy + d^\top x (c≠0c \ne 0) or when xx is replaced by an invertible affine map of itself, and under the null with independent Gaussian random walks its law does not depend on β\beta or the scales. Lines L2 to L4 compute the Dickey-Fuller t ratio of the residuals, by the same argument as on the ADF page. Under cointegration with xtx_t a random walk independent of the stationary error, n(β^−β)n(\hat\beta - \beta) is bounded in probability, with E Sxx=σv2(n2−1)/6E\,S_{xx} = \sigma_v^2(n^2 - 1)/6 exactly. The null limit law of τ\tau (Phillips and Ouliaris 1990) and the general superconsistency result (Stock 1987) are cited, not proved.

Proof: Engle-Granger computes the residual Dickey-Fuller t ratio, the ratio is invariant to affine changes of the series and pivotal under a Gaussian null, and the levels slope is superconsistentfull

We prove that lines L1 to L4 compute the least squares residuals and their Dickey-Fuller t ratio (Lemmas 1 and 2), that τ\tau is unchanged by the affine maps listed on the page (Lemma 3), that under a null of Gaussian random walks the law of τ\tau depends only on NN, nn, pp and the case, so a Monte Carlo p-value from independent walks is exact (Theorem 4), and that in the bivariate cointegrated model with an exogenous random walk regressor n(β^−β)n(\hat\beta - \beta) is bounded in probability (Theorem 5). Theorem 5 uses one cited fact, the functional central limit theorem for the denominator. We do not prove the limit law of τ\tau under the null (Phillips and Ouliaris 1990), the general superconsistency result with an endogenous regressor (Stock 1987), the consistency of the test, or the accuracy of the MacKinnon (2010) response surface, which is itself a fit to simulations.

Lemma 1 (line L1). Let ZZ be the n×kn \times k matrix with the deterministic columns and the mm regressor columns, of full column rank kk, and let Z=QRZ = QR be its thin QR factorization, which modified Gram-Schmidt computes. Then b^=R−1Q⊤y\hat b = R^{-1}Q^\top y minimizes ∥y−Zb∥\lVert y - Zb\rVert, and the residual is u^=My\hat u = My with M=I−QQ⊤M = I - QQ^\top, the orthogonal projection onto the complement of the column span of ZZ.

Proof. For any bb, y−Zb=(y−QQ⊤y)+Q(Q⊤y−Rb)y - Zb = (y - QQ^\top y) + Q(Q^\top y - Rb), and the two terms are orthogonal because Q⊤(I−QQ⊤)=0Q^\top(I - QQ^\top) = 0. So ∥y−Zb∥2=∥My∥2+∥Q⊤y−Rb∥2\lVert y - Zb\rVert^2 = \lVert My\rVert^2 + \lVert Q^\top y - Rb\rVert^2, which is smallest when Rb=Q⊤yRb = Q^\top y. RR is upper triangular with positive diagonal when ZZ has full rank, so b^=R−1Q⊤y\hat b = R^{-1}Q^\top y is the unique minimizer, and y−Zb^=Myy - Z\hat b = My. When a column is in the span of the earlier ones, its Gram-Schmidt remainder is 0, and the implementation stops with an error. □\square

Lemma 2 (lines L2 to L4). Let WW be the matrix with columns u^t−1\hat u_{t-1} and ∇u^t−i\nabla\hat u_{t-i}, i=1..pi = 1..p, for t=p+2..nt = p + 2..n, and let r=∇u^r = \nabla\hat u on the same rows. If WW has full rank p+1p + 1, line L4 returns τ=ρ^/(s[(W⊤W)−1]11)\tau = \hat\rho/(s\sqrt{[(W^\top W)^{-1}]_{11}}) with s2=∥r−Wc^∥2/(T−p−1)s^2 = \lVert r - W\hat c\rVert^2/(T - p - 1) and T=n−p−1T = n - p - 1. This is the ordinary least squares t ratio of the first coefficient.

Proof. By Lemma 1 applied to WW, c^=RW−1QW⊤r\hat c = R_W^{-1}Q_W^\top r is the least squares fit and ρ^=c^1\hat\rho = \hat c_1. Since W⊤W=RW⊤RWW^\top W = R_W^\top R_W, (W⊤W)−1=RW−1RW−⊤(W^\top W)^{-1} = R_W^{-1}R_W^{-\top}, whose (1,1)(1, 1) entry is the squared norm of the first row of RW−1R_W^{-1}. The implementation computes RW−1R_W^{-1} by back substitution and takes se⁡(ρ^)=s∥(RW−1)1,⋅∥\operatorname{se}(\hat\rho) = s\lVert(R_W^{-1})_{1,\cdot}\rVert. □\square

Lemma 3 (invariance). Let c≠0c \ne 0, let aa be in the span of the deterministic columns, and let d∈Rmd \in \mathbb{R}^m. Replacing yy by a+cy+Xda + cy + Xd, where XX holds the regressor columns, or replacing XX by XA+1g⊤XA + \mathbf 1 g^\top for an invertible m×mm \times m matrix AA and any gg, leaves τ\tau unchanged.

Proof. The first map changes the residual to M(a+cy+Xd)=cMyM(a + cy + Xd) = cMy, since aa and XdXd lie in the span of ZZ, which MM annihilates. The second map does not change the span of ZZ, so it does not change MM or u^\hat u. In lines L2 and L3 every column of WW and the response rr are linear in u^\hat u, so multiplying u^\hat u by cc multiplies c^\hat c by 1, the residual of line L3 by cc, ss by ∣c∣|c| and (W⊤W)−1(W^\top W)^{-1} by c−2c^{-2}. Hence ρ^\hat\rho is unchanged and se⁡(ρ^)\operatorname{se}(\hat\rho) is unchanged. □\square

Theorem 4 (an exact pivot under a Gaussian null). Let (yt,xt⊤)⊤=∑s≤tηs(y_t, x_t^\top)^\top = \sum_{s \le t}\eta_s, with ηs\eta_s iid N(0,Σ)N(0, \Sigma) in RN\mathbb{R}^{N} and Σ\Sigma positive definite. Then for fixed nn, pp and case, the law of τ\tau does not depend on Σ\Sigma. So τ\tau has the same law as for NN independent standard Gaussian walks, and the rank of the observed τ\tau among RR simulated values from independent walks gives an exact Monte Carlo p-value.

Proof. Write Σ\Sigma in blocks, with Σxx\Sigma_{xx} the m×mm \times m block of the regressors. Let d=Σxx−1Σxyd = \Sigma_{xx}^{-1}\Sigma_{xy} and ω2=Σyy−ΣyxΣxx−1Σxy>0\omega^2 = \Sigma_{yy} - \Sigma_{yx}\Sigma_{xx}^{-1}\Sigma_{xy} > 0. For a Gaussian vector, ηsy−d⊤ηsx\eta^y_s - d^\top\eta^x_s is independent of ηsx\eta^x_s with variance ω2\omega^2. So yt=d⊤xt+ωwty_t = d^\top x_t + \omega w_t, where wtw_t is a standard Gaussian walk independent of xx. Also xt=Σxx1/2ξtx_t = \Sigma_{xx}^{1/2}\xi_t with ξ\xi an mm-vector of independent standard walks, independent of ww. By Lemma 3, τ(y,x)=τ(ωw+xd,x)=τ(w,x)=τ(w,ξ⊤)\tau(y, x) = \tau(\omega w + xd, x) = \tau(w, x) = \tau(w, \xi^\top), using the second map with A=Σxx1/2A = \Sigma_{xx}^{1/2}. The right side is a fixed function of NN independent standard walks. If the observed τ\tau and RR simulated values are exchangeable, the rank of the observed value is uniform, which makes (1+#{τi≤τ})/(R+1)(1 + \#\{\tau_i \le \tau\})/(R + 1) an exact p-value. □\square

The function simulate_null draws exactly the independent standard walks of Theorem 4. With non-Gaussian or serially correlated increments the law of τ\tau changes in finite samples, and only the asymptotic statement of Phillips and Ouliaris applies, with p→∞p \to \infty when the increments are serially correlated.

Theorem 5 (superconsistency, bivariate exogenous case). Let yt=α+βxt+uty_t = \alpha + \beta x_t + u_t, t=1..nt = 1..n, where xt=∑s≤tvsx_t = \sum_{s \le t}v_s with vsv_s iid, mean 0, variance σv2>0\sigma_v^2 > 0, and utu_t iid, mean 0, variance σu2\sigma_u^2, independent of (vs)(v_s). Let β^\hat\beta be the slope of line L1 in case "c". Then E Sxx=σv2(n2−1)/6E\,S_{xx} = \sigma_v^2(n^2 - 1)/6 exactly, with Sxx=∑t(xt−xˉ)2S_{xx} = \sum_t(x_t - \bar x)^2, and n(β^−β)=Op(1)n(\hat\beta - \beta) = O_p(1).

Proof. The slope is β^=β+∑t(xt−xˉ)ut/Sxx\hat\beta = \beta + \sum_t(x_t - \bar x)u_t/S_{xx}. First the mean of Sxx=∑txt2−nxˉ2S_{xx} = \sum_tx_t^2 - n\bar x^2. Since Cov⁡(xs,xt)=σv2min⁡(s,t)\operatorname{Cov}(x_s, x_t) = \sigma_v^2\min(s, t),

E∑txt2=σv2∑t=1nt=σv2n(n+1)2,E nxˉ2=σv2n∑s,tmin⁡(s,t)=σv2n∑k=1nk2=σv2(n+1)(2n+1)6,E\sum_tx_t^2 = \sigma_v^2\sum_{t=1}^{n}t = \sigma_v^2\frac{n(n+1)}{2}, \qquad E\,n\bar x^2 = \frac{\sigma_v^2}{n}\sum_{s,t}\min(s, t) = \frac{\sigma_v^2}{n}\sum_{k=1}^{n}k^2 = \sigma_v^2\frac{(n+1)(2n+1)}{6},

where ∑s,tmin⁡(s,t)=∑k=1n(number of pairs with both s,t≥k)=∑k(n−k+1)2\sum_{s,t}\min(s, t) = \sum_{k=1}^{n}(\text{number of pairs with both } s, t \ge k) = \sum_k(n - k + 1)^2. The difference is σv2(n+1)(3n−2n−1)/6=σv2(n2−1)/6\sigma_v^2(n+1)(3n - 2n - 1)/6 = \sigma_v^2(n^2 - 1)/6.

Next, conditional on xx, the numerator ∑t(xt−xˉ)ut\sum_t(x_t - \bar x)u_t has mean 0 and variance σu2Sxx\sigma_u^2S_{xx}, since the utu_t are uncorrelated and independent of xx. So, conditional on xx, β^−β\hat\beta - \beta has mean 0 and variance σu2/Sxx\sigma_u^2/S_{xx}. For M>0M > 0 and ϵ>0\epsilon > 0, conditional Chebyshev gives

P(n∣β^−β∣>M)≤P(Sxx<ϵn2)+E[n2σu2M2Sxx1{Sxx≥ϵn2}]≤P(n−2Sxx<ϵ)+σu2M2ϵ.P(n|\hat\beta - \beta| > M) \le P(S_{xx} < \epsilon n^2) + E\left[\frac{n^2\sigma_u^2}{M^2S_{xx}}\mathbf 1\{S_{xx} \ge \epsilon n^2\}\right] \le P(n^{-2}S_{xx} < \epsilon) + \frac{\sigma_u^2}{M^2\epsilon}.

The cited fact is the functional central limit theorem (Donsker), with the continuous mapping theorem: n−2Sxx⇒σv2∫01W~(r)2drn^{-2}S_{xx} \Rightarrow \sigma_v^2\int_0^1\tilde W(r)^2dr, where W~=W−∫01W\tilde W = W - \int_0^1W is a demeaned standard Brownian motion. The limit is positive with probability 1 and has a continuous distribution, so lim sup⁡nP(n−2Sxx<ϵ)=P(σv2∫W~2<ϵ)\limsup_nP(n^{-2}S_{xx} < \epsilon) = P(\sigma_v^2\int\tilde W^2 < \epsilon), which tends to 0 as ϵ→0\epsilon \to 0. Given δ>0\delta > 0, choose ϵ\epsilon so that this term is below δ/2\delta/2 for all large nn, then MM so that σu2/(M2ϵ)<δ/2\sigma_u^2/(M^2\epsilon) < \delta/2. Hence n(β^−β)=Op(1)n(\hat\beta - \beta) = O_p(1). □\square

The exact mean says that the denominator grows like n2n^2, which is the source of the rate: with a stationary regressor SxxS_{xx} grows like nn, and the same argument gives only n(β^−β)=Op(1)\sqrt n(\hat\beta - \beta) = O_p(1). The mean alone does not bound SxxS_{xx} away from 0 in probability; that is the role of the cited limit. Stock (1987) proves n(β^−β)=Op(1)n(\hat\beta - \beta) = O_p(1) when utu_t is stationary and correlated with vtv_t, where the conditional argument above does not apply and n(β^−β)n(\hat\beta - \beta) has a nonzero mean in the limit. Under the same assumptions the residuals satisfy u^t−ut=−(α^−α)−(β^−β)xt\hat u_t - u_t = -(\hat\alpha - \alpha) - (\hat\beta - \beta)x_t, and since max⁡t∣xt∣=Op(n)\max_t|x_t| = O_p(\sqrt n) the error is Op(n−1/2)O_p(n^{-1/2}) uniformly in tt. That is why the step-two regression on u^\hat u behaves like a regression on the stationary uu in large samples.

Termination. Line L1 is a QR factorization of kk columns of length nn and one back substitution. Line L3 is one more factorization with p+1p + 1 columns, or one for each p≤pmax⁡p \le p_{\max} when the lag is chosen by AIC or BIC. All loops have fixed bounds, so the procedure stops after O(n(k2+pmax⁡3))O(n(k^2 + p_{\max}^3)) operations.

Complexity

On a real RAM, line L1 is a least squares fit with nn rows and m+1m + 1 or m+2m + 2 columns, Θ(nm2)\Theta(nm^2) by QR. Lines L2 to L4 are a regression with p+1p + 1 columns, Θ(np2)\Theta(np^2). With lag selection over p≤pmax⁡p \le p_{\max}, the second step costs Θ(npmax⁡3)\Theta(np_{\max}^3), or Θ(npmax⁡2)\Theta(np_{\max}^2) with column updates of the QR factorization. The total is Θ(n(m+p)2)\Theta(n(m + p)^2) time and Θ(n(m+p))\Theta(n(m + p)) space for the design matrices. The error correction step is one more regression of the same size.

Numerical stability. I(1) regressors in levels have large and strongly correlated columns, and the constant is close to their span when the series are far from zero. Use a QR factorization, not the normal equations, and center the columns if needed. Centering changes δ^\hat\delta but not β^\hat\beta or the residuals.

Properties

  • Superconsistent. Under cointegration, β^−β=Op(1/n)\hat\beta - \beta = O_p(1/n), faster than the 1/n1/\sqrt n rate of stationary regression (Stock 1987). This holds even when xtx_t is correlated with utu_t, which would make OLS inconsistent in a stationary model.
  • Biased in finite samples. When utu_t is correlated with ∇xt\nabla x_t or serially correlated, β^\hat\beta has a bias of order 1/n1/n and a nonstandard limit law, so t ratios from the levels regression are not valid. Fully modified OLS and dynamic OLS fix this.
  • Not invariant to normalization. The choice of which series is yty_t changes β^\hat\beta and τ\tau. In large samples all choices agree under cointegration, but in small samples they can give different answers.
  • Invariant to affine maps. τ\tau is unchanged by changes of level and scale of yy and of each xjx_j, and by adding a combination of the xjx_j to yy.
  • One relation only. The residual test treats cointegration as a yes or no question with a single vector.
  • Critical values depend on NN. Each added regressor moves the 5% point to the left by about 0.35 to 0.4 in case "c".

Variants and improvements

  • Phillips-Ouliaris tests. Use the Phillips-Perron correction in place of the lagged differences, or a variance ratio statistic, on the same residuals.
  • Fully modified OLS (Phillips and Hansen 1990). Corrects the levels regression for endogeneity and serial correlation with long-run covariance estimates, so that t tests on β\beta have normal limits.
  • Dynamic OLS (Stock and Watson 1993). Adds leads and lags of ∇xt\nabla x_t to the levels regression for the same purpose.
  • Error correction test. Test α=0\alpha = 0 in the error correction model directly, with its own critical values. It can be more powerful when the long-run relation is known.
  • KPSS on the residuals. Take cointegration as the null and test the residuals for stationarity with the KPSS statistic, with critical values that account for the estimated β\beta.
  • Known cointegrating vector. If theory fixes β\beta, as for a spread or a ratio, form ut=yt−β⊤xtu_t = y_t - \beta^\top x_t directly and use the ordinary ADF critical values. No estimation step means more power.
  • System methods. The Johansen test estimates all cointegrating relations in a vector autoregression and treats all series alike.

When to use it

Use the Engle-Granger test for two or three series, when there is at most one long-run relation and a natural choice of the dependent variable, for example a spot and a futures price, or consumption and income. It is simple to compute and explain. For more series, or when the number of relations is the question, use the Johansen test. If the cointegrating vector is known, test the known combination with the ADF test.

Pitfalls

  • ADF critical values on residuals. The residuals are chosen to be as small as possible, so they look stationary. Using −2.86-2.86 instead of −3.34-3.34 for N=2N = 2 rejects "no cointegration" far too often.
  • Levels regression without a test. A large R2R^2 and a large t ratio between two I(1) series mean nothing by themselves (Granger and Newbold 1974, Phillips 1986). In the example, independent walks gave t=−9.5t = -9.5.
  • t tests on β^\hat\beta. The standard errors printed by the levels regression are not valid, even under cointegration. Use FM-OLS or DOLS for inference on β\beta.
  • Constant in the residual regression. The step-two regression has no constant; the critical values assume that. Adding one changes the null law.
  • Series of different orders. If one series is I(0) and the other I(1), or one is I(2), the test does not measure cointegration. Test each series for a unit root first.
  • Normalization in small samples. Report results for each choice of the dependent variable when the answers differ.
  • Breaks in the relation. A shift in the long-run relation makes the residuals look like a random walk, and the test fails to find cointegration that holds in each regime.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

eg_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/engle-granger-test/. The authors are listed in prov/33J9EX.jsonl.
"""The Engle-Granger residual-based test for cointegration, and the two-step
error correction estimate.

Step 1 regresses y_t on deterministic terms and on the m regressors x_t by
least squares and keeps the residuals u_t. Step 2 runs a Dickey-Fuller
regression on u_t with no deterministic terms,

    du_t = rho u_(t-1) + sum_(i=1..p) g_i du_(t-i) + e_t,

and returns the t ratio tau of rho. Under the null of no cointegration tau has
a nonstandard law that depends on N = m + 1 and on the deterministic terms, so
it is compared with the MacKinnon (2010) response surface for N variables.
The code is in this file and not in engle_granger_test.py, because tools
treat a file whose name ends in _test.py as a test file.
"""

import math
import random

# MacKinnon (2010), Queen's Economics Department Working Paper 1227, Table 2.
# Keys: (case, N) -> {level: (b0, b1, b2, b3)}; critical value b0 + b1/T + b2/T^2 + b3/T^3.
MACKINNON_2010 = {
    ("c", 1): {0.01: (-3.43035, -6.5393, -16.786, -79.433), 0.05: (-2.86154, -2.8903, -4.234, -40.040),
               0.10: (-2.56677, -1.5384, -2.809, 0.0)},
    ("c", 2): {0.01: (-3.89644, -10.9519, -33.527, 0.0), 0.05: (-3.33613, -6.1101, -6.823, 0.0),
               0.10: (-3.04445, -4.2412, -2.720, 0.0)},
    ("c", 3): {0.01: (-4.29374, -14.4354, -33.195, 47.433), 0.05: (-3.74066, -8.5632, -10.852, 27.982),
               0.10: (-3.45218, -6.2143, -3.718, 0.0)},
    ("c", 4): {0.01: (-4.64332, -18.1031, -37.972, 0.0), 0.05: (-4.09600, -11.2349, -11.175, 0.0),
               0.10: (-3.81020, -8.3931, -4.137, 0.0)},
    ("c", 5): {0.01: (-4.95756, -21.8883, -45.142, 0.0), 0.05: (-4.41519, -14.0405, -12.575, 0.0),
               0.10: (-4.13157, -10.7417, -3.784, 0.0)},
    ("ct", 1): {0.01: (-3.95877, -9.0531, -28.428, -134.155), 0.05: (-3.41049, -4.3904, -9.036, -45.374),
                0.10: (-3.12705, -2.5856, -3.925, -22.380)},
    ("ct", 2): {0.01: (-4.32762, -15.4387, -35.679, 0.0), 0.05: (-3.78057, -9.5106, -12.074, 0.0),
                0.10: (-3.49631, -7.0815, -7.538, 21.892)},
    ("ct", 3): {0.01: (-4.66305, -18.7688, -49.793, 104.244), 0.05: (-4.11890, -11.8922, -19.031, 77.332),
                0.10: (-3.83511, -9.0723, -8.504, 35.403)},
    ("ct", 4): {0.01: (-4.96940, -22.4694, -52.599, 51.314), 0.05: (-4.42871, -14.5876, -18.228, 39.647),
                0.10: (-4.14633, -11.2500, -9.873, 54.109)},
    ("ct", 5): {0.01: (-5.25276, -26.2183, -59.631, 50.646), 0.05: (-4.71537, -17.3569, -22.660, 91.359),
                0.10: (-4.43422, -13.6078, -10.238, 76.781)},
}


def mackinnon_critical_value(case, nvars, level, nobs=None):
    """Lower-tail critical value for the residual t ratio with nvars = N series."""
    b = MACKINNON_2010[(case, nvars)][level]
    if nobs is None:
        return b[0]
    u = 1.0 / nobs
    return b[0] + b[1] * u + b[2] * u * u + b[3] * u * u * u


def ols(columns, y):
    """Least squares by modified Gram-Schmidt QR. Returns (coef, resid, se)."""
    n, k = len(y), len(columns)
    if n <= k:
        raise ValueError("need more observations than regressors")
    q, r = [], [[0.0] * k for _ in range(k)]
    for j in range(k):
        v = [float(a) for a in columns[j]]
        norm0 = math.sqrt(sum(a * a for a in v))
        for i in range(j):
            d = sum(a * b for a, b in zip(q[i], v))
            r[i][j] = d
            v = [a - d * b for a, b in zip(v, q[i])]
        nrm = math.sqrt(sum(a * a for a in v))
        if norm0 == 0.0 or nrm <= 1e-12 * norm0:
            raise ValueError("the regressors are linearly dependent")
        r[j][j] = nrm
        q.append([a / nrm for a in v])
    rinv = [[0.0] * k for _ in range(k)]
    for c in range(k):
        for j in range(c, -1, -1):
            rhs = (1.0 if j == c else 0.0) - sum(r[j][l] * rinv[l][c] for l in range(j + 1, c + 1))
            rinv[j][c] = rhs / r[j][j]
    qty = [sum(a * float(b) for a, b in zip(qj, y)) for qj in q]
    coef = [sum(rinv[j][c] * qty[c] for c in range(j, k)) for j in range(k)]
    resid = [float(y[t]) - sum(coef[j] * float(columns[j][t]) for j in range(k)) for t in range(n)]
    s2 = sum(e * e for e in resid) / (n - k)
    se = [math.sqrt(s2 * sum(rinv[j][c] ** 2 for c in range(j, k))) for j in range(k)]
    return coef, resid, se


def _deterministic(n, case):
    if case == "c":
        return [[1.0] * n]
    if case == "ct":
        return [[1.0] * n, [float(t + 1) for t in range(n)]]
    raise ValueError("case must be 'c' or 'ct'")


def residual_adf(u, lags):
    """t ratio of rho in du_t = rho u_(t-1) + sum g_i du_(t-i) + e_t (no constant)."""
    n = len(u)
    du = [0.0] + [u[t] - u[t - 1] for t in range(1, n)]
    rows = range(lags + 1, n)
    cols = [[u[t - 1] for t in rows]] + [[du[t - i] for t in rows] for i in range(1, lags + 1)]
    coef, resid, se = ols(cols, [du[t] for t in rows])
    return coef[0] / se[0], len(rows), sum(e * e for e in resid), len(cols)


def select_lags(u, max_lag, criterion="aic"):
    """AIC or BIC choice of the number of lagged differences, on common rows."""
    n = len(u)
    du = [0.0] + [u[t] - u[t - 1] for t in range(1, n)]
    rows = range(max_lag + 1, n)
    best, best_ic = 0, math.inf
    for p in range(max_lag + 1):
        cols = [[u[t - 1] for t in rows]] + [[du[t - i] for t in rows] for i in range(1, p + 1)]
        _, resid, _ = ols(cols, [du[t] for t in rows])
        rss, m = sum(e * e for e in resid), len(rows)
        pen = 2.0 if criterion == "aic" else math.log(m)
        ic = m * math.log(rss / m) + pen * len(cols)
        if ic < best_ic - 1e-12:
            best, best_ic = p, ic
    return best


def engle_granger(y, xs, case="c", lags=0, max_lag=None, criterion="aic"):
    """The Engle-Granger test of no cointegration between y and the series in xs.

    xs is a list of m regressor series. lags is the number of lagged differences
    in step 2, or None to choose it by criterion up to max_lag (default
    floor(12 (n/100)^(1/4))). Returns tau, the step-1 coefficients (deterministic
    terms first), the residuals, nobs, the critical values and reject (5%)."""
    n = len(y)
    m = len(xs)
    if not 1 <= m <= 4:
        raise ValueError("between 1 and 4 regressors are supported")
    cols = _deterministic(n, case) + [[float(v) for v in x] for x in xs]
    beta, u, _ = ols(cols, y)  # @line L1
    du = [u[t] - u[t - 1] for t in range(1, n)]  # @line L2
    if lags is None:
        if max_lag is None:
            max_lag = int(12.0 * (n / 100.0) ** 0.25)
        lags = select_lags(u, max(0, min(max_lag, (n - 4) // 3)), criterion)
    tau, nobs, _, _ = residual_adf(u, lags)  # @line L3
    crit = {a: mackinnon_critical_value(case, m + 1, a, nobs) for a in (0.01, 0.05, 0.10)}  # @line L5
    return {"tau": tau, "beta": beta, "resid": u, "dresid": du, "nobs": nobs, "lags": lags,  # @line L4
            "critical": crit, "reject": tau < crit[0.05]}  # @line L6


def error_correction(y, x, u, lags=0):
    """Engle-Granger step two: regress dy_t on 1, u_(t-1), dx_t and lags of dy and dx.

    Returns the coefficients (constant, alpha on u_(t-1), dx_t, then the lags)
    and their standard errors. alpha < 0 is the speed of adjustment."""
    n = len(y)
    dy = [0.0] + [y[t] - y[t - 1] for t in range(1, n)]
    dx = [0.0] + [x[t] - x[t - 1] for t in range(1, n)]
    rows = range(lags + 1, n)
    cols = [[1.0] * len(rows), [u[t - 1] for t in rows], [dx[t] for t in rows]]
    for i in range(1, lags + 1):
        cols.append([dy[t - i] for t in rows])
        cols.append([dx[t - i] for t in rows])
    coef, _, se = ols(cols, [dy[t] for t in rows])
    return coef, se


def simulate_null(n, nvars=2, case="c", reps=1000, rng=None):
    """tau for reps sets of nvars independent Gaussian random walks of length n."""
    rng = rng or random.Random(0)
    out = []
    for _ in range(reps):
        walks = []
        for _ in range(nvars):
            s, w = 0.0, []
            for _ in range(n):
                s += rng.gauss(0.0, 1.0)
                w.append(s)
            walks.append(w)
        out.append(engle_granger(walks[0], walks[1:], case, 0)["tau"])
    return out
engle_granger_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/engle-granger-test/. The authors are listed in prov/33J9EX.jsonl.
"""Entry point named after the slug. The code lives in eg_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from eg_core import (MACKINNON_2010, engle_granger, error_correction, mackinnon_critical_value, ols,
                     residual_adf, select_lags, simulate_null)

__all__ = ["MACKINNON_2010", "engle_granger", "error_correction", "mackinnon_critical_value", "ols",
           "residual_adf", "select_lags", "simulate_null"]
test_engle_granger_test.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/engle-granger-test/. The authors are listed in prov/33J9EX.jsonl.

import math
import random
from fractions import Fraction

import pytest

from engle_granger_test import (engle_granger, error_correction, mackinnon_critical_value, ols,
                                residual_adf, simulate_null)


def walk(rng, n, start=0.0):
    s, out = start, []
    for _ in range(n):
        s += rng.gauss(0.0, 1.0)
        out.append(s)
    return out


def cointegrated_pair(seed, n=200, beta=2.0, phi=0.5):
    rng = random.Random(seed)
    x = walk(rng, n)
    u, a = [], 0.0
    for _ in range(n):
        a = phi * a + rng.gauss(0.0, 1.0)
        u.append(a)
    return [1.0 + beta * xi + ui for xi, ui in zip(x, u)], x


def exact_ols(columns, y):
    """Brute force: the normal equations in exact rationals by Gauss-Jordan."""
    k = len(columns)
    cols = [[Fraction(v) for v in c] for c in columns]
    yy = [Fraction(v) for v in y]
    a = [[sum(p * q for p, q in zip(cols[i], cols[j])) for j in range(k)]
         + [sum(p * q for p, q in zip(cols[i], yy))] for i in range(k)]
    for c in range(k):
        piv = next(r for r in range(c, k) if a[r][c] != 0)
        a[c], a[piv] = a[piv], a[c]
        for r in range(k):
            if r != c and a[r][c] != 0:
                f = a[r][c] / a[c][c]
                a[r] = [u - f * v for u, v in zip(a[r], a[c])]
    return [a[i][k] / a[i][i] for i in range(k)]


def test_worked_example() -> None:
    # The page example.
    y = [2, 2, 7, 6, 8, 12, 15, 12, 18, 18]
    x = [0, 1, 3, 2, 4, 5, 7, 6, 8, 9]
    r = engle_granger(y, [x], "c", 0)
    b = exact_ols([[1] * 10, x], y)
    assert b == [Fraction(14, 11), Fraction(64, 33)]
    assert abs(r["beta"][0] - 14 / 11) < 1e-12 and abs(r["beta"][1] - 64 / 33) < 1e-12
    u = [Fraction(v) - b[0] - b[1] * xv for v, xv in zip(y, x)]
    assert all(abs(float(p) - q) < 1e-12 for p, q in zip(u, r["resid"]))
    num = sum(u[t - 1] * (u[t] - u[t - 1]) for t in range(1, 10))
    den = sum(u[t - 1] ** 2 for t in range(1, 10))
    rho = num / den
    assert rho == Fraction(-2163, 1301)
    rss = sum((u[t] - u[t - 1] - rho * u[t - 1]) ** 2 for t in range(1, 10))
    tau = float(rho) / math.sqrt(float(rss / 8 / den))
    assert abs(r["tau"] - tau) < 1e-10
    assert abs(r["tau"] - (-6.27828)) < 1e-5
    assert r["nobs"] == 9 and abs(r["critical"][0.05] - (-4.09926)) < 1e-5
    assert r["reject"]


@pytest.mark.parametrize("case", ["c", "ct"])
def test_step_one_matches_exact_normal_equations(case) -> None:
    rng = random.Random(3)
    n = 15
    x1 = [rng.randint(-9, 9) for _ in range(n)]
    x2 = [rng.randint(-9, 9) for _ in range(n)]
    y = [rng.randint(-20, 20) for _ in range(n)]
    det = [[1] * n] + ([[t + 1 for t in range(n)]] if case == "ct" else [])
    b = exact_ols(det + [x1, x2], y)
    r = engle_granger(y, [x1, x2], case, 0)
    assert all(abs(p - float(q)) < 1e-9 for p, q in zip(r["beta"], b))


def test_residual_adf_closed_form() -> None:
    rng = random.Random(4)
    u = [rng.gauss(0, 1) for _ in range(30)]
    tau, nobs, rss, k = residual_adf(u, 0)
    num = sum(u[t - 1] * (u[t] - u[t - 1]) for t in range(1, 30))
    den = sum(u[t - 1] ** 2 for t in range(1, 30))
    rho = num / den
    s2 = sum((u[t] - u[t - 1] - rho * u[t - 1]) ** 2 for t in range(1, 30)) / (29 - 1)
    assert nobs == 29 and k == 1
    assert abs(tau - rho / math.sqrt(s2 / den)) < 1e-10


def test_invariance() -> None:
    # tau depends only on the step-1 residuals, which do not change when y is
    # moved by a + d x or scaled, or when x is moved by an affine map.
    y, x = cointegrated_pair(1, 80)
    base = engle_granger(y, [x], "c", 2)["tau"]
    for yy, xx in (([3.0 - 0.7 * v for v in y], x), ([v + 5.0 * w for v, w in zip(y, x)], x),
                   (y, [4.0 + 0.1 * w for w in x])):
        assert abs(engle_granger(yy, [xx], "c", 2)["tau"] - base) < 1e-8


def test_size_against_mackinnon_surface() -> None:
    # Two independent random walks, n = 100 (nobs 99), 1500 samples: the share
    # of tau below the 5% value for N = 2 must be within 4 binomial SE (0.0225).
    reps = 1500
    sims = simulate_null(100, 2, "c", reps, random.Random(17))
    crit = mackinnon_critical_value("c", 2, 0.05, 99)
    rate = sum(1 for s in sims if s < crit) / reps
    assert abs(rate - 0.05) < 4 * math.sqrt(0.05 * 0.95 / reps)


def test_critical_values_shift_with_more_variables() -> None:
    for case in ("c", "ct"):
        vals = [mackinnon_critical_value(case, nv, 0.05, 200) for nv in range(1, 6)]
        assert all(a > b for a, b in zip(vals, vals[1:]))
    assert abs(mackinnon_critical_value("c", 2, 0.05) - (-3.33613)) < 1e-12


def test_superconsistency() -> None:
    # The spread of beta-hat shrinks like 1/n, not 1/sqrt(n): multiplying n by 4
    # divides the interquartile range by about 4 (between 2.8 and 6 here).
    def iqr(n, seed):
        rng = random.Random(seed)
        bs = []
        for _ in range(200):
            x = walk(rng, n)
            y = [2.0 * xi + rng.gauss(0.0, 1.0) for xi in x]
            bs.append(engle_granger(y, [x], "c", 0)["beta"][1])
        bs.sort()
        return bs[150] - bs[50]
    ratio = iqr(50, 1) / iqr(200, 2)
    assert 2.8 < ratio < 6.0


def test_detects_cointegration_and_spurious_regression() -> None:
    y, x = cointegrated_pair(2026, 200)
    r = engle_granger(y, [x], "c", None)
    assert r["reject"] and abs(r["beta"][1] - 2.0) < 0.1
    rng = random.Random(99)
    rejections = 0
    for _ in range(20):
        a, b = walk(rng, 200), walk(rng, 200)
        rejections += engle_granger(a, [b], "c", None)["reject"]
    assert rejections <= 4


def test_error_correction_speed() -> None:
    # With u_t = 0.5 u_(t-1) + e_t, dy_t = 2 dx_t - 0.5 u_(t-1) + e_t, so alpha = -0.5.
    y, x = cointegrated_pair(7, 400)
    r = engle_granger(y, [x], "c", 0)
    coef, se = error_correction(y, x, r["resid"], 0)
    assert abs(coef[1] + 0.5) < 4 * se[1]
    assert abs(coef[2] - 2.0) < 4 * se[2]


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        engle_granger([1, 2, 3, 4], [[1, 2, 3, 4]], "x", 0)
    with pytest.raises(ValueError):
        ols([[1, 2, 3], [2, 4, 6]], [1, 2, 3])

History

Clive Granger introduced the idea of cointegration around 1981, from his work on spurious regressions with Paul Newbold and on error correction models of the kind used by Davidson, Hendry, Srba and Yeo (1978). Robert Engle and Granger published the formal theory in Econometrica in 1987: the Granger representation theorem, which links cointegration and error correction, and the residual-based tests, with critical values they simulated. James Stock proved superconsistency in the same year. Phillips and Ouliaris (1990) derived the limit laws, and MacKinnon (1991, 2010) gave response surfaces for any number of variables. Engle and Granger shared the 2003 Nobel Memorial Prize in Economic Sciences, Granger for cointegration and Engle for ARCH-type volatility models.

References

  1. Robert F. Engle and C. W. J. Granger, Co-integration and error correction, representation, estimation, and testing, Econometrica 55(2) (1987), pages 251 to 276, the residual-based tests, the two-step estimator, and the Granger representation theorem
  2. James H. Stock, Asymptotic properties of least squares estimators of cointegrating vectors, Econometrica 55(5) (1987), pages 1035 to 1056, the superconsistency of the levels regression (rate n) and its second-order bias
  3. P. C. B. Phillips and S. Ouliaris, Asymptotic properties of residual based tests for cointegration, Econometrica 58(1) (1990), pages 165 to 193, the limit laws of the residual-based statistics as functionals of a vector Brownian motion, which depend on the number of variables
  4. MacKinnon 2010, Table 2, the response surface coefficients for N = 1 to 12 variables, cases c and ct
  5. James D. Hamilton, Time Series Analysis, Princeton University Press, 1994, Chapter 19 (cointegration), the residual-based tests and their critical values
  6. C. W. J. Granger and P. Newbold, Spurious regressions in econometrics, Journal of Econometrics 2(2) (1974), pages 111 to 120, the simulations of regressions between independent random walks

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example