Does one series lead another? in Python
The Granger test asks whether past x improves a forecast of y.
import numpy as np
from statsmodels.tsa.stattools import grangercausalitytests
rng = np.random.default_rng(16)
n = 300
leader = rng.normal(size=n)
follower = np.zeros(n)
for i in range(2, n):
follower[i] = 0.5 * leader[i - 2] + rng.normal(scale=0.5)
data = np.column_stack([follower, leader])
results = grangercausalitytests(data, maxlag=3, verbose=False)
for lag, result in results.items():
pvalue = result[0]["ssr_ftest"][1]
print(f"lag {lag}: p={pvalue:.5f}")
How it works
- The data goes in as two columns, y first.
maxlagbounds how far back to look.- It tests prediction, which is not the same as causation.
Keywords and builtins used here
asforprintrange
The run, in numbers
- Lines
- 16
- Characters to type
- 465
- Tokens
- 142
- Three-star pace
- 115 tpm
At the three-star pace of 115 tokens a minute, this run takes about 74 seconds.
Step 6 of 6 in Time series, step 18 of 19 in Statistics with statsmodels.