Skip to content

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.

Applied ~11 min10 steps

What runs in CodeSplash

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

01

The question

Read

Does the past of xx help predict yy, beyond what yy's own past already gives?

yt=α+∑j=1paj yt−j+∑j=1pbj xt−j+ety_t = \alpha + \sum_{j=1}^{p} a_j\, y_{t-j} + \sum_{j=1}^{p} b_j\, x_{t-j} + e_t

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 b1=⋯=bp=0b_1 = \dots = b_p = 0. If it rejects, xx "Granger-causes" yy, which is a statement about prediction and nothing more.

02

Predict a misreading

Predict

Predict 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?

Advertising causes salesAdvertising helps predict sales; a shared cause could explain itSales can't affect advertising
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.

03

Read both directions

In the app

On simulated data where xx does lead yy:

Granger causality (predictive) testRecorded · Python and R agreeRecorded 2026-11-17 · 11 values compared
R

x → y: F = 35.77, p < .001; y → x: F = 2.83, p = .040

F (x → y)
35.768
p
2.255e-18

Plots

Cross-correlation of x and yDoes one series lead or lag the other, and by how many steps?
View data
xy
−0.93110
−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.05430.9923
1.403−0.0287
0.24460.1965
−0.39480.5923
0.7436−1.208
0.2321−0.2000
−0.34471.664
−0.10861.260
−0.3653−0.8615
1.499−1.180
0.53671.935
−0.32370.9070
−0.0273−0.4212
1.145−0.3520
0.3287−0.4571
−0.9926−0.3772
−0.12190.4273
−0.37171.468
0.37300.2100
1.263−0.2242
1.401−0.4890
1.3971.638
2.0560.6953
1.1082.432
−0.66932.352
−1.050−0.0246
0.8205−1.197
1.980−0.9062
0.4885−0.0581
0.63210.2697
1.576−0.2594
2.2560.5936
1.8631.482
0.91532.120
0.89931.853
1.2020.3091
0.26901.334
0.43971.326
0.10620.5253
1.292−0.6508
−0.0265−0.4865
−0.7395−1.382
−1.547−1.599
0.1994−0.8990
0.19900.1416
−0.52400.1441
2.2710.3104
3.4360.8524
1.3382.208
2.4021.373
2.5912.952
0.54931.903

First 60 of 200 rows.

Granger causality

DirectionFdfpAt α = .05
x → y35.7683, 190< .001helps predict
y → x2.8263, 190.040helps 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
))
Python

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

DirectionFdfpAt α = .05
x → y35.7683, 190< .001helps predict
y → x2.8263, 190.040helps 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,
})

x→yx \to y: F(3, 190) = 35.8, p < .001.

y→xy \to x: 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?

05

Unit roots

Predict

Predict first

Both series have unit roots. Can you still use the usual F test on their levels?

Yes: F is valid at any timeNo: its distribution changes under unit rootsOnly with a very short lag
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.

06

Toda–Yamamoto

Read

Toda–Yamamoto fits the VAR in levels with dmax⁡d_{\max} extra lags, then tests only the original pp lags with a Wald test. That restores a standard χ2\chi^2 reference, whatever the order of integration or cointegration.

On a cointegrated pair: χ2\chi^2(2) = 14.9, p < .001. In the reverse direction, p = .176.

07

How would you word it?

Reflect

Your 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.

08

Check your understanding

Checkpoint

Check yourself

A Granger F test uses 4 lags of xx. How many coefficients does it test (numerator degrees of freedom)?

Show the answer

Answer: 4

One per lag of xx: 4.

Check yourself

"xx Granger-causes yy" 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.

09

Do it in CodeSplash

In the app

The 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.

Python
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)
R
# install.packages("lmtest")
df <- read.csv("granger.csv")
lmtest::grangertest(y ~ x, order = 3, data = df)
lmtest::grangertest(x ~ y, order = 3, data = df)
10

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