The three numbers p, d, q
p is how many past values the model looks at. d is how many times you difference the series. q is how many past mistakes it looks at. A model written ARIMA(1, 1, 1) uses one of each.
Seasonal ARIMA adds a second set of numbers (P, D, Q) and the period m. For our weekly cafe, m is 7.
Pick the numbers by looking at plots
ACF shows how strongly today relates to each earlier day. PACF shows the same, with the in-between days removed. Plot both on the differenced series.
A rough guide: if PACF stops after p lags and ACF fades slowly, try AR(p). If ACF stops after q lags and PACF fades, try MA(q). Spikes at lag 7 and 14 point to weekly seasonal terms.
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.graphics.tsaplots import plot_acf, plot_pacf
d = s.diff().dropna()
plot_acf(d, lags=28)
plot_pacf(d, lags=28)Fit a seasonal model
Start small. Do not try to be perfect. A simple model such as (1, 1, 1) with seasonal (1, 0, 1, 7) is a strong first guess for this data.
from statsmodels.tsa.statespace.sarimax import SARIMAX
train, test = s[:-28], s[-28:]
model = SARIMAX(train, order=(1, 1, 1),
seasonal_order=(1, 0, 1, 7)).fit(disp=False)
fc = model.get_forecast(28).summary_frame(alpha=0.05)
fc[["mean", "mean_ci_lower", "mean_ci_upper"]].head()Always check the leftover mistakes
If the model learned the pattern, what is left (the residuals) should look like random noise. The diagnostics plot shows this. If you still see a pattern, add a term or a feature.
model.plot_diagnostics(figsize=(9, 6))
from statsmodels.stats.diagnostic import acorr_ljungbox
acorr_ljungbox(model.resid[8:], lags=[10]) # p-value above 0.05 is good