Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 9 of 16
Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
Before training a forecast model for a small shop, decide what a wrong forecast costs. On synthetic milk, bread and rice demand, same weekday last week misses by 6.78 units, yesterday's sales by 18.97, and adding 5 units raises the error but cuts the bill from 17,365 to 14,032.
What you will learn
- Treat a forecast as a decision made before the day starts
- Price a short unit and an extra unit differently with a business_cost function
- Let the business set the forecast horizon
- Pick the plain baseline from the data and see why the lowest error is not always the lowest bill
Before you start
- Basic pandas (groupby and shift)
- Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
This is the first part of an end-to-end use case: a daily demand forecast for a small shop that sells milk, bread and rice. Over four parts we go from the business question to a nightly job, a read endpoint and a monitor that asks for a retrain. Today we don't train any model. We ask what the forecast is for, put a price on being wrong, and set a plain forecast that any model has to beat.
The demand data is synthetic, made by a small generator with seed 7, and the costs are assumptions I picked for this project. Read every number with that in mind.
Loaves before sunrise
Picture a bakery. The baker has to decide how many loaves to bake before the first customer walks in. Bake too few, and the shelf is empty by noon; those sales are gone. Bake too many, and some loaves are left at closing. That's a loss too, but a smaller one. And once the ovens are on, she can't change her mind, so she decides hours ahead.
So think of a forecast as a decision somebody makes before the day starts, with a bill attached if it's wrong. Our shop has exactly the same problem with milk, bread and rice.
A price on each mistake: cost.py
The first business question is what each kind of mistake costs. Here it lives in cost.py:
"""Business cost: a stock-out hurts more."""
import numpy as np
SHORT_COST = 3.0 # per unit we forecast too low
EXTRA_COST = 1.0 # per unit we forecast too high
def business_cost(actual, forecast):
gap = np.asarray(actual) - np.asarray(forecast)
short = np.clip(gap, 0, None).sum() * SHORT_COST
extra = np.clip(-gap, 0, None).sum() * EXTRA_COST
return float(short + extra)
def mae(actual, forecast):
gap = np.asarray(actual) - np.asarray(forecast)
return float(np.abs(gap).mean())
A unit we forecast too low costs 3, and a unit too high costs 1. That 3-to-1 is an assumption for this project. In a real shop, you'd ask the owner.
Try it on two small cases. Actual is 10 and the forecast is 8: we're short by 2, and 2 times 3 gives a cost of 6. Flip it. Actual is 10 and the forecast is 12: we're over by 2, and that costs only 2. Same size of miss, three times the bill. Mean absolute error treats those two the same, and business_cost doesn't. If the idea of a price per mistake is new, The Cost of Being Wrong builds it up for a classifier.
The horizon comes from the business
The second question is how far ahead the decision happens. If the owner orders tonight for tomorrow, the horizon is one day, and the newest number she has is from the day before. If the supplier needs three days' notice, the horizon becomes three days, and her newest number is three days old.
So the horizon isn't a modelling choice. It comes from the supplier and the shop, and you ask about it before you write any code. It also sets the rule for everything after: a forecast can only use what's known that far ahead.
The demand data
The data comes from data.py. Three products with base levels of 120 for milk, 80 for bread and 40 for rice, and on top of that a weekly wave, a slow upward trend and some noise:
"""Synthetic daily demand, three products."""
import numpy as np
import pandas as pd
PRODUCTS = {"milk": 120, "bread": 80, "rice": 40}
def make_demand(days=420, seed=7):
rng = np.random.default_rng(seed)
dates = pd.date_range("2025-01-01", periods=days)
rows = []
for name, base in PRODUCTS.items():
dow = dates.dayofweek
week = 1 + 0.35 * np.sin(2 * np.pi * dow / 7)
trend = 1 + 0.0008 * np.arange(days)
noise = rng.normal(0, 0.08 * base, days)
units = np.maximum(base * week * trend + noise, 0)
rows.append(pd.DataFrame({
"date": dates, "product": name,
"units": units.round()}))
return pd.concat(rows, ignore_index=True)
420 days times 3 products gives 1,260 rows, from 2025-01-01 to 2026-02-24. The first three milk rows are 161, 141 and 99. That's a big drop in two days, so the day of the week clearly matters here.
The line to beat: same weekday last week
What's the simplest forecast that respects the week? The same weekday, last week. It's one line in features.py:
def naive_forecast(df):
"""Same weekday last week."""
return df.groupby("product")["units"].shift(7)
We group by product and shift the units by seven, so every value slides seven days forward. On 15 January, milk sold 162. A week earlier it sold 175, so this guess is off by 13. It needs no training, and you can explain it to the owner in one sentence. If a model can't beat this, we don't need the model. (Lags and shift are covered in Time Series Basics, so I won't re-teach them here.)
Three plain guesses, scored on the same rows
Is that really the best plain guess? baseline_check.py scores several guesses on the same rows, every day that has a last-week value:
"""Simple guesses on simulated demand, seed 7."""
from cost import business_cost, mae
from data import make_demand
def results():
df = make_demand()
g = df.groupby("product")["units"]
week = g.shift(7)
ok = week.notna()
units = df.loc[ok, "units"]
guesses = {
"yesterday": g.shift(1),
"3 days back": g.shift(3),
"last week": week,
"last week + 5": week + 5,
"last week + 10": week + 10,
}
rows = []
for name, guess in guesses.items():
rows.append({
"guess": name,
"mae": round(mae(units, guess[ok]), 2),
"cost": round(business_cost(units, guess[ok])),
})
return {"rows": len(units), "guesses": rows}
if __name__ == "__main__":
res = results()
print(f"{res['rows']} rows, simulated demand")
for r in res["guesses"]:
print(f"{r['guess']:<15} mae {r['mae']:>6.2f}"
f" cost {r['cost']:>6}")
Running python baseline_check.py prints:
1239 rows, simulated demand
yesterday mae 18.97 cost 47072
3 days back mae 41.13 cost 102159
last week mae 6.78 cost 17365
last week + 5 mae 7.93 cost 14032
last week + 10 mae 11.11 cost 15719
Read the first three lines:
- Yesterday's sales miss by 18.97 units a day.
- 3 days back, which is what you'd have with three days' notice, misses by 41.13. Now we land on a different part of the week.
- Same weekday last week misses by just 6.78, and it's already known for any horizon up to seven days.
So the data picks the baseline. Here the weekly pattern matters more than how fresh the number is.
Lower error, lower bill?
Now price that baseline. An error of 6.78 comes with a bill of 17,365 (in units of the 3-to-1 rule). The last two lines simulate a change to the order: add 5 units to every forecast, so we lean towards extra stock. The error gets worse, up to 7.93. But the bill comes down to 14,032. Push it to 10 extra and both move against us: the error is 11.11 and the bill climbs back to 15,719. So there's a limit.
baseline_check.py on 1,239 rows of synthetic demand. Bar lengths are to scale within each chart.So the most accurate forecast and the cheapest order can be two different numbers. That's why we agree on the cost before we train anything. Once a model looks good, it's tempting to pick whichever metric flatters it.
Common mistakes
- Starting with a model. Without a baseline, a model's error has nothing to be compared with. Here the plain guess already sits at 6.78.
- Treating the horizon as a tuning knob. If the supplier needs three days' notice, a feature from yesterday is not allowed, however much it helps the score.
- Choosing the freshest number by habit. Yesterday's sales sound sensible and miss by 18.97, almost three times the weekly guess.
- Reporting only MAE. MAE can't see that a short unit hurts more than an extra one, so it can rank forecasts in the wrong order for the bill.
Recap
| Idea | In this project |
|---|---|
| A forecast is a decision | Made before the day starts, with a bill if it's wrong |
| Price per mistake | Short 3, extra 1 (assumed) |
| Horizon | Set by the supplier and the shop, and it limits what a forecast may know |
| Baseline | Same weekday last week: MAE 6.78, cost 17,365 on 1,239 rows |
| Error vs bill | +5 units: MAE 7.93 but cost 14,032 |
Try it yourself: set SHORT_COST to 5 in cost.py, run python baseline_check.py again, and see which version now gives the lowest bill. The starter and finished project files are in the community, free to join.
Next, in Part 2, we train models against this baseline with a walk-forward backtest.
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
Related course on Udemy
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 (paid course, opens in a new tab)Related posts
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.