- formulas and safety stock (Day 52);
- simulation-optimization (Day 49);
- robust sets (Day 57);
- validation on held-out data (Days 54 and 58);
- stress tests (Day 50).
The question from the DC manager: which replenishment policy should we use, and will it hold up if things get worse? Fit every policy on the first four months of history, judge it on the last two, then stress it.
60.1 The brief and the split
Create day60/replenish.py:
"""Day 60 capstone: replenishment policies for DC-MTL's six ambient items, fitted on the first four months and
judged on the last two, as tested and under stress.
Import it: from replenish import split_history, fit_policies, simulate_item, evaluate
"""
import numpy as np
import pandas as pd
from scipy import stats
from inventory import eoq, k_for_fill_rate, sigma_lead_time
def split_history(con, train_days=120):
"""Daily demand and purchase-order lead times, split by date: the first train_days days to fit, the rest to test."""
dem = con.sql("SELECT item_id, demand_date, cases FROM dc_daily_demand ORDER BY demand_date").df()
cut = sorted(dem.demand_date.unique())[train_days]
po = con.sql("""SELECT item_id, supplier_id, ordered_on, received_on - ordered_on AS lead FROM purchase_orders""").df()
part = lambda df, col, train: df[(df[col] < cut) if train else (df[col] >= cut)]
out = {}
for name, train in (("train", True), ("test", False)):
out[name] = {"demand": {i: g.cases.to_numpy() for i, g in part(dem, "demand_date", train).groupby("item_id")},
"lead": {i: g.lead.to_numpy() for i, g in part(po, "ordered_on", train).groupby("item_id")}}
return out, pd.Timestamp(cut).date()
def fit_policies(items, settings, train, sim_opt=None):
"""Five policies per item, all from training data only:
weekly today: every 7 days order up to S (98% fill-rate formula), one order per item
weekly_joint the same S, but one order per supplier each week (items share the order cost)
sQ_formula Day 52: EOQ and a 98% fill-rate reorder point
sQ_tuned Day 49: EOQ, reorder point searched by simulation (cheapest with simulated fill >= 98%)
sQ_robust Day 57: EOQ, reorder point for the longest lead time + sqrt(L) high days"""
K, fill, R = settings["order_cost_per_po"], settings["target_fill_rate"], int(settings["review_period_days"])
rows = []
for item, i in items.iterrows():
d, l = train["demand"][item], train["lead"][item]
mean, sd, lm, ls = d.mean(), d.std(ddof=1), l.mean(), l.std(ddof=1)
q = float(np.round(eoq(mean * 365, K, i.hold_per_case_year)))
sig = sigma_lead_time(mean, sd, lm, ls)
s_formula = float(np.round(mean * lm + k_for_fill_rate(fill, q, sig) * sig))
sig_r = sigma_lead_time(mean, sd, lm + R, ls)
big_s = float(np.round(mean * (R + lm) + k_for_fill_rate(fill, mean * R, sig_r) * sig_r))
high = np.quantile(d, 0.90) - mean
s_robust = float(np.round(mean * l.max() + np.sqrt(l.max()) * high))
s_tuned = sim_opt(item, q, s_formula) if sim_opt else s_formula
rows.append((item, i.supplier_id, q, s_formula, s_tuned, s_robust, big_s))
return pd.DataFrame(rows, columns=["item", "supplier", "Q", "s_formula", "s_tuned", "s_robust", "S_weekly"]).set_index("item")
def simulate_item(dem, lead, rng, days, s=None, q=None, review=None, up_to=None, demand_factor=1.0, extra_lead=0):
"""Day 52's simulation (lost sales), also returning the days on which orders were placed (for joint ordering)."""
on_hand = up_to if up_to is not None else s + q
pipeline, order_days = {}, []
wanted = shipped = stock = 0.0
for day in range(days):
on_hand += pipeline.pop(day, 0)
dd = round(dem[rng.integers(len(dem))] * demand_factor)
ship = min(dd, on_hand)
on_hand -= ship
wanted += dd
shipped += ship
stock += on_hand
position = on_hand + sum(pipeline.values())
qty = (q if position <= s else 0) if review is None else (max(0, up_to - position) if day % review == 0 else 0)
if qty > 0:
arrive = day + int(lead[rng.integers(len(lead))]) + extra_lead
pipeline[arrive] = pipeline.get(arrive, 0) + qty
order_days.append(day)
return {"wanted": wanted, "shipped": shipped, "avg_stock": stock / days, "order_days": order_days}
def evaluate(policies, items, settings, data, policy, reps=20, days=730, seed=60, demand_factor=1.0, late=None, extra=0):
"""Cost a year (holding + ordering + lost margin), fill rate and stock of one policy for all six items.
Every policy uses the same seed for each item: common random numbers."""
K = settings["order_cost_per_po"]
totals = {"holding": 0.0, "ordering": 0.0, "lost_margin": 0.0, "wanted": 0.0, "shipped": 0.0, "stock": 0.0}
item_fill = {}
joint_days = {}
for item, pol in policies.iterrows():
i = items.loc[item]
rng = np.random.default_rng([seed, int(item[-2:])])
ex = extra if late == i.supplier_id else 0
res = []
for r in range(reps):
if policy.startswith("weekly"):
out = simulate_item(data["demand"][item], data["lead"][item], rng, days, review=int(settings["review_period_days"]),
up_to=pol.S_weekly, demand_factor=demand_factor, extra_lead=ex)
else:
out = simulate_item(data["demand"][item], data["lead"][item], rng, days, s=pol[f"s_{policy[3:]}"], q=pol.Q,
demand_factor=demand_factor, extra_lead=ex)
res.append(out)
if policy == "weekly_joint":
joint_days.setdefault((pol.supplier, r), set()).update(out["order_days"])
year = 365 / days / reps
wanted, shipped = sum(o["wanted"] for o in res), sum(o["shipped"] for o in res)
totals["holding"] += np.mean([o["avg_stock"] for o in res]) * i.hold_per_case_year
totals["lost_margin"] += (wanted - shipped) * year * i.margin_per_case
if policy != "weekly_joint":
totals["ordering"] += sum(len(o["order_days"]) for o in res) * year * K
totals["wanted"] += wanted
totals["shipped"] += shipped
totals["stock"] += np.mean([o["avg_stock"] for o in res])
item_fill[item] = shipped / wanted
if policy == "weekly_joint":
totals["ordering"] = sum(len(v) for v in joint_days.values()) * 365 / days / reps * K
return {"cost_a_year": totals["holding"] + totals["ordering"] + totals["lost_margin"],
"holding": totals["holding"], "ordering": totals["ordering"], "lost_margin": totals["lost_margin"],
"fill_rate": totals["shipped"] / totals["wanted"], "worst_item_fill": min(item_fill.values()),
"stock": totals["stock"]}
Then day60/run_capstone.py:
# ---------- 60.1 The brief and the split ----------
print("--- split")
data, cut = split_history(con)
for name in ("train", "test"):
n_days = len(next(iter(data[name]["demand"].values())))
n_po = sum(len(v) for v in data[name]["lead"].values())
print(f"{name}: {n_days} days of demand, {n_po} purchase orders")
print(f"split on {cut}")
means = pd.DataFrame({n: {i: v.mean() for i, v in data[n]["demand"].items()} for n in ("train", "test")}).round(2)
means["lead_train"] = {i: v.mean() for i, v in data["train"]["lead"].items()}
means["lead_test"] = {i: v.mean() for i, v in data["test"]["lead"].items()}
print(means.round(2).to_string())
--- split
train: 120 days of demand, 105 purchase orders
test: 62 days of demand, 51 purchase orders
split on 2026-09-22
train test lead_train lead_test
AM-01 120.38 117.34 5.65 6.56
AM-02 86.69 87.73 6.12 5.78
AM-03 25.84 27.39 10.61 10.75
AM-04 17.83 17.55 11.94 11.44
AM-05 42.27 43.31 8.00 8.62
AM-06 63.27 59.34 8.06 8.12
Demand changes little between the periods. Lead times move by up to a day: SUP-A's pasta orders took 6.6 days in the test months against 5.7 before. A policy fitted on the past meets a slightly different future, as always.
60.2 Five policies, fitted on training data
| Policy | From | Rule |
|---|---|---|
weekly | today | every 7 days, order up to S (98% fill formula), one order per item |
weekly_joint | Day 52's note | the same, but one order per supplier each week |
sQ_formula | Day 52 | EOQ and the 98% fill-rate reorder point |
sQ_tuned | Day 49 | EOQ; reorder point searched by simulation on training data (cheapest with fill ≥ 98%) |
sQ_robust | Day 57 | EOQ; reorder point covering the longest lead time + √L high days |
# ---------- 60.2 Five policies, fitted on training data ----------
print("--- policies")
K, fill = settings["order_cost_per_po"], settings["target_fill_rate"]
def tune(item, q, s0):
"""Day 49: try reorder points around the formula's on the training data (same random numbers for each), keep the
cheapest with simulated fill rate >= 98%."""
i = items.loc[item]
best = None
for s in np.round(s0 * np.arange(0.70, 1.41, 0.05)):
rng = np.random.default_rng([600, int(item[-2:])])
res = [simulate_item(data["train"]["demand"][item], data["train"]["lead"][item], rng, 730, s=s, q=q)
for _ in range(20)]
f = sum(o["shipped"] for o in res) / sum(o["wanted"] for o in res)
cost = (np.mean([o["avg_stock"] for o in res]) * i.hold_per_case_year
+ sum(o["wanted"] - o["shipped"] for o in res) / 40 * i.margin_per_case)
if f >= fill and (best is None or cost < best[0]):
best = (cost, s)
return float(best[1]) if best else float(s0)
pol = fit_policies(items, settings, data["train"], sim_opt=tune)
print(pol.to_string())
--- policies
supplier Q s_formula s_tuned s_robust S_weekly
item
AM-01 SUP-A 1999.0 729.0 875.0 1109.0 1693.0
AM-02 SUP-A 1291.0 568.0 710.0 793.0 1249.0
AM-03 SUP-B 439.0 350.0 420.0 462.0 577.0
AM-04 SUP-B 394.0 274.0 315.0 350.0 448.0
AM-05 SUP-C 857.0 370.0 463.0 530.0 726.0
AM-06 SUP-C 837.0 609.0 731.0 776.0 1110.0
The tuned reorder points are about 20% above the formula's: in simulation, the formula falls short of 98% with lost sales and the real, skewed lead times. The robust points are higher still.
60.3 On the held-out months
# ---------- 60.3 On the held-out months ----------
print("--- test")
rows = []
for p in POLICIES:
r = evaluate(pol, items, settings, data["test"], p)
rows.append((p, round(r["cost_a_year"]), round(r["holding"]), round(r["ordering"]), round(r["lost_margin"]),
round(r["fill_rate"], 4), round(r["worst_item_fill"], 4), round(r["stock"])))
test = pd.DataFrame(rows, columns=["policy", "cost_a_year", "holding", "ordering", "lost_margin", "fill_rate",
"worst_item_fill", "stock_cases"])
print(test.to_string(index=False))
--- test
policy cost_a_year holding ordering lost_margin fill_rate worst_item_fill stock_cases
weekly 70224 16258 47250 6716 0.9927 0.9839 2178
weekly_joint 46599 16258 23625 6716 0.9927 0.9839 2178
sQ_formula 55315 23502 18915 12899 0.9847 0.9720 3300
sQ_tuned 49122 27856 19125 2141 0.9973 0.9951 3869
sQ_robust 50308 31027 19155 126 0.9999 0.9997 4369
- Ordering weekly item by item, as today, is the most expensive policy ($70,200 a year): $47,250 of it is order costs.
- Joint weekly orders cut that in half and are the cheapest policy on the test months ($46,600), with the same stock and service.
- The formula (s, Q) misses its target on the test months: 97.2% for the worst item, with $12,900 of lost margin. A policy fitted to the past met a future with slower suppliers.
- The tuned and robust policies keep every item above 99.5%, for $49,100 and $50,300.
60.4 Under stress
replenishment_scenarios: demand 20% higher, SUP-B three days later than usual, or both.
# ---------- 60.4 Under stress ----------
print("--- stress")
scen = con.sql("SELECT * FROM replenishment_scenarios").df()
rows = []
for s in scen.itertuples():
for p in POLICIES:
r = evaluate(pol, items, settings, data["test"], p, demand_factor=s.demand_factor,
late=None if s.late_supplier == "none" else s.late_supplier, extra=int(s.extra_lead_days))
rows.append((s.scenario, p, round(r["cost_a_year"]), round(r["fill_rate"], 4), round(r["worst_item_fill"], 4)))
stress = pd.DataFrame(rows, columns=["scenario", "policy", "cost_a_year", "fill_rate", "worst_item_fill"])
print(stress.pivot(index="policy", columns="scenario", values="cost_a_year").loc[POLICIES, scen.scenario].to_string())
print(stress.pivot(index="policy", columns="scenario", values="worst_item_fill").loc[POLICIES, scen.scenario].to_string())
fig, axes = plt.subplots(1, len(scen), figsize=(12, 3.4), sharey=True)
colours = dict(zip(POLICIES, ["#9aa4b2", "#6b7280", "#3b82f6", "#22a06b", "#e5484d"]))
for ax, s in zip(axes, scen.scenario):
g = stress[stress.scenario == s]
for r in g.itertuples():
ax.scatter(r.worst_item_fill * 100, r.cost_a_year / 1000, color=colours[r.policy], s=40, label=r.policy)
ax.axvline(98, ls="--", color="#c0c6d0", lw=1)
ax.set_title(s.replace("_", " "), fontsize=9)
ax.set_xlabel("worst item's fill rate (%)", fontsize=8)
ax.spines[["top", "right"]].set_visible(False)
axes[0].set_ylabel("cost a year ($ thousands)")
axes[0].legend(frameon=False, fontsize=7)
fig.tight_layout()
fig.savefig("figures/day60_policies.png", dpi=150)
print("saved figures/day60_policies.png")
--- stress
scenario as_tested demand_up_20 sup_b_late_3_days both
policy
weekly 70224 125218 76997 150411
weekly_joint 46599 101593 53372 126786
sQ_formula 55315 97411 66755 127927
sQ_tuned 49122 64680 51581 82930
sQ_robust 50308 54845 49860 62831
scenario as_tested demand_up_20 sup_b_late_3_days both
policy
weekly 0.9839 0.9100 0.9510 0.8442
weekly_joint 0.9839 0.9100 0.9510 0.8442
sQ_formula 0.9720 0.9282 0.9287 0.8208
sQ_tuned 0.9951 0.9720 0.9801 0.9089
sQ_robust 0.9997 0.9904 0.9937 0.9574
saved figures/day60_policies.png

- The weekly policies collapse: with 20% more demand, the worst item's fill rate falls to 91% and lost margin doubles the cost. Their order-up-to levels have no room for surprises between reviews.
- The robust policy barely moves: $62,800 a year with both stresses at once (worst item 95.7%), against $82,900 for the tuned policy and $126,800–150,400 for the weekly ones.
- The tuned policy is the best compromise if stress is unlikely. The robust one costs $1,200 a year more as tested and saves $1,700–$20,000 a year if SUP-B's delays or demand get worse.
60.5 The memo
A model memo
To: the DC-MTL manager and Purchasing. Re: how we reorder ambient items.
"We tested five reordering policies for our six ambient items. Each was fitted on May to September and judged on September to November, then stressed with 20% more demand and SUP-B three days late.
- Stop ordering every item weekly, one order each. It is our most expensive policy ($70,000 a year), mostly order costs, and it fails under stress (91% fill for the worst item when demand rises 20%).
- Reorder each item when its stock reaches a reorder point, with order quantities from the EOQ. Set the reorder points robustly: cover the longest lead time we have seen, plus a margin for high-demand days. As tested it costs about $50,000 a year with 99.9% fill. With higher demand and SUP-B late, it still fills 96% for the worst item at $63,000, while weekly ordering would cost $127,000–150,000.
- Next step: combine orders per supplier. Joint weekly ordering showed that sharing order costs saves about $23,000 a year. A policy that reorders by reorder point and adds other items from the same supplier to the truck when they are close to theirs (a 'can-order' policy) should get both savings.
- Watch the suppliers. SUP-A and SUP-B deliver one to two days later than quoted. Lead times, not demand, are our biggest risk."
Module 6 wrap-up
| Day | Idea | Northbound decision |
|---|---|---|
| 51 | The newsvendor | Croissant batches, yule logs, pooling |
| 52 | Inventory policies, safety stock | Reorder points at DC-MTL; a faster supplier? |
| 53 | Two-stage stochastic programs | The bakery's week with a top-up bake; an oven lease |
| 54 | Sample average approximation | How many scenarios; bounds on the gap |
| 55 | VSS and EVPI | What modelling uncertainty and better forecasts are worth |
| 56 | Chance constraints | Service promises; the union's overtime cap |
| 57 | Robust optimization | Oven times that vary; ordering without probabilities |
| 58 | CVaR | The bakery's bad weeks; the CFO's floor |
| 59 | MDPs, DP, Q-learning | Olive oil from an overnight wholesaler |
| 60 | Capstone | A replenishment policy that holds up |
Module 7 moves from uncertainty to trade-offs: decision trees and the value of information, several objectives at once, and how to present a choice between options that are each best at something.
Commit and tag
git add .
git commit -m "Day 60: capstone, a replenishment policy that holds up"
git tag v6.0-module6
git push
git push --tags
Then run the tests: tests/test_risk_and_dp.py checks Days 58–60:
- VaR and CVaR on known numbers;
- the CVaR model against its own weeks;
- a small DP that no (s, S) policy beats;
- weekly review ordering every week;
- the train/test split.
Add "day58", "day59" and "day60" to the folders in conftest.py.
"""Known answers for Days 58-60: VaR and CVaR, the CVaR model, dynamic programming, the capstone's simulation."""
import numpy as np
import pyomo.environ as pyo
import pytest
from bakery import solve
from cvar import add_cvar, var_cvar
from mdp import policy_cost, value_iteration
from replenish import simulate_item, split_history
from two_stage import build_two_stage, load_two_stage, scenario_profits
def test_var_cvar():
v, c = var_cvar(np.arange(1, 101), 0.05)
assert v == 5 and c == pytest.approx(3.0) # worst 5 of 100: 1..5, average 3
assert var_cvar([10.0, 20.0], 0.25)[1] == 10.0
def test_cvar_model_matches_its_weeks(con):
d, econ, st, demand, weeks = load_two_stage(con)
m = add_cvar(build_two_stage(d, econ, st, demand, weeks), 0.05, weight=1.0)
solve(m)
assert pyo.value(m.cvar) == pytest.approx(var_cvar(scenario_profits(m), 0.05)[1], abs=1e-4)
def test_dynamic_programming_small():
p = {"cap": 30, "pmf": np.full(6, 1 / 6), "K": 10.0, "m": 5.0, "h": 0.1, "step": 5}
order_up, avg, _ = value_iteration(p)
assert policy_cost(p, order_up)["cost_a_day"] == pytest.approx(avg, abs=1e-4)
n = np.arange(31)
for s, S in [(2, 10), (5, 15), (8, 20), (0, 30)]: # no (s, S) policy beats the DP
other = np.where(n <= s, S, n)
assert policy_cost(p, other)["cost_a_day"] >= avg - 1e-6
def test_weekly_review_orders_weekly():
out = simulate_item(np.array([5]), np.array([2]), np.random.default_rng(0), 70, review=7, up_to=50)
assert len(out["order_days"]) == 10 and out["shipped"] == out["wanted"]
def test_split(con):
data, cut = split_history(con)
assert len(data["train"]["demand"]["AM-01"]) == 120 and len(data["test"]["demand"]["AM-01"]) == 62
89 passed
Day 60 checklist
- I fit policies on one period and judge them on another.
- I compare policies by full cost (holding, ordering, lost margin) and by the worst item's service.
- I stress-test policies and choose one that holds up, at a price I can state.
- I can combine formulas, simulation-optimization and robust sets in one comparison.
- I can write a memo that says what to change, what it costs, and what to do next.