Skip to content

Capstone 6 — Demand forecasting

The supply team of the store chain orders stock every four weeks. Each order must cover the next 28 days. Today the planners use one rule: “next week sells like last week”. The head of supply asks you for a better plan:

  1. A daily units forecast, 28 days ahead. The team turns it into weekly order quantities.
  2. A range, not only a number. The team holds safety stock: extra stock above the forecast that protects against a stockout when demand is higher than planned. It needs a band to size it.
  3. A fair comparison. A colleague says a classical statistical model is enough. Another wants machine learning. The head of supply wants the evidence, and she wants to know where each model fails.
  4. A recommendation. Which model to use, how to use its band and on which days the planners must not trust it.

The forecast supports two decisions: the weekly order quantity and the size of the safety stock.

Deliverables:

  • One script, demand_forecast.py, that runs from the project folder and prints every number it uses.
  • A backtest table that compares every model on MAE, RMSE and MASE.
  • A holdout report: the scores of the two last 28-day plans, scored once, a forecast chart with an 80% band and an error analysis by day type.
  • The forecast for 2025-01-01 to 2025-01-28 as a weekly plan, and a recommendation memo for the supply team.

How this capstone goes beyond module 40. The module 40 mini-project forecast the same daily units with five folds, one 28-day holdout and lag features that are at least 28 days old. This capstone adds the parts that a real planning job needs: an explicit zero fill per category (ready for category forecasts; the total series has no gap), a holiday and promotion calendar used by both models, a one-year backtest with 13 forecast origins, a LightGBM model that uses the newest data on each origin, a forecast combination, mean forecasts for weekly sums, daily and weekly bands with a coverage check and an 8-week holdout that contains Black Friday.

Skills practiced:

Module What you use it for
25. pandas advanced pivot_table, reindex, rolling, shift, resample
26. Data cleaning missing rows that mean zero, not unknown
27. Exploratory data analysis weekday and month profiles, event uplift against a baseline
28. Visualization a mosaic figure, a forecast chart with a band
29. Statistics and probability quantiles, interval coverage
33. Feature engineering lag, rolling, calendar and holiday features
37. Model evaluation and tuning choose on the backtest, score the holdout once
38. Ensembles LightGBM, averaging two models
40. Time series baselines, SARIMAX, TimeSeriesSplit, MASE

One file: data/sales.csv, 20,228 order lines from 2023-01-01 to 2024-12-31. The data dictionary describes every column.

Column Use
order_date the day of the sale; the time index
category one of six product categories; used for the zero-fill check
quantity units on the line; summed per day, this is the target
revenue summed per day for the noise comparison in milestone 3

Facts from the data dictionary that matter here:

  • Every day of 2023–2024 has orders (731 days). The total is 29,533 units.
  • Volume grows about 45% from the start to the end of the period. Saturday is the peak. There is a November–December peak and a January–February dip.
  • Promotion days: Black Friday (2023-11-24, 2024-11-29), the weekend after it, Cyber Monday (2023-11-27, 2024-12-02) and summer sales (2023-07-11/12, 2024-07-16/17). Low days: Thanksgiving and 2024-01-01. On 2023-12-25 and 2024-12-25 the stores are closed, so all orders are online.
  • 29 bulk lines have 10–25 units. They add spikes that no calendar explains.
  • Daily revenue is noisy because of high-price electronics. Daily units are a smoother target, and stock is counted in units.

Known quirk. A day with no sale has no row. The total series has a row for every day, but a single category does not. Milestone 1 counts those category-days and fills them with 0 on purpose.

The calendar. Both models may use event days, because the supply team knows the holiday and promotion calendar in advance. Thanksgiving comes from a pandas holiday rule; Black Friday, its weekend and Cyber Monday follow from it. The summer sale dates come from the marketing plan (the data dictionary lists them).

Milestone 1 — Build and validate the daily series

Section titled “Milestone 1 — Build and validate the daily series”

Goal: one daily units series that you can trust, with no silent gaps.

Acceptance criteria:

  • Build units per category and day with a full daily calendar. Count the category-days with no row, then fill them with 0 explicitly.
  • Build daily units and daily revenue on the same calendar.
  • Assert: the index equals the calendar, no value is missing, the units total equals the order lines (29,533), the revenue total matches within 0.01, and every day has units.

Review: 25. pandas advanced, 26. Data cleaning.

Goal: keep an honest test that no modeling choice has seen.

Acceptance criteria:

  • Split off the last 8 weeks (56 days) before any exploration or modeling choice.
  • The holdout holds two planning windows of 28 days. Print the origin of each plan (the last day of data the planners have) and the days it covers.
  • From here until milestone 8, every choice uses only the training data.

Review: 37. Model evaluation and tuning, 40. Time series.

Milestone 3 — Explore seasonality and events

Section titled “Milestone 3 — Explore seasonality and events”

Goal: know the patterns that a 28-day forecast must reproduce.

Acceptance criteria:

  • Build the event calendar (holidays and promotions) for every day of the data and the 28 days after it.
  • On the training data, measure each event day against a baseline: the median of the same weekday in the four weeks before.
  • Print a weekday index per year, the mean units per day per month and year (complete months only) and the growth from 2023 to 2024.
  • Compare the noise of daily units and daily revenue with one number.
  • One figure with three panels: the training series with a rolling mean and the event days, the weekly pattern and the yearly pattern.

Review: 27. Exploratory data analysis, 28. Visualization.

Milestone 4 — Baselines and the backtest harness

Section titled “Milestone 4 — Baselines and the backtest harness”

Goal: a fair test bench and the numbers to beat.

Acceptance criteria:

  • Write MAE, RMSE and MASE (scaled by the in-sample weekly seasonal naive error).
  • Write two baselines: naive (repeat the last day) and seasonal naive (repeat the last week; the current rule).
  • Create a rolling-origin backtest with TimeSeriesSplit(n_splits=13, test_size=28) on the training data: 13 forecast origins, one year of test days. Print the folds and the event days in each.
  • Write one backtest function that every model goes through, with an assert that training ends before testing starts. Score the baselines.

Review: 40. Time series, 37. Model evaluation and tuning.

Milestone 5 — Classical model: SARIMAX with event regressors

Section titled “Milestone 5 — Classical model: SARIMAX with event regressors”

Goal: a statistical model that knows the weekly pattern and the calendar.

Acceptance criteria:

  • SARIMAX on the log of units, weekly seasonal period, with the event columns as exogenous regressors.
  • Compare at least three candidates on the training data with AIC, with the same differencing, including one with yearly Fourier terms. State the choice rule before you look at the table.
  • Every fit converges (mle_retvals["converged"]) and prints no warning.
  • Print the chosen model’s event effects as multipliers.
  • Forecast the mean, not the median: back-transform the log forecast with exp⁡(μ+σ2/2)\exp(\mu + \sigma^2/2).

Review: 40. Time series.

Milestone 6 — ML model: LightGBM with lag, rolling, calendar and holiday features

Section titled “Milestone 6 — ML model: LightGBM with lag, rolling, calendar and holiday features”

Goal: a machine learning model that uses the newest data on every forecast origin.

Acceptance criteria:

  • Build a multi-horizon training table: one row per (origin, horizon) pair, for horizons 1 to 28. Features are known on the origin: recent levels, the newest same-weekday value, the value a year ago, the target day’s weekday and month, and its event flags. The horizon is a feature too.
  • The target is the log ratio of the target day to the 28-day level on the origin, so the trees do not need to extrapolate the trend.
  • LGBMRegressor with verbose=-1, random_state=42 and a few hundred trees.
  • Prove with an assert that the features of an origin do not change when later days exist.

Review: 33. Feature engineering, 38. Ensembles, 40. Time series.

Milestone 7 — Compare all models in the backtest and build bands

Section titled “Milestone 7 — Compare all models in the backtest and build bands”

Goal: choose one model with the backtest only, and give it an honest band.

Acceptance criteria:

  • Backtest SARIMAX and LightGBM with the same harness. Add a forecast combination: the mean of the SARIMAX and LightGBM forecasts.
  • Print the MAE per fold and the mean MAE, RMSE and MASE per model, plus the folds each model wins. Choose the model with the lowest mean MAE.
  • Check the bias of the 28-day totals: print forecast ÷ actual per fold and model.
  • Build a residual-based prediction band for each model: the 10% and 90% quantiles of the backtest ratio actual ÷ forecast, per week of the horizon.
  • Build a weekly band from the backtest weekly totals, and compare its coverage with summed daily band edges.

Review: 37. Model evaluation and tuning, 29. Statistics and probability.

Milestone 8 — Score the holdout once and recommend

Section titled “Milestone 8 — Score the holdout once and recommend”

Goal: tell the supply team how good the plan is and how to use it.

Acceptance criteria:

  • Make the two holdout plans exactly as the planners would: refit every model on the data up to each origin, then forecast 28 days. Score all models once.
  • Check the coverage of the 80% bands (the share of days inside the band), for the chosen model’s backtest band and for the SARIMAX model interval.
  • Compare errors on event days and other days, and the weekly totals with the weekly band and its coverage.
  • One chart of both plans with the band.
  • Forecast 2025-01-01 to 2025-01-28 and print it as a weekly plan with the weekly band. If the evidence says the chosen model fails on this plan, say so and print the plan you recommend instead.
  • A memo of five to seven recommendations. Each number comes from the printed output.

Review: 28. Visualization, 27. Exploratory data analysis, 40. Time series.

Score each criterion at one level. The maximum is 40 points.

Criterion Needs work (0–1) Meets (2–3) Excellent (4–5) Max
Daily series Missing days not checked Full calendar, explicit zero fill, totals asserted Plus category-level gaps counted and a revenue cross-check 5
Holdout discipline Holdout used for a choice 8-week holdout locked before modeling Two planning windows, refit per origin, scored once 5
Exploration One line chart Weekly and yearly patterns quantified Event uplift against a stated baseline, on training data only 5
Baselines and harness A single train/test split Naive, seasonal naive and TimeSeriesSplit One harness for every model, asserts on fold order, a full year of origins 5
Classical model Orders guessed, warnings shown SARIMAX chosen by AIC, converged Event regressors, a yearly candidate, a stated choice rule, readable effects 5
ML model Features that see the future Lags and calendar features with verbose=-1 Origin-based features, a horizon feature, a leakage assert 5
Comparison and bands One metric, one fold MAE, RMSE and MASE per fold, model chosen on the backtest Plus a combination and residual-based bands with a coverage check 5
Recommendation Only the winning score A model, a band and a weekly plan Failure cases (promo days, season turns) with numbers and actions 5
Total 40

32 points or more: you are ready for Capstone 7.

Try each milestone yourself first. Your names and chart styling can differ; with the same models and seeds your numbers must not. The blocks run top to bottom as one script, demand_forecast.py, in about 30 seconds.

Reference solution — Milestone 1: Build and validate the daily series

Step 1 — Imports and settings. Two constants fix the planning horizon and the holdout length.

demand_forecast.py (setup)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from lightgbm import LGBMRegressor
from pandas.tseries.holiday import USThanksgivingDay
from sklearn.model_selection import TimeSeriesSplit
from statsmodels.tsa.statespace.sarimax import SARIMAX
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
HORIZON = 28 # the supply team plans 4 weeks ahead
HOLDOUT_DAYS = 2 * HORIZON # the last 8 weeks: two plans, locked until milestone 8

Step 2 — Units per category on a full calendar. reindex(calendar) adds a row for every day, so a day with no sale shows up as a missing value that you can count.

demand_forecast.py (milestone 1a)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
calendar = pd.date_range(sales["order_date"].min(), sales["order_date"].max())
by_category = sales.pivot_table(
index="order_date", columns="category", values="quantity", aggfunc="sum"
).reindex(calendar)
print(by_category.isna().sum().to_frame("days with no sale").T)
by_category = by_category.fillna(0).astype(int) # no sale means 0 units, not unknown
Output
category Beauty Books Clothing Electronics Home Sports
days with no sale 29 42 14 10 17 19

Every category has days with no row. Here a missing row means “nothing sold”, so 0 is the correct value. An interpolation would invent sales. The fill is explicit, so a reader sees the decision.

Step 3 — Daily units and revenue, with checks. The total is the sum of the categories. The asserts tie the series to the order lines and to the data dictionary.

demand_forecast.py (milestone 1b)
units = by_category.sum(axis=1).astype(float).rename("units")
revenue = sales.groupby("order_date")["revenue"].sum().reindex(calendar, fill_value=0.0)
daily = pd.DataFrame({"units": units, "revenue": revenue})
print(f"{len(daily)} days, {calendar[0].date()} to {calendar[-1].date()}")
assert units.index.equals(calendar) and units.notna().all()
assert units.sum() == sales["quantity"].sum() == 29_533
assert abs(revenue.sum() - sales["revenue"].sum()) < 0.01
assert (units > 0).all() # every day has orders, as the data dictionary says
Output
731 days, 2023-01-01 to 2024-12-31

The total series has no gap, so the zero fill does not change it. The fill matters for any category-level work, such as stretch goal 1. The script describes the values only after milestone 2 locks the holdout.

Reference solution — Milestone 2: Lock the final holdout

The holdout is split off before any chart or test. The supply team plans every 28 days, so the 8-week holdout is two plans. Each plan is made on its forecast origin, the last day with data.

demand_forecast.py (milestone 2)
train = units.iloc[:-HOLDOUT_DAYS]
ORIGINS = [train.index[-1], train.index[-1] + pd.Timedelta(days=HORIZON)]
print(f"train {train.index[0].date()} to {train.index[-1].date()}: {len(train)} days")
for k, origin in enumerate(ORIGINS, start=1):
first, last = origin + pd.Timedelta(days=1), origin + pd.Timedelta(days=HORIZON)
print(f"plan {k} made on {origin.date()}, covers {first.date()} to {last.date()}")
assert ORIGINS[1] + pd.Timedelta(days=HORIZON) == units.index[-1]
print(daily.loc[train.index].describe().T[["mean", "std", "min", "50%", "max"]])
Output
train 2023-01-01 to 2024-11-05: 675 days
plan 1 made on 2024-11-05, covers 2024-11-06 to 2024-12-03
plan 2 made on 2024-12-03, covers 2024-12-04 to 2024-12-31
mean std min 50% max
units 37.467 16.637 5.00 35.00 214.00
revenue 4542.826 2594.424 162.76 4066.76 31222.69

The smallest training day has 5 units, so the log of units is defined. The models use it. From here until milestone 8, all code uses train. Two places touch units earlier, and neither makes a choice: the event calendar (known in advance) and the leakage check in milestone 6.

Reference solution — Milestone 3: Explore seasonality and events

Step 1 — The event calendar. The calendar covers the data and the 28 days after it, because a forecast needs the events of the days it predicts.

demand_forecast.py (milestone 3a)
future_days = pd.date_range(calendar[-1] + pd.Timedelta(days=1), periods=HORIZON)
all_days = calendar.append(future_days)
thanksgiving = USThanksgivingDay.dates(all_days[0], all_days[-1])
SUMMER_SALES = ["2023-07-11", "2023-07-12", "2024-07-16", "2024-07-17"]
def after_thanksgiving(*offsets: int) -> pd.DatetimeIndex:
return pd.DatetimeIndex(
[day + pd.Timedelta(days=n) for day in thanksgiving for n in offsets]
)
EVENT_DAYS = {
"thanksgiving": thanksgiving,
"black_friday": after_thanksgiving(1),
"bf_weekend": after_thanksgiving(2, 3),
"cyber_monday": after_thanksgiving(4),
"summer_sale": pd.DatetimeIndex(SUMMER_SALES),
"christmas": all_days[(all_days.month == 12) & (all_days.day == 25)],
"new_year": all_days[(all_days.month == 1) & (all_days.day == 1)],
}
events = pd.DataFrame(
{name: all_days.isin(days).astype(float) for name, days in EVENT_DAYS.items()},
index=all_days,
)
print(events.groupby(events.index.year).sum().astype(int))
Output
thanksgiving black_friday bf_weekend cyber_monday summer_sale christmas new_year
2023 1 1 2 1 2 1 1
2024 1 1 2 1 2 1 1
2025 0 0 0 0 0 0 1

Step 2 — How big is each event? Compare each event day in the training data with the median of the same weekday in the four weeks before.

demand_forecast.py (milestone 3b)
baseline = pd.concat([train.shift(7 * w) for w in range(1, 5)], axis=1).median(axis=1)
seen = events.loc[train.index]
uplift = pd.DataFrame(
[{"day": day.date(), "event": name, "units": train[day],
"baseline": baseline[day], "ratio": train[day] / baseline[day]}
for name in events.columns for day in seen.index[seen[name] == 1]]
).dropna() # 2023-01-01 has no earlier weeks
print(uplift.to_string(index=False))
Output
day event units baseline ratio
2023-11-23 thanksgiving 22.0 29.5 0.746
2023-11-24 black_friday 214.0 42.5 5.035
2023-11-25 bf_weekend 95.0 45.0 2.111
2023-11-26 bf_weekend 79.0 57.0 1.386
2023-11-27 cyber_monday 67.0 23.0 2.913
2023-07-11 summer_sale 41.0 22.5 1.822
2023-07-12 summer_sale 56.0 32.0 1.750
2024-07-16 summer_sale 68.0 32.0 2.125
2024-07-17 summer_sale 77.0 41.0 1.878
2023-12-25 christmas 7.0 47.0 0.149
2024-01-01 new_year 24.0 40.0 0.600

Black Friday 2023 sold about 5 times a normal Friday. The weekend after it and Cyber Monday sold 1.4 to 2.9 times their baseline. The summer sales roughly doubled their days. Christmas Day and Thanksgiving are low days. Each event has one or two examples in the training data, so every model learns its size from very little evidence.

Step 3 — Weekly and yearly patterns. November 2024 has only 5 training days, so the month table uses complete months.

demand_forecast.py (milestone 3c)
weekday = train.groupby([train.index.year, train.index.day_of_week]).mean().unstack()
weekday = weekday.div(weekday.mean(axis=1), axis=0)
weekday.columns = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print("weekday index (1 = average day of that year):")
print(weekday.round(2))
full_months = train.loc[:"2024-10-31"]
monthly = (
full_months.groupby([full_months.index.year, full_months.index.month])
.mean()
.unstack()
)
print("mean units per day by month:")
print(monthly.round(1))
growth = monthly.loc[2024, 1:10].mean() / monthly.loc[2023, 1:10].mean() - 1
print(f"Jan-Oct growth 2023 -> 2024: {growth:+.1%}")
day_revenue = revenue.loc[train.index]
noise = {name: float((s - s.shift(7)).abs().mean() / s.mean())
for name, s in [("units", train), ("revenue", day_revenue)]}
print("weekly naive MAE / mean:", {k: round(v, 3) for k, v in noise.items()})
Output
weekday index (1 = average day of that year):
Mon Tue Wed Thu Fri Sat Sun
2023 0.81 0.82 0.92 0.89 1.12 1.3 1.14
2024 0.86 0.84 0.88 0.92 1.07 1.3 1.14
mean units per day by month:
1 2 3 4 5 6 7 8 9 10 11 12
2023 28.1 25.0 26.3 29.1 36.8 36.8 34.7 37.7 35.7 34.4 49.6 58.5
2024 30.4 31.5 35.7 34.6 37.8 43.3 45.3 43.4 41.4 43.7 NaN NaN
Jan-Oct growth 2023 -> 2024: +19.2%
weekly naive MAE / mean: {'units': 0.372, 'revenue': 0.5}

The weekly shape is stable across the two years: Saturday is about 30% above an average day, Monday and Tuesday 14–19% below. The yearly shape repeats too, at a higher level in 2024: about +19% from January to October. November and December 2023 sit far above the rest of the year. The relative error of “same day last week” is 37% for units and 50% for revenue: revenue is the noisier target, so units are the right series to plan stock.

Step 4 — One figure for the three patterns.

demand_forecast.py (milestone 3d)
fig, axes = plt.subplot_mosaic(
[["series", "series"], ["weekday", "month"]], figsize=(11, 7)
)
ax = axes["series"]
ax.plot(train, color="0.6", linewidth=0.8, label="daily units")
ax.plot(train.rolling(28).mean(), color="tab:blue", label="28-day mean")
flagged = seen.index[seen.any(axis=1)]
ax.scatter(flagged, train[flagged], color="tab:red", s=18, zorder=3, label="event day")
ax.set(title="Training data: growth, a November-December peak and event spikes",
ylabel="units per day")
ax.legend(loc="upper left")
weekday.T.plot(ax=axes["weekday"], marker="o")
axes["weekday"].axhline(1, color="0.5", linewidth=0.8)
axes["weekday"].set(title="Weekly pattern: Saturday peak",
ylabel="index (1 = average day)")
monthly.T.plot(ax=axes["month"], marker="o")
axes["month"].set(title="Yearly pattern: mean units per day", xlabel="month",
ylabel="units per day", xticks=range(1, 13))
fig.tight_layout()
plt.show()
Three panels. Top: daily units from January 2023 to early November 2024 with a rising 28-day mean, a spike above 200 units on Black Friday 2023 and red event markers at the summer sales, Thanksgiving, Christmas and New Year. Bottom left: the weekday index for 2023 and 2024 nearly overlaps, lowest on Monday and Tuesday and highest on Saturday at about 1.3. Bottom right: mean units per day by month; 2024 runs above 2023 in every month, and 2023 climbs steeply in November and December.
The training data: a trend, a stable weekly shape, a yearly peak and a few large event days.
Reference solution — Milestone 4: Baselines and the backtest harness

Step 1 — Metrics and baselines. MASE divides the MAE by the in-sample error of the weekly seasonal naive forecast. Below 1 means better than “same day last week” is inside the training data.

demand_forecast.py (milestone 4a)
def mae(actual, forecast) -> float:
return float(np.mean(np.abs(np.asarray(actual) - np.asarray(forecast))))
def rmse(actual, forecast) -> float:
return float(np.sqrt(np.mean((np.asarray(actual) - np.asarray(forecast)) ** 2)))
def mase(actual, forecast, history: pd.Series, m: int = 7) -> float:
"""MAE divided by the in-sample MAE of the weekly seasonal naive forecast."""
values = history.to_numpy()
return mae(actual, forecast) / float(np.mean(np.abs(values[m:] - values[:-m])))
def naive(history: pd.Series, target: pd.DatetimeIndex) -> np.ndarray:
return np.full(len(target), history.iloc[-1])
def seasonal_naive(history: pd.Series, target: pd.DatetimeIndex) -> np.ndarray:
return np.resize(history.iloc[-7:].to_numpy(), len(target))

Step 2 — Thirteen forecast origins. With test_size=28, each fold is one planning window. Thirteen folds cover a full year of test days, so every season, including the 2023 holiday peak, is tested once.

demand_forecast.py (milestone 4b)
FOLDS = list(TimeSeriesSplit(n_splits=13, test_size=HORIZON).split(train))
fold_info = pd.DataFrame(
[{"fold": k, "train days": len(tr), "test from": train.index[te[0]].date(),
"test to": train.index[te[-1]].date(),
"event days": int(events.loc[train.index[te]].any(axis=1).sum())}
for k, (tr, te) in enumerate(FOLDS, start=1)]
)
print(fold_info.to_string(index=False))
Output
fold train days test from test to event days
1 311 2023-11-08 2023-12-05 5
2 339 2023-12-06 2024-01-02 2
3 367 2024-01-03 2024-01-30 0
4 395 2024-01-31 2024-02-27 0
5 423 2024-02-28 2024-03-26 0
6 451 2024-03-27 2024-04-23 0
7 479 2024-04-24 2024-05-21 0
8 507 2024-05-22 2024-06-18 0
9 535 2024-06-19 2024-07-16 1
10 563 2024-07-17 2024-08-13 1
11 591 2024-08-14 2024-09-10 0
12 619 2024-09-11 2024-10-08 0
13 647 2024-10-09 2024-11-05 0

Fold 1 tests Black Friday 2023 with a model that has never seen a Black Friday. That is the hardest fold on purpose: it is what happens with the first promotion of its kind.

Step 3 — One harness for every model. A forecaster is any function (history, target days) -> forecasts. The harness calls it on every fold and keeps every test day, so later steps can compute any metric or band.

demand_forecast.py (milestone 4c)
def backtest(forecasters: dict) -> pd.DataFrame:
"""One row per test day of every fold, one column per forecaster."""
parts = []
for k, (tr, te) in enumerate(FOLDS, start=1):
history, test = train.iloc[tr], train.iloc[te]
assert history.index[-1] < test.index[0] # only the past predicts
part = pd.DataFrame({"fold": k, "h": np.arange(1, HORIZON + 1),
"actual": test}, index=test.index)
for name, forecaster in forecasters.items():
part[name] = forecaster(history, test.index)
parts.append(part)
return pd.concat(parts)
def score(wide: pd.DataFrame, models: list[str], series: pd.Series) -> pd.DataFrame:
"""MAE, RMSE and MASE per fold and model; MASE scaled on the days before."""
rows = []
for k, part in wide.groupby("fold"):
history = series.loc[: part.index[0] - pd.Timedelta(days=1)]
for m in models:
rows.append({"fold": k, "model": m, "MAE": mae(part["actual"], part[m]),
"RMSE": rmse(part["actual"], part[m]),
"MASE": mase(part["actual"], part[m], history)})
return pd.DataFrame(rows)
BASELINES = ["naive", "seasonal naive"]
results = backtest({"naive": naive, "seasonal naive": seasonal_naive})
base_scores = score(results, BASELINES, train).groupby("model")[["MAE", "RMSE", "MASE"]]
print(base_scores.mean().round(2))
Output
MAE RMSE MASE
model
naive 16.94 21.33 1.24
seasonal naive 15.16 19.46 1.10

score takes the MASE scale from the days before each test window only. The current rule, seasonal naive, misses by about 15 units a day on average. That is the number to beat.

Reference solution — Milestone 5: Classical model, SARIMAX with event regressors

Step 1 — Candidates and the choice rule. All candidates model the log of units with one regular and one weekly difference, so their AIC values are comparable. Fourier terms are sine and cosine waves with a yearly period; two pairs give a smooth yearly shape. The rule, fixed before the table: keep the candidate with the fewest parameters among those within 2 AIC points of the best.

demand_forecast.py (milestone 5a)
def fourier(index: pd.DatetimeIndex, k: int, period: float = 365.25) -> pd.DataFrame:
"""k sine-cosine pairs with a yearly period: a smooth yearly shape."""
t = (index - index[0]).days.to_numpy()
return pd.DataFrame(
{f"{fn.__name__}{i}": fn(2 * np.pi * i * t / period)
for i in range(1, k + 1) for fn in (np.sin, np.cos)},
index=index,
)
YEARLY = fourier(all_days, k=2)
def regressors(days: pd.DatetimeIndex, seen: pd.DatetimeIndex, yearly: bool):
"""Event columns seen after a 28-day warm-up, plus optional yearly terms."""
cols = events.columns[events.loc[seen[28:]].any()]
exog = events.loc[days, cols]
return exog.join(YEARLY.loc[days]) if yearly else exog
def fit_sarimax(history: pd.Series, order: tuple, yearly: bool = False):
exog = regressors(history.index, history.index, yearly)
model = SARIMAX(np.log(history), exog=exog, order=order,
seasonal_order=(0, 1, 1, 7))
result = model.fit(disp=False, maxiter=200)
assert result.mle_retvals["converged"], order
return result
CANDIDATES = {
"(0,1,1)(0,1,1)7 + events": {"order": (0, 1, 1)},
"(1,1,1)(0,1,1)7 + events": {"order": (1, 1, 1)},
"(0,1,2)(0,1,1)7 + events": {"order": (0, 1, 2)},
"(0,1,1)(0,1,1)7 + events + yearly": {"order": (0, 1, 1), "yearly": True},
}
fits = {name: fit_sarimax(train, **spec) for name, spec in CANDIDATES.items()}
aic = pd.DataFrame({"params": [len(r.params) for r in fits.values()],
"AIC": [r.aic for r in fits.values()]}, index=list(fits))
aic["delta"] = aic["AIC"] - aic["AIC"].min()
print(aic.round(1))
CHOSEN = aic[aic["delta"] <= 2].sort_values(["params", "AIC"]).index[0]
SPEC = CANDIDATES[CHOSEN]
print("chosen:", CHOSEN)
Output
params AIC delta
(0,1,1)(0,1,1)7 + events 10 570.6 0.0
(1,1,1)(0,1,1)7 + events 11 571.2 0.6
(0,1,2)(0,1,1)7 + events 11 571.3 0.7
(0,1,1)(0,1,1)7 + events + yearly 14 571.9 1.3
chosen: (0,1,1)(0,1,1)7 + events

regressors keeps only the event columns that occur in the history after its first 28 days. In fold 1 no Black Friday is in the history yet, and a column of zeros would leave its coefficient undefined. The warm-up drops 2023-01-01, the first day of the series: one day with no past is too little to estimate a New Year effect. The AR term, a second MA term and the yearly terms all fail to lower the AIC. The airline model wins: SARIMA (0,1,1)(0,1,1)s(0,1,1)(0,1,1)_s, one regular and one seasonal difference with one MA term each, here with s=7s = 7 and the event regressors.

Step 2 — Read the chosen model and back-transform to a mean. On the log scale, exp(coefficient) is a multiplier: the factor by which the event changes the units of a normal day. A second point matters for stock. exp of a log-scale forecast is the median forecast, not the mean. Weekly orders are sums of daily forecasts, and sums need means, so medians would under-order. If the log forecast is normal with variance σh2\sigma_h^2, the mean is exp⁡(μh+σh2/2)\exp(\mu_h + \sigma_h^2 / 2).

demand_forecast.py (milestone 5b)
chosen_fit = fits[CHOSEN]
multipliers = np.exp(chosen_fit.params[events.columns])
print(multipliers.round(2).to_frame("multiplier").T)
print("other parameters:", chosen_fit.params.drop(events.columns).round(3).to_dict())
def sarimax_forecast(history: pd.Series, target: pd.DatetimeIndex) -> np.ndarray:
"""Mean forecast in units: exp(mean + variance / 2) of the log forecast."""
result = fit_sarimax(history, **SPEC)
exog = regressors(target, history.index, SPEC.get("yearly", False))
fc = result.get_forecast(len(target), exog=exog)
return np.exp(fc.predicted_mean + fc.var_pred_mean / 2).to_numpy()
fc = chosen_fit.get_forecast(HORIZON, exog=regressors(future_days, train.index, False))
mean_over_median = np.exp(fc.var_pred_mean.to_numpy() / 2)
print(f"mean / median: {mean_over_median[0]:.3f} at h=1, "
f"{mean_over_median[-1]:.3f} at h=28")
Output
thanksgiving black_friday bf_weekend cyber_monday summer_sale christmas new_year
multiplier 0.57 4.71 1.61 1.8 1.91 0.17 0.82
other parameters: {'ma.L1': -0.901, 'ma.S.L7': -0.999, 'sigma2': 0.127}
mean / median: 1.066 at h=1, 1.085 at h=28

The model says Black Friday multiplies a normal Friday by about 4.7 and Christmas Day keeps about a sixth of a normal day. Those two agree with the event table of milestone 3. Cyber Monday, Thanksgiving and New Year differ from it, because each rests on one or two noisy examples. The seasonal MA coefficient is almost exactly −1. That means the weekly shape is close to fixed: the weekly difference and this term together act like constant weekday effects. This matches the stable weekday index of milestone 3. The last line shows the size of the mean correction: the mean is 6.6% above the median one day ahead and 8.5% above it 28 days ahead.

Reference solution — Milestone 6: ML model, LightGBM with lag, rolling, calendar and holiday features

Step 1 — Features known on the origin. The module 40 model used only lags that are at least 28 days old, so one feature table worked for every horizon. Here each row is one (origin, horizon) pair. A forecast made on a Tuesday can use Monday’s sales for every day it predicts, and the horizon h tells the model how far ahead it looks. All lag and rolling features are relative to the 28-day level on the origin.

demand_forecast.py (milestone 6a)
def origin_features(log_y: pd.Series, h: int) -> pd.DataFrame:
"""For each origin day: features known that day, for the target day origin + h."""
level = log_y.rolling(28).mean()
target_days = log_y.index + pd.Timedelta(days=h)
weeks_back = -(-h // 7) # the newest value of the target's weekday
feats = pd.DataFrame(
{"h": h,
"last_7": log_y.rolling(7).mean() - level,
"same_weekday": log_y.shift(7 * weeks_back - h) - level,
"year_ago": log_y.shift(364 - h) - level.shift(364),
"day_of_week": target_days.day_of_week,
"month": target_days.month},
index=log_y.index,
)
return feats.join(events.reindex(target_days).set_axis(log_y.index))
def training_rows(history: pd.Series) -> tuple[pd.DataFrame, pd.Series]:
"""One row per (origin, horizon) pair whose target is in the history."""
log_y = np.log(history)
level = log_y.rolling(28).mean()
X, y = [], []
for h in range(1, HORIZON + 1):
target = log_y.shift(-h) - level # log(target day / 28-day level at origin)
known = target.notna() & level.notna()
X.append(origin_features(log_y, h)[known])
y.append(target[known])
return pd.concat(X), pd.concat(y)
def lgbm_forecast(history: pd.Series, target: pd.DatetimeIndex) -> np.ndarray:
X, y = training_rows(history)
model = LGBMRegressor(n_estimators=300, learning_rate=0.05, num_leaves=15,
min_child_samples=20, subsample=0.8, subsample_freq=1,
colsample_bytree=0.8, n_jobs=1, random_state=42, verbose=-1)
model.fit(X, y)
log_y = np.log(history)
origin = history.index[-1]
rows = pd.concat([origin_features(log_y, h).loc[[origin]]
for h in range(1, len(target) + 1)])
return np.exp(model.predict(rows) + log_y.iloc[-28:].mean())

year_ago compares the target’s weekday 52 weeks earlier with the level a year before the origin. It carries the yearly shape as a ratio, so it still works when the level has grown. Before a full year of history exists the feature is missing, and LightGBM handles missing values natively. The trees predict a log ratio; lgbm_forecast adds the log level back and takes exp.

Step 2 — Look at the table and prove that it does not leak.

demand_forecast.py (milestone 6b)
X_train, y_train = training_rows(train)
print("training rows:", X_train.shape)
log_train = np.log(train)
plan_rows = pd.DataFrame(
{f"h={h}": origin_features(log_train, h).iloc[-1] for h in (1, 24)}
)
print(f"prediction rows on {train.index[-1].date()}:")
print(plan_rows.round(3))
# No leakage: the features of an origin are the same whether or not later days exist.
for h in (1, 28):
with_future = origin_features(np.log(units), h).loc[train.index[-1]]
pd.testing.assert_series_equal(with_future, origin_features(log_train, h).iloc[-1])
Output
training rows: (17738, 13)
prediction rows on 2024-11-05:
h=1 h=24
h 1.000 24.000
last_7 0.183 0.183
same_weekday -0.112 0.170
year_ago 0.119 1.002
day_of_week 2.000 4.000
month 11.000 11.000
thanksgiving 0.000 0.000
black_friday 0.000 1.000
bf_weekend 0.000 0.000
cyber_monday 0.000 0.000
summer_sale 0.000 0.000
christmas 0.000 0.000
new_year 0.000 0.000

On 2024-11-05, horizon 24 is Black Friday 2024, and its row has black_friday = 1. Its year_ago value is about 1.0 on the log scale: 52 weeks earlier, on Friday 2023-12-01, the chain sold about e ≈ 2.7 times the level of the year-ago origin. That is the 2023 holiday ramp. Black Friday moves with Thanksgiving, so a 364-day lag does not land on last year’s Black Friday; the event flag carries the spike instead. The assert rebuilds the features from the full series, holdout included, and finds the same values: no feature looks past its origin.

Reference solution — Milestone 7: Compare all models in the backtest and build bands

Step 1 — Backtest the two models and their combination. The combination needs no extra fit: it is the mean of two forecasts that already exist.

demand_forecast.py (milestone 7a)
models = {"SARIMAX": sarimax_forecast, "LightGBM": lgbm_forecast}
results = results.join(backtest(models)[list(models)])
results["SARIMAX + LightGBM"] = results[["SARIMAX", "LightGBM"]].mean(axis=1)
MODELS = [*BASELINES, *models, "SARIMAX + LightGBM"]
scores = score(results, MODELS, train)
by_fold = scores.pivot(index="fold", columns="model", values="MAE")[MODELS]
print(by_fold.round(1))
summary = scores.groupby("model")[["MAE", "RMSE", "MASE"]].mean()
wins = by_fold.idxmin(axis=1).value_counts()
summary["folds won"] = wins.reindex(summary.index, fill_value=0)
summary = summary.sort_values("MAE")
print(summary.round(2))
BEST = summary.index[0]
print("chosen model:", BEST)
gap = by_fold[BEST] - by_fold["SARIMAX"]
print(f"{BEST} vs SARIMAX: better in {(gap < 0).sum()} of 13 folds, "
f"mean MAE gap {gap.mean():+.2f} (standard error {gap.sem():.2f})")
assert BEST == "SARIMAX + LightGBM"
assert summary.loc[BEST, "MAE"] < summary.loc["seasonal naive", "MAE"]
Output
model naive seasonal naive SARIMAX LightGBM SARIMAX + LightGBM
fold
1 35.2 22.5 22.1 23.2 22.4
2 23.1 19.3 15.6 17.5 13.5
3 11.0 23.8 31.0 15.6 22.8
4 11.0 12.0 8.2 9.6 8.5
5 12.1 9.7 8.4 9.5 8.7
6 18.4 13.9 7.7 10.6 8.8
7 10.7 11.2 9.1 9.2 9.0
8 13.2 10.7 8.6 8.4 8.3
9 12.3 13.6 8.0 10.6 8.9
10 24.4 14.0 8.0 10.2 9.0
11 14.5 17.0 13.2 14.2 13.5
12 14.3 13.2 9.5 10.2 9.1
13 20.0 16.1 10.9 11.5 10.4
MAE RMSE MASE folds won
model
SARIMAX + LightGBM 11.76 15.33 0.86 5
SARIMAX 12.32 15.73 0.90 7
LightGBM 12.33 16.53 0.90 0
seasonal naive 15.16 19.46 1.10 0
naive 16.94 21.33 1.24 1
chosen model: SARIMAX + LightGBM
SARIMAX + LightGBM vs SARIMAX: better in 6 of 13 folds, mean MAE gap -0.56 (standard error 0.68)

SARIMAX and LightGBM tie on mean MAE (12.32 and 12.33). SARIMAX wins more folds and has the lower RMSE, so it makes fewer large misses. Their errors differ from fold to fold: in fold 3, the January after the holiday peak, SARIMAX misses by 31.0 units a day and LightGBM by 15.6. Averaging the two cancels part of each model’s errors, so the combination has the lowest mean MAE, RMSE and MASE, and by the rule fixed in the milestone it is the chosen model. Its edge is small: it beats SARIMAX in 6 of 13 folds, and the mean gap of −0.56 units has a standard error of 0.68, so the two are statistically tied. The clear result is that all three beat the current rule. The baselines still win some folds: seasonal naive is close to the best in fold 1 (the first Black Friday, 22.5), and “repeat the last day” wins fold 3 (11.0).

Step 2 — Are the 28-day totals biased? The planners order the sum of the daily forecasts, so a forecast that is a few percent low every day becomes a short order. Compare the forecast total of each fold with the actual total.

demand_forecast.py (milestone 7b)
totals = results.groupby("fold")[["actual", *MODELS]].sum()
ratio = totals[MODELS].div(totals["actual"], axis=0)
print("28-day total, forecast / actual:")
print(ratio.round(2))
print(pd.DataFrame({"median, all folds": ratio.median(),
"mean, folds 4-13": ratio.loc[4:].mean()}).T.round(3))
Output
28-day total, forecast / actual:
naive seasonal naive SARIMAX LightGBM SARIMAX + LightGBM
fold
1 0.35 0.69 0.67 0.64 0.66
2 0.66 0.92 0.86 1.18 1.02
3 0.74 1.70 1.97 1.37 1.67
4 0.72 1.01 0.96 0.85 0.91
5 0.71 0.93 1.03 1.01 1.02
6 0.47 1.02 1.06 1.23 1.15
7 0.91 0.90 0.99 1.04 1.02
8 0.73 0.95 0.99 0.89 0.94
9 0.83 0.91 0.98 0.82 0.90
10 1.53 1.12 1.06 1.09 1.07
11 0.85 0.95 1.04 1.00 1.02
12 0.68 1.05 1.07 0.90 0.98
13 0.60 0.88 0.91 0.87 0.89
naive seasonal naive SARIMAX LightGBM SARIMAX + LightGBM
median, all folds 0.721 0.946 0.994 1.003 1.019
mean, folds 4-13 0.804 0.972 1.010 0.971 0.991

No model is far off on the totals once SARIMAX uses the mean back-transform: the median ratio is between 0.99 and 1.02, and outside the holiday folds (4–13) between 0.97 and 1.01. Without the correction of milestone 5, SARIMAX would sit about 7–8% lower (the mean/median factor of 1.066–1.085). LightGBM needs no correction here: its median ratio is 1.00. The fold-to-fold scatter (0.82 to 1.23 for LightGBM in folds 4–13) is much larger than any remaining bias, so a further scale factor would be fitting noise. Folds 1 and 3 show the real problem: about 0.66 of the units in the first holiday season, and 1.4 to 2.0 times the units in the January after it.

Step 3 — Bands from the backtest errors. For each model and each week of the horizon, take the 10% and 90% quantiles of actual ÷ forecast. Multiplying a new forecast by these two factors gives an 80% band that reflects the errors the model really made on 13 origins.

demand_forecast.py (milestone 7c)
log_errors = np.log(results[MODELS].rdiv(results["actual"], axis=0))
log_errors["week"] = (results["h"] - 1) // 7 + 1
BANDS = np.exp(log_errors.groupby("week").quantile([0.1, 0.9])) # 80% band factors
print(BANDS[["seasonal naive", "SARIMAX", "LightGBM", BEST]].unstack().round(2).T)
print("log scale,", BEST, "week 1:", np.log(BANDS.loc[1, BEST]).round(2).to_dict())
def band_factors(model: str, h: pd.Series) -> tuple[np.ndarray, np.ndarray]:
"""Daily 80% band factors for the horizons in `h`."""
weeks = (h.to_numpy() - 1) // 7 + 1
return (BANDS.xs(0.1, level=1)[model].loc[weeks].to_numpy(),
BANDS.xs(0.9, level=1)[model].loc[weeks].to_numpy())
Output
week 1 2 3 4
seasonal naive 0.1 0.53 0.56 0.54 0.62
0.9 1.97 1.67 1.85 1.95
SARIMAX 0.1 0.60 0.55 0.54 0.55
0.9 1.44 1.41 1.70 1.43
LightGBM 0.1 0.66 0.59 0.55 0.64
0.9 1.57 1.50 1.81 1.67
SARIMAX + LightGBM 0.1 0.65 0.58 0.54 0.62
0.9 1.46 1.43 1.59 1.49
log scale, SARIMAX + LightGBM week 1: {0.1: -0.43, 0.9: 0.38}

For the combination, the band in week 1 runs from 0.65 to 1.46 times the forecast. It is asymmetric in units only because the errors are multiplicative: on the log scale the band is nearly symmetric (−0.43 to +0.38 in week 1). The band does not widen steadily with the horizon: most of the error is day-to-day noise, not drift.

Step 4 — A weekly band from weekly errors. The supply team orders by week. Adding up the daily band edges of seven days gives a band that is too wide: high and low days within a week partly cancel. Build the weekly band from the backtest weekly totals instead, and compare the two on the 52 backtest weeks.

demand_forecast.py (milestone 7d)
def weekly_totals(frame: pd.DataFrame, cols: list[str]) -> pd.DataFrame:
"""Sums over each 7-day block of each plan (h 1-7, 8-14, 15-21, 22-28)."""
return frame.groupby([frame["fold"], (frame["h"] - 1) // 7 + 1])[cols].sum()
week_sums = weekly_totals(results, ["actual", *MODELS])
week_ratio = week_sums[MODELS].rdiv(week_sums["actual"], axis=0)
WEEKLY_BANDS = week_ratio.quantile([0.1, 0.9])
lo_factor, hi_factor = band_factors(BEST, results["h"])
edges = weekly_totals(results.assign(lo=results[BEST] * lo_factor,
hi=results[BEST] * hi_factor), ["lo", "hi"])
low, high = WEEKLY_BANDS[BEST]
weekly_check = pd.DataFrame(
{"low factor": [low, (edges["lo"] / week_sums[BEST]).mean()],
"high factor": [high, (edges["hi"] / week_sums[BEST]).mean()],
"coverage": [week_ratio[BEST].between(low, high).mean(),
week_sums["actual"].between(edges["lo"], edges["hi"]).mean()]},
index=["weekly errors", "summed daily edges"],
)
print(f"{BEST}, 52 backtest weeks:")
print(weekly_check.round(2))
print("weekly band factors:")
print(WEEKLY_BANDS[["SARIMAX", "LightGBM", BEST]].round(2))
Output
SARIMAX + LightGBM, 52 backtest weeks:
low factor high factor coverage
weekly errors 0.81 1.20 0.77
summed daily edges 0.60 1.49 0.94
weekly band factors:
SARIMAX LightGBM SARIMAX + LightGBM
0.1 0.83 0.78 0.81
0.9 1.25 1.29 1.20

The weekly band from weekly errors runs from 0.81 to 1.20 times the weekly forecast and covers 77% of the 52 backtest weeks, close to its 80% target. The summed daily edges average 0.60 to 1.49 and cover 94%: their upper edge is almost 30 points of the forecast higher, which would tie up stock for no benefit. The weekly band is the one to size safety stock with.

Reference solution — Milestone 8: Score the holdout once and recommend

Step 1 — Make the two plans and score them, once. Each plan refits every model on the data up to its origin, as the planners would. No choice changes here: the models, the rule and the bands are fixed. SARIMAX also returns its own 80% interval, for comparison.

demand_forecast.py (milestone 8a)
def sarimax_with_band(history, target, alpha=0.2):
"""Mean forecast and the model's own (1 - alpha) prediction interval."""
result = fit_sarimax(history, **SPEC)
exog = regressors(target, history.index, SPEC.get("yearly", False))
fc = result.get_forecast(len(target), exog=exog)
band = np.exp(fc.conf_int(alpha=alpha).to_numpy())
mean = np.exp(fc.predicted_mean + fc.var_pred_mean / 2).to_numpy()
return mean, band[:, 0], band[:, 1]
plans = []
for k, origin in enumerate(ORIGINS, start=1):
history = units.loc[:origin]
target = pd.date_range(origin + pd.Timedelta(days=1), periods=HORIZON)
plan = pd.DataFrame({"fold": k, "h": np.arange(1, HORIZON + 1),
"actual": units.loc[target]}, index=target)
plan["naive"] = naive(history, target)
plan["seasonal naive"] = seasonal_naive(history, target)
plan["SARIMAX"], plan["sarimax_lo"], plan["sarimax_hi"] = sarimax_with_band(
history, target
)
plan["LightGBM"] = lgbm_forecast(history, target)
plans.append(plan)
final = pd.concat(plans)
final["SARIMAX + LightGBM"] = final[["SARIMAX", "LightGBM"]].mean(axis=1)
assert final.index.equals(units.index[-HOLDOUT_DAYS:])
holdout_scores = score(final, MODELS, units)
print("holdout MAE per plan:")
by_plan = holdout_scores.pivot(index="fold", columns="model", values="MAE")
print(by_plan[MODELS].round(1))
holdout_summary = holdout_scores.groupby("model")[["MAE", "RMSE", "MASE"]].mean()
print(holdout_summary.loc[summary.index].round(2))
baseline_mae = holdout_summary.loc[BASELINES, "MAE"].min()
assert holdout_summary.loc[["SARIMAX", "LightGBM", BEST], "MAE"].max() < baseline_mae
Output
holdout MAE per plan:
model naive seasonal naive SARIMAX LightGBM SARIMAX + LightGBM
fold
1 30.4 26.2 16.1 16.9 16.0
2 21.0 64.8 12.8 21.8 14.9
MAE RMSE MASE
model
SARIMAX + LightGBM 15.45 22.86 1.09
SARIMAX 14.49 22.04 1.03
LightGBM 19.36 27.18 1.37
seasonal naive 45.48 67.13 3.20
naive 25.73 40.29 1.83

The holdout does not repeat the backtest order: SARIMAX has the lowest holdout MAE (14.49), the combination is second (15.45) and LightGBM third (19.36). This is consistent with the backtest, where SARIMAX and the combination were tied within noise; the choice stays as fixed before the holdout. What the holdout does confirm: every model beats both baselines by a wide margin. The baselines also swap places: naive beats seasonal naive here, because the seasonal naive forecast of plan 2 copies the Black Friday week into December. Every MASE is higher than in the backtest: November and December are harder than an average month.

Step 2 — Do the bands hold?

demand_forecast.py (milestone 8b)
lo_factor, hi_factor = band_factors(BEST, final["h"])
final["lo"], final["hi"] = final[BEST] * lo_factor, final[BEST] * hi_factor
bands = {
f"{BEST}, backtest band": ("lo", "hi"),
"SARIMAX, model interval": ("sarimax_lo", "sarimax_hi"),
}
coverage = pd.DataFrame(
{"coverage": [final["actual"].between(final[lo], final[hi]).mean()
for lo, hi in bands.values()],
"mean width": [(final[hi] - final[lo]).mean() for lo, hi in bands.values()]},
index=list(bands),
)
print("80% bands on the 56 holdout days:")
print(coverage.round(2))
assert coverage["coverage"].between(0.7, 1).all()
Output
80% bands on the 56 holdout days:
coverage mean width
SARIMAX + LightGBM, backtest band 0.91 64.79
SARIMAX, model interval 0.91 63.35

Both 80% daily bands contain the actual units on 91% of the holdout days, and both are 63–65 units wide on average. They are a little wide for 80%, which is the safe side for safety stock. Fifty-six correlated days are too few to tune them further. The backtest band is easier to explain to planners, and it works for any model, including the combination, which has no interval of its own.

Step 3 — Where does the plan fail?

demand_forecast.py (milestone 8c)
is_event = events.loc[final.index].any(axis=1)
final["event"] = events.loc[final.index].idxmax(axis=1).where(is_event, "")
print(final.loc[is_event, ["event", "actual", "SARIMAX", "LightGBM", BEST, "hi"]]
.round(0))
day_type = is_event.map({True: "event days", False: "other days"})
print(pd.DataFrame(
{m: (final[m] - final["actual"]).abs().groupby(day_type).mean() for m in MODELS}
).round(1))
weekly = final[["actual", BEST]].resample("W-TUE", label="right", closed="right").sum()
weekly["error %"] = 100 * (weekly[BEST] / weekly["actual"] - 1)
weekly["low"], weekly["high"] = weekly[BEST] * low, weekly[BEST] * high
weekly["inside"] = weekly["actual"].between(weekly["low"], weekly["high"])
weekly.index.name = "week to"
print(weekly.round(1))
print(f"weekly band coverage on the holdout: {weekly['inside'].mean():.0%}")
Output
event actual SARIMAX LightGBM SARIMAX + LightGBM hi
2024-11-28 thanksgiving 32.0 28.0 32.0 30.0 44.0
2024-11-29 black_friday 242.0 268.0 248.0 258.0 384.0
2024-11-30 bf_weekend 179.0 115.0 93.0 104.0 155.0
2024-12-01 bf_weekend 119.0 99.0 106.0 102.0 152.0
2024-12-02 cyber_monday 185.0 81.0 86.0 83.0 124.0
2024-12-25 christmas 16.0 11.0 14.0 13.0 19.0
naive seasonal naive SARIMAX LightGBM SARIMAX + LightGBM
event days 98.7 96.2 37.3 34.4 35.9
other days 17.0 39.4 11.7 17.6 13.0
actual SARIMAX + LightGBM error % low high inside
week to
2024-11-12 400.0 358.9 -10.3 290.6 430.8 True
2024-11-19 424.0 378.5 -10.7 306.4 454.2 True
2024-11-26 414.0 370.4 -10.5 299.9 444.6 True
2024-12-03 892.0 676.6 -24.2 547.8 811.9 False
2024-12-10 510.0 562.9 10.4 455.7 675.5 True
2024-12-17 615.0 571.3 -7.1 462.5 685.5 True
2024-12-24 527.0 597.6 13.4 483.8 717.2 True
2024-12-31 461.0 541.1 17.4 438.1 649.4 True
weekly band coverage on the holdout: 88%

Black Friday itself is forecast well: LightGBM is 6 units over and the combination 16 units over, because the SARIMAX regressor and the LightGBM event flag both carry the 2023 spike. The days after it are not. Cyber Monday 2024 sold 185 units against a combined forecast of 83, above the daily upper band of 124. In 2023 Cyber Monday was a much smaller day, and the models had only that one example. On event days the combination misses by about 36 units a day, almost three times its error on other days. The weekly totals show a second failure: every week of plan 1 is 10–11% short even with mean forecasts, and the Black Friday week is 24% short, the one week outside the weekly band (7 of 8 weeks inside, 88%). The models start November near the October level and only partly see the holiday ramp.

Step 4 — Chart both plans.

demand_forecast.py (milestone 8d)
fig, ax = plt.subplots(figsize=(11, 4.5))
ax.plot(units.loc["2024-10-15":"2024-11-05"], color="0.6", label="training data")
ax.plot(final["actual"], color="black", linewidth=1.8, label="actual (holdout)")
for k, plan in final.groupby("fold"):
first = k == 1 # label each line once
ax.fill_between(plan.index, plan["lo"], plan["hi"], color="tab:green",
alpha=0.2, label="80% band" if first else None)
ax.plot(plan[BEST], color="tab:green", linewidth=1.8,
label=BEST if first else None)
ax.plot(plan["SARIMAX"], color="tab:blue", linewidth=0.9, linestyle="--",
label="SARIMAX" if first else None)
ax.plot(plan["LightGBM"], color="tab:orange", linewidth=0.9, linestyle="--",
label="LightGBM" if first else None)
ax.axvline(ORIGINS[1], color="0.4", linestyle=":", linewidth=1)
ax.scatter(final.index[is_event], final.loc[is_event, "actual"], color="tab:red",
zorder=3, s=20, label="event day")
ax.set(title="Two 28-day plans on the locked holdout", ylabel="units per day")
ax.legend(loc="upper left", ncols=2, fontsize=8)
plt.show()
Daily units from mid-October to the end of December 2024. The holdout actual line moves between about 35 and 95 units through November, jumps to about 240 units on Black Friday and stays high over the weekend and Cyber Monday. The green combined forecast follows the weekly shape and hits the Black Friday spike, but stays well below the Saturday after it and Cyber Monday, which sit above the green 80% band. In December the actual values mostly stay inside the band, with a drop on Christmas Day that the forecast also shows. A dotted vertical line marks the second plan on December 3.
The combined forecast and its 80% band for the two holdout plans. The Saturday after Black Friday and Cyber Monday break out of the band.

Step 5 — The plan for January 2025. Refit on all 731 days and forecast the next 28. Two checks put the result in context: the backtest fold that started after the 2023 holiday peak, and a year-ago ratio.

demand_forecast.py (milestone 8e)
target = future_days
plan = pd.DataFrame(index=target)
plan["SARIMAX"] = sarimax_forecast(units, target)
plan["LightGBM"] = lgbm_forecast(units, target)
plan[BEST] = plan[["SARIMAX", "LightGBM"]].mean(axis=1)
print("fold 3 (January 2024):")
fold3 = pd.DataFrame({"MAE": by_fold.loc[3], "forecast / actual": ratio.loc[3]})
print(fold3.T.round(2))
jan_vs_dec = units.loc["2024-01-01":"2024-01-28"].mean() / units.loc["2023-12"].mean()
year_ago_check = units.loc["2024-12"].mean() * jan_vs_dec * HORIZON
print(f"year-ago check for Jan 1-28, 2025: {year_ago_check:,.0f} units")
# January override: LightGBM's daily shape, scaled to the midpoint of its total
# and the year-ago check.
lgbm_total = plan["LightGBM"].sum()
plan["January plan"] = plan["LightGBM"] * (lgbm_total + year_ago_check) / 2 / lgbm_total
weeks = plan.resample("W-TUE", label="right", closed="right").sum()
weeks["low"] = weeks["January plan"] * WEEKLY_BANDS.loc[0.1, "LightGBM"]
weeks["high"] = weeks["January plan"] * WEEKLY_BANDS.loc[0.9, "LightGBM"]
weeks.index.name = "week to"
print(weeks.round(0))
print(weeks.drop(columns=["low", "high"]).sum().round(0).to_frame("28-day total").T)
assert len(plan) == HORIZON and (plan > 0).all().all()
Output
fold 3 (January 2024):
naive seasonal naive SARIMAX LightGBM SARIMAX + LightGBM
MAE 10.96 23.82 31.00 15.63 22.77
forecast / actual 0.74 1.70 1.97 1.37 1.67
year-ago check for Jan 1-28, 2025: 1,194 units
SARIMAX LightGBM SARIMAX + LightGBM January plan low high
week to
2025-01-07 557.0 366.0 461.0 332.0 260.0 427.0
2025-01-14 578.0 356.0 467.0 323.0 253.0 416.0
2025-01-21 586.0 378.0 482.0 344.0 269.0 442.0
2025-01-28 595.0 364.0 479.0 331.0 259.0 425.0
SARIMAX LightGBM SARIMAX + LightGBM January plan
28-day total 2315.0 1465.0 1890.0 1330.0

The two models disagree strongly about January: 2,315 units for SARIMAX against 1,465 for LightGBM. SARIMAX has no yearly component, so it carries the December level forward. LightGBM sees the January dip through year_ago. The backtest already showed this risk in fold 3 (January 2024): SARIMAX forecast 1.97 times the units sold, LightGBM 1.37 times, and “repeat the last day” had the lowest error. The year-ago check (December 2024 scaled by last year’s January-to-December ratio) gives 1,194 units. So for this one plan the script overrides the combination: the January plan keeps LightGBM’s daily shape and scales it to the midpoint of LightGBM and the year-ago check, 1,330 units. Its weekly band uses LightGBM’s weekly factors. The override is a judgment based on one backtest fold and one year-ago ratio, so the planners should replan after the first week.

Step 6 — The memo for the supply team.

  1. Use the combination of SARIMAX and LightGBM for the regular 28-day plan. It had the lowest backtest MAE (11.76 units a day against 15.16 for “same day last week”). Its edge over SARIMAX alone is within noise, and on the holdout SARIMAX was slightly better (14.49 against 15.45); both cut the current rule’s holdout error (45.48) by about two thirds.
  2. Size weekly safety stock with the weekly band, not with summed daily edges. Order the forecast, and hold stock up to 1.20 times the weekly forecast. That band covered 77% of the backtest weeks and 7 of the 8 holdout weeks. Summed daily edges (up to 1.49 times) covered 94% and would hold far more stock.
  3. Add a manual uplift for the promotion weekend and Cyber Monday. The models get Black Friday about right but under-forecast the following days: Cyber Monday 2024 sold 185 units against a forecast of 83, above the band. Each promotion has one or two past examples. Ask marketing for the expected size of each promotion and plan those days by hand.
  4. Expect the November plan to fall short. With mean forecasts the totals are unbiased on average over the year, but every week of the November holdout plan was 10–11% below the actual units. That shortfall is the holiday ramp, which the models see only once in two years. Add an uplift to the November weeks and review it weekly.
  5. For January 2025, use the January plan, not the combination. Order 332, 323, 344 and 331 units for the four weeks (1,330 in total), with a weekly band of about 253 to 442. The combined forecast (1,890) repeats the fold-3 error of January 2024, when SARIMAX forecast 1.97 times the units sold. Replan after the first week.
  6. Classical versus ML: neither wins alone. SARIMAX wins more folds, has the best holdout score and is easy to read (event multipliers). LightGBM handles the turn after the holiday peak better (fold 3: 15.6 against 31.0 units a day). Averaging them is cheap and at least as good as the better of the two on the backtest.
  7. Refit every 4 weeks and track the error. Rerun the backtest each quarter and check that the bias stays near 1 and the band coverage near 80%.

How it works:

  1. Trust the series first. The explicit zero fill and the asserts make a silent gap impossible.
  2. Lock the test before looking. The holdout is split before any chart, and the models, the choice rule and the bands are fixed before it is scored.
  3. Test like you plan. Every fold is a 28-day plan made on one origin. Thirteen origins cover a full year, so the backtest includes a holiday season and a summer sale.
  4. Give both models the calendar. Known future events go into SARIMAX as regressors and into LightGBM as features. Both learn the size of each event from one or two examples, which explains where they fail.
  5. Use the newest data. The multi-horizon table lets LightGBM use the last day before the origin for every horizon, and the log-ratio target removes the trend that trees cannot extrapolate.
  6. Means for sums, bands from real errors. SARIMAX forecasts are back-transformed to means, because orders add up daily forecasts. The backtest quantiles turn 364 daily errors and 52 weekly errors per model into bands that any model, even a combination, can use. The holdout checks their coverage.

Alternative: replace SARIMAX with exponential smoothing (statsmodels.tsa.holtwinters.ExponentialSmoothing with a weekly season) plus a separate event multiplier table. It is faster to fit, but the events then need their own estimate instead of coming out of one model.

  1. Forecast by category. Forecast each category’s units with the same harness and add the forecasts up. Compare the sum with the total forecast in the backtest. Which categories carry the November ramp?
  2. Quantile LightGBM. Train LGBMRegressor(objective="quantile", alpha=0.9) on the same table and compare its coverage with the backtest band.
  3. Weekly bands per horizon week. The weekly band pools all four weeks of the horizon. Build one per week (52 errors become 13 per week) and check whether the fourth week needs a wider band.
  4. Promo size as an input. Add the planned discount depth of each promotion as a feature. It must come from the promotion plan, fixed before the origin (for example the announced maximum discount per event). The realized daily mean discount in sales.csv is only known after the day, so using it would leak future information. Check whether the planned depth explains the difference between Cyber Monday 2023 and 2024.
  5. Weighted combination. Choose the weight of SARIMAX in the combination on the backtest (for example 0.3, 0.5 or 0.7). Does a weight other than 0.5 help, or does it overfit 13 folds?
  6. Revenue plan. Forecast daily revenue with the same models. How much wider are the bands?