Cointegration
Find a long-run relationship between wandering series, with Engle–Granger, Phillips–Ouliaris and Johansen, and see why ordinary regression can't tell it from a spurious link.
What runs in CodeSplash
- STAT203Engle–Granger cointegration test Runs in CodeSplash
- STAT204Phillips–Ouliaris cointegration test Runs in CodeSplash
- STAT205Johansen trace test Runs in CodeSplash
- STAT206Johansen maximum eigenvalue test Runs in CodeSplash
- Cointegration tests Verified in Python and R
You will be able to
- Define cointegration, and tell it apart from correlation and spurious regression
- Run the two-step Engle–Granger test, and use its special critical values
- Read Johansen trace and maximum-eigenvalue tests to pick a cointegrating rank
Read first
A drunk and her dog
ReadEach walks at random, so each path has a unit root. But she holds the lead. They can wander anywhere, as long as the distance between them stays bounded.
Two unit-root series are cointegratedCointegrationNon-stationary series that share a long-run equilibrium, so a combination of them is stationary. if some combination of them is stationary:
Spot and futures prices, or income and consumption, are classic candidates. Each may wander, but the gap between them tends to come back.
Correlated isn't cointegrated
PredictPredict first
Two trending series have = 0.95. Can you conclude that they share a long-run equilibrium?
Reveal
No. Unrelated random walks can have very high correlation by chance, which is what spurious regression means. Cointegration needs a stationary gap, so you test the gap, not the correlation.
Engle–Granger in two steps
Read- Regress one series on the other to get .
- Test the residuals for a unit root, with ADF.
says there's no cointegration. There's a catch: was chosen to make the residuals look as stationary as possible. So the test needs its own critical values, further out than plain ADF's.
Read a result
In the appEngle–Granger τ = -9.01, p < .001
- Statistic
- −9.014
- p
- 7.994e-14
Plots
View data
| quarter | residual |
|---|---|
| 157,766,400,000 | 0.6421 |
| 165,542,400,000 | −0.3902 |
| 173,404,800,000 | 1.748 |
| 181,353,600,000 | 0.9690 |
| 189,302,400,000 | 1.842 |
| 197,164,800,000 | 0.5539 |
| 205,027,200,000 | −0.1220 |
| 212,976,000,000 | 0.6617 |
| 220,924,800,000 | 0.7617 |
| 228,700,800,000 | −0.3462 |
| 236,563,200,000 | −0.2077 |
| 244,512,000,000 | 1.478 |
| 252,460,800,000 | 0.4388 |
| 260,236,800,000 | 0.3653 |
| 268,099,200,000 | 0.1614 |
| 276,048,000,000 | −0.4998 |
| 283,996,800,000 | −0.6926 |
| 291,772,800,000 | −0.2356 |
| 299,635,200,000 | −1.122 |
| 307,584,000,000 | −0.6284 |
| 315,532,800,000 | −1.396 |
| 323,395,200,000 | −0.6234 |
| 331,257,600,000 | −1.904 |
| 339,206,400,000 | −1.250 |
| 347,155,200,000 | 0.1429 |
| 354,931,200,000 | −1.230 |
| 362,793,600,000 | −1.598 |
| 370,742,400,000 | 0.7288 |
| 378,691,200,000 | 0.6943 |
| 386,467,200,000 | 0.0341 |
| 394,329,600,000 | 0.8791 |
| 402,278,400,000 | −0.6645 |
| 410,227,200,000 | 0.5249 |
| 418,003,200,000 | −0.2693 |
| 425,865,600,000 | 0.0370 |
| 433,814,400,000 | −0.5902 |
| 441,763,200,000 | 0.1345 |
| 449,625,600,000 | 1.306 |
| 457,488,000,000 | 1.444 |
| 465,436,800,000 | 0.1764 |
| 473,385,600,000 | −0.6042 |
| 481,161,600,000 | −0.1910 |
| 489,024,000,000 | 0.5495 |
| 496,972,800,000 | −0.0822 |
| 504,921,600,000 | 0.1978 |
| 512,697,600,000 | 0.4540 |
| 520,560,000,000 | 0.0974 |
| 528,508,800,000 | −0.1395 |
| 536,457,600,000 | −1.216 |
| 544,233,600,000 | −0.1904 |
| 552,096,000,000 | −1.183 |
| 560,044,800,000 | 1.117 |
| 567,993,600,000 | 0.3361 |
| 575,856,000,000 | −0.2510 |
| 583,718,400,000 | 0.4372 |
| 591,667,200,000 | 0.6851 |
| 599,616,000,000 | 0.8274 |
| 607,392,000,000 | 2.252 |
| 615,254,400,000 | −0.8613 |
| 623,203,200,000 | −1.215 |
First 60 of 200 rows.
Cointegration
| Test | Statistic | p | 5 % critical value | Lags / bandwidth | At α = .05 |
|---|---|---|---|---|---|
| Engle–Granger τ | −9.014 | < .001 | −3.367 | 0 | cointegrated |
- Cointegration is about series that each have a unit root; test the series first (Unit-root tests).
- p-values: MacKinnon (1994) response surfaces for the residual tests; Johansen p interpolated between the 90/95/99 % critical values of MacKinnon, Haug & Michelis (1999).
The exact R script · R R version 4.5.1 (2025-06-13)
# Cointegration tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.cointegration 1.0.2 · spec aa7367a731d5295f
# Dataset: ts_coint (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_coint.parquet", col_select = c("x2", "x1", "quarter")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x2", "x1", "quarter")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x2", "x1", "quarter")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VARS <- c("x2", "x1")
TIME <- "quarter"
TEMPORAL <- TRUE
TEST <- "eg"
TREND <- "c"
DET <- c(none = -1, constant = 0, trend = 1)[["constant"]]
K_AR <- NULL
LAG_RULE <- "aic"
BW <- "short"
s <- cs_ts_ordered(df, VARS[1], TIME, TEMPORAL)
df <- s$df
labels <- s$labels
Y <- as.matrix(df[, VARS, drop = FALSE])
storage.mode(Y) <- "double"
n <- nrow(Y)
k <- ncol(Y)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
# Inputs the tests can't use stop with a catalog message (registry/errors.yaml), the same in Python: the
# long-run regression needs more observations than coefficients, and every series must vary.
if (TEST %in% c("eg", "po")) cs_check_rows(n, k + c(n = 0, c = 1, ct = 2, ctt = 3)[[TREND]], "The cointegration test")
for (v in VARS) cs_check_not_constant(df[[v]], v)
values <- list(n_obs = n, n_vars = k, test = TEST)
rows <- list()
kind <- if (TEMPORAL) "temporal" else "numeric"
tcol <- if (is.null(TIME)) "index" else TIME
# %% Test
if (TEST %in% c("eg", "po")) {
eg <- cs_ts_engle_granger(Y[, 1], Y[, -1, drop = FALSE], TREND, autolag = LAG_RULE)
r <- if (TEST == "eg") eg else cs_ts_phillips_ouliaris(Y[, 1], Y[, -1, drop = FALSE], TREND, BW)
values$stat <- r$stat
values$p <- r$p
values$lags <- r$lags
values$crit_5 <- r$crit[2]
values$reject <- as.integer(r$p < 0.05)
for (j in seq_along(eg$beta)) values[[paste0("beta_", j)]] <- eg$beta[j]
label <- if (TEST == "eg") "Engle–Granger τ" else "Phillips–Ouliaris Ẑ_t"
rows[[1]] <- list(test = label, statistic = r$stat, p = r$p, crit_5 = r$crit[2], lags = r$lags,
verdict = if (r$p < 0.05) "cointegrated" else "no evidence of cointegration")
summary <- paste0(sprintf("%s for %s on %s: %.3f, %s — ", label, VARS[1], paste(VARS[-1], collapse = ", "), r$stat, cs_fmt_p(r$p)),
if (r$p < 0.05) "the long-run residuals are stationary, so the series are cointegrated." else "no evidence of cointegration.")
apa <- sprintf("%s = %.2f, %s", label, r$stat, cs_fmt_p(r$p))
columns <- list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "crit_5", label = "5 % critical value", type = "number"),
list(key = "lags", label = "Lags / bandwidth", type = "integer"), list(key = "verdict", label = "At α = .05", type = "string"))
charts <- list(cs_chart("spread", "coint-spread", sprintf("Long-run residual: %s − fitted", VARS[1]),
list(x = cs_col(tcol, labels, kind = kind), y = cs_col("residual", eg$resid))))
} else {
k_ar <- if (is.null(K_AR)) max(cs_ts_var_lag_aic(Y, min(8, max(1, n %/% 10))) - 1, 0) else as.integer(K_AR)
j <- cs_ts_johansen(Y, DET, k_ar)
for (r in j$rows) {
i <- r$r
values[[paste0("trace_", i)]] <- r$trace
values[[paste0("trace_p_", i)]] <- r$trace_p
values[[paste0("maxeig_", i)]] <- r$maxeig
values[[paste0("maxeig_p_", i)]] <- r$maxeig_p
values[[paste0("eigen_", i)]] <- r$eigenvalue
rows[[length(rows) + 1]] <- list(r = sprintf("r ≤ %d", i), eigenvalue = r$eigenvalue, trace = r$trace, trace_cv95 = r$trace_cv95,
trace_p = r$trace_p, maxeig = r$maxeig, maxeig_cv95 = r$maxeig_cv95, maxeig_p = r$maxeig_p)
}
values$stat <- j$rows[[1]]$trace
values$p <- j$rows[[1]]$trace_p
values$reject <- as.integer(j$rank_trace >= 1)
values$rank_trace <- j$rank_trace
values$rank_maxeig <- j$rank_maxeig
values$k_ar_diff <- k_ar
summary <- sprintf("Johansen tests on %s (%d observations, %d lagged difference%s): the trace test finds %d and the maximum-eigenvalue test %d cointegrating relationship(s) at the 5 %% level.",
paste(VARS, collapse = ", "), n, k_ar, if (k_ar != 1) "s" else "", j$rank_trace, j$rank_maxeig)
apa <- sprintf("trace(r = 0) = %.2f; max-eigenvalue(r = 0) = %.2f", j$rows[[1]]$trace, j$rows[[1]]$maxeig)
columns <- list(list(key = "r", label = "H₀", type = "string"), list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
list(key = "trace", label = "Trace", type = "number"), list(key = "trace_cv95", label = "95 % cv", type = "number"),
list(key = "trace_p", label = "p (trace)", type = "pvalue"), list(key = "maxeig", label = "Max eigenvalue", type = "number"),
list(key = "maxeig_cv95", label = "95 % cv", type = "number"), list(key = "maxeig_p", label = "p (max)", type = "pvalue"))
z <- scale(Y)
charts <- list(cs_chart("series", "series-line", "Standardized series", list(
x = cs_col(tcol, rep(labels, k), kind = kind), y = cs_col("z", as.numeric(z)),
group = cs_col("series", rep(VARS, each = n), kind = "categorical", levels = VARS))))
}
cs_publish(list(
method = "ts.cointegration",
methodVersion = "1.0.2",
title = "Cointegration tests",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = apa,
statistics = list(list(key = "stat", label = "Statistic", value = values$stat), list(key = "p", label = "p", value = values$p)),
tables = list(list(key = "tests", title = "Cointegration", columns = columns, rows = rows)),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = list("Cointegration is about series that each have a unit root; test the series first (Unit-root tests).",
"p-values: MacKinnon (1994) response surfaces for the residual tests; Johansen p interpolated between the 90/95/99 % critical values of MacKinnon, Haug & Michelis (1999)."),
charts = charts,
values = values
))
Engle–Granger τ = -9.01, p < .001
- Statistic
- −9.014
- p
- 7.994e-14
To keep this page light, the plots are shown once, under the R tab.
Cointegration
| Test | Statistic | p | 5 % critical value | Lags / bandwidth | At α = .05 |
|---|---|---|---|---|---|
| Engle–Granger τ | −9.014 | < .001 | −3.367 | 0 | cointegrated |
- Cointegration is about series that each have a unit root; test the series first (Unit-root tests).
- p-values: MacKinnon (1994) response surfaces for the residual tests; Johansen p interpolated between the 90/95/99 % critical values of MacKinnon, Haug & Michelis (1999).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cointegration tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.cointegration 1.0.2 · spec aa7367a731d5295f
# Dataset: ts_coint (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_coint.parquet", columns=["x2", "x1", "quarter"])
n_input = len(df)
df = df.dropna(subset=["x2", "x1", "quarter"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x2", "x1", "quarter"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VARS = ["x2", "x1"]
TIME = "quarter"
TEMPORAL = True
TEST = "eg"
TREND = "c"
DET = {"none": -1, "constant": 0, "trend": 1}["constant"]
K_AR = None
LAG_RULE = "aic"
BW = "short"
s = ts.ordered(df, VARS[0], TIME, TEMPORAL)
df = s["df"]
labels = s["labels"]
Y = df[VARS].to_numpy(dtype=float)
n, k = Y.shape
if s["dups"]:
warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
# Inputs the tests can't use stop with a catalog message (registry/errors.yaml), the same in R: the long-run
# regression needs more observations than coefficients, and every series must vary.
if TEST in ("eg", "po"):
cs.check_rows(n, k + {"n": 0, "c": 1, "ct": 2, "ctt": 3}[TREND], "The cointegration test")
for v in VARS:
check_not_constant(df[v], v)
values = {"n_obs": n, "n_vars": k, "test": TEST}
rows = []
kind = "temporal" if TEMPORAL else "numeric"
tcol = TIME or "index"
# %% Test
if TEST in ("eg", "po"):
eg = ts.engle_granger(Y[:, 0], Y[:, 1:], TREND, autolag=LAG_RULE)
r = eg if TEST == "eg" else ts.phillips_ouliaris(Y[:, 0], Y[:, 1:], TREND, BW)
values.update({"stat": r["stat"], "p": r["p"], "lags": r["lags"], "crit_5": r["crit"][1], "reject": int(r["p"] < 0.05)})
for j, b in enumerate(eg["beta"], start=1):
values[f"beta_{j}"] = b
label = "Engle–Granger τ" if TEST == "eg" else "Phillips–Ouliaris Ẑ_t"
rows.append({"test": label, "statistic": r["stat"], "p": r["p"], "crit_5": r["crit"][1], "lags": r["lags"],
"verdict": "cointegrated" if r["p"] < 0.05 else "no evidence of cointegration"})
summary = (f"{label} for {VARS[0]} on {', '.join(VARS[1:])}: {r['stat']:.3f}, {cs.fmt_p(r['p'])} — "
+ ("the long-run residuals are stationary, so the series are cointegrated." if r["p"] < 0.05 else "no evidence of cointegration."))
apa = f"{label} = {r['stat']:.2f}, {cs.fmt_p(r['p'])}"
columns = [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "crit_5", "label": "5 % critical value", "type": "number"},
{"key": "lags", "label": "Lags / bandwidth", "type": "integer"}, {"key": "verdict", "label": "At α = .05", "type": "string"}]
charts = [cs.chart("spread", "coint-spread", f"Long-run residual: {VARS[0]} − fitted", {"x": cs.col(tcol, labels, kind=kind), "y": cs.col("residual", eg["resid"])})]
else:
if K_AR is None:
k_ar = max(ts.var_lag_aic(Y, min(8, max(1, n // 10))) - 1, 0)
else:
k_ar = int(K_AR)
j = ts.johansen(Y, DET, k_ar)
for r in j["rows"]:
i = r["r"]
values.update({f"trace_{i}": r["trace"], f"trace_p_{i}": r["trace_p"], f"maxeig_{i}": r["maxeig"], f"maxeig_p_{i}": r["maxeig_p"], f"eigen_{i}": r["eigenvalue"]})
rows.append({"r": f"r ≤ {i}", "eigenvalue": r["eigenvalue"], "trace": r["trace"], "trace_cv95": r["trace_cv95"], "trace_p": r["trace_p"],
"maxeig": r["maxeig"], "maxeig_cv95": r["maxeig_cv95"], "maxeig_p": r["maxeig_p"]})
values.update({"stat": j["rows"][0]["trace"], "p": j["rows"][0]["trace_p"], "reject": int(j["rank_trace"] >= 1),
"rank_trace": j["rank_trace"], "rank_maxeig": j["rank_maxeig"], "k_ar_diff": k_ar})
summary = (f"Johansen tests on {', '.join(VARS)} ({n} observations, {k_ar} lagged difference{'s' if k_ar != 1 else ''}): the trace test finds "
f"{j['rank_trace']} and the maximum-eigenvalue test {j['rank_maxeig']} cointegrating relationship(s) at the 5 % level.")
apa = f"trace(r = 0) = {j['rows'][0]['trace']:.2f}; max-eigenvalue(r = 0) = {j['rows'][0]['maxeig']:.2f}"
columns = [{"key": "r", "label": "H₀", "type": "string"}, {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "trace", "label": "Trace", "type": "number"}, {"key": "trace_cv95", "label": "95 % cv", "type": "number"},
{"key": "trace_p", "label": "p (trace)", "type": "pvalue"}, {"key": "maxeig", "label": "Max eigenvalue", "type": "number"},
{"key": "maxeig_cv95", "label": "95 % cv", "type": "number"}, {"key": "maxeig_p", "label": "p (max)", "type": "pvalue"}]
z = (Y - Y.mean(axis=0)) / Y.std(axis=0, ddof=1)
charts = [cs.chart("series", "series-line", "Standardized series", {
"x": cs.col(tcol, [l for _ in VARS for l in labels], kind=kind), "y": cs.col("z", z.T.reshape(-1)),
"group": cs.col("series", [v for v in VARS for _ in range(n)], kind="categorical", levels=VARS)})]
cs.publish({
"method": "ts.cointegration",
"methodVersion": "1.0.2",
"title": "Cointegration tests",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": apa,
"statistics": [{"key": "stat", "label": "Statistic", "value": values["stat"]}, {"key": "p", "label": "p", "value": values["p"]}],
"tables": [{"key": "tests", "title": "Cointegration", "columns": columns, "rows": rows}],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": ["Cointegration is about series that each have a unit root; test the series first (Unit-root tests).",
"p-values: MacKinnon (1994) response surfaces for the residual tests; Johansen p interpolated between the 90/95/99 % critical values of MacKinnon, Haug & Michelis (1999)."],
"charts": charts,
"values": values,
})
= 0.81, and the test statistic is −9.01 against a 5% value of −3.37, with p < .001.
Open the chart of the long-run residual. Does the gap come back to zero? How long do excursions last?
A pair that isn't
PredictPredict first
Another pair gives a statistic of −3.40. With a trend in the long-run regression, the 5% value is −3.83.
Does this reject "no cointegration"?
Reveal
No, since it doesn't reach the critical value: p = .123. The data are compatible with no long-run relationship, though with this test's limited power they don't exclude one.
The order of variables
ReflectEngle–Granger names one variable as the outcome. Swap them, and you can get a different result. With more than two series, there may be more than one equilibrium, and this method finds only one.
Phillips–Ouliaris replaces ADF's lags with a long-run variance correction. On three series, = −9.10, p < .001.
Which of your variables has a clear "this one depends on that one" reading? Which doesn't?
Johansen: how many relationships?
ReadWith series, there can be 0 to cointegrating relationships. That number is the cointegrating rankCointegrating rankHow many independent stationary combinations a set of wandering series has; Johansen's tests count them one step at a time.. Johansen estimates it from a VAR, and treats all the series alike.
You test in sequence: ? If rejected, ? Stop at the first test you can't reject.
- Trace: tests against more than .
- Maximum eigenvalue: tests against .
Read the sequence
PredictPredict first
Three series. Trace at is 72.5, with a p-value of 0.01.
At it's 2.8, with a p-value of 0.10. What rank do you choose?
Make your guess between 0 and 2 cointegrating rank, then reveal.
Reveal
Rank 1: reject , then stop at the first non-rejection. Maximum eigenvalue agrees, at rank 1. p-values come from tables and are bounded, so read them as "at most" and "at least".
Check your understanding
CheckpointCheck yourself
Engle–Granger gives p = 0.30. What can you say?
Show the answer
Answer: b
The null is no cointegration. A large p doesn't establish that, and it says nothing about short-run links.
Check yourself
With four series, Johansen's trace test rejects and , and doesn't reject . What rank do you choose?
Show the answer
Answer: 2
Stop at the first test you can't reject, which is . So the rank is 2.
Check yourself
Before testing for cointegration, what should you check?
Show the answer
Answer: b
A stationary series can't share a stochastic trend. Run a unit-root test on each series first.
Do it in CodeSplash
In the appPut the Series in the order you want, with the outcome first for Engle–Granger. Test switches method. This is also the Cointegration step in the Series lab. When you've found a rank, a VECM is the model that uses it.
import pandas as pd
from statsmodels.tsa.stattools import coint
from statsmodels.tsa.vector_ar.vecm import coint_johansen
df = pd.read_csv("coint.csv")
print(coint(df["x2"], df["x1"])[:2])
res = coint_johansen(df[["x1", "x2", "x3"]], det_order=0, k_ar_diff=1)
print(res.lr1, res.lr2)# install.packages("urca")
df <- read.csv("coint.csv")
Y <- df[c("x1", "x2", "x3")]
summary(urca::ca.po(Y, demean = "constant"))
summary(urca::ca.jo(Y, type = "trace", K = 2))
summary(urca::ca.jo(Y, type = "eigen", K = 2))Recap
Recap- Cointegrated series can wander, but a combination of them stays stationary.
- Correlation can't tell this apart from a spurious link. You need to test the gap.
- Engle–Granger needs its own critical values and names an outcome. Johansen doesn't, and estimates a rank.
- Read Johansen's sequence, and stop at the first test you can't reject.
Concepts in this lesson