DTime series · ts.granger
Granger causality (predictive) test
Do past values of one series help predict another beyond its own past — in either direction?
F test of the lagged predictor in a regression of the outcome on its own lags (Granger 1969), run in both directions, or the Toda–Yamamoto Wald test that stays valid when the series have unit roots or are cointegrated. Lags by AIC or fixed. "Granger causality" is predictive precedence, not causation.
A real result
Example “X leads y”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
x → y: F = 35.77, p < .001; y → x: F = 2.83, p = .040
- F (x → y)
- 35.768
- p
- 2.255e-18
Plots
View data
| x | y |
|---|---|
| −0.9311 | 0 |
| −0.9749 | −0.7641 |
| −1.913 | −0.6300 |
| −0.5044 | −2.090 |
| −1.684 | −0.9840 |
| −2.414 | −0.5464 |
| 0.5253 | −2.046 |
| −0.5671 | −1.450 |
| 0.0543 | 0.9923 |
| 1.403 | −0.0287 |
| 0.2446 | 0.1965 |
| −0.3948 | 0.5923 |
| 0.7436 | −1.208 |
| 0.2321 | −0.2000 |
| −0.3447 | 1.664 |
| −0.1086 | 1.260 |
| −0.3653 | −0.8615 |
| 1.499 | −1.180 |
| 0.5367 | 1.935 |
| −0.3237 | 0.9070 |
| −0.0273 | −0.4212 |
| 1.145 | −0.3520 |
| 0.3287 | −0.4571 |
| −0.9926 | −0.3772 |
| −0.1219 | 0.4273 |
| −0.3717 | 1.468 |
| 0.3730 | 0.2100 |
| 1.263 | −0.2242 |
| 1.401 | −0.4890 |
| 1.397 | 1.638 |
| 2.056 | 0.6953 |
| 1.108 | 2.432 |
| −0.6693 | 2.352 |
| −1.050 | −0.0246 |
| 0.8205 | −1.197 |
| 1.980 | −0.9062 |
| 0.4885 | −0.0581 |
| 0.6321 | 0.2697 |
| 1.576 | −0.2594 |
| 2.256 | 0.5936 |
| 1.863 | 1.482 |
| 0.9153 | 2.120 |
| 0.8993 | 1.853 |
| 1.202 | 0.3091 |
| 0.2690 | 1.334 |
| 0.4397 | 1.326 |
| 0.1062 | 0.5253 |
| 1.292 | −0.6508 |
| −0.0265 | −0.4865 |
| −0.7395 | −1.382 |
| −1.547 | −1.599 |
| 0.1994 | −0.8990 |
| 0.1990 | 0.1416 |
| −0.5240 | 0.1441 |
| 2.271 | 0.3104 |
| 3.436 | 0.8524 |
| 1.338 | 2.208 |
| 2.402 | 1.373 |
| 2.591 | 2.952 |
| 0.5493 | 1.903 |
First 60 of 200 rows.
Granger causality
| Direction | F | df | p | At α = .05 |
|---|---|---|---|---|
| x → y | 35.768 | 3, 190 | < .001 | helps predict |
| y → x | 2.826 | 3, 190 | .040 | helps predict |
- Granger causality is about prediction: a common driver or a missing variable can make one series 'Granger-cause' another.
- The F test needs stationary series — difference unit-root series, or use Toda–Yamamoto.
x → y: F = 35.77, p < .001; y → x: F = 2.83, p = .040
- F (x → y)
- 35.768
- p
- 2.255e-18
To keep this page light, the plots are shown once, under the R tab.
Granger causality
| Direction | F | df | p | At α = .05 |
|---|---|---|---|---|
| x → y | 35.768 | 3, 190 | < .001 | helps predict |
| y → x | 2.826 | 3, 190 | .040 | helps predict |
- Granger causality is about prediction: a common driver or a missing variable can make one series 'Granger-cause' another.
- The F test needs stationary series — difference unit-root series, or use Toda–Yamamoto.
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
- X leads yts_granger · outcome: y · predictor: x · time: day
- Unrelated fixed lagsts_granger · outcome: z · predictor: x · time: day
- Toda yamamoto cointts_coint · outcome: x2 · predictor: x1 · time: quarter
- Degenerate constantts_granger · outcome: y · predictor: x · time: day
- Degenerate n3ts_granger · outcome: y · predictor: x · time: day
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
- Effect (predicted)numeric · 1 column
- The series whose prediction is improved (or not).
- Cause (predictor)numeric · 1 column
- The series whose past values are tested; the reverse direction is reported too.
- Timetemporal / numeric · 0–1 column
- Orders the rows (omit to use the row order).
Choices you make
hypothesis
- Testdefault f
H₀: the predictor's lags add nothing (all their coefficients are 0).
- Granger F test(default) — Valid for stationary series; difference unit-root series first.
- Toda–Yamamoto Wald χ² — Adds d_max extra unrestricted lags so levels with unit roots or cointegration can be tested directly.
- Lagsdefault —
Lags of both series; automatic = VAR order minimizing AIC.
options
- Largest lag considereddefault 8
Largest lag considered when choosing the VAR order.
- Extra lags (d_max)default 1
The highest order of integration you expect (1 for random-walk-like series).
What it reports
- n_obs
- How many independent units the analysis used; it sets precision and power.
- lags
- Whether past values of one series improve forecasts of another; predictive, not causal in the everyday sense.
- 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.
- stat_rev
- Whether past values of one series improve forecasts of another; predictive, not causal in the everyday sense.
- p_rev
- How surprising your data would be if the null hypothesis were true, as a probability.
- reject_rev
- Whether past values of one series improve forecasts of another; predictive, not causal in the everyday sense.
Per group, level or term: test, df1, df2
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Same twin in both engines; the F test equals statsmodels' ssr_ftest and lmtest::grangertest for the same lags.
The exact script CodeSplash ran for example “X leads y” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Granger causality (predictive) test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.granger 1.0.2 · spec dc9de08f8738448a
# Dataset: ts_granger (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_granger.parquet", columns=["y", "x", "day"])
n_input = len(df)
df = df.dropna(subset=["y", "x", "day"]) # 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, ["y", "x", "day"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
Y = "y"
X = "x"
TIME = "day"
TEMPORAL = True
TEST = "f"
LAGS = None
MAX_LAG = 8
DMAX = 1
s = ts.ordered(df, Y, TIME, TEMPORAL)
y = s["x"]
x = s["df"][X].to_numpy(dtype=float)
n = len(y)
if s["dups"]:
warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
extra = DMAX if TEST == "toda_yamamoto" else 0
# With m = lags (+ extra) lags, the unrestricted regression has 1 + 2m coefficients on n − m rows, so it needs
# n ≥ 3m + 2; choosing the lags fits a two-series VAR that needs n ≥ 3p + 3 for its largest order p. Both series
# must vary (registry/errors.yaml; the same checks in R).
need = 3 * ((int(LAGS) if LAGS is not None else 1) + extra) + 2
if LAGS is None:
need = max(need, 3 * max(1, min(MAX_LAG, n // 5)) + 3)
cs.check_rows(n, need, "The Granger test")
check_not_constant(y, Y)
check_not_constant(x, X)
lags = int(LAGS) if LAGS is not None else ts.var_lag_aic(np.column_stack([y, x]), max(1, min(MAX_LAG, n // 5)))
cs.check_rows(n, 3 * (lags + extra) + 2, "The Granger test")
# %% Test
fwd = ts.granger(y, x, lags, extra)
rev = ts.granger(x, y, lags, extra)
values = {"n_obs": n, "test": TEST, "lags": lags, "stat": fwd["stat"], "p": fwd["p"], "reject": int(fwd["p"] < 0.05),
"stat_rev": rev["stat"], "p_rev": rev["p"], "reject_rev": int(rev["p"] < 0.05), "df1": fwd["df1"]}
if fwd["df2"] is not None:
values["df2"] = fwd["df2"]
label = "F" if TEST == "f" else "Wald χ²"
rows = [{"direction": f"{X} → {Y}", "statistic": fwd["stat"], "df": f"{fwd['df1']}, {fwd['df2']}" if fwd["df2"] is not None else str(fwd["df1"]),
"p": fwd["p"], "verdict": "helps predict" if fwd["p"] < 0.05 else "no evidence"},
{"direction": f"{Y} → {X}", "statistic": rev["stat"], "df": f"{rev['df1']}, {rev['df2']}" if rev["df2"] is not None else str(rev["df1"]),
"p": rev["p"], "verdict": "helps predict" if rev["p"] < 0.05 else "no evidence"}]
summary = (f"With {lags} lag{'s' if lags != 1 else ''}, past {X} " + ("helps" if fwd["p"] < 0.05 else "does not help") + f" predict {Y} ({cs.fmt_p(fwd['p'])}), "
f"and past {Y} " + ("helps" if rev["p"] < 0.05 else "does not help") + f" predict {X} ({cs.fmt_p(rev['p'])}). Predictive precedence, not proof of cause.")
kind = "temporal" if TEMPORAL else "numeric"
cs.publish({
"method": "ts.granger",
"methodVersion": "1.0.2",
"title": "Granger causality (predictive) test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{X} → {Y}: {label} = {fwd['stat']:.2f}, {cs.fmt_p(fwd['p'])}; {Y} → {X}: {label} = {rev['stat']:.2f}, {cs.fmt_p(rev['p'])}",
"statistics": [{"key": "stat", "label": f"{label} ({X} → {Y})", "value": fwd["stat"]}, {"key": "p", "label": "p", "value": fwd["p"]}],
"tables": [{
"key": "granger", "title": "Granger causality",
"columns": [{"key": "direction", "label": "Direction", "type": "string"}, {"key": "statistic", "label": label, "type": "number"},
{"key": "df", "label": "df", "type": "string"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "verdict", "label": "At α = .05", "type": "string"}],
"rows": rows,
}],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": ["Granger causality is about prediction: a common driver or a missing variable can make one series 'Granger-cause' another.",
"The F test needs stationary series — difference unit-root series, or use Toda–Yamamoto." if TEST == "f"
else f"Toda–Yamamoto: {DMAX} extra unrestricted lag(s), Wald test on the first {lags}."],
"charts": [cs.chart("ccf", "cross-correlation", f"Cross-correlation of {X} and {Y}", {"a": cs.col(X, x), "b": cs.col(Y, y)})],
"values": values,
})
The exact script CodeSplash ran for example “X leads y” · R version 4.5.1 (2025-06-13)
# Granger causality (predictive) test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.granger 1.0.2 · spec dc9de08f8738448a
# Dataset: ts_granger (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_granger.parquet", col_select = c("y", "x", "day")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y", "x", "day")]), , 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("y", "x", "day")) # infinite values stop the run (registry/errors.yaml)
# %% Series
Y <- "y"
X <- "x"
TIME <- "day"
TEMPORAL <- TRUE
TEST <- "f"
LAGS <- NULL
MAX_LAG <- 8
DMAX <- 1
s <- cs_ts_ordered(df, Y, TIME, TEMPORAL)
y <- s$x
x <- as.numeric(s$df[[X]])
n <- length(y)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
extra <- if (TEST == "toda_yamamoto") DMAX else 0
# With m = lags (+ extra) lags, the unrestricted regression has 1 + 2m coefficients on n - m rows, so it needs
# n >= 3m + 2; choosing the lags fits a two-series VAR that needs n >= 3p + 3 for its largest order p. Both series
# must vary (registry/errors.yaml; the same checks in Python).
need <- 3 * ((if (!is.null(LAGS)) as.integer(LAGS) else 1L) + extra) + 2
if (is.null(LAGS)) need <- max(need, 3 * max(1L, min(MAX_LAG, n %/% 5L)) + 3)
cs_check_rows(n, need, "The Granger test")
cs_check_not_constant(y, Y)
cs_check_not_constant(x, X)
lags <- if (!is.null(LAGS)) as.integer(LAGS) else cs_ts_var_lag_aic(cbind(y, x), max(1L, min(MAX_LAG, n %/% 5L)))
cs_check_rows(n, 3 * (lags + extra) + 2, "The Granger test")
# %% Test
fwd <- cs_ts_granger(y, x, lags, extra)
rev <- cs_ts_granger(x, y, lags, extra)
values <- list(n_obs = n, test = TEST, lags = lags, stat = fwd$stat, p = fwd$p, reject = as.integer(fwd$p < 0.05),
stat_rev = rev$stat, p_rev = rev$p, reject_rev = as.integer(rev$p < 0.05), df1 = fwd$df1)
if (!is.null(fwd$df2)) values$df2 <- fwd$df2
label <- if (TEST == "f") "F" else "Wald χ²"
dfs <- function(r) if (!is.null(r$df2)) sprintf("%d, %d", r$df1, r$df2) else as.character(r$df1)
rows <- list(list(direction = sprintf("%s → %s", X, Y), statistic = fwd$stat, df = dfs(fwd), p = fwd$p, verdict = if (fwd$p < 0.05) "helps predict" else "no evidence"),
list(direction = sprintf("%s → %s", Y, X), statistic = rev$stat, df = dfs(rev), p = rev$p, verdict = if (rev$p < 0.05) "helps predict" else "no evidence"))
summary <- sprintf("With %d lag%s, past %s %s predict %s (%s), and past %s %s predict %s (%s). Predictive precedence, not proof of cause.",
lags, if (lags != 1) "s" else "", X, if (fwd$p < 0.05) "helps" else "does not help", Y, cs_fmt_p(fwd$p),
Y, if (rev$p < 0.05) "helps" else "does not help", X, cs_fmt_p(rev$p))
cs_publish(list(
method = "ts.granger",
methodVersion = "1.0.2",
title = "Granger causality (predictive) test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s → %s: %s = %.2f, %s; %s → %s: %s = %.2f, %s", X, Y, label, fwd$stat, cs_fmt_p(fwd$p), Y, X, label, rev$stat, cs_fmt_p(rev$p)),
statistics = list(list(key = "stat", label = sprintf("%s (%s → %s)", label, X, Y), value = fwd$stat), list(key = "p", label = "p", value = fwd$p)),
tables = list(list(
key = "granger", title = "Granger causality",
columns = list(list(key = "direction", label = "Direction", type = "string"), list(key = "statistic", label = label, type = "number"),
list(key = "df", label = "df", type = "string"), list(key = "p", label = "p", type = "pvalue"),
list(key = "verdict", label = "At α = .05", type = "string")),
rows = rows
)),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = list("Granger causality is about prediction: a common driver or a missing variable can make one series 'Granger-cause' another.",
if (TEST == "f") "The F test needs stationary series — difference unit-root series, or use Toda–Yamamoto." else
sprintf("Toda–Yamamoto: %d extra unrestricted lag(s), Wald test on the first %d.", DMAX, lags)),
charts = list(cs_chart("ccf", "cross-correlation", sprintf("Cross-correlation of %s and %s", X, Y), list(a = cs_col(X, x), b = cs_col(Y, y)))),
values = values
))
Sources
- Granger, C. W. J. (1969). Investigating causal relations by econometric models and cross-spectral methods. Econometrica, 37, 424–438.
- Toda, H. Y., & Yamamoto, T. (1995). Statistical inference in vector autoregressions with possibly integrated processes. J. Econometrics, 66, 225–250.
From the CodeSplash method registry · ts.granger v1.0.2.