Autocorrelation in Python
How much a series remembers, at each lag.
import numpy as np
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.stattools import acf, pacf
rng = np.random.default_rng(11)
series = np.zeros(200)
for i in range(1, 200):
series[i] = 0.7 * series[i - 1] + rng.normal()
print(acf(series, nlags=5).round(3))
print(pacf(series, nlags=5).round(3))
test = acorr_ljungbox(series, lags=[5, 10])
print(test["lb_pvalue"].round(6).tolist())
How it works
acfincludes indirect effects;pacfremoves them.nlagsbounds how far back to look.acorr_ljungboxtests whether any of it is significant.
Keywords and builtins used here
asforprintrange
The run, in numbers
- Lines
- 14
- Characters to type
- 413
- Tokens
- 133
- Three-star pace
- 115 tpm
At the three-star pace of 115 tokens a minute, this run takes about 69 seconds.
Step 1 of 6 in Time series, step 13 of 19 in Statistics with statsmodels.