Skip to content

DTime series · ts.cointegration

Cointegration tests

Do several wandering (unit-root) series move together in the long run, so that some combination of them is stationary?

Engle–Granger and Phillips–Ouliaris residual tests (the first series regressed on the others) and the Johansen trace and maximum-eigenvalue tests of the cointegrating rank, with MacKinnon and MacKinnon–Haug–Michelis critical values.

Verified in Python and R Python and R agree to 6 decimals Also called Engle-Granger, EG test, Phillips-Ouliaris…

A real result

Example “Eg cointegrated”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Cointegration testsRecorded · Python and R agreeRecorded 2026-11-17 · 9 values compared
R

Engle–Granger τ = -9.01, p < .001

Statistic
−9.014
p
7.994e-14

Plots

Long-run residual: x2 − fittedDoes the gap between series that should move together keep returning to its mean?
View data
quarterresidual
157,766,400,0000.6421
165,542,400,000−0.3902
173,404,800,0001.748
181,353,600,0000.9690
189,302,400,0001.842
197,164,800,0000.5539
205,027,200,000−0.1220
212,976,000,0000.6617
220,924,800,0000.7617
228,700,800,000−0.3462
236,563,200,000−0.2077
244,512,000,0001.478
252,460,800,0000.4388
260,236,800,0000.3653
268,099,200,0000.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,0000.1429
354,931,200,000−1.230
362,793,600,000−1.598
370,742,400,0000.7288
378,691,200,0000.6943
386,467,200,0000.0341
394,329,600,0000.8791
402,278,400,000−0.6645
410,227,200,0000.5249
418,003,200,000−0.2693
425,865,600,0000.0370
433,814,400,000−0.5902
441,763,200,0000.1345
449,625,600,0001.306
457,488,000,0001.444
465,436,800,0000.1764
473,385,600,000−0.6042
481,161,600,000−0.1910
489,024,000,0000.5495
496,972,800,000−0.0822
504,921,600,0000.1978
512,697,600,0000.4540
520,560,000,0000.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,0001.117
567,993,600,0000.3361
575,856,000,000−0.2510
583,718,400,0000.4372
591,667,200,0000.6851
599,616,000,0000.8274
607,392,000,0002.252
615,254,400,000−0.8613
623,203,200,000−1.215

First 60 of 200 rows.

Cointegration

TestStatisticp5 % critical valueLags / bandwidthAt α = .05
Engle–Granger τ−9.014< .001−3.3670cointegrated
  • 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).
Python

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

TestStatisticp5 % critical valueLags / bandwidthAt α = .05
Engle–Granger τ−9.014< .001−3.3670cointegrated
  • 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).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Eg cointegratedts_coint · time: quarter · variables: x2, x1
  • Eg not cointegratedts_coint · time: quarter · variables: x3, x1
  • Po cointegratedts_coint · time: quarter · variables: x2, x1, x3
  • Johansen threets_coint · time: quarter · variables: x1, x2, x3
  • Johansen trend k2ts_coint · variables: x1, x2
  • Degenerate constantts_coint · time: quarter · variables: x2, x1
  • Degenerate n2ts_coint · time: quarter · variables: x2, x1

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Seriesnumeric · 2–6 columns
Two to six series measured at the same times. Engle–Granger and Phillips–Ouliaris regress the first on the others.
Timetemporal / numeric · 0–1 column
Orders the rows (omit to use the row order).

Choices you make

hypothesis

Testdefault eg

H₀: no cointegration (Engle–Granger, Phillips–Ouliaris) or rank ≤ r (Johansen).

  • Engle–Granger (ADF on residuals)(default) — Two steps: the long-run regression, then an ADF test on its residuals.
  • Phillips–Ouliaris Ẑ_t — The residual autoregression corrected non-parametrically, like Phillips–Perron.
  • Johansen trace and maximum eigenvalue — Estimates how many independent long-run relationships there are (the rank).
Deterministic terms in the long-run regressiondefault c

Deterministic terms in the Engle–Granger long-run regression: a constant, a constant and trend, or none.

  • Constant(default) — Allows a constant; pick it when the series don't trend.
  • Constant and trend — Allows a constant and a trend; pick it when the series drift up or down.
  • None — Leaves out constant and trend; pick it only when the series have mean zero.
Deterministic terms (Johansen)default constant

Deterministic terms in the Johansen test: none, a constant, or a constant and trend.

  • None — Leaves out constant and trend; pick it only when the series have mean zero.
  • Constant(default) — Allows a constant; the usual choice for series without a trend.
  • Constant and trend — Allows a constant and a linear trend; pick it when the series trend.

options

Lagged differencesdefault —

Lags of the differenced series in the VECM; automatic = VAR order chosen by AIC (up to 8) minus one.

ADF lag selectiondefault aic

How the ADF lag length is chosen in the Engle–Granger test.

  • AIC(default) — Chooses the lag count by AIC; tends to keep more lags, a safe default.
  • BIC — Chooses the lag count by BIC; tends to keep fewer lags, which suits short series.
  • General-to-specific t — Starts long and drops the last lag until it's significant; helps keep the test's size near nominal.
Long-run variance bandwidthdefault short

Lags in the long-run variance estimate for Phillips–Ouliaris. Long is safer with strong autocorrelation.

  • Short ⌊4(n/100)^¼⌋(default) — Uses fewer lags in the long-run variance; steadier in small samples when autocorrelation is weak.
  • Long ⌊12(n/100)^¼⌋ — Uses more lags in the long-run variance; safer when autocorrelation is strong.

What it reports

n_obs
How many independent units the analysis used; it sets precision and power.
n_vars
How many independent units the analysis used; it sets precision and power.
stat
A single number that summarizes how far your data are from what H₀ predicts.
p
How surprising your data would be if the null hypothesis were true, as a probability.
reject
A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.

Per group, level or term: test, lags, crit_5, rank_trace, rank_maxeig, k_ar_diff, trace_<r>, trace_p_<r>, maxeig_<r>, maxeig_p_<r>, eigen_<r>, beta_<k>

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Same twin in both engines; Johansen follows LeSage's jplv7 / statsmodels deterministic handling (data detrended by a polynomial before the reduced-rank regression) with MacKinnon–Haug–Michelis (1999) critical values; Johansen p-values are interpolated between the 90/95/99 % critical values.
Python

The exact script CodeSplash ran for example “Eg cointegrated” · 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,
})
R

The exact script CodeSplash ran for example “Eg cointegrated” · 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
))

Sources

  • Engle, R. F., & Granger, C. W. J. (1987). Co-integration and error correction. Econometrica, 55, 251–276.
  • Phillips, P. C. B., & Ouliaris, S. (1990). Asymptotic properties of residual based tests for cointegration. Econometrica, 58, 165–193.
  • Johansen, S. (1991). Estimation and hypothesis testing of cointegration vectors in Gaussian VAR models. Econometrica, 59, 1551–1580.
  • MacKinnon, J. G., Haug, A. A., & Michelis, L. (1999). Numerical distribution functions of likelihood ratio tests for cointegration. J. Applied Econometrics, 14, 563–577.

From the CodeSplash method registry · ts.cointegration v1.0.2.