Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 10 of 16
Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
Walk forward through four 28-day folds of synthetic shop demand. Ridge beats the same-weekday baseline in all 12 product-fold cells (MAE 5.81 vs 6.91), default gradient boosting lands at 6.07, a new product is short for weeks, and a leaky rolling mean fakes a drop to 5.19.
What you will learn
- Build lag features that only use what was known before the day
- Score a forecast with a four-fold walk-forward backtest against the same-weekday baseline
- Compare Ridge with a gradient boosting model on the same folds and features
- Find what the average hides: a new product and a leaky feature
Before you start
- Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
- Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
In Part 1 we set the line to beat for our shop: same weekday last week, with a short unit costing 3 and an extra unit costing 1 (assumed). Now we train forecast models and test them the way they'd actually be used: one stretch of days at a time, with the future covered. We'll put a simple model against a boosted one, and then look at where a good average hides a bad forecast.
The demand is still synthetic (milk, bread and rice, seed 7). Please don't expect results this clean on a real shop.
Past seasons, one at a time
Say you've got a new stocking plan and five years of records. How do you test it? You open the records up to the end of one season and cover everything after that with your hand. You decide using only what's showing, then uncover the next season and score yourself. Then you move your hand forward one season and do it again. You get many honest exams, and in every one the future stays covered. That's a walk-forward backtest.
Features from the past: features.py
You've built lags before (Time Series Basics covers them), so here we just apply them:
def add_lags(df, leak=False):
out = df.copy()
g = out.groupby("product")["units"]
out["lag_7"] = g.shift(7)
out["lag_14"] = g.shift(14)
out["mean_7"] = g.transform(
lambda s: s.shift(1).rolling(7).mean())
if leak:
out["mean_7"] = g.transform(
lambda s: s.rolling(2).mean())
out["dow"] = out["date"].dt.dayofweek
return out.dropna().reset_index(drop=True)
Fill in the row for milk on 15 January 2025:
| Feature | Meaning | Value |
|---|---|---|
lag_7 | Same weekday last week | 175 |
lag_14 | Same weekday two weeks back | 161 |
mean_7 | Mean of the 7 days ending yesterday (note the shift(1) before rolling) | 121.1 |
dow | Day of the week | 2 (a Wednesday) |
The first 14 days of each product have no lag_14, so they drop out. 1,260 rows become 1,218. Ignore the leak flag for now; we'll switch it on at the end.
Walk forward through time: backtest.py
A random split would let the model train on the future, so we walk forward instead:
"""Walk-forward backtest, one model for all products."""
import pandas as pd
from sklearn.linear_model import Ridge
from cost import business_cost, mae
from data import make_demand
from features import add_lags
COLS = ["lag_7", "lag_14", "mean_7", "dow"]
def walk_forward(df, folds=4, horizon=28):
rows = []
last = df["date"].max()
for k in range(folds, 0, -1):
cut = last - pd.Timedelta(days=horizon * k)
end = cut + pd.Timedelta(days=horizon)
train = df[df["date"] <= cut]
test = df[df["date"].between(cut, end)]
test = test[test["date"] > cut]
model = Ridge().fit(train[COLS], train["units"])
pred = model.predict(test[COLS])
test = test.assign(pred=pred)
for name, part in test.groupby("product"):
rows.append({
"fold": folds - k + 1, "product": name,
"naive_mae": mae(part.units, part.lag_7),
"model_mae": mae(part.units, part.pred),
"model_cost": business_cost(part["units"],
part["pred"]),
})
return pd.DataFrame(rows)
- Four folds of 28 days, so the first cut sits four windows before the end of the data.
- Everything up to the cut is training; the 28 days after it are the test.
- One Ridge model is fitted across all products, then each product is scored on its own.
- Every test row carries features from just before its day, so each one is a next-day forecast.
- Then the cut moves forward 28 days. Training grows, the test slides, and we do it again.
What Ridge scored
Three products times four folds gives twelve cells. Here is the mean absolute error of each:
| Fold | Product | Baseline MAE | Ridge MAE |
|---|---|---|---|
| 1 | bread | 7.89 | 6.65 |
| 1 | milk | 7.50 | 7.04 |
| 1 | rice | 3.32 | 3.02 |
| 2 | bread | 6.75 | 5.95 |
| 2 | milk | 10.64 | 8.49 |
| 2 | rice | 3.93 | 3.10 |
| 3 | bread | 7.93 | 5.29 |
| 3 | milk | 10.21 | 8.49 |
| 3 | rice | 3.29 | 3.00 |
| 4 | bread | 6.82 | 6.36 |
| 4 | milk | 11.14 | 9.36 |
| 4 | rice | 3.50 | 2.99 |
Ridge beats the same-weekday baseline in all twelve. Running python backtest.py prints the per-product means:
naive_mae model_mae
product
bread 7.35 6.06
milk 9.88 8.35
rice 3.51 3.03
Over all the test days, the baseline misses by 6.91 and Ridge by 5.81. On the 3-to-1 cost rule, the baseline comes to 4,722 and Ridge to 3,806. (These are the backtest test days only, so they're not comparable with the 6.78 and 17,365 from Part 1, which were measured on all 1,239 rows.)
Now look at milk across the folds: 7.04 in fold 1, 9.36 in fold 4. A single split would have shown you one of those and hidden the spread.
A boosted model: same folds, one line changed
Ridge is simple, so let's try something stronger. boosted_slices.py uses GradientBoostingRegressor with default settings and random_state=7, on the same features and the same folds. Only the model changes:
def ridge():
return Ridge()
def boosted():
return GradientBoostingRegressor(random_state=7)
Running python boosted_slices.py prints:
simulated demand, 4 folds
naive mae 6.91 cost 4722
ridge mae 5.81 cost 3806
boosted mae 6.07 cost 4348
boosted beats ridge in 4 of 12
The boosted model beats the baseline but not Ridge, on error (6.07 against 5.81) and on cost (4,348 against 3,806). It wins only 4 of the 12 cells. Tuning might close the gap, but that's the result we got with defaults. So the backtest gets the final say, not the name of the model. (For how boosting works, see Boosting.)
Slice 1: a new product
A good average can hide a bad forecast. So the script adds a simulated new product, oats, launched 70 days before the end and ramping up over its first 28 days. The rest of the output:
oats, first forecast at age 14 days
milk, bread, rice mae 5.83
age 14-27 days 14 units 44.9 naive 9.29 model 12.47 bias -12.47
age 28-41 days 14 units 59.1 naive 6.07 model 8.51 bias -8.36
age 42-69 days 28 units 60.2 naive 5.0 model 4.75 bias 1.02
- No forecast at all for 14 days.
lag_14needs two weeks of history, so oats has no row until it's 14 days old. - Days 14 to 27: the model misses by 12.47 and the plain guess by 9.29. The model loses. The bias is also -12.47, the same size as the error, so it's short every single day, and short is the expensive side.
- Days 28 to 41: still behind, 8.51 against 6.07.
- From day 42: the climb is over and oats is in the training data. Now it's 4.75 against 5.0.
Meanwhile milk, bread and rice average 5.83 in this same backtest. That number never showed you any of this. Scoring group by group is the idea behind Slice Evaluation.
boosted_slices.py. Bars are to scale.Slice 2: a score that's too good
One more failure, and this one flatters you. With leak=True, mean_7 becomes s.rolling(2).mean() with no shift. That window covers yesterday and today, and today is the answer we're trying to predict. Half of the feature is the answer itself.
naive_mae model_mae
product
bread 7.35 5.35
milk 9.88 7.46
rice 3.51 2.76
The overall error drops from 5.81 to 5.19, and the cost from 3,806 to about 3,430. Nothing warns you. So ask one question of every feature: would I know this value when I place the order? If not, that gain won't show up in the shop. The general version of this trap is in Train-Test Split and Data Leakage.
Common mistakes
- A random split on time data. The model trains on days after the ones it's tested on.
- One test window. Milk ranged from 7.04 to 9.36 across folds; one window shows you one number.
- Trusting a stronger model's name. Default boosting lost to Ridge here.
- Reading only the average. The new product was short for weeks while the average looked fine.
- A rolling window without a shift. It quietly includes the target.
Recap
| Run | MAE | Cost |
|---|---|---|
| Same-weekday baseline (4 folds) | 6.91 | 4,722 |
| Ridge | 5.81 | 3,806 |
| Gradient boosting, defaults | 6.07 | 4,348 |
| Ridge with the leak (not real) | 5.19 | about 3,430 |
Try it yourself: change shift(1) to shift(3) in mean_7, run python backtest.py again, and see whether Ridge still beats 6.91.
In Part 3, the forecast becomes a job that runs every night on its own.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
Next →Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.