ARIMA Intuition + statsmodels
Lesson opener
In one line: AR, I, and MA pieces in plain language.
Why it matters: ARIMA is widely available in Python stacks Indian data teams already ship.
Before this lesson: Exponential smoothing / Holt-Winters
Before you start
| Resource | Link |
|---|---|
| Previous | Exponential smoothing / Holt-Winters |
| Next | Evaluation and backtesting |
| Prerequisites | Exponential smoothing / Holt-Winters |
| Time | ~60 minutes |
What you will learn
- AR, I, and MA pieces in plain language
- Differencing for trend; when a series looks closer to stationary
- Fitting
ARIMAwithstatsmodels==0.14.4 - Residual checks after fit (mean near zero, no huge leftover season)
- Comparing ARIMA to a seasonal naive baseline on a holdout
Pinned libraries for this course
pip install -r docs/timeseries/requirements.txtPinned in docs/timeseries/requirements.txt:
numpy==2.1.3
pandas==2.2.3
statsmodels==0.14.4
scipy==1.14.1This lesson uses statsmodels.tsa.arima.model.ARIMA with numpy / pandas synthetic KPIs. Pins keep coefficient tables reproducible across Bengaluru and remote CI runners.
ARIMA in one paragraph
AR(p) — the point depends on the last p values (autoregression).
I(d) — difference the series d times to remove trend-like non-stationarity.
MA(q) — the point depends on the last q forecast errors (moving average).
Order is written (p, d, q). Seasonal ARIMA adds another triple and a period; this lesson stays with non-seasonal ARIMA plus honest baselines for weekly patterns, so you learn the API without drowning in identification folklore.
WHY ARIMA is widely available in Python stacks Indian data teams already ship.
WHEN After baselines and when residuals from HW still show short-run autocorrelation worth modelling.
Demo 1 — Difference toward stationarity
# Offline demo: first difference reduces linear trend
import numpy as np
import pandas as pd
idx = pd.date_range("2026-01-01", periods=40, freq="D")
y = pd.Series(np.linspace(100, 160, 40) + np.sin(np.arange(40) / 2), index=idx)
d1 = y.diff().dropna()
print("level range:", round(float(y.max() - y.min()), 1))
print("diff mean:", round(float(d1.mean()), 3))
assert abs(d1.mean()) < abs(y.diff().mean()) + 1 # sanity
assert d1.std() < y.std()Fit a small ARIMA
Start simple: (1,1,1) on a mildly trending KPI. Use train only, then get_forecast(steps=h).
Demo 2 — ARIMA(1,1,1) forecast
# Offline demo: ARIMA(1,1,1) on synthetic daily KPI
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import warnings
rng = np.random.default_rng(21)
n = 80
idx = pd.date_range("2026-02-01", periods=n, freq="D")
y = pd.Series(
200 + np.cumsum(rng.normal(0.2, 1.0, n)),
index=idx,
name="orders",
)
train, test = y.iloc[:-7], y.iloc[-7:]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fit = ARIMA(train, order=(1, 1, 1)).fit()
fc = fit.forecast(7)
mae = float(np.mean(np.abs(test.to_numpy() - fc.to_numpy())))
print("AIC:", round(float(fit.aic), 1), "MAE:", round(mae, 2))
assert len(fc) == 7
assert np.isfinite(fit.aic)Demo 3 — Compare orders by AIC on train
# Offline demo: pick among small ARIMA orders via AIC
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import warnings
rng = np.random.default_rng(3)
y = pd.Series(
50 + np.cumsum(rng.normal(0, 1, 60)),
index=pd.date_range("2026-03-01", periods=60, freq="D"),
)
candidates = [(1, 0, 0), (0, 1, 1), (1, 1, 1), (2, 1, 0)]
scores = {}
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for order in candidates:
scores[order] = float(ARIMA(y, order=order).fit().aic)
best = min(scores, key=scores.get)
print({str(k): round(v, 1) for k, v in scores.items()})
print("best", best)
assert best in candidates[!important] Lowest AIC on train is not a licence to skip holdout MAE. AIC helps shortlist; the business metric decides.
Residuals after fit
Plotting is offline-limited here; still compute residual mean and lag-1 correlation as a smoke test. Large leftover weekly correlation suggests you need seasonal structure (SARIMA or HW) rather than a bigger non-seasonal ARIMA.
Demo 4 — Residual smoke checks
# Offline demo: residual mean and lag-1 correlation after ARIMA
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import warnings
rng = np.random.default_rng(9)
y = pd.Series(
120 + np.cumsum(rng.normal(0.05, 1.2, 70)),
index=pd.date_range("2026-04-01", periods=70, freq="D"),
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fit = ARIMA(y, order=(1, 1, 1)).fit()
resid = fit.resid.dropna()
lag1 = float(np.corrcoef(resid.values[1:], resid.values[:-1])[0, 1])
print("resid mean:", round(float(resid.mean()), 4))
print("lag1 corr:", round(lag1, 3))
assert np.isfinite(float(resid.mean()))
assert abs(lag1) < 0.5Demo 5 — Holdout vs seasonal naive
# Offline demo: ARIMA bakeoff vs seasonal naive on weekly-ish series
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import warnings
def seasonal_naive(train, horizon, period=7):
hist = train.to_numpy(dtype=float)
out = [hist[-period + ((h - 1) % period)] for h in range(1, horizon + 1)]
idx = pd.date_range(train.index[-1] + train.index.freq, periods=horizon, freq=train.index.freq)
return pd.Series(out, index=idx)
rng = np.random.default_rng(11)
n = 70
idx = pd.date_range("2026-05-04", periods=n, freq="D")
season = np.tile([0, 1, 0, 2, 5, 8, -4], 10)
y = pd.Series(250 + np.arange(n) * 0.2 + season + rng.normal(0, 2, n), index=idx)
train, test = y.iloc[:-7], y.iloc[-7:]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
arima_fc = ARIMA(train, order=(1, 1, 1)).fit().forecast(7)
sn = seasonal_naive(train, 7)
ar_mae = float(np.mean(np.abs(test - arima_fc)))
sn_mae = float(np.mean(np.abs(test - sn)))
print({"arima_mae": round(ar_mae, 2), "seasonal_naive_mae": round(sn_mae, 2)})
# On strong weekly season, naive seasonal often wins — assert both finite
assert np.isfinite(ar_mae) and np.isfinite(sn_mae)Demo 6 — Confidence interval stub from get_forecast
# Offline demo: forecast mean and 95% interval frame
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
import warnings
rng = np.random.default_rng(2)
y = pd.Series(
80 + np.cumsum(rng.normal(0, 1, 50)),
index=pd.date_range("2026-06-01", periods=50, freq="D"),
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fit = ARIMA(y, order=(1, 1, 0)).fit()
pred = fit.get_forecast(5)
mean = pred.predicted_mean
ci = pred.conf_int(alpha=0.05)
print(mean.round(2).tolist())
print(ci.round(2).head())
assert len(mean) == 5
assert (ci.iloc[:, 1] >= ci.iloc[:, 0]).all()Indian workplace framing
A Hyderabad payments team forecasting daily settlement volume can try ARIMA after HW. If weekdays dominate, seasonal naive or Holt-Winters may still win the bakeoff — publish that result. Leadership in Indian product orgs often equates "ARIMA" with seriousness; your job is to show MAE in INR-relevant units (failed settlements, missed deliveries), not to worship (p,d,q).
WHY Model prestige does not staff a warehouse.
WHEN In the readout: one table with baseline, HW, ARIMA, holdout MAE.
Failure modes
- Over-differencing — extra
dinvents patterns; check ifd=1already flattens trend. - Huge
(p,q)on short series — overfit; prefer small grids. - Ignoring season — non-seasonal ARIMA loses to seasonal naive every week.
- Trusting AIC alone — without holdout MAE / backtests (next lesson).
Official ARIMA docs cover order and forecast; pin statsmodels==0.14.4.
Explaining this to a workplace stakeholder
In Indian product and ops teams the forecast is a staffing and cash decision, not a notebook trophy. Walk the stakeholder through three questions before any chart: what KPI is defined in the dictionary, what timezone and calendar the daily bucket uses, and what happens on known closure days. If those answers are fuzzy, stop modelling and fix the definition. A crisp definition plus seasonal naive often beats a glamorous model on a muddy series.
When you present numbers, lead with units the listener already uses — paid orders, tickets, settlements — and put the baseline column first. Only then show the candidate. If the candidate wins by a thin margin, say so out loud and recommend keeping the simpler method until the edge is stable across several origins. Document the pinned library versions (numpy==2.1.3, pandas==2.2.3, statsmodels==0.14.4, scipy==1.14.1) in the same ticket so a teammate in another city can reproduce the table next Monday without guessing which wheel file you had installed.
Watch for process failure modes that look like model failure: a marketing push that was not flagged, a payment-rail outage labelled as demand drop, or a festival week treated as ordinary seasonality. Write those caveats next to the MAE. The goal of this course lesson is judgment under workplace constraints — reproducible pins, chronological validation, and a decision rule you can defend in a standup without inventing accuracy.
For remote-friendly handoffs, paste the decision rule and the latest rolling means into the ticket description. Link the official docs you relied on. Avoid pasting secrets, live warehouse credentials, or hard-coded FX rates. Keep the script offline-friendly so continuous integration can re-run every code fence the same way learners do on a laptop in Pune or Hyderabad.
Finally, schedule an owner for the Monday re-run. Models without owners quietly rot after the first festival. A one-page readout with KPI, pins, origins, control MAE, candidate MAE, and the ship-or-keep decision is enough for most Bengaluru and Mumbai ops leads if the numbers are honest.
Verified against numpy 2.1.3, pandas 2.2.3, statsmodels 0.14.4 (+1 more) documentation, September 2026.
Test yourself
- What do p, d, and q stand for in ARIMA?
- Why difference a trending KPI before AR/MA pieces?
- True or false: lowest AIC guarantees the best ops forecast.
- What smoke checks help after fit?
- When might seasonal naive beat non-seasonal ARIMA?
- Which statsmodels class did we call?
- Why fit on train only before
forecast(7)? - What does
get_forecastadd beyond a point forecast? - Which pinned
pandasversion does this course use? - True or false: calling the model ARIMA is enough to skip the baseline column.