Granger causality: predictive, not causal
Ask whether one series' past helps predict another, handle unit roots with Toda–Yamamoto, and keep the word "causality" in its place.
What runs in CodeSplash
- STAT214Granger causality test Runs in CodeSplash
- Granger causality (predictive) test Verified in Python and R
You will be able to
- State what a Granger test measures, and what it doesn't
- Read a Granger F test in both directions
- Use Toda–Yamamoto when series may be non-stationary or cointegrated
Read first
The question
ReadDoes the past of help predict , beyond what 's own past already gives?
The Granger testGranger causalityWhether past values of one series improve forecasts of another; predictive, not causal in the everyday sense. is an F test of . If it rejects, "Granger-causes" , which is a statement about prediction and nothing more.
Predict a misreading
PredictPredict first
Monthly advertising Granger-causes sales, with p < 0.001. But budgets are set before each holiday season, and sales rise in those seasons too.
What can you conclude?
Reveal
Advertising helps predict sales. A shared driver, here the season, can create this pattern with no causal link. To claim cause, you need a design: an experiment, an intervention or a credible natural experiment.
Read both directions
In the appOn simulated data where does lead :
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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})
: F(3, 190) = 35.8, p < .001.
: F = 2.83, p = .040.
The reverse direction also falls below 0.05. Look at the sizes: which link is much stronger? And what does the cross-correlation chart show about the lead?
A pair with no link
ReadHere, and an unrelated series , using 3 lags, give p = .528 one way and p = .202 the other. The data are compatible with no predictive link in either direction.
Remember that the test only sees the variables you include. It's silent about any third series.
Unit roots
PredictPredict first
Both series have unit roots. Can you still use the usual F test on their levels?
Reveal
No. With unit roots, the F statistic doesn't have its usual distribution. Differencing is one route, but it throws away any long-run link if the series are cointegrated.
Toda–Yamamoto
ReadToda–Yamamoto fits the VAR in levels with extra lags, then tests only the original lags with a Wald test. That restores a standard reference, whatever the order of integration or cointegration.
On a cointegrated pair: (2) = 14.9, p < .001. In the reverse direction, p = .176.
How would you word it?
ReflectYour dashboard says "marketing spend causes revenue (Granger test, p < 0.01)". Rewrite that sentence so a reader can't take it the wrong way.
Then list two things that could produce the same pattern with no causal effect. What sampling frequency are you using? A monthly series can hide a daily lead, or make a same-day link look like a lead.
Check your understanding
CheckpointCheck yourself
A Granger F test uses 4 lags of . How many coefficients does it test (numerator degrees of freedom)?
Show the answer
Answer: 4
One per lag of : 4.
Check yourself
" Granger-causes " means what?
Show the answer
Answer: b
It's about prediction, given the information in the model.
Check yourself
Both directions are significant. What's a sound reading?
Show the answer
Answer: b
Feedback and common drivers both produce this pattern. The data alone can't separate them.
Do it in CodeSplash
In the appThe role names follow the test's language: Cause (predictor) and Effect (predicted). CodeSplash labels the result as predictive, not causal. Lags picks by AIC unless you set it. It's the Relationships step of the Series lab too.
import pandas as pd
from statsmodels.tsa.stattools import grangercausalitytests
df = pd.read_csv("granger.csv")
# Tests whether the second column predicts the first
grangercausalitytests(df[["y", "x"]], maxlag=3)# install.packages("lmtest")
df <- read.csv("granger.csv")
lmtest::grangertest(y ~ x, order = 3, data = df)
lmtest::grangertest(x ~ y, order = 3, data = df)Recap
Recap- A Granger test asks if one series' past improves prediction of another.
- It isn't evidence of cause: shared drivers and feedback produce the same pattern.
- Read both directions, and compare their strength.
- Use Toda–Yamamoto, or a VECM, when unit roots are in play.
Concepts in this lesson