Split it with STL
STL separates the series into three lines you can plot. Use period=7 because our cafe repeats every week.
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
days = pd.date_range("2024-01-01", periods=365, freq="D")
trend = np.linspace(100, 140, 365) # sales slowly grow
week = np.array([-8, -6, -4, 0, 6, 16, 12])[days.dayofweek] # busy weekends
s = pd.Series(trend + week + rng.normal(0, 4, 365), index=days, name="sales")
from statsmodels.tsa.seasonal import STL
res = STL(s, period=7, robust=True).fit()
res.plot() # observed, trend, seasonal, residual
res.seasonal[:7] # the weekly pattern, one value per weekdayWhat does stationary mean?
A stationary series has no trend and no changing spread. Its average and its wobble stay about the same over time, like a heart rate at rest. Our cafe is not stationary, because sales grow.
Why care? Models like ARIMA learn patterns that must stay the same over time. A growing series breaks that rule, so we remove the trend first.
Test it with ADF and KPSS
Two tests answer the question from opposite sides. ADF starts by assuming the series is not stationary. KPSS starts by assuming it is. Use both: if they agree, you can trust the answer.
Read the p-value like this. For ADF, a p-value under 0.05 means stationary. For KPSS, a p-value over 0.05 means stationary.
from statsmodels.tsa.stattools import adfuller, kpss
print("ADF p-value:", round(adfuller(s)[1], 3))
print("KPSS p-value:", round(kpss(s, nlags="auto")[1], 3))You should see
ADF p-value: 0.93 (above 0.05: not stationary) KPSS p-value: 0.01 (below 0.05: not stationary)
Both tests agree: our cafe series is not stationary. KPSS may print a warning that the real p-value is even smaller. That is fine.
Fix it by differencing
diff() subtracts yesterday from today, which removes the trend. Our cafe also has a weekly pattern, so diff(7) is better: it subtracts the same weekday from last week, and removes the trend and the weekly pattern together.
d = s.diff(7).dropna() # this Monday minus last Monday, and so on
print("ADF p-value after diff:", round(adfuller(d)[1], 3))
print("KPSS p-value after diff:", round(kpss(d, nlags="auto")[1], 3))You should see
ADF p-value after diff: 0.0 (below 0.05: stationary) KPSS p-value after diff: 0.1 (above 0.05: stationary)
Now both tests agree that the series is stationary. A plain s.diff() gives a borderline KPSS result (about 0.04), because the weekly pattern is still in there.