The one-line mental model
ARIMA models the series from its own past through differencing and autocorrelations; Prophet models trend, seasonality, and holidays as a regression â pick based on how clean your history is and how much domain structure you need to inject.
You will be able to:
- Translate ACF/PACF or auto_arima output into ARIMA(p,d,q) and SARIMA orders
- Fit SARIMA with seasonal periods and extract prediction intervals
- Configure Prophet for trend changes, custom seasonalities, and holidays
- Evaluate forecasts with MAE, RMSE, MAPE, and MASE, then read residual diagnostics
Prerequisites
- !Stationarity tests and differencing
- !ACF and PACF interpretation
- !Train/test splitting in time order
What You'll Learn
- 1Explain what each of p, d, q and P, D, Q, s does inside a fitted model
- 2Use auto_arima for a principled starting order, then refine manually
- 3Decide when Prophet's additive structure beats a pure ARIMA
- 4Run Ljung-Box and Q-Q checks before trusting a forecast
The ARIMA trio in plain language
ARIMA(p, d, q) combines three ideas. The integrated order d is how many times you difference the series to make it stationary. The autoregressive order p says today's value depends on the last p differenced values. The moving-average order q says today's value depends on the last q forecast errors. Together they model residuals that look like white noise â the goal of any good fit.
SARIMA extends this with a second set of orders (P, D, Q) applied at seasonal lag s â typically 7 for daily data with weekly cycles, 12 for monthly data with yearly cycles. The seasonal part differences and autocorrelates the series against itself one season ago, which is how monthly retail forecasts capture the December spike without an external regressor.
| Symbol | Role | How to choose |
|---|---|---|
| d | Non-seasonal differencing | ADF/KPSS until stationary; usually 0 or 1 |
| D | Seasonal differencing | Decomposition; usually 0 or 1 |
| p | AR order | PACF cutoff on differenced series |
| q | MA order | ACF cutoff on differenced series |
| P, Q | Seasonal AR/MA | Seasonal ACF/PACF at lags s, 2s |
| s | Seasonal period | Domain: 7 daily, 12 monthly, 4 quarterly |
Fitting ARIMA without guessing orders
Manual order selection from ACF/PACF remains the most interpretable route, but auto_arima (from the pmdarima package) automates a stepwise search over candidate orders scored by AIC. Treat its output as a strong candidate, not gospel â verify residuals before shipping.
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
warnings.filterwarnings("ignore")
ts = pd.read_csv("data/monthly_sales.csv",
index_col="date", parse_dates=True)["sales"]
split = int(len(ts) * 0.8)
train, test = ts.iloc[:split], ts.iloc[split:]
try:
from pmdarima import auto_arima
auto = auto_arima(
train,
start_p=0, max_p=4, start_q=0, max_q=4, d=None,
seasonal=True, m=12,
start_P=0, max_P=2, start_Q=0, max_Q=2, D=None,
stepwise=True, trace=False,
error_action="ignore", suppress_warnings=True,
)
order, seasonal_order = auto.order, auto.seasonal_order
print(f"auto_arima â order={order}, seasonal={seasonal_order}")
except ImportError:
order, seasonal_order = (1, 1, 1), (1, 1, 1, 12)
print(f"pmdarima unavailable; using {order} {seasonal_order}")
model = SARIMAX(
train,
order=order,
seasonal_order=seasonal_order,
enforce_stationarity=False,
enforce_invertibility=False,
)
fitted = model.fit(disp=False)
print(fitted.summary().tables[1])
Reading the parameter table: coefficients far from zero with small p-values are doing real work; large standard errors or p-values near one suggest you can drop that term and simplify. Lower AIC means a better complexity-adjusted fit â use it to compare candidate orders on the same series, never across different transformations.
Extracting forecasts with honest intervals
A point forecast without an interval is a number with no error bar. SARIMAX can return both the predicted mean and a confidence band that widens with horizon, which is exactly the behavior stakeholders need to see.
forecast = fitted.get_forecast(steps=len(test))
mean_fc = forecast.predicted_mean
ci = forecast.conf_int()
plt.figure(figsize=(12, 5))
plt.plot(train.index, train, label="Train")
plt.plot(test.index, test, label="Actual", color="black")
plt.plot(test.index, mean_fc, label="SARIMA forecast", color="crimson")
plt.fill_between(test.index, ci.iloc[:, 0], ci.iloc[:, 1],
color="crimson", alpha=0.2, label="95% CI")
plt.legend()
plt.title("SARIMA forecast with prediction interval")
plt.tight_layout()
plt.show()
coverage = ((test.values >= ci.iloc[:, 0].values) &
(test.values <= ci.iloc[:, 1].values)).mean()
print(f"Empirical 95% CI coverage on holdout: {coverage:.1%}")
Coverage on the holdout is the check that matters: a nominal 95% band that covers only 70% of actuals is overconfident, which usually means missing seasonality, structural breaks, or underestimated innovation variance.
Prophet when you need structure, not statistics
Prophet decomposes a series into trend (with optional changepoints), multiple Fourier seasonalities, and holiday effects, then fits by Stan under the hood. It is remarkably tolerant of missing points, large outliers, and short histories, which is why it became the default inside many companies for business time series with heavy calendar effects.
from prophet import Prophet
df_p = pd.DataFrame({"ds": train.index, "y": train.values})
model_p = Prophet(
growth="linear",
seasonality_mode="multiplicative",
changepoint_prior_scale=0.05,
yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=False,
)
model_p.add_seasonality(name="monthly", period=30.5, fourier_order=5)
model_p.add_country_holidays(country_name="US")
model_p.fit(df_p)
future = model_p.make_future_dataframe(periods=len(test), freq="MS")
pred = model_p.predict(future)
fig = model_p.plot(pred)
plt.scatter(test.index, test.values, color="black", s=12, label="Actual")
plt.legend()
plt.show()
fig2 = model_p.plot_components(pred)
plt.show()
The components plot is the real deliverable for business users: it shows how much of next quarter's forecast is trend versus December seasonality versus a named holiday. changepoint_prior_scale controls flexibility â raise it to let the trend follow regime changes, lower it to resist fitting noise.
Comparing models with the right metrics
MAE and RMSE share the units of the target; RMSE punishes large misses harder. MAPE is intuitive in percentage terms but explodes near zero and is undefined for zero actuals. MASE scales errors against a seasonal-naive baseline, so a value below one means you beat "last season's value" â the only honest bar for a forecasting model.
Beyond the headline numbers, look at how errors distribute across the horizon and across segments of the series. A model that is excellent for the next four weeks but degrades badly at the twelve-week horizon may still be the right choice if the business decision window is short â or the wrong one if you are planning inventory a year out. Slice metrics by horizon, by product category, and by season before declaring a winner. Aggregate scores hide the failure modes that generate angry stakeholder emails, and the only way to surface them is to disaggregate deliberately.
from sklearn.metrics import mean_absolute_error, mean_squared_error
def forecast_metrics(actual, predicted, seasonal_period=12, train=None):
actual = np.asarray(actual, dtype=float)
predicted = np.asarray(predicted, dtype=float)
mae = mean_absolute_error(actual, predicted)
rmse = np.sqrt(mean_squared_error(actual, predicted))
nonzero = actual != 0
mape = (np.abs((actual[nonzero] - predicted[nonzero]) / actual[nonzero])
).mean() * 100 if nonzero.any() else np.nan
smape = (2 * np.abs(actual - predicted) /
(np.abs(actual) + np.abs(predicted) + 1e-12)).mean() * 100
mase = np.nan
if train is not None and len(train) > seasonal_period:
naive = np.abs(np.diff(train.values[seasonal_period - 1:],
train.values[:-seasonal_period]))
denom = np.mean(np.abs(np.diff(train.values[seasonal_period - 1:])))
mase = mae / denom if denom > 0 else np.nan
return {"MAE": mae, "RMSE": rmse, "MAPE%": mape,
"sMAPE%": smape, "MASE": mase}
sarima_m = forecast_metrics(test, mean_fc, seasonal_period=12, train=train)
prophet_fc = pred.set_index("ds").loc[test.index, "yhat"].values
prophet_m = forecast_metrics(test, prophet_fc, seasonal_period=12, train=train)
print(pd.DataFrame({"SARIMA": sarima_m, "Prophet": prophet_m}).round(3))
Report all five together. A model that wins on MAPE while losing on MASE is usually gaming easy periods; MASE plus a visual of the holdout is the tiebreak most forecasting teams settle on.
Residual diagnostics: the step everyone skips
If the model captured the structure, what remains should be white noise: zero mean, constant variance, no autocorrelation, roughly normal. The Ljung-Box test formalizes the autocorrelation check â a small p-value means leftover signal that a better model could still harvest.
Residual plots are the most underused diagnostic in applied forecasting. A time plot of residuals reveals drift and variance changes that summary statistics miss; a histogram and Q-Q plot expose skew and heavy tails that make confidence intervals under-cover; the residual ACF is the single most informative panel, because any significant spike is a direct suggestion for the next model iteration. Teams that skip this step ship models that look fine on a holdout MAPE but fail visibly during regime changes â the residual plots would have flagged the instability weeks earlier.
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.graphics.gofplots import qqplot
from statsmodels.graphics.tsaplots import plot_acf
resid = fitted.resid.dropna()
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
axes[0, 0].plot(resid)
axes[0, 0].axhline(0, color="red", linestyle="--", linewidth=1)
axes[0, 0].set_title("Residuals over time")
axes[0, 1].hist(resid, bins=30, edgecolor="black", density=True)
axes[0, 1].set_title("Residual distribution")
plot_acf(resid, lags=24, ax=axes[1, 0])
axes[1, 0].set_title("ACF of residuals")
qqplot(resid, line="45", fit=True, ax=axes[1, 1])
axes[1, 1].set_title("Q-Q plot")
plt.tight_layout()
plt.show()
lb = acorr_ljungbox(resid, lags=[12, 24], return_df=True)
print(lb)
print(f"Residual mean={resid.mean():.4f}, std={resid.std():.4f}")
When Ljung-Box rejects, look for the signature: significant seasonal lags mean you under-specified seasonality; a drifting residual mean means you under-differenced; isolated spikes suggest an outlier intervention term rather than a different (p, q).