Forecast a daily series with naive baselines, STL, ETS, SARIMAX and gradient boosting, then rank the models honestly with rolling-origin backtests, MASE and interval coverage instead of a single lucky split.
Most forecasting mistakes are evaluation mistakes: a model looks good because it saw the future during validation, or because nobody compared it with a forecast that just repeats last week. This tutorial builds forecasts for a daily series with trend, weekly and yearly seasonality, starting from naive baselines and working up to ETS, SARIMAX and gradient boosting. Every model is judged with rolling-origin backtesting, scale-free metrics and interval coverage, so the ranking you end up with is one you can defend.
The examples were run on Python 3.13.7 with numpy 2.5.5, pandas 3.1.2, scipy 1.18.1, statsmodels 0.15.0 and scikit-learn 1.9.1. Gradient boosting uses scikit-learn's HistGradientBoostingRegressor, so no extra boosting library is needed. All data is generated locally with a fixed seed.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "numpy>=2.5,<3" "pandas>=3.1,<4" "scipy>=1.18,<2" \
"statsmodels>=0.15,<1" "scikit-learn>=1.9,<2"
Two version notes. pandas 3 deprecates DatetimeIndex.dayofweek and dayofyear in favour of day_of_week and day_of_year, which the code below uses. statsmodels 0.15 warns that adfuller will return a result object instead of a tuple; passing result_object=True opts in now and silences the warning.
The code is one script split into blocks; run them in order in one session.
Synthetic data has one big advantage: you know the truth. The series has a linear trend, a weekly pattern with a weekend peak, a yearly sine wave and Gaussian noise. level scales everything, which we use later to create many series.
import numpy as np
import pandas as pd
def make_series(n_days=4 * 365 + 1, level=100.0, seed=42, start="2022-01-01"):
rng = np.random.default_rng(seed)
idx = pd.date_range(start, periods=n_days, freq="D")
t = np.arange(n_days)
trend = level + 0.03 * t
weekly = np.array([-6, -2, 0, 1, 3, 9, 7])[idx.day_of_week] * level / 100
yearly = 10 * np.sin(2 * np.pi * idx.day_of_year / 365.25) * level / 100
noise = rng.normal(0, 3 * level / 100, n_days)
return pd.Series(trend + weekly + yearly + noise, index=idx, name="y")
y = make_series()
print(y.describe().round(2).to_string())
count 1461.00
mean 123.57
std 14.43
min 90.13
...
max 159.28
Four years of daily data, 2022-01-01 to 2025-12-31. The forecast horizon throughout is H = 28 days.
Shuffled K-fold assumes the rows are exchangeable. A time series is not. After shuffling, the training folds contain days both before and after each validation day, so a model with lag features can interpolate between known neighbours, which it can never do in production. A time index feature makes it worse: the model can look up the level of the surrounding weeks. Evaluate the same model under both schemes:
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_score
X1 = pd.DataFrame({f"lag_{k}": y.shift(k) for k in (1, 2, 7)})
X1["dow"] = y.index.day_of_week
X1["t"] = np.arange(len(y))
ok = X1.notna().all(axis=1)
X1, y1 = X1[ok], y[ok]
gbm = HistGradientBoostingRegressor(max_iter=200, random_state=0)
for name, cv in [("KFold(shuffle)", KFold(5, shuffle=True, random_state=0)),
("TimeSeriesSplit", TimeSeriesSplit(5, test_size=90))]:
s = -cross_val_score(gbm, X1, y1, cv=cv, scoring="neg_mean_absolute_error")
print(f"{name:<16} MAE per fold: {np.round(s, 2)} mean={s.mean():.2f}")
KFold(shuffle) MAE per fold: [2.95 2.99 2.98 3.36 2.93] mean=3.04
TimeSeriesSplit MAE per fold: [3.93 4.54 3.31 4.22 3.98] mean=4.00
Shuffled CV reports an error about 25% lower than the forward-only split. Only the evaluation changed. TimeSeriesSplit trains on the past and validates on the block that follows. This is still a one-step task with a lag-1 feature; the rest of the tutorial evaluates the real 28-day horizon.
No single metric fits every purpose, so report several:
def mae(y_true, y_pred):
return float(np.mean(np.abs(np.asarray(y_true) - np.asarray(y_pred))))
def rmse(y_true, y_pred):
return float(np.sqrt(np.mean((np.asarray(y_true) - np.asarray(y_pred)) ** 2)))
def smape(y_true, y_pred):
a, f = np.asarray(y_true), np.asarray(y_pred)
return float(100 * np.mean(2 * np.abs(f - a) / (np.abs(a) + np.abs(f))))
def mase(y_true, y_pred, y_train, m=7):
y_train = np.asarray(y_train)
scale = np.mean(np.abs(y_train[m:] - y_train[:-m]))
return mae(y_true, y_pred) / scale
def report(name, y_true, y_pred, y_train):
return {"model": name, "MAE": mae(y_true, y_pred), "RMSE": rmse(y_true, y_pred),
"MASE": mase(y_true, y_pred, y_train), "sMAPE": smape(y_true, y_pred)}
The asymmetry is easy to demonstrate:
a = np.array([0.5, 0.5, 0.5])
print("sMAPE under-forecast:", round(smape(a, a * 0.5), 1),
" over-forecast:", round(smape(a, a * 1.5), 1))
sMAPE under-forecast: 66.7 over-forecast: 40.0
The same absolute miss costs more when you under-forecast, so optimising sMAPE nudges forecasts upward. Plain MAPE has the opposite bias and is undefined at zero. For intermittent demand prefer MASE.
A baseline is the number every model must beat to justify its complexity, and on real data it is beaten less often than people expect. Naive repeats the last observation; seasonal naive repeats the last seven days.
H = 28
train, test = y.iloc[:-H], y.iloc[-H:]
def naive(train, h):
return np.repeat(train.iloc[-1], h)
def seasonal_naive(train, h, m=7):
last_season = train.iloc[-m:].to_numpy()
return np.resize(last_season, h) # repeats the last m values
rows = [report("naive", test, naive(train, H), train),
report("seasonal_naive", test, seasonal_naive(train, H), train)]
print(pd.DataFrame(rows).round(3).to_string(index=False))
model MAE RMSE MASE sMAPE
naive 8.716 10.018 2.554 6.191
seasonal_naive 4.924 6.116 1.443 3.505
Seasonal naive halves the naive error because the weekly pattern is strong. Its MASE of 1.44 shows the caveat above: it is the denominator method, evaluated 28 days ahead instead of one step.
STL (Seasonal-Trend decomposition using Loess) splits a series into trend, seasonal and remainder. MSTL handles several seasonal periods, which daily data usually has. The strength of seasonality, 1 - Var(remainder) / Var(seasonal + remainder), is a number between 0 and 1 that is comparable across series.
from statsmodels.tsa.seasonal import STL, MSTL
stl = STL(train, period=7, robust=True).fit()
def strength(component, resid):
return max(0.0, 1 - np.var(resid) / np.var(component + resid))
print("weekly strength:", round(strength(stl.seasonal, stl.resid), 3))
mstl = MSTL(train, periods=(7, 365)).fit()
print(mstl.seasonal.columns.tolist())
print("weekly amplitude:", round(float(np.ptp(mstl.seasonal["seasonal_7"].iloc[-7:])), 2))
print("yearly amplitude:", round(float(np.ptp(mstl.seasonal["seasonal_365"].iloc[-365:])), 2))
weekly strength: 0.79
['seasonal_7', 'seasonal_365']
weekly amplitude: 12.93
yearly amplitude: 30.42
A weekly strength of 0.79 is high, and the yearly component swings more than twice as far as the weekly one, so a model with only weekly seasonality leaves a lot on the table. Use robust=True on real data so outliers do not leak into the seasonal component.
ARIMA-type models assume that, after differencing, the series has constant mean and autocorrelation. Two tests with opposite null hypotheses are better than one:
import warnings
from statsmodels.tsa.stattools import adfuller, kpss
def check(series, label):
adf_p = adfuller(series.dropna(), autolag="AIC", result_object=True).pvalue
with warnings.catch_warnings():
warnings.simplefilter("ignore") # KPSS warns when p is outside its table
kpss_p = kpss(series.dropna(), regression="c", nlags="auto")[1]
print(f"{label:<22} ADF p={adf_p:.3f} KPSS p={kpss_p:.3f}")
check(train, "level")
check(train.diff(), "first difference")
check(train.diff().diff(7), "diff + seasonal diff")
level ADF p=0.705 KPSS p=0.010
first difference ADF p=0.000 KPSS p=0.100
diff + seasonal diff ADF p=0.000 KPSS p=0.100
Both tests agree that the level is non-stationary and the first difference is stationary, so d = 1. KPSS p-values are interpolated from a table and clipped at 0.01 and 0.1, hence the round numbers. No seasonal difference is needed; over-differencing inflates forecast variance. Treat the tests as guidance, not a gate: the backtest decides.
ETS models describe a series as error, trend and seasonal components updated recursively. ETSModel supports additive or multiplicative errors and returns prediction intervals. A damped trend is the safer choice for multi-week horizons because it stops a short-term slope from being extrapolated indefinitely.
from statsmodels.tsa.exponential_smoothing.ets import ETSModel
ets = ETSModel(train, error="add", trend="add", damped_trend=True,
seasonal="add", seasonal_periods=7).fit(disp=False)
ets_pred = ets.get_prediction(start=len(train), end=len(train) + H - 1)
ets_frame = ets_pred.summary_frame(alpha=0.2)
rows.append(report("ets_AAdA", test, ets_frame["mean"], train))
print(ets_frame.head(3).round(2).to_string())
mean pi_lower pi_upper
2025-12-04 139.92 135.91 143.93
2025-12-05 141.61 137.58 145.63
2025-12-06 148.05 144.01 152.09
alpha=0.2 requests an 80% interval. ETS handles one seasonal period, so the yearly cycle is absorbed by the level and trend, which react to it with a lag.
A seasonal ARIMA with period 365 needs a huge state vector and fits slowly and unreliably. Instead, keep the weekly seasonality in the ARIMA part and model the yearly cycle with a few Fourier terms as exogenous regressors. They depend only on the calendar, so they are known for future dates.
from statsmodels.tsa.statespace.sarimax import SARIMAX
def fourier(index, period=365.25, K=3):
t = index.day_of_year.to_numpy()
cols = {}
for k in range(1, K + 1):
cols[f"sin{k}"] = np.sin(2 * np.pi * k * t / period)
cols[f"cos{k}"] = np.cos(2 * np.pi * k * t / period)
return pd.DataFrame(cols, index=index)
future_idx = pd.date_range(train.index[-1] + pd.Timedelta(days=1), periods=H, freq="D")
sarimax = SARIMAX(train, exog=fourier(train.index), order=(1, 1, 1),
seasonal_order=(1, 0, 1, 7)).fit(disp=False, maxiter=200)
fc = sarimax.get_forecast(steps=H, exog=fourier(future_idx))
sarima_ci = fc.conf_int(alpha=0.2)
rows.append(report("sarimax_fourier", test, fc.predicted_mean, train))
print(pd.DataFrame(rows).round(3).to_string(index=False))
model MAE RMSE MASE sMAPE
naive 8.716 10.018 2.554 6.191
seasonal_naive 4.924 6.116 1.443 3.505
ets_AAdA 3.443 4.359 1.009 2.426
sarimax_fourier 2.682 3.496 0.786 1.887
Both models beat the baselines on this holdout, SARIMAX most clearly. maxiter=200 avoids the convergence warnings the default of 50 iterations produces here. Tune the number of harmonics K by backtest or information criterion.
Tree ensembles turn forecasting into tabular regression: each row is a target day, the columns describe what was known at forecast time. This scales to many series and external regressors, and opens many ways to leak the future.
We use a direct strategy: one model predicts every day of the next 28 directly from information at least 28 days old. Every lag is therefore >= H. The alternative, a recursive one-step model that feeds its own predictions back in, can use shorter lags but compounds its errors over the horizon.
def make_features(y, h):
df = pd.DataFrame({"y": y})
base = y.shift(h) # newest value known at forecast time
for lag in (0, 7, 14, 21, 336): # lags h, h+7, ..., all >= h
df[f"lag_{h + lag}"] = y.shift(h + lag)
df["roll_mean_7"] = base.rolling(7).mean()
df["roll_mean_28"] = base.rolling(28).mean()
df["roll_std_28"] = base.rolling(28).std()
df["dow"] = y.index.day_of_week
df["doy_sin"] = np.sin(2 * np.pi * y.index.day_of_year / 365.25)
df["doy_cos"] = np.cos(2 * np.pi * y.index.day_of_year / 365.25)
df["t"] = np.arange(len(y))
return df
Calendar features are known in advance and safe. Lags at multiples of seven keep the weekly phase aligned; lag_364 is last year's value on the same weekday.
The most common leak in feature-based forecasting is a rolling window that includes the target day. y.rolling(7).mean() at day t averages days t-6 to t, including the value you are trying to predict. The correct version shifts first, then rolls:
leaky = y.rolling(7).mean() # includes today's value
safe = y.shift(H).rolling(7).mean() # only data available H days earlier
print(f"corr with y: leaky={y.corr(leaky):.3f} safe={y.corr(safe):.3f}")
corr with y: leaky=0.921 safe=0.877
The leaky feature correlates more with the target, so the model leans on it and validation looks better than production ever will. The rule: every feature for a target at time t may use only data up to t - H. With several series, the shift must also happen per series (groupby(...).shift()), as shown later; a plain shift on a stacked frame leaks the last values of one series into the first rows of the next.
Trees cannot extrapolate beyond the target range seen in training, so with an upward trend the forecast would flatten. Predicting the change relative to lag_28 fixes this, because the change has a stable distribution while the level drifts.
from sklearn.ensemble import HistGradientBoostingRegressor
def fit_predict_gbm(y_hist, h, **kw):
"""Direct model: features use only values >= h days old.
Target is the change versus lag h, so the trees need not extrapolate the level."""
ext_idx = pd.date_range(y_hist.index[0], periods=len(y_hist) + h, freq="D")
y_ext = y_hist.reindex(ext_idx) # future y = NaN
X = make_features(y_ext, h)
target = X["y"] - X[f"lag_{h}"]
feats = [c for c in X.columns if c != "y"]
fit_mask = target.notna() & X[feats].notna().all(axis=1)
model = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05,
categorical_features=["dow"], random_state=0, **kw)
model.fit(X.loc[fit_mask, feats], target[fit_mask])
Xf = X.iloc[-h:][feats]
return model.predict(Xf) + Xf[f"lag_{h}"].to_numpy()
gbm_pred = fit_predict_gbm(train, H)
rows.append(report("gbm_direct", test, gbm_pred, train))
print(pd.DataFrame(rows).round(3).to_string(index=False))
model MAE RMSE MASE sMAPE
...
ets_AAdA 3.443 4.359 1.009 2.426
sarimax_fourier 2.682 3.496 0.786 1.887
gbm_direct 2.919 3.786 0.855 2.062
The future rows of y_ext are NaN, so they never enter training. On this holdout the boosted model beats ETS and nearly matches SARIMAX. But one holdout is a sample of size one.
A backtest repeats the forecast at several origins, training only on data before each. With an expanding window each fold uses all history up to its origin, as a retrained production model would. Eight origins 28 days apart cover the last 224 days without overlap.
def backtest(y, forecasters, h=28, n_folds=8, step=28):
results = []
first_origin = len(y) - h - (n_folds - 1) * step
for fold in range(n_folds):
origin = first_origin + fold * step
y_tr, y_te = y.iloc[:origin], y.iloc[origin:origin + h]
for name, fn in forecasters.items():
pred = np.asarray(fn(y_tr, h))
r = report(name, y_te, pred, y_tr)
r["fold"], r["origin"] = fold, y_te.index[0].date()
results.append(r)
return pd.DataFrame(results)
def ets_fc(y_tr, h):
m = ETSModel(y_tr, error="add", trend="add", damped_trend=True,
seasonal="add", seasonal_periods=7).fit(disp=False)
return m.forecast(h)
def sarimax_fc(y_tr, h):
idx = pd.date_range(y_tr.index[-1] + pd.Timedelta(days=1), periods=h, freq="D")
m = SARIMAX(y_tr, exog=fourier(y_tr.index), order=(1, 1, 1),
seasonal_order=(1, 0, 1, 7)).fit(disp=False, maxiter=200)
return m.forecast(h, exog=fourier(idx))
forecasters = {"seasonal_naive": seasonal_naive, "ets": ets_fc,
"sarimax": sarimax_fc, "gbm": fit_predict_gbm}
bt = backtest(y, forecasters)
summary = bt.groupby("model")[["MAE", "RMSE", "MASE", "sMAPE"]].agg(["mean", "std"])
print(summary.round(2).to_string())
wins = bt.pivot(index="fold", columns="model", values="MAE")
print((wins["gbm"] < wins["seasonal_naive"]).sum(), "of", len(wins), "folds gbm beats snaive")
MAE RMSE MASE sMAPE
mean std mean std mean std mean std
model
ets 2.96 0.49 3.66 0.58 0.87 0.14 2.15 0.35
gbm 3.28 0.61 4.11 0.60 0.96 0.18 2.38 0.42
sarimax 2.59 0.23 3.22 0.31 0.76 0.07 1.88 0.19
seasonal_naive 4.22 0.56 5.14 0.74 1.24 0.16 3.06 0.41
7 of 8 folds gbm beats snaive
The ranking changed. On the single holdout the boosted model beat ETS; across eight origins ETS wins on every metric, and SARIMAX is best with the lowest spread. One split would have picked the wrong runner-up. Practical rules:
A planner needs to know whether "140" means 138 to 142 or 120 to 160. Statistical models produce intervals from their likelihood; for boosting, train separate quantile-loss models. Either way, check the empirical coverage: the share of actuals inside the interval across the backtest.
def gbm_quantiles(y_hist, h, qs=(0.1, 0.9)):
return {q: fit_predict_gbm(y_hist, h, loss="quantile", quantile=q) for q in qs}
def coverage(lo, hi, actual):
a = np.asarray(actual)
return float(np.mean((a >= np.asarray(lo)) & (a <= np.asarray(hi))))
cov = {"ets": [], "sarimax": [], "gbm_quantile": []}
first_origin = len(y) - H - 7 * 28
for fold in range(8):
origin = first_origin + fold * 28
y_tr, y_te = y.iloc[:origin], y.iloc[origin:origin + H]
m = ETSModel(y_tr, error="add", trend="add", damped_trend=True,
seasonal="add", seasonal_periods=7).fit(disp=False)
f = m.get_prediction(start=len(y_tr), end=len(y_tr) + H - 1).summary_frame(alpha=0.2)
cov["ets"].append(coverage(f["pi_lower"], f["pi_upper"], y_te))
idx = y_te.index
s = SARIMAX(y_tr, exog=fourier(y_tr.index), order=(1, 1, 1),
seasonal_order=(1, 0, 1, 7)).fit(disp=False, maxiter=200)
ci = s.get_forecast(H, exog=fourier(idx)).conf_int(alpha=0.2)
cov["sarimax"].append(coverage(ci.iloc[:, 0], ci.iloc[:, 1], y_te))
q = gbm_quantiles(y_tr, H)
cov["gbm_quantile"].append(coverage(q[0.1], q[0.9], y_te))
print({k: round(float(np.mean(v)), 3) for k, v in cov.items()})
{'ets': 0.754, 'sarimax': 0.754, 'gbm_quantile': 0.603}
Nominal coverage is 80%. ETS and SARIMAX reach 75%, typical because the intervals ignore model and parameter uncertainty. The quantile boosting models cover only 60%: trees fit training data more closely than they fit the future. The fix is calibration on out-of-sample residuals: collect backtest errors per horizon step and use their empirical quantiles, the idea behind split conformal prediction. Coverage belongs in the backtest report next to MAE.
Real problems rarely have one series. With hundreds of products or stores there are two strategies:
A global model needs per-series features and a common scale, so a series averaging 500 does not dominate one averaging 20. Each series is divided by its expanding mean of values at least H days old, so the scale uses only past data.
levels = np.random.default_rng(7).uniform(20, 500, size=30)
panel = pd.concat(
[make_series(level=lv, seed=100 + i).rename("y").to_frame().assign(series_id=f"s{i:02d}")
for i, lv in enumerate(levels)]
).rename_axis("ds").reset_index()
def panel_features(df, h):
df = df.sort_values(["series_id", "ds"]).copy()
g = df.groupby("series_id")["y"]
scale = g.transform(lambda s: s.shift(h).expanding().mean()) # past-only level
df["scale"] = scale
df["y_s"] = df["y"] / scale
gs = df.groupby("series_id")["y_s"]
for lag in (h, h + 7, h + 14, h + 336):
df[f"lag_{lag}"] = gs.shift(lag)
df["roll_mean_28"] = gs.transform(lambda s: s.shift(h).rolling(28).mean())
df["dow"] = df["ds"].dt.day_of_week
df["doy_sin"] = np.sin(2 * np.pi * df["ds"].dt.day_of_year / 365.25)
df["doy_cos"] = np.cos(2 * np.pi * df["ds"].dt.day_of_year / 365.25)
df["series_id"] = df["series_id"].astype("category")
return df
pf = panel_features(panel, H)
feats = [c for c in pf.columns if c.startswith(("lag_", "roll_", "doy_")) or c in ("dow", "series_id")]
cutoff = pf["ds"].max() - pd.Timedelta(days=H)
tr = pf[(pf["ds"] <= cutoff)].dropna(subset=feats + ["y_s"])
te = pf[pf["ds"] > cutoff]
glob = HistGradientBoostingRegressor(max_iter=400, learning_rate=0.05,
categorical_features="from_dtype", random_state=0)
glob.fit(tr[feats], tr["y_s"] - tr[f"lag_{H}"])
te = te.assign(pred=(glob.predict(te[feats]) + te[f"lag_{H}"]) * te["scale"])
def per_series(df):
hist = panel[(panel.series_id == df.name) & (panel.ds <= cutoff)]["y"]
snaive = np.resize(hist.iloc[-7:].to_numpy(), len(df))
return pd.Series({"MASE_global": mase(df["y"], df["pred"], hist),
"MASE_snaive": mase(df["y"], snaive, hist)})
scores = te.groupby("series_id", observed=True)[["y", "pred"]].apply(per_series)
print(scores.describe().loc[["mean", "50%", "max"]].round(3).to_string())
print("series where global beats snaive:", int((scores.MASE_global < scores.MASE_snaive).sum()), "/ 30")
MASE_global MASE_snaive
mean 0.753 1.254
50% 0.746 1.236
max 1.096 2.109
series where global beats snaive: 30 / 30
One model beats seasonal naive on all thirty series, mean MASE 0.75. Aggregate MASE, not MAE, or the largest series dominates the summary. On real data also report per segment (new, low volume, high volume), since a global average can hide a group where the baseline wins. For brevity this uses one cutoff; in practice, run the rolling-origin loop with features rebuilt per origin.
H steps old, and shift per series in panel data.error="mul") to the backtest and compare its coverage with the additive one.Found a mistake in this tutorial? Let us know and we will fix it.