Project 7: Sales Forecasting
A chain of five shops orders stock every Sunday for the next four weeks. Too little and shelves are empty on the busiest Saturday; too much and fresh goods are thrown away. The buyers want a daily forecast per shop for the next 28 days, with a range they can plan safety stock from, and they want it before Christmas, the hardest month of the year. This intermediate project builds it: a multi-store sales history with trend, weekly and yearly seasons, holidays and promotions; honest baselines; a gradient-boosted model with lag features that respect the horizon; a rolling-origin backtest; MASE; prediction intervals checked for coverage; and the weekly report the buyers read.
Time-Series Backtesting explains walk-forward evaluation on one series with a one-step forecast, and lag, rolling and group features the "only the past" rule. This project uses both, and adds what a real forecasting job needs on top: many series in one model, a multi-day horizon that decides which lags are allowed, calendar features that are known in advance (holidays, planned promotions), a scale-free metric to compare shops of different size, and intervals whose coverage is measured instead of assumed.
Goal and success criteria
Agreed with the buyers before any model is fitted:
| Criterion | Target | Measured on |
|---|---|---|
| accuracy | MASE below 1, and at least 20 % below the best baseline | the test month, December 2024, used once |
| stability | MASE below 1 in every backtest fold | 6 folds, June to November 2024 |
| uncertainty | 90 % intervals that contain between 85 % and 95 % of the actual days | test month |
| deliverable | weekly forecast per shop with a 90 % range, for the next 4 weeks | the report in Step 4 |
The data
make_sales generates 5 shops from 3 January 2022 to 29 December 2024 (156 weeks), plus the 28 days after it, whose sales are unknown but whose promotion plan is already fixed. Each shop has its own level (150 to 600 units a day) and growth (0 to 12 % a year). The mean sales of a day are the product of
- a weekly pattern (Saturday 1.5, Sunday 0.7 of an average day),
- a yearly wave (summer high, winter low) plus a Christmas run from 10 to 24 December and Black Friday at 2.5 times,
- promotions, about 14 per shop, 3 to 7 days long, at 1.3 times,
- closures on 1 January, 25 and 26 December (sales 0),
with Poisson noise and a few percent of day-to-day variation on top. Real data would come from the point-of-sale system, aggregated per shop and day; it carries no personal data at that level, but it is commercially confidential, and the data of Kaggle's retail competitions (Rossmann, M5 from Walmart) comes under competition rules that usually limit its use outside the competition; read them before reusing it. Every score below describes this generator.
Step 1: explore
import numpy as np
import pandas as pd
def make_sales(seed=7, n_stores=5, start="2022-01-03", days=1120):
"""Daily unit sales of 5 shops, 2022-01-03 to 2025-01-26: trend, weekly and yearly season, holidays, promotions.
The last 28 days are the future: their promotions are planned (known), their sales are not (NaN)."""
rng = np.random.default_rng(seed)
date = pd.date_range(start, periods=days, freq="D")
doy, dow = date.dayofyear.to_numpy(), date.dayofweek.to_numpy()
md = date.strftime("%m-%d")
closed = np.isin(md, ["01-01", "12-25", "12-26"])
black_friday = (date.month == 11) & (dow == 4) & (date.day >= 23) & (date.day <= 29)
christmas_run = (date.month == 12) & (date.day >= 10) & (date.day <= 24)
week = np.array([0.9, 0.85, 0.9, 1.0, 1.2, 1.5, 0.7])[dow] # Monday ... Sunday
year = 1 + 0.15 * np.sin(2 * np.pi * (doy - 100) / 365.25) + 0.35 * christmas_run + 1.5 * black_friday
rows = []
for s in range(n_stores):
level, growth = rng.uniform(150, 600), rng.uniform(0.0, 0.12) # units per day, growth per year
promo = np.zeros(days, bool)
for p0 in rng.choice(days - 7, 14, replace=False): # about 14 promotions of 3-7 days
promo[p0:p0 + rng.integers(3, 8)] = True
mean = level * (1 + growth) ** (np.arange(days) / 365.25) * week * year * np.where(promo, 1.3, 1.0)
sales = np.where(closed, 0, rng.poisson(mean * rng.lognormal(0, 0.08, days))).astype(float)
sales[-28:] = np.nan
rows.append(pd.DataFrame({"date": date, "store": s, "sales": sales, "promo": promo}))
return pd.concat(rows, ignore_index=True)
df = make_sales()
known = df.dropna(subset=["sales"])
print(f"{df['store'].nunique()} stores, {known['date'].min().date()} to {known['date'].max().date()} observed, "
f"{df['sales'].isna().sum() // 5} future days with a promotion plan")
mean = known["sales"].mean()
dow = known.groupby(known["date"].dt.dayofweek)["sales"].mean() / mean
print("weekday index Mon..Sun:", dow.round(2).tolist())
month = known.groupby(known["date"].dt.month)["sales"].mean() / mean
print("month index Jan..Dec: ", month.round(2).tolist())
open_days = known[known["sales"] > 0]
print(f"promotion uplift: {open_days.groupby('promo')['sales'].mean().pipe(lambda s: s[True] / s[False]):.2f}x, "
f"closed days per store per year: {(known['sales'] == 0).sum() / 5 / 3:.0f}")
bf = known[(known["date"].dt.month == 11) & (known["date"].dt.dayofweek == 4) & known["date"].dt.day.between(23, 29)]
fri = known[(known["date"].dt.month == 11) & (known["date"].dt.dayofweek == 4) & ~known["date"].isin(bf["date"])]
print(f"Black Friday vs other November Fridays: {bf['sales'].mean() / fri['sales'].mean():.2f}x")
print("mean daily sales by store and year:")
print(known.groupby(["store", known["date"].dt.year])["sales"].mean().unstack().round(0).astype(int))5 stores, 2022-01-03 to 2024-12-29 observed, 28 future days with a promotion plan
weekday index Mon..Sun: [0.88, 0.84, 0.89, 0.98, 1.23, 1.49, 0.69]
month index Jan..Dec: [0.78, 0.83, 0.9, 0.98, 1.04, 1.12, 1.15, 1.12, 1.06, 1.0, 1.0, 1.01]
promotion uplift: 1.35x, closed days per store per year: 3
Black Friday vs other November Fridays: 2.58x
mean daily sales by store and year:
date 2022 2023 2024
store
0 476 516 590
1 187 210 232
2 225 242 272
3 278 302 338
4 618 682 721
The weekly pattern is strong (Saturday 1.49, Sunday 0.69 of the mean), the yearly wave runs from 0.78 in January to 1.15 in July, promotions add about 35 %, and Black Friday sells 2.58 times an ordinary November Friday. The shops differ by a factor of three in size (store 1 sells about 230 units a day in 2024, store 4 about 720) and all grow. Errors must therefore be compared on a scale-free metric, or the big shops decide everything.
The forecasting set-up
On a Sunday, the origin , the buyers need forecasts for days to with . A feature of a target day may only use sales up to the origin. A lag of days, , is known at the origin for every day of the horizon only if : the last horizon day needs . So the model uses lags 28, 35 and 364 and a 28-day mean that ends 28 days back, plus everything known in advance: weekday, day of year, month, holidays, days to Christmas and the promotion plan. One model then serves all 28 horizons. (The alternatives are one model per horizon, which can use shorter lags for near days, and recursive forecasting, which feeds its own forecasts back in as lags and lets errors compound over the horizon.)
Why not just cross-validate with shuffled days? The lab compares the two on a random walk with a nearest-day model: a shuffled 80/20 split reports , because every test day sits between two training days that are almost equal to it; the split by time reports and the next 40 days give . The shuffled score measures interpolation, not forecasting.
Step 2: baselines and the model in a rolling-origin backtest
Three baselines, each a real forecasting method that a spreadsheet can do:
| Baseline | Forecast for day of the horizon |
|---|---|
| naive | the last observed day, |
| seasonal naive | the same weekday in the last observed week, |
| last year | the same weekday 52 weeks earlier, |
The model is LightGBM on (sales are multiplicative, so the log turns factors into sums and keeps the big shops from dominating the loss), one model for all five shops with the shop as a categorical feature. The metric is the mean absolute scaled error of Hyndman and Koehler (2006), in its seasonal form (the paper scales by the one-step naive forecast; for weekly cycles the scale is usually the seasonal naive): the forecast's mean absolute error divided by that of the one-week-back forecast on the training days of the same shop,
so MASE below 1 means "better than repeating last week was, on average, one week ahead", and shops of any size can be averaged. The backtest uses six origins 28 days apart, from June to November 2024, and refits every model at every origin on the data up to it; December 2024 stays untouched for Step 3.
import numpy as np
import pandas as pd
import lightgbm as lgb
def make_sales(seed=7, n_stores=5, start="2022-01-03", days=1120):
"""Daily unit sales of 5 shops, 2022-01-03 to 2025-01-26: trend, weekly and yearly season, holidays, promotions.
The last 28 days are the future: their promotions are planned (known), their sales are not (NaN)."""
rng = np.random.default_rng(seed)
date = pd.date_range(start, periods=days, freq="D")
doy, dow = date.dayofyear.to_numpy(), date.dayofweek.to_numpy()
md = date.strftime("%m-%d")
closed = np.isin(md, ["01-01", "12-25", "12-26"])
black_friday = (date.month == 11) & (dow == 4) & (date.day >= 23) & (date.day <= 29)
christmas_run = (date.month == 12) & (date.day >= 10) & (date.day <= 24)
week = np.array([0.9, 0.85, 0.9, 1.0, 1.2, 1.5, 0.7])[dow] # Monday ... Sunday
year = 1 + 0.15 * np.sin(2 * np.pi * (doy - 100) / 365.25) + 0.35 * christmas_run + 1.5 * black_friday
rows = []
for s in range(n_stores):
level, growth = rng.uniform(150, 600), rng.uniform(0.0, 0.12) # units per day, growth per year
promo = np.zeros(days, bool)
for p0 in rng.choice(days - 7, 14, replace=False): # about 14 promotions of 3-7 days
promo[p0:p0 + rng.integers(3, 8)] = True
mean = level * (1 + growth) ** (np.arange(days) / 365.25) * week * year * np.where(promo, 1.3, 1.0)
sales = np.where(closed, 0, rng.poisson(mean * rng.lognormal(0, 0.08, days))).astype(float)
sales[-28:] = np.nan
rows.append(pd.DataFrame({"date": date, "store": s, "sales": sales, "promo": promo}))
return pd.concat(rows, ignore_index=True)
H = 28 # forecast horizon, days
def add_features(df):
"""Calendar, holiday and promotion features (known in advance) and lags of at least H days."""
d = df.sort_values(["store", "date"]).copy()
d["dow"], d["doy"], d["month"] = d["date"].dt.dayofweek, d["date"].dt.dayofyear, d["date"].dt.month
md = d["date"].dt.strftime("%m-%d")
d["closed"] = md.isin(["01-01", "12-25", "12-26"]).astype(int)
d["black_friday"] = ((d["month"] == 11) & (d["dow"] == 4) & d["date"].dt.day.between(23, 29)).astype(int)
d["days_to_xmas"] = (pd.to_datetime(d["date"].dt.year.astype(str) + "-12-25") - d["date"]).dt.days.clip(-10, 40)
g = d.groupby("store")["sales"]
for lag in [H, H + 7, 364]:
d[f"lag{lag}"] = g.shift(lag)
d["mean28_lagH"] = g.transform(lambda s: s.shift(H).rolling(28).mean())
return d
FEATURES = ["store", "dow", "doy", "month", "closed", "black_friday", "days_to_xmas", "promo",
"lag28", "lag35", "lag364", "mean28_lagH"]
def forecasts(d, origin):
"""Fit on days up to `origin`, forecast the next H days with every method."""
hist = d[(d["date"] <= origin)]
fut = d[(d["date"] > origin) & (d["date"] <= origin + pd.Timedelta(days=H))].copy()
fut["h"] = (fut["date"] - origin).dt.days
fut["naive"] = fut["store"].map(hist.groupby("store")["sales"].last()) # last observed day
week = {(r.store, r.dow): r.sales for r in hist.groupby("store").tail(7).itertuples()}
fut["seasonal_naive"] = [week[k] for k in zip(fut["store"], fut["dow"])] # last observed week
fut["last_year"] = fut["lag364"] # same weekday, 52 weeks ago
train = hist.dropna(subset=["mean28_lagH"])
gbm = lgb.LGBMRegressor(n_estimators=300, learning_rate=0.05, num_leaves=15, min_child_samples=10,
verbose=-1, random_state=0)
gbm.fit(train[FEATURES], np.log1p(train["sales"]), categorical_feature=["store"])
fut["gbm"] = np.expm1(gbm.predict(fut[FEATURES])).clip(0)
return fut
def mase_scale(d, origin):
"""Per store: mean absolute error of the one-week-back forecast on the training days."""
return d[d["date"] <= origin].groupby("store")["sales"].apply(lambda s: s.diff(7).abs().mean())
METHODS = ["naive", "seasonal_naive", "last_year", "gbm"]
d = add_features(make_sales())
TEST_ORIGIN = pd.Timestamp("2024-12-01") # December 2024 is the test, kept for Step 3
origins = [TEST_ORIGIN - pd.Timedelta(days=H * k) for k in range(6, 0, -1)]
print("backtest origins:", [o.strftime("%m-%d") for o in origins], "2024, horizon", H, "days")
rows = []
for o in origins:
f = forecasts(d, o) # refit at every origin, on the past only
sc = f["store"].map(mase_scale(d, o))
rows.append(pd.DataFrame({m: (f["sales"] - f[m]).abs() / sc for m in METHODS}).assign(origin=o, h=f["h"]))
ase = pd.concat(rows)
print("MASE over 6 folds x 5 stores x 28 days:", ase[METHODS].mean().round(3).to_dict())
print("MASE per fold:"); print(ase.groupby(ase["origin"].dt.strftime("%m-%d"))[METHODS].mean().round(2))
print("MASE by horizon week:"); print(ase.groupby((ase["h"] - 1) // 7 + 1)[METHODS].mean().round(2))backtest origins: ['06-16', '07-14', '08-11', '09-08', '10-06', '11-03'] 2024, horizon 28 days
MASE over 6 folds x 5 stores x 28 days: {'naive': 2.639, 'seasonal_naive': 1.217, 'last_year': 1.399, 'gbm': 0.783}
MASE per fold:
naive seasonal_naive last_year gbm
origin
06-16 2.68 1.39 1.35 0.77
07-14 2.95 1.28 1.32 0.80
08-11 2.76 1.34 1.28 0.65
09-08 2.36 0.85 1.09 0.87
10-06 2.25 1.10 1.41 0.72
11-03 2.83 1.35 1.95 0.89
MASE by horizon week:
naive seasonal_naive last_year gbm
h
1 2.57 1.14 1.15 0.72
2 2.56 1.14 1.28 0.77
3 2.63 1.17 1.65 0.85
4 2.81 1.42 1.51 0.79
The GBM's MASE is 0.783 against 1.217 for the best baseline, the seasonal naive (36 % lower), and it is below 1 in every fold (worst 0.89). Two patterns are worth noticing. The naive forecast is hopeless (about 2.6) because one day says nothing about the weekly cycle. And the baselines get worse with the horizon (seasonal naive 1.14 in week 1, 1.42 in week 4), while the GBM stays flat (0.72 to 0.85): it only ever uses lags of 28 days or more, so the near days do not profit from recent data and the far days do not suffer. The jump of the seasonal naive in week 4 comes from the November fold, whose last week contains Black Friday.
Step 3: the test month, and intervals that are checked
A point forecast is not enough for ordering: the buyers need a range. Split conformal intervals use the backtest errors as a sample of future errors: for each horizon week, take the 5 % and 95 % quantiles , of the log errors , and widen each new forecast by them:
If future errors behave like the backtest errors, about 90 % of days fall inside. That "if" is checked on the test month, December 2024, scored once.
import numpy as np
import pandas as pd
import lightgbm as lgb
def make_sales(seed=7, n_stores=5, start="2022-01-03", days=1120):
"""Daily unit sales of 5 shops, 2022-01-03 to 2025-01-26: trend, weekly and yearly season, holidays, promotions.
The last 28 days are the future: their promotions are planned (known), their sales are not (NaN)."""
rng = np.random.default_rng(seed)
date = pd.date_range(start, periods=days, freq="D")
doy, dow = date.dayofyear.to_numpy(), date.dayofweek.to_numpy()
md = date.strftime("%m-%d")
closed = np.isin(md, ["01-01", "12-25", "12-26"])
black_friday = (date.month == 11) & (dow == 4) & (date.day >= 23) & (date.day <= 29)
christmas_run = (date.month == 12) & (date.day >= 10) & (date.day <= 24)
week = np.array([0.9, 0.85, 0.9, 1.0, 1.2, 1.5, 0.7])[dow] # Monday ... Sunday
year = 1 + 0.15 * np.sin(2 * np.pi * (doy - 100) / 365.25) + 0.35 * christmas_run + 1.5 * black_friday
rows = []
for s in range(n_stores):
level, growth = rng.uniform(150, 600), rng.uniform(0.0, 0.12) # units per day, growth per year
promo = np.zeros(days, bool)
for p0 in rng.choice(days - 7, 14, replace=False): # about 14 promotions of 3-7 days
promo[p0:p0 + rng.integers(3, 8)] = True
mean = level * (1 + growth) ** (np.arange(days) / 365.25) * week * year * np.where(promo, 1.3, 1.0)
sales = np.where(closed, 0, rng.poisson(mean * rng.lognormal(0, 0.08, days))).astype(float)
sales[-28:] = np.nan
rows.append(pd.DataFrame({"date": date, "store": s, "sales": sales, "promo": promo}))
return pd.concat(rows, ignore_index=True)
H = 28 # forecast horizon, days
def add_features(df):
"""Calendar, holiday and promotion features (known in advance) and lags of at least H days."""
d = df.sort_values(["store", "date"]).copy()
d["dow"], d["doy"], d["month"] = d["date"].dt.dayofweek, d["date"].dt.dayofyear, d["date"].dt.month
md = d["date"].dt.strftime("%m-%d")
d["closed"] = md.isin(["01-01", "12-25", "12-26"]).astype(int)
d["black_friday"] = ((d["month"] == 11) & (d["dow"] == 4) & d["date"].dt.day.between(23, 29)).astype(int)
d["days_to_xmas"] = (pd.to_datetime(d["date"].dt.year.astype(str) + "-12-25") - d["date"]).dt.days.clip(-10, 40)
g = d.groupby("store")["sales"]
for lag in [H, H + 7, 364]:
d[f"lag{lag}"] = g.shift(lag)
d["mean28_lagH"] = g.transform(lambda s: s.shift(H).rolling(28).mean())
return d
FEATURES = ["store", "dow", "doy", "month", "closed", "black_friday", "days_to_xmas", "promo",
"lag28", "lag35", "lag364", "mean28_lagH"]
def forecasts(d, origin):
"""Fit on days up to `origin`, forecast the next H days with every method."""
hist = d[(d["date"] <= origin)]
fut = d[(d["date"] > origin) & (d["date"] <= origin + pd.Timedelta(days=H))].copy()
fut["h"] = (fut["date"] - origin).dt.days
fut["naive"] = fut["store"].map(hist.groupby("store")["sales"].last()) # last observed day
week = {(r.store, r.dow): r.sales for r in hist.groupby("store").tail(7).itertuples()}
fut["seasonal_naive"] = [week[k] for k in zip(fut["store"], fut["dow"])] # last observed week
fut["last_year"] = fut["lag364"] # same weekday, 52 weeks ago
train = hist.dropna(subset=["mean28_lagH"])
gbm = lgb.LGBMRegressor(n_estimators=300, learning_rate=0.05, num_leaves=15, min_child_samples=10,
verbose=-1, random_state=0)
gbm.fit(train[FEATURES], np.log1p(train["sales"]), categorical_feature=["store"])
fut["gbm"] = np.expm1(gbm.predict(fut[FEATURES])).clip(0)
return fut
def mase_scale(d, origin):
"""Per store: mean absolute error of the one-week-back forecast on the training days."""
return d[d["date"] <= origin].groupby("store")["sales"].apply(lambda s: s.diff(7).abs().mean())
METHODS = ["naive", "seasonal_naive", "last_year", "gbm"]
d = add_features(make_sales())
TEST_ORIGIN = pd.Timestamp("2024-12-01")
origins = [TEST_ORIGIN - pd.Timedelta(days=H * k) for k in range(6, 0, -1)]
back = pd.concat([forecasts(d, o) for o in origins])
# 90 % intervals from the backtest errors on the log scale, per horizon week (split conformal)
err = np.log1p(back["sales"]) - np.log1p(back["gbm"])
q = err.groupby((back["h"] - 1) // 7 + 1).quantile([0.05, 0.95]).unstack()
print("backtest log-error quantiles by horizon week:", {w: (round(a, 3), round(b, 3)) for w, a, b in q.itertuples()})
test = forecasts(d, TEST_ORIGIN) # December 2024, scored once
week = (test["h"] - 1) // 7 + 1
sc = test["store"].map(mase_scale(d, TEST_ORIGIN))
print("TEST", test["date"].min().date(), "to", test["date"].max().date(),
{m: round(float(((test["sales"] - test[m]).abs() / sc).mean()), 3) for m in METHODS})
lo = np.expm1(np.log1p(test["gbm"]) + week.map(q[0.05])).clip(0)
hi = np.expm1(np.log1p(test["gbm"]) + week.map(q[0.95]))
inside = test["sales"].between(lo, hi)
print(f"90 % interval coverage: {inside.mean():.3f} of {len(test)} store-days; by week {inside.groupby(week).mean().round(2).tolist()}")
print(f"bias (forecast - actual) / actual on open days, Dec 16-24: "
f"{((test['gbm'] - test['sales']) / test['sales'])[test['date'].between('2024-12-16', '2024-12-24')].mean():+.3f}")
show = test[(test["store"] == 0) & test["date"].between("2024-12-20", "2024-12-27")]
print(show.assign(date=show["date"].dt.strftime("%a %m-%d"))[["date", "sales", "gbm", "seasonal_naive", "last_year"]]
.round(0).astype({c: int for c in ["sales", "gbm", "seasonal_naive", "last_year"]}).to_string(index=False))backtest log-error quantiles by horizon week: {1: (-0.195, 0.193), 2: (-0.167, 0.211), 3: (-0.213, 0.2), 4: (-0.187, 0.2)}
TEST 2024-12-02 to 2024-12-29 {'naive': 3.425, 'seasonal_naive': 3.705, 'last_year': 1.982, 'gbm': 0.898}
90 % interval coverage: 0.807 of 140 store-days; by week [0.8, 0.86, 0.89, 0.69]
bias (forecast - actual) / actual on open days, Dec 16-24: -0.093
date sales gbm seasonal_naive last_year
Fri 12-20 820 715 1674 792
Sat 12-21 985 875 759 835
Sun 12-22 459 478 387 438
Mon 12-23 639 531 398 0
Tue 12-24 549 370 422 0
Wed 12-25 0 0 420 448
Thu 12-26 0 0 542 486
Fri 12-27 602 562 1674 501
The point forecast passes: MASE 0.898 on December, below 1 and 55 % below the best baseline (last year, 1.982). The baselines fail in instructive ways, visible in the store-0 table. The seasonal naive repeats the last observed week, which contains Black Friday, so it forecasts 1,674 units for every Friday of December; it also forecasts normal sales on the closed 25 and 26 December. "Last year" is shifted by 364 days, so 23 and 24 December 2024 get the zero sales of last year's closed 25 and 26 December. The GBM gets the closures right (0) because the calendar features tell it.
The interval criterion fails: 0.807 coverage instead of at least 0.85, and only 0.69 in the Christmas week. The backtest errors come from June to November, calm months, and the model under-forecasts the run-up to Christmas by 9.3 % on average (from 16 to 24 December): a bias that no interval from calm months can hold. This is the most valuable result of the project, because it was found before the buyers relied on the ranges. The write-up reports it as a failed criterion, with the fixes: calibrate December intervals on last year's December, give the model a better Christmas feature, or widen the December ranges by a margin agreed with the buyers. Changing the intervals now and re-scoring December would turn the test month into a validation month, so the next honest check is December 2025.
Step 4: the forecast report
After the test, December joins the history: the model is refit on everything up to 29 December 2024 and forecasts 30 December to 26 January. The buyers order per week, so the report gives weekly totals per shop, with 90 % ranges computed the same conformal way from the backtest errors of weekly totals (summing daily intervals would assume that all daily errors go the same way). The promotion days come from the plan.
import numpy as np
import pandas as pd
import lightgbm as lgb
def make_sales(seed=7, n_stores=5, start="2022-01-03", days=1120):
"""Daily unit sales of 5 shops, 2022-01-03 to 2025-01-26: trend, weekly and yearly season, holidays, promotions.
The last 28 days are the future: their promotions are planned (known), their sales are not (NaN)."""
rng = np.random.default_rng(seed)
date = pd.date_range(start, periods=days, freq="D")
doy, dow = date.dayofyear.to_numpy(), date.dayofweek.to_numpy()
md = date.strftime("%m-%d")
closed = np.isin(md, ["01-01", "12-25", "12-26"])
black_friday = (date.month == 11) & (dow == 4) & (date.day >= 23) & (date.day <= 29)
christmas_run = (date.month == 12) & (date.day >= 10) & (date.day <= 24)
week = np.array([0.9, 0.85, 0.9, 1.0, 1.2, 1.5, 0.7])[dow] # Monday ... Sunday
year = 1 + 0.15 * np.sin(2 * np.pi * (doy - 100) / 365.25) + 0.35 * christmas_run + 1.5 * black_friday
rows = []
for s in range(n_stores):
level, growth = rng.uniform(150, 600), rng.uniform(0.0, 0.12) # units per day, growth per year
promo = np.zeros(days, bool)
for p0 in rng.choice(days - 7, 14, replace=False): # about 14 promotions of 3-7 days
promo[p0:p0 + rng.integers(3, 8)] = True
mean = level * (1 + growth) ** (np.arange(days) / 365.25) * week * year * np.where(promo, 1.3, 1.0)
sales = np.where(closed, 0, rng.poisson(mean * rng.lognormal(0, 0.08, days))).astype(float)
sales[-28:] = np.nan
rows.append(pd.DataFrame({"date": date, "store": s, "sales": sales, "promo": promo}))
return pd.concat(rows, ignore_index=True)
H = 28 # forecast horizon, days
def add_features(df):
"""Calendar, holiday and promotion features (known in advance) and lags of at least H days."""
d = df.sort_values(["store", "date"]).copy()
d["dow"], d["doy"], d["month"] = d["date"].dt.dayofweek, d["date"].dt.dayofyear, d["date"].dt.month
md = d["date"].dt.strftime("%m-%d")
d["closed"] = md.isin(["01-01", "12-25", "12-26"]).astype(int)
d["black_friday"] = ((d["month"] == 11) & (d["dow"] == 4) & d["date"].dt.day.between(23, 29)).astype(int)
d["days_to_xmas"] = (pd.to_datetime(d["date"].dt.year.astype(str) + "-12-25") - d["date"]).dt.days.clip(-10, 40)
g = d.groupby("store")["sales"]
for lag in [H, H + 7, 364]:
d[f"lag{lag}"] = g.shift(lag)
d["mean28_lagH"] = g.transform(lambda s: s.shift(H).rolling(28).mean())
return d
FEATURES = ["store", "dow", "doy", "month", "closed", "black_friday", "days_to_xmas", "promo",
"lag28", "lag35", "lag364", "mean28_lagH"]
def forecasts(d, origin):
"""Fit on days up to `origin`, forecast the next H days with every method."""
hist = d[(d["date"] <= origin)]
fut = d[(d["date"] > origin) & (d["date"] <= origin + pd.Timedelta(days=H))].copy()
fut["h"] = (fut["date"] - origin).dt.days
fut["naive"] = fut["store"].map(hist.groupby("store")["sales"].last()) # last observed day
week = {(r.store, r.dow): r.sales for r in hist.groupby("store").tail(7).itertuples()}
fut["seasonal_naive"] = [week[k] for k in zip(fut["store"], fut["dow"])] # last observed week
fut["last_year"] = fut["lag364"] # same weekday, 52 weeks ago
train = hist.dropna(subset=["mean28_lagH"])
gbm = lgb.LGBMRegressor(n_estimators=300, learning_rate=0.05, num_leaves=15, min_child_samples=10,
verbose=-1, random_state=0)
gbm.fit(train[FEATURES], np.log1p(train["sales"]), categorical_feature=["store"])
fut["gbm"] = np.expm1(gbm.predict(fut[FEATURES])).clip(0)
return fut
def mase_scale(d, origin):
"""Per store: mean absolute error of the one-week-back forecast on the training days."""
return d[d["date"] <= origin].groupby("store")["sales"].apply(lambda s: s.diff(7).abs().mean())
d = add_features(make_sales())
LAST = d.dropna(subset=["sales"])["date"].max() # 2024-12-29: the newest observed day
origins = [LAST - pd.Timedelta(days=H * k) for k in range(6, 0, -1)]
back = pd.concat([forecasts(d, o).assign(origin=o) for o in origins])
back["week"] = (back["h"] - 1) // 7 + 1
# intervals for what the stores order by: weekly totals, from backtest errors of weekly totals
wk = back.groupby(["origin", "store", "week"])[["sales", "gbm"]].sum()
q = np.log(wk["sales"] / wk["gbm"]).groupby("week").quantile([0.05, 0.95]).unstack()
fc = forecasts(d, LAST) # refit on everything, forecast the next 28 days
fc["week"] = (fc["h"] - 1) // 7 + 1
rep = fc.groupby(["store", "week"]).agg(starts=("date", "min"), promo_days=("promo", "sum"), forecast=("gbm", "sum"))
rep["low_90"] = rep["forecast"] * np.exp(rep.index.get_level_values("week").map(q[0.05]))
rep["high_90"] = rep["forecast"] * np.exp(rep.index.get_level_values("week").map(q[0.95]))
rep["starts"] = rep["starts"].dt.strftime("%Y-%m-%d")
print(f"forecast made {LAST.date()} for {fc['date'].min().date()} to {fc['date'].max().date()}; "
f"model refit on {int((d['date'] <= LAST).sum())} store-days; intervals from {len(wk)} backtest store-weeks")
print(rep.loc[[0, 3]].round(0).astype({"forecast": int, "low_90": int, "high_90": int}).to_string())
print("all stores, week 1:", int(rep.xs(1, level="week")["forecast"].sum()), "units")forecast made 2024-12-29 for 2024-12-30 to 2025-01-26; model refit on 5460 store-days; intervals from 120 backtest store-weeks
starts promo_days forecast low_90 high_90
store week
0 1 2024-12-30 0 2833 2566 3093
2 2025-01-06 0 3436 2978 3958
3 2025-01-13 0 3544 3209 3986
4 2025-01-20 0 3542 3315 4025
3 1 2024-12-30 0 1782 1614 1946
2 2025-01-06 0 2084 1806 2401
3 2025-01-13 1 2155 1951 2424
4 2025-01-20 2 2169 2031 2465
all stores, week 1: 10802 units
The table is what the buyers get: for shop 3, week 4 has 2 promotion days and a forecast of 2,169 units with a 90 % range of 2,031 to 2,465. Week 1 is lower everywhere because it contains 1 January (closed) and the January low. The range is asymmetric (more room above than below) because the errors were measured on the log scale. With the December finding in mind, the report should say that these ranges have been checked only in calm months; January is one, so they are a reasonable guide here.
Extensions
- December intervals: add a backtest fold at last year's December (origin 3 December 2023) and recompute the coverage on the test month (Practice 2).
- Quantile regression: LightGBM with
objective="quantile"andalpha=0.05and0.95learns intervals that depend on the features (wider around holidays); compare its coverage with conformal. - Per-horizon models: a model for horizon 1 to 7 with lags of 7 or more, and the lag-28 model for the rest; check in the backtest whether week 1 improves.
- Hierarchy: forecast the chain total and the shops and make them add up (reconciliation).
- Monitoring: recompute MASE every week on the newest 28 days and alert when it rises above 1 (monitoring, retraining).
- A service: wrap Step 4 in a FastAPI endpoint that returns a shop's forecast for a date range (FastAPI basics).
Write-up template
| This run | Yours | |
|---|---|---|
| Data | 5 shops, 2022-01-03 to 2024-12-29, daily; promotion plan for 28 days ahead | |
| Horizon and features | 28 days; lags 28, 35, 364, 28-day mean at lag 28, calendar, holidays, promotions | |
| Backtest | 6 origins, June to November 2024, refit at each | |
| Backtest MASE | GBM 0.783, seasonal naive 1.217, last year 1.399, naive 2.639 | |
| Test MASE (December 2024, once) | GBM 0.898, best baseline 1.982 | |
| Interval coverage, target 0.85 to 0.95 | 0.807 (failed; 0.69 in the Christmas week) | |
| Largest error | 9.3 % under-forecast from 16 to 24 December | |
| Next steps | December calibration fold, Christmas feature, quantile model |
Practice
- Why does the GBM use lag 28 and not lag 7, even though last week's sales are the best single predictor of next week's?
Answer
For a forecast made at origin , lag 7 of day is day , which lies in the future. The feature would be available in the backtest table (it is just a shifted column) but not on the Sunday the forecast is made, so the backtest would be optimistic and production would break. With one model for the whole 28-day horizon, every lag must be at least 28. A separate model for the first week could use lag 7.
- Add a backtest fold at 3 December 2023 to the origins of Step 3 (
origins = [pd.Timestamp("2023-12-03")] + ...). Does the test coverage reach 0.85?
Answer
It improves, but not enough: coverage rises from 0.807 to 0.829, still 0.74 in the Christmas week. One December fold adds only 140 of 980 errors, and the problem is mostly a bias (under-forecasting before Christmas) rather than too narrow a spread. A December-only calibration set or a better Christmas feature is needed. And note that this practice result looks at the test month again: in a real project, decide the fix on the backtest, then wait for the next December to check it.
- A colleague computes MAE in units instead of MASE and finds the model "worst for shop 4". Is that a problem with shop 4?
Answer
Probably not. Shop 4 sells about three times as much as shop 1, so its errors in units are larger even when its relative errors are the same. MASE divides each shop's error by the error of a simple forecast on the same shop, so shops of different size become comparable. Compare shops by MASE (or by a percentage error, which has its own problems on days with sales near 0, such as the closures).
Test yourself
The forecast horizon is 28 days and one model serves all of it. Which lag may that model use?
- lag 1
- lag 7
- lag 14
- lag 28
What does a MASE of 0.783 mean?
- The forecast is 78.3 % accurate
- Its mean absolute error is 0.783 times that of the one-week-back forecast on the training days
- It explains 78.3 % of the variance
- Its error is 0.783 units per day
Why did the seasonal naive forecast 1,674 units for every Friday of December 2024 for shop 0?
- Fridays are always the busiest day
- It repeats the last observed week, which contained Black Friday
- It uses the same day last year
- Because of the promotions
The 90 % intervals covered 0.807 of the December days. What is the right next step?
- Widen them until December reaches 0.90 and report that
- Report the failed criterion, and fix the calibration on past data (e.g. last year's December) before the next test
- Drop the intervals
- Use a shuffled cross-validation to estimate them