Part 1 introduced a three-metric scorecard - WMAPE, Total Bias, and Active Seller Bias- for judging whether a SKU_level forecast puts the units in the right place. Here, we turn the framework into a reusable,leakage-safe backtesting framework in Python, using the public M5 Forecasting dataset from Walmart.

https://hackernoon.com/evaluating-sku-level-forecasts-with-wmape-total-bias-and-active-seller-bias?embedable=true

Why M5, and how does it map to allocation problems?

M5 has ~30,400 item-store sales (3049 products, 10 stores in California, Texas, and Wisconsin, 3 categories, 7 departments) covering 1,941 days. It’s intermittent and long-tailed, with plenty of zeros and late launches, which is exactly the setting where allocation errors hide.

Scorecard Concept

In a sizing/allocation context

M5 equivalent used here

SKU

product-size-store

item_id X store_id

Backtest Window

6 weeks, summed

6 Walmart weeks ( wm, yr, wk), summer

Product Age

New vs Existing products

New if first sale in the store is < 26 weeks before the forecast origin

Regional group

Differentiation at regional level or type of store group

state_id (CA/TX/WI) as the regional cut

Product type

Apparel, Cosmetics, Food items, etc.

cat_id, dept_id

Store level

Door

store_id

Link to M5 Dataset : https://www.kaggle.com/competitions/m5-forecasting-accuracy/data

The pipeline at a glance.

STEP 1

STEP 2

STEP 3

STEP 4

STEP 5

STEP 6

Load daily M5 data
→ weekly panel

Tag product age at each
origin

Rolling-origin folds

Run candidate models

Score: WMAPE and BIAS

Segment Reports + Diagnosis

# pip install pandas numpy scikit-learn matplotlib # Data : Kaggle --> M5 Forecasting- Accuracy --> accept rules --> download # sales_train_evaluation.csv (30,490 items-store series, daily units) # calendar.csv # Full script: python retail_backtestin.py --date-dir # Smoke test: python retail_backtesting.py --syntheic #schema-idnetical fake data 

Step 1: Daily Sales to a Weekly Panel

M5 data comes in wide format: one column per day. We keep only complete Saturday-to-Friday Walmart weeks, summing days into weeks with np.add.reduceat while the data is still wide, and then melt to a long store-item-week table.

# 1. DATA: load M5 and roll daily sales up to store-item-week def load_m5_weekly(data_dir: str | Path, stores: list[str] | None = None) -> pd.DataFrame: """Return a long table at store-item-week grain (full 7-day weeks only).""" data_dir = Path(data_dir) cal = pd.read_csv(data_dir / "calendar.csv", usecols=["d", "wm_yr_wk", "date"]) sales = pd.read_csv(data_dir / "sales_train_evaluation.csv") if stores: sales = sales[sales["store_id"].isin(stores)].reset_index(drop=True) day_cols = [c for c in sales.columns if c.startswith("d_")] cal = cal.set_index("d").loc[day_cols].reset_index() # keep only complete Walmart weeks (Sat-Fri) so every week has 7 days days_per_week = cal.groupby("wm_yr_wk")["d"].transform("size") cal = cal[days_per_week == 7] day_cols = cal["d"].tolist() # daily -> weekly in wide form with numpy (fast, low memory) arr = sales[day_cols].to_numpy(dtype=np.int32) week_ids = cal["wm_yr_wk"].to_numpy() starts = np.flatnonzero(np.r_[True, week_ids[1:] != week_ids[:-1]]) weekly = np.add.reduceat(arr, starts, axis=1) week_labels = week_ids[starts] wide = pd.DataFrame(weekly, columns=week_labels) wide = pd.concat([sales[KEYS + ATTRS], wide], axis=1) long = wide.melt(id_vars=KEYS + ATTRS, var_name="wm_yr_wk", value_name="units") # sequential week index 0..N-1 is easier to reason about than wm_yr_wk week_map = {w: i for i, w in enumerate(week_labels)} long["week"] = long["wm_yr_wk"].map(week_map).astype(np.int16) long["units"] = long["units"].astype(np.float32) return long.drop(columns="wm_yr_wk") 

MEMORY TIP

The full file is about 30k X 1,941 integers. Pass stores=[…] to work with a subset while you develop, and run on all 10 stores for the final numbers.

Step 2: Product Age at the Forecast Origin

For a product to be defined as “New”, it has to be defined relative to the forecast origin. Otherwise, an item launched after the origin leaks into the label. An item-store counts as “New” if its first sale occurred less than 26 weeks before the origin.

# 2. SEGMENTS: product age (new vs existing) def add_product_age(panel: pd.DataFrame, origin: int, new_window: int = 26) -> pd.Series: """'New' if the item's first sale (in that store) is within `new_window` weeks of the origin.""" hist = panel[(panel["week"] <= origin) & (panel["units"] > 0)] first = hist.groupby(KEYS)["week"].min().rename("first_week") return first.apply(lambda w: "New" if origin - w < new_window else "Old").rename("product_age") 

Step 3: Rolling-origin Backtesting

A single train/test split tells you about one six-week window. Rolling-origin backtesting repeats the exercise at several forecast origins, so you can see whether the metrics are stable or just an occurrence by chance. Each fold trains only on data up to its origin and forecasts the next six weeks. With the defaults (4 folds, 6-week step), the latest origin T is placed so its window ends at the last week of data.

Fold

Training history (origin)

Scoring window (6 weeks)

Fold 1

All weeks up to T − 18

T-17…………………T-12

Fold 2

All weeks up to T − 12

T-11 ………………… T-6

Fold 3

All weeks up to T − 6

T-5 ……………………T

Fold 4

All weeks up to T

T+1 ………………… t+6

The Leakage Rule

For a mode trained at past origins o, the target window o+1 ….. o+6 has to end on or before the backtest origin. In the GBM below, the latest origin is origin-horizon, so its label ends exactly at the origin.

# 3. FEATURES + MODELS LAGS = [1, 2, 3, 4, 6, 8] ROLLS = [4, 8, 13, 26, 52] def build_features(wide: np.ndarray, origin: int) -> pd.DataFrame: """Features known at the end of week `origin` (inclusive). wide = [n_series, n_weeks].""" hist = wide[:, : origin + 1] f = {f"lag_{l}": hist[:, -l] for l in LAGS} for r in ROLLS: f[f"mean_{r}"] = hist[:, -r:].mean(axis=1) f["std_8"] = hist[:, -8:].std(axis=1) f["zero_share_13"] = (hist[:, -13:] == 0).mean(axis=1) sold = hist > 0 first = np.where(sold.any(axis=1), sold.argmax(axis=1), origin + 1) f["weeks_since_first_sale"] = origin - first last = np.where(sold.any(axis=1), hist.shape[1] - 1 - sold[:, ::-1].argmax(axis=1), -1) f["weeks_since_last_sale"] = origin - last f["trend_4_vs_13"] = f["mean_4"] - f["mean_13"] return pd.DataFrame(f) def future_sum(wide: np.ndarray, origin: int, horizon: int) -> np.ndarray: return wide[:, origin + 1: origin + 1 + horizon].sum(axis=1) 

Step 4: Three Candidate Models, Chosen on Purpose

The goal is not to win M5. It’s to show that the scorecard can tell apart models with different behaviors.

  • MovingAvg_8w: the classic baseline, recent run-rate X 6
  • GroupSpread: a deliberately naive model that gets department X store total right and then splits it evenly across every item that has ever sold there. It reproduces the “spread on non-sellers” failure model from Part 1.
  • GBM Poisson: a direct six-week-ahead gradient boosting model (Poisson loss, suited to count data) trained on lag, rolling, and recency features.
def model_moving_average(wide, origin, horizon, window=8, **_): """Baseline: recent weekly run-rate x horizon.""" return wide[:, origin - window + 1: origin + 1].mean(axis=1) * horizon def model_group_spread(wide, origin, horizon, meta, window=8, **_): """Deliberately naive: forecast the dept-store total well, then split it EVENLY across every item that has ever sold there. Good totals, poor allocation.""" run_rate = wide[:, origin - window + 1: origin + 1].mean(axis=1) * horizon ever_sold = (wide[:, : origin + 1].sum(axis=1) > 0).astype(float) g = meta[["store_id", "dept_id"]].astype(str).agg("|".join, axis=1).to_numpy() tot = pd.Series(run_rate).groupby(g).transform("sum").to_numpy() cnt = pd.Series(ever_sold).groupby(g).transform("sum").to_numpy() return np.where(ever_sold > 0, tot / np.maximum(cnt, 1), 0.0) def model_gbm(wide, origin, horizon, meta, n_train_origins=12, step=2, **_): """Direct multi-horizon GBM (Poisson loss) trained on past origins only (no leakage).""" X_list, y_list = [], [] last_train_origin = origin - horizon # its target window ends exactly at `origin` for o in range(last_train_origin, last_train_origin - n_train_origins * step, -step): if o < max(ROLLS): break X_list.append(build_features(wide, o)) y_list.append(future_sum(wide, o, horizon)) X_tr = pd.concat(X_list, ignore_index=True) y_tr = np.concatenate(y_list) cat = pd.Categorical(meta["dept_id"]).codes X_tr["dept"] = np.tile(cat, len(X_list)) gbm = HistGradientBoostingRegressor(loss="poisson", max_iter=300, learning_rate=0.06, max_leaf_nodes=31, min_samples_leaf=50, categorical_features=[X_tr.columns.get_loc("dept")], random_state=0) gbm.fit(X_tr, y_tr) X_te = build_features(wide, origin) X_te["dept"] = cat return np.clip(gbm.predict(X_te), 0, None) MODELS = {"MovingAvg_8w": model_moving_average, "GroupSpread": model_group_spread, "GBM_Poisson": model_gbm} 

A BUILT-IN SANITY CHECK

By design, GroupSpread and MovingAvg_8w forecast the same total volume, so their Total Bias is identical. Any gap in Active Seller Bias between them is pure allocation. It’s a quick way to show stakeholders why Total Bias alone isn’t enough.

Step 5: The Scorecard as a Function

One function scores any cut of the data. You pass the grouping columns and get back the counts, the three core metrics, % predictions on sellers, and a 3X3 matrix.

# 4. METRICS + DIAGNOSIS def diagnose(total_bias: float, asb: float, tol: float = 0.05) -> str: """Map (Total Bias, Active Seller Bias) to a plain-English behaviour label.""" vol = "balanced" if abs(total_bias - 1) <= tol else ("under" if total_bias < 1 else "over") foc = "low" if asb < 0.60 else ("mid" if asb <= 0.80 else "high") table = { ("balanced", "low"): "Balanced overall, but volume is not reaching selling SKUs", ("balanced", "mid"): "Balanced overall; focus on selling SKUs can improve", ("balanced", "high"): "Healthy: right volume, right places", ("under", "low"): "Under-forecasting and poorly identifying sellers", ("under", "mid"): "Under-forecasting with partial seller alignment", ("under", "high"): "Under-forecasting, but sellers are recognised", ("over", "low"): "Over-forecasting and missing sellers (volume on low/non-sellers)", ("over", "mid"): "Over-forecasting; seller focus can improve", ("over", "high"): "Over-forecasting, but in the right places", } return table[(vol, foc)] def backtest_metrics(df: pd.DataFrame, by: list[str] | None = None, pred: str = "pred", act: str = "actual") -> pd.DataFrame: """Compute the metric set for any reporting cut (grain = one row per SKU per window).""" d = df.assign(_seller=df[act] > 0, _abs_err_s=np.where(df[act] > 0, (df[pred] - df[act]).abs(), 0.0), _pred_s=np.where(df[act] > 0, df[pred], 0.0)) grp = d.groupby(by, observed=True) if by else d.assign(_all="All").groupby("_all") out = grp.agg(skus=(act, "size"), sellers=("_seller", "sum"), total_pred=(pred, "sum"), actuals=(act, "sum"), pred_on_sellers=("_pred_s", "sum"), abs_err_sellers=("_abs_err_s", "sum")) out["wmape"] = out["abs_err_sellers"] / out["actuals"] out["total_bias"] = out["total_pred"] / out["actuals"] out["active_seller_bias"] = out["pred_on_sellers"] / out["actuals"] out["pct_pred_on_sellers"] = out["pred_on_sellers"] / out["total_pred"] out["diagnosis"] = [diagnose(tb, a) for tb, a in zip(out["total_bias"], out["active_seller_bias"])] return out.drop(columns="abs_err_sellers").round(3) 

Step 6: Run the Backtest

def run_backtest(panel: pd.DataFrame, horizon: int = 6, n_folds: int = 4, fold_step: int = 6, models: dict = MODELS) -> pd.DataFrame: """Rolling-origin backtest. Each fold: train on data <= origin, forecast the next `horizon` weeks, aggregate to store-item (one row per SKU per fold).""" wide_df = panel.pivot_table(index=KEYS, columns="week", values="units", fill_value=0) meta = panel.drop_duplicates(KEYS).set_index(KEYS).loc[wide_df.index, ATTRS].reset_index() wide = wide_df.to_numpy(dtype=np.float32) n_weeks = wide.shape[1] last_origin = n_weeks - 1 - horizon origins = [last_origin - k * fold_step for k in range(n_folds)][::-1] results = [] for fold, origin in enumerate(origins, start=1): live = wide[:, : origin + 1].sum(axis=1) > 0 # SKU has launched by the origin age = add_product_age(panel, origin) base = meta.copy() base["fold"], base["origin_week"] = fold, origin base["actual"] = future_sum(wide, origin, horizon) base = base.join(age, on=KEYS) for name, fn in models.items(): res = base.copy() res["model"] = name res["pred"] = fn(wide, origin, horizon, meta=meta) results.append(res[live]) print(f"fold {fold}: origin week {origin}, forecast weeks {origin+1}-{origin+horizon}") out = pd.concat(results, ignore_index=True) out["product_age"] = out["product_age"].fillna("Old") return out 

The output has one row per store x item x fold x model, with the actual 6-week units, the prediction, and every segment attribute. Every report after this is just a groupby.

Step 7: Reports That Answer Business Questions

def store_flags(bt: pd.DataFrame, model: str, asb_threshold: float = 0.60) -> pd.DataFrame: s = backtest_metrics(bt[bt["model"] == model], by=["store_id"]) return s[s["active_seller_bias"] < asb_threshold].sort_values("active_seller_bias") def top_gaps(bt: pd.DataFrame, model: str, n: int = 10) -> pd.DataFrame: """Selling items where the model left the most demand unforecast.""" d = bt[(bt["model"] == model) & (bt["actual"] > 0)] g = d.groupby(["item_id", "dept_id"]).agg(actual=("actual", "sum"), pred=("pred", "sum")) g["gap"] = g["actual"] - g["pred"] g["asb"] = (g["pred"] / g["actual"]).round(2) return g.sort_values("gap", ascending=False).head(n) def plot_diagnostic_map(summary: pd.DataFrame, path: str | Path, label_col: str = "label"): import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 5.5)) zones = [(0, 0.6, "#fde2e1"), (0.6, 0.8, "#fff3cd"), (0.8, 1.6, "#dff5e3")] for y0, y1, c in zones: ax.axhspan(y0, y1, color=c, zorder=0) ax.axvspan(0.95, 1.05, color="#1f3b73", alpha=0.07, zorder=0) ax.axvline(1, color="#1f3b73", lw=1, ls="--") ax.scatter(summary["total_bias"], summary["active_seller_bias"], s=120, c="#1f3b73", edgecolor="white", zorder=3) for _, r in summary.iterrows(): ax.annotate(r[label_col], (r["total_bias"], r["active_seller_bias"]), xytext=(7, 5), textcoords="offset points", fontsize=9) ax.set_xlabel("Total Bias (sum F / sum A)") ax.set_ylabel("Active Seller Bias (sum F on sellers / sum A)") ax.set_title("Backtest diagnostic map", loc="left", fontweight="bold") ax.set_ylim(0, max(1.2, summary["active_seller_bias"].max() + 0.1)) fig.tight_layout() fig.savefig(path, dpi=160) plt.close(fig) 

 # 7. MAIN def main(): p = argparse.ArgumentParser() p.add_argument("--data-dir", default="./m5") p.add_argument("--stores", nargs="*", default=None, help="subset of store_ids, e.g. CA_1 TX_1") p.add_argument("--horizon", type=int, default=6) p.add_argument("--folds", type=int, default=4) p.add_argument("--synthetic", action="store_true", help="smoke-test on generated data") p.add_argument("--out", default="./backtest_out") a = p.parse_args() data_dir = make_synthetic_m5("./synthetic_m5") if a.synthetic else a.data_dir out = Path(a.out) out.mkdir(exist_ok=True) panel = load_m5_weekly(data_dir, a.stores) print(f"panel: {panel.shape[0]:,} rows | {panel[KEYS].drop_duplicates().shape[0]:,} SKUs " f"| {panel['week'].nunique()} weeks") bt = run_backtest(panel, horizon=a.horizon, n_folds=a.folds) bt.to_parquet(out / "backtest_rows.parquet") if _has_parquet() else bt.to_csv(out / "backtest_rows.csv", index=False) pd.set_option("display.width", 200, "display.max_columns", 20) overall = backtest_metrics(bt, by=["model"]) print("\n=== Model comparison (all folds) ===\n", overall) print("\n=== Stability across folds ===\n", backtest_metrics(bt, by=["model", "fold"])[["wmape", "total_bias", "active_seller_bias"]]) best = "GBM_Poisson" print(f"\n=== {best}: Product Age x State ===\n", backtest_metrics(bt[bt.model == best], by=["product_age", "state_id"])) print(f"\n=== {best}: Category ===\n", backtest_metrics(bt[bt.model == best], by=["cat_id"])) print(f"\n=== {best}: Stores with ASB < 0.60 ===\n", store_flags(bt, best)) print(f"\n=== {best}: Largest unforecast demand on sellers ===\n", top_gaps(bt, best)) m = overall.reset_index().rename(columns={"model": "label"}) plot_diagnostic_map(m, out / "diagnostic_map.png") overall.to_csv(out / "model_comparison.csv") def _has_parquet() -> bool: try: import pyarrow # noqa: F401 return True except ImportError: return False if __name__ == "__main__": main() 

How to Read the Output

Report

Question it answers

What to look for

Model Comparison

Which model should we trust?

Lowest WMAPE and Active Seller Bias closest to 1. Watch for models that win on WMAPE but lose on active seller bias.

Per-fold Stability

Is the result reproducible?

Metrics that jump between folds point to sensitivity to seasonality or events.

Product age x state

Is the problem systematic or local?

“New” rows usually show less seller bias: less history means more spreading.

Category/Department

Is it skewed by category?

A single department dragging the total down is a candidate for its own model or features

Store flags (ASB < 0.60)

Which doors need attention?

Stores where WMAPE looks fine but seller bias is low: forecasted volume is going to the wrong items

Top Gaps

Which items leave demand on the table?

Largest (actual-forecast) on sellers. Good for item-level deep dives.

PUBLISHING YOUR NUMBERS

Run the script on the M5 files and paste the model_comparison.csv and segment tables in here. The metric definitions, thresholds, and diagnosis text stay exactly the same.

Taking it Further

  • Price and Events: The dataset also has selling price information. Join the sell_prices.csv and the SNAP/event flags from calendar.csv as GBM features.
  • Censored Demand: Treat long zero runs after steady sales as possible stock-outs and exclude them from the seller/non-seller split.
  • Size-level data: Add size to KEYS. Seller bias at size level is often where spreading shows up first.
  • Release Gates: Make “WMAPE does not get worse and Active Seller Bias improves on New x every channel” as pass/fal check in your model CI.

KEY TAKEAWAYS

  1. Sum to a fixed window (e.g 6 weeks) at the Store x SKU grain before scoring.
  2. Use rolling origins with a strict leakage rule, so stability is visible and not assumed.
  3. Include a “spread” model as control: it shows the gap between total accuracy and allocation accuracy.
  4. Keep one scoring function and use it for every cut, so every report stays consistent.

This article concludes the two-part series on the Retail Backtesting Framework and key metrics to track to save retail and similar companies that deal in forecasts millions of dollars in misallocation and lost revenue.