Stationarity in Python
Most time-series models assume it, so test and difference first.
import numpy as np
from statsmodels.tsa.stattools import adfuller, kpss
rng = np.random.default_rng(12)
walk = np.cumsum(rng.normal(size=300))
statistic, pvalue, lags, nobs, crit, _ = adfuller(walk)
print(round(statistic, 3), round(pvalue, 4), "non-stationary" if pvalue > 0.05
else "stationary")
print({k: round(v, 2) for k, v in crit.items()})
differenced = np.diff(walk)
print(round(adfuller(differenced)[1], 6))
print(round(kpss(differenced, nlags="auto")[1], 4))
How it works
adfullertests the null that the series is non-stationary.- A trend makes the test fail; differencing usually fixes it.
kpsstests the opposite null, which is why people run both.
Keywords and builtins used here
aselseforifprintround
The run, in numbers
- Lines
- 14
- Characters to type
- 470
- Tokens
- 150
- Three-star pace
- 115 tpm
At the three-star pace of 115 tokens a minute, this run takes about 78 seconds.
Step 2 of 6 in Time series, step 14 of 19 in Statistics with statsmodels.