typestar

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

  1. acf includes indirect effects; pacf removes them.
  2. nlags bounds how far back to look.
  3. acorr_ljungbox tests whether any of it is significant.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 6 in Time series, step 13 of 19 in Statistics with statsmodels.

← Previous Next →