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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and be integrated of order one, I(1), as on the ARIMA model page, . Consider the levels regression
with (case "c") or (case "ct"). The null hypothesis is : is I(1) for every , so is not cointegrated. The alternative is : for the true , is stationary, so is a cointegrating vector. The test assumes at most one cointegrating relation, and that enters it with a nonzero coefficient.
Statistic. Let 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"),
and take the t ratio .
Null distribution. Asymptotic and nonstandard. Under , converges to a functional of an -dimensional Brownian motion, , which depends on 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 when , with the response surface of MacKinnon (2010), where :
| case | 1% | 5% | 10% | 5% at | |
|---|---|---|---|---|---|
| "c" | 2 | ||||
| "c" | 3 | ||||
| "c" | 4 | ||||
| "ct" | 2 | ||||
| "ct" | 3 |
The first three columns are the limits . For in case "c" the 5% point is far below the ADF value . The size is asymptotically .
p-value. MacKinnon (1996) gives response surface p-values for by 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 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
ENGLE-GRANGER(y, x₁..x_m, case, p)- 1
(δ̂, β̂) ← OLS of y_t on d_t and x_t; û_t ← y_t − δ̂ᵀd_t − β̂ᵀx_t - 2
Δû_t ← û_t − û_{t−1}, t = 2..n - 3
fit Δû_t = ρ û_{t−1} + Σ_{i=1..p} γ_i Δû_{t−i} + e_t by OLS, t = p+2..n - 4
τ ← ρ̂ / se(ρ̂) - 5
c ← MacKinnon(N = m + 1, case, T = n − p − 1, α) - 6
return (τ, β̂, reject ⇔ τ < c)
The two-step method continues after a rejection. With from line L1, fit the error correction model
by OLS. All regressors are stationary under cointegration, so the usual t and F tests apply to this regression, and measures how fast returns to the long-run relation. The number of lags in line L3 is chosen as for the ADF test, by AIC or BIC on common rows.
Example
By hand. Take , and , case "c" and .
| step | value |
|---|---|
| L1: , , , | , , , |
| L1: , | , |
| L1: | |
| L3: | |
| L3: | 0.50266 |
| L4: , | 0.26481, |
| L5: |
Since , 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 be a Gaussian random walk of length 200, , and . Then a second, independent random walk is regressed on .
| pair | slope t ratio | lags | decision | |||
|---|---|---|---|---|---|---|
| on | 1.968 | 2 | cointegrated | |||
| on | 0 | not cointegrated |
The spurious regression of on has and a slope t ratio of , 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 (standard error 0.064) on and on , close to the true values and .
Superconsistency. For with a random walk and iid , the interquartile range of over 400 samples was at , at and at . So times the range stayed near 3.6 to 3.9: the error shrinks like , not like . With two independent random walks of length 100, the 5% rejection rate against 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 onto the orthogonal complement of the regressors, so depends on only through that projection. Hence is unchanged when is replaced by () or when is replaced by an invertible affine map of itself, and under the null with independent Gaussian random walks its law does not depend on 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 a random walk independent of the stationary error, is bounded in probability, with exactly. The null limit law of (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 is unchanged by the affine maps listed on the page (Lemma 3), that under a null of Gaussian random walks the law of depends only on , , 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 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 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 be the matrix with the deterministic columns and the regressor columns, of full column rank , and let be its thin QR factorization, which modified Gram-Schmidt computes. Then minimizes , and the residual is with , the orthogonal projection onto the complement of the column span of .
Proof. For any , , and the two terms are orthogonal because . So , which is smallest when . is upper triangular with positive diagonal when has full rank, so is the unique minimizer, and . When a column is in the span of the earlier ones, its Gram-Schmidt remainder is 0, and the implementation stops with an error.
Lemma 2 (lines L2 to L4). Let be the matrix with columns and , , for , and let on the same rows. If has full rank , line L4 returns with and . This is the ordinary least squares t ratio of the first coefficient.
Proof. By Lemma 1 applied to , is the least squares fit and . Since , , whose entry is the squared norm of the first row of . The implementation computes by back substitution and takes .
Lemma 3 (invariance). Let , let be in the span of the deterministic columns, and let . Replacing by , where holds the regressor columns, or replacing by for an invertible matrix and any , leaves unchanged.
Proof. The first map changes the residual to , since and lie in the span of , which annihilates. The second map does not change the span of , so it does not change or . In lines L2 and L3 every column of and the response are linear in , so multiplying by multiplies by 1, the residual of line L3 by , by and by . Hence is unchanged and is unchanged.
Theorem 4 (an exact pivot under a Gaussian null). Let , with iid in and positive definite. Then for fixed , and case, the law of does not depend on . So has the same law as for independent standard Gaussian walks, and the rank of the observed among simulated values from independent walks gives an exact Monte Carlo p-value.
Proof. Write in blocks, with the block of the regressors. Let and . For a Gaussian vector, is independent of with variance . So , where is a standard Gaussian walk independent of . Also with an -vector of independent standard walks, independent of . By Lemma 3, , using the second map with . The right side is a fixed function of independent standard walks. If the observed and simulated values are exchangeable, the rank of the observed value is uniform, which makes an exact p-value.
The function simulate_null draws exactly the independent standard walks of Theorem 4. With non-Gaussian or serially correlated increments the law of changes in finite samples, and only the asymptotic statement of Phillips and Ouliaris applies, with when the increments are serially correlated.
Theorem 5 (superconsistency, bivariate exogenous case). Let , , where with iid, mean 0, variance , and iid, mean 0, variance , independent of . Let be the slope of line L1 in case "c". Then exactly, with , and .
Proof. The slope is . First the mean of . Since ,
where . The difference is .
Next, conditional on , the numerator has mean 0 and variance , since the are uncorrelated and independent of . So, conditional on , has mean 0 and variance . For and , conditional Chebyshev gives
The cited fact is the functional central limit theorem (Donsker), with the continuous mapping theorem: , where is a demeaned standard Brownian motion. The limit is positive with probability 1 and has a continuous distribution, so , which tends to 0 as . Given , choose so that this term is below for all large , then so that . Hence .
The exact mean says that the denominator grows like , which is the source of the rate: with a stationary regressor grows like , and the same argument gives only . The mean alone does not bound away from 0 in probability; that is the role of the cited limit. Stock (1987) proves when is stationary and correlated with , where the conditional argument above does not apply and has a nonzero mean in the limit. Under the same assumptions the residuals satisfy , and since the error is uniformly in . That is why the step-two regression on behaves like a regression on the stationary in large samples.
Termination. Line L1 is a QR factorization of columns of length and one back substitution. Line L3 is one more factorization with columns, or one for each when the lag is chosen by AIC or BIC. All loops have fixed bounds, so the procedure stops after operations.
Complexity
On a real RAM, line L1 is a least squares fit with rows and or columns, by QR. Lines L2 to L4 are a regression with columns, . With lag selection over , the second step costs , or with column updates of the QR factorization. The total is time and 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 but not or the residuals.
Properties
- Superconsistent. Under cointegration, , faster than the rate of stationary regression (Stock 1987). This holds even when is correlated with , which would make OLS inconsistent in a stationary model.
- Biased in finite samples. When is correlated with or serially correlated, has a bias of order 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 changes and . In large samples all choices agree under cointegration, but in small samples they can give different answers.
- Invariant to affine maps. is unchanged by changes of level and scale of and of each , and by adding a combination of the to .
- One relation only. The residual test treats cointegration as a yes or no question with a single vector.
- Critical values depend on . 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 have normal limits.
- Dynamic OLS (Stock and Watson 1993). Adds leads and lags of to the levels regression for the same purpose.
- Error correction test. Test 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 .
- Known cointegrating vector. If theory fixes , as for a spread or a ratio, form 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 instead of for rejects "no cointegration" far too often.
- Levels regression without a test. A large 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 tests on . The standard errors printed by the levels regression are not valid, even under cointegration. Use FM-OLS or DOLS for inference on .
- 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.
# 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
- 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
- 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
- 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
- MacKinnon 2010, Table 2, the response surface coefficients for N = 1 to 12 variables, cases c and ct
- James D. Hamilton, Time Series Analysis, Princeton University Press, 1994, Chapter 19 (cointegration), the residual-based tests and their critical values
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 33J9EX Edit this page History Report an error Markdown