Part 2: Implementation - Building a Retail Backtesting Framework in Python on the M5 Walmart Data

Part 2: Implementation - Building a Retail Backtesting Framework in Python on the M5 Walmart Data

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. 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 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"] 0)] first = hist.groupby(KEYS)["week"].min().rename("first_week") return first.apply(lambda w: "New" if origin - w 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 str: """Map (Total Bias, Active Seller Bias) to a plain-English behaviour label.""" vol = "balanced" if abs(total_bias - 1) 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 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"] 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 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 Sum to a fixed window (e.g 6 weeks) at the Store x SKU grain before scoring. Use rolling origins with a strict leakage rule, so stability is visible and not assumed. Include a “spread” model as control: it shows the gap between total accuracy and allocation accuracy. 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.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.