Prescriptive Analytics & Decision Intelligence
Overview / Module 6 / Day 51
Module 6 · Optimization under Uncertainty · Day 51 of 80

The Newsvendor

Module 5 measured how plans behave when the forecast is wrong. Module 6 builds that uncertainty into the decision itself. It starts with the simplest decision under uncertainty, and one of the most useful.

▶
Video for Day 51 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
51.1 The critical ratio
0:45–1:45
51.2 Which distribution?
1:45–2:00
Break
2:00–2:45
51.3 Leftovers and lost customers
2:45–3:45
51.4 How flat is the top?; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: yule logs for Christmas
4:45–5:00
Commit with Git + checklist

You order once, before demand is known. Order too much and the extra is wasted; order too little and the sales are lost. Newspapers, Christmas trees, fresh croissants and yule logs all work this way. The best order has a famous answer, the critical ratio, and you have used it twice already (Days 41 and 45). Today you derive it and choose the right distribution for it. You also see how leftovers that still sell and customers who don't come back change it.

Update the course data

Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). New for Days 51–53:

  • yule_log_history, yule_log_forecast and yule_log_economics: three Christmases of yule log sales, and this year's forecast.
  • dc_items, dc_suppliers, dc_daily_demand, purchase_orders, inventory_settings and dc_supplier_offers: six ambient items at DC-MTL.
  • bakery_two_stage: the day-old shelf and a mid-week top-up bake.

51.1 The critical ratio

Think about the last unit you order. It sells if demand is at least that high, with chance P(D≥Q)P(D \ge Q), and earns the margin you would otherwise lose, cuc_u (cost of under-ordering). Otherwise it is left over and costs coc_o (cost of over-ordering). Keep ordering while the last unit is worth it:

P(D≥Q) cu  ≥  P(D<Q) co⟹P(D<Q∗)=cucu+coP(D \ge Q)\, c_u \;\ge\; P(D < Q)\, c_o \quad\Longrightarrow\quad P(D < Q^*) = \frac{c_u}{c_u + c_o}

The best order is the quantile of demand at the critical ratio. If cuc_u is large compared with coc_o, order well above the forecast; if it is small, order below it. Create day51/newsvendor.py:

"""Day 51: the newsvendor. One order before demand is known; too much is wasted, too little is lost.

Import it:  from newsvendor import critical_ratio, q_normal, q_empirical, expected_profit, normal_expected_profit
"""
import numpy as np
from scipy import stats


def critical_ratio(price, cost, salvage=0.0, penalty=0.0):
    """under = what one unit too few costs (lost margin + lost goodwill); over = what one unit too many costs
    (cost - what a leftover still brings in). Order up to the quantile under / (under + over)."""
    under, over = price - cost + penalty, cost - salvage
    if under <= 0 or over <= 0:
        raise ValueError("a unit short and a unit left over must both cost something")
    return under / (under + over)


def q_normal(mean, sd, ratio):
    return mean + stats.norm.ppf(ratio) * sd


def q_empirical(samples, ratio):
    """The ratio-quantile of demand seen in history (or simulated): no distribution assumed."""
    return float(np.quantile(np.asarray(samples, dtype=float), ratio, method="inverted_cdf"))


def expected_profit(q, demand, price, cost, salvage=0.0, penalty=0.0):
    """Average profit of ordering q against many demand values (history or simulation)."""
    d = np.asarray(demand, dtype=float)
    sold = np.minimum(d, q)
    return float(np.mean(price * sold - cost * q + salvage * (q - sold) - penalty * (d - sold)))


def normal_expected_profit(q, mean, sd, price, cost, salvage=0.0, penalty=0.0):
    """The same for normal demand, with the loss function: E[short] = sd * L(z), L(z) = pdf(z) - z (1 - cdf(z))."""
    z = (q - mean) / sd
    short = sd * (stats.norm.pdf(z) - z * stats.norm.sf(z))
    sold = mean - short
    return price * sold - cost * q + salvage * (q - sold) - penalty * short

Then day51/run_newsvendor.py:

# ---------- 51.1 The critical ratio ----------
print("--- critical ratio")
e = econ.loc["BK-CR"]
price, cost = e.units_per_batch * e.transfer_price, e.units_per_batch * e.ingredient_cost      # per batch
ratio = critical_ratio(price, cost)
q = q_normal(e.forecast, 0.09 * e.forecast, ratio)
print(f"BK-CR: a batch short loses ${price - cost:,.0f}, a batch left over loses ${cost:,.0f}: "
      f"critical ratio {ratio:.3f}")
print(f"forecast {e.forecast:.0f} batches, sd 9% (Day 41): order up to {q:.2f} -> {int(np.ceil(q))} batches "
      f"(Day 41's simulation: 33)")
--- critical ratio
BK-CR: a batch short loses $250, a batch left over loses $100: critical ratio 0.714
forecast 31 batches, sd 9% (Day 41): order up to 32.58 -> 33 batches (Day 41's simulation: 33)

The formula gives Day 41's simulation answer in one line: 33 batches.

51.2 Which distribution?

Day 41 assumed normal errors with a 9% spread. Day 42 found the real forecast errors aren't normal: mostly small, with a few huge holiday weeks. The newsvendor needs one number from the distribution, its quantile at the critical ratio, so get that number right:

# ---------- 51.2 Which distribution? ----------
print("--- distribution")
errors = error_table(con)
rows = []
for sku in ("BK-SD", "BK-WW", "BK-CR"):
    e = econ.loc[sku]
    price, cost = e.units_per_batch * e.transfer_price, e.units_per_batch * e.ingredient_cost
    r = critical_ratio(price, cost)
    hist = e.forecast * errors[sku].to_numpy()                    # last 103 weeks' errors on this week's forecast
    qn = q_normal(hist.mean(), hist.std(ddof=1), r)
    qe = q_empirical(hist, r)
    rows.append((sku, round(r, 3), e.forecast, round(qn, 2), round(qe, 2),
                 round(expected_profit(e.forecast, hist, price, cost), 2), round(expected_profit(qn, hist, price, cost), 2),
                 round(expected_profit(qe, hist, price, cost), 2)))
print(pd.DataFrame(rows, columns=["sku", "ratio", "forecast", "q_normal", "q_history", "profit_forecast",
                                  "profit_normal", "profit_history"]).to_string(index=False))
print("(profits: average over the 103 historical weeks, per week; quantities in batches)")
--- distribution
  sku  ratio  forecast  q_normal  q_history  profit_forecast  profit_normal  profit_history
BK-SD  0.667      35.0     35.80      35.47         10264.01       10271.16        10280.50
BK-WW  0.625      45.0     45.74      45.68          8805.39        8819.54         8820.05
BK-CR  0.714      31.0     32.68      31.57          7557.81        7523.74         7581.89
(profits: average over the 103 historical weeks, per week; quantities in batches)
  • For bread, the two answers are close. For croissants, the normal distribution says 32.7 batches and the history says 31.6.
  • The normal's spread is inflated by the Christmas and January weeks. That pushes its 71st percentile too high, and ordering it earns less than simply ordering the forecast ($7,524 against $7,558).
  • The history's own quantile earns the most.
  • When the critical ratio is in the middle of the distribution and the tails are odd, use the empirical quantile. Fit a distribution when you need the far tail and have too little data for it.

51.3 Leftovers and lost customers

Two things change the ratio:

  • Salvage: leftovers that still bring in something. The bakery could open a day-old shelf: 30% of the price, and 40% of leftovers sell there.
  • Penalty: a customer who finds an empty shelf may not come back. That costs more than today's margin.

cu=price−cost+penalty,co=cost−salvagec_u = \text{price} - \text{cost} + \text{penalty}, \qquad c_o = \text{cost} - \text{salvage}

# ---------- 51.3 Leftovers and lost customers ----------
print("--- salvage and penalty")
salvage_share = shelf["day_old_price_share"] * shelf["day_old_sell_share"]
rows = []
for sku in ("BK-SD", "BK-WW", "BK-CR"):
    e = econ.loc[sku]
    hist = e.forecast * errors[sku].to_numpy()
    for label, salvage, penalty in [("thrown away", 0.0, 0.0), ("day-old shelf", salvage_share * e.transfer_price, 0.0),
                                    ("day-old shelf + lost goodwill $1", salvage_share * e.transfer_price, 1.0)]:
        r = critical_ratio(e.transfer_price, e.ingredient_cost, salvage, penalty)       # per unit
        rows.append((sku, label, round(r, 3), round(q_empirical(hist, r), 2)))
print(f"day-old shelf: {shelf['day_old_price_share']:.0%} of the price, {shelf['day_old_sell_share']:.0%} of leftovers "
      f"sell -> a leftover brings back {salvage_share:.0%} of the price")
print(pd.DataFrame(rows, columns=["sku", "leftovers", "ratio", "order_up_to"]).to_string(index=False))
--- salvage and penalty
day-old shelf: 30% of the price, 40% of leftovers sell -> a leftover brings back 12% of the price
  sku                        leftovers  ratio  order_up_to
BK-SD                      thrown away  0.667        35.47
BK-SD                    day-old shelf  0.758        35.73
BK-SD day-old shelf + lost goodwill $1  0.806        35.82
BK-WW                      thrown away  0.625        45.68
BK-WW                    day-old shelf  0.710        45.83
BK-WW day-old shelf + lost goodwill $1  0.786        46.04
BK-CR                      thrown away  0.714        31.57
BK-CR                    day-old shelf  0.812        31.81
BK-CR day-old shelf + lost goodwill $1  0.838        31.89

The day-old shelf raises every ratio by about 0.09, because a leftover now loses less. Lost goodwill raises it further. The quantities move only a little here, because the history's errors are tightly packed in the middle. The ratio is the policy: Store Operations can debate the penalty, and the quantity follows.

51.4 How flat is the top?

With normal demand there is a formula for expected profit, through the loss function L(z)=φ(z)−z(1−Φ(z))L(z) = \varphi(z) - z(1 - \Phi(z)). Expected units short are σL(z)\sigma L(z). Expected sales are the mean minus that.

# ---------- 51.4 How flat is the top? ----------
print("--- flat top")
e = econ.loc["BK-CR"]
price, cost = e.units_per_batch * e.transfer_price, e.units_per_batch * e.ingredient_cost
mean, sd = e.forecast, 0.09 * e.forecast
best = q_normal(mean, sd, critical_ratio(price, cost))
top = normal_expected_profit(best, mean, sd, price, cost)
for q in (27, 29, 31, 33, 35, 37):
    print(f"{q} batches: expected ${normal_expected_profit(q, mean, sd, price, cost):,.2f} "
          f"({normal_expected_profit(q, mean, sd, price, cost) - top:+,.2f} against the best, {best:.2f})")
qs = np.linspace(24, 40, 161)
fig, ax = plt.subplots(figsize=(7, 3.6))
for k, colour in [(0.09, "#3b82f6"), (0.18, "#e5484d")]:
    s = k * mean
    ax.plot(qs, [normal_expected_profit(x, mean, s, price, cost) for x in qs], color=colour, label=f"error sd {k:.0%}")
    qb = q_normal(mean, s, critical_ratio(price, cost))
    ax.plot([qb], [normal_expected_profit(qb, mean, s, price, cost)], "o", color=colour)
ax.axvline(mean, ls="--", color="#9aa4b2", lw=1)
ax.text(mean + 0.2, ax.get_ylim()[0] + 50, "forecast", color="#6b7280", fontsize=8)
ax.set(xlabel="croissant batches made", ylabel="expected profit a week ($)", title="The newsvendor's profit curve (BK-CR)")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("figures/day51_newsvendor.png", dpi=150)
print("saved figures/day51_newsvendor.png")
--- flat top
27 batches: expected $6,716.77 (-701.31 against the best, 32.58)
29 batches: expected $7,114.42 (-303.67 against the best, 32.58)
31 batches: expected $7,360.43 (-57.65 against the best, 32.58)
33 batches: expected $7,414.42 (-3.67 against the best, 32.58)
35 batches: expected $7,316.77 (-101.31 against the best, 32.58)
37 batches: expected $7,144.51 (-273.57 against the best, 32.58)
saved figures/day51_newsvendor.png

The newsvendor's profit curve

  • Near the top, the curve is flat: 33 batches loses $4 against the exact optimum.
  • The forecast (31) loses $58 a week. Two batches below the forecast, 29, loses $304. Being short costs more than being over, because cu>coc_u > c_o.
  • More uncertainty (the red curve) lowers the whole curve and moves the best order up.
  • The cost of uncertainty is the gap between the curves at their tops, about $330 a week here. Better forecasts are worth money: Day 55 puts a number on that.

Decision it supports: a one-shot order under uncertain demand: fresh food, seasonal goods, event capacity.

Other decisions you can support the same way: how many seats to overbook (the same ratio, with no-shows) · how much cloud capacity to reserve · how many temporary staff to hire for a peak.

The planted bug

day51/bug_ratio.py sets the croissant order with the critical ratio. Run it.

under, over = price - cost, cost
ratio = over / (under + over)                     # "the chance of having too much"
q = forecast + stats.norm.ppf(ratio) * 0.09 * forecast
print(f"critical ratio {ratio:.3f}: make {q:.2f} batches (forecast {forecast:.0f})")
What happens, and why
critical ratio 0.286: make 29.42 batches (forecast 31)

The answer is 29 batches, below the forecast for a product where running short costs 2.5 times as much as a leftover. The ratio is upside down: co/(cu+co)c_o/(c_u + c_o) is the chance of being short at the optimum, not the quantile to order. Sanity check: when a shortage costs more than a leftover, the answer must be above the median forecast.

Mini-project: yule logs for Christmas

Yule logs are baked once, on December 20, and sell until the 24th; on Boxing Day the leftovers go at half price and 60% of them sell. yule_log_history has three Christmases at every store (S40 only since it opened). Compare two options for 2026:

  • A: every store orders its own newsvendor quantity.
  • B: order for the chain, then move logs between stores on the 22nd and 23rd ($1.50 a log) to where they sell.
Solution
"""Day 51 mini-project: how many yule logs for Christmas 2026? The bakery makes them once (December 20); what isn't
sold by the 24th goes on sale at half price on Boxing Day, where 60% of them sell. Option A: every store orders its
own newsvendor quantity. Option B: order for the chain and move logs between stores on the 22nd and 23rd
($1.50 a log) to where they sell. Which earns more, and why?

Run from the repository root (after day06/load_tables.py):  python day51/mini_project_yule_logs.py
"""
import sys

import duckdb
import numpy as np
import pandas as pd

sys.path.insert(0, "day51")
from newsvendor import critical_ratio, q_empirical

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
econ = dict(con.sql("SELECT * FROM yule_log_economics").fetchall())
hist = con.sql("SELECT *, demand_logs / forecast_logs AS ratio FROM yule_log_history").df()
fc = con.sql("SELECT store_id, forecast_logs FROM yule_log_forecast ORDER BY store_id").df()
price, cost, move = econ["price"], econ["cost"], econ["transfer_cost_per_log"]
salvage = econ["boxing_day_price"] * econ["boxing_day_sell_share"]
ratio = critical_ratio(price, cost, salvage)
season = hist.groupby("season").ratio.mean()
print(f"a log short loses ${price - cost:.2f}, a log left over ${cost - salvage:.2f}: critical ratio {ratio:.3f}")
print("average error by season (demand / forecast): " + ", ".join(f"{s} {v:.3f}" for s, v in season.items())
      + f"; store-level spread {hist.ratio.std(ddof=1):.3f}")

# scenarios: a season's chain-wide level, times a store's own error from the same history (a bootstrap)
rng = np.random.default_rng(51)
resid = (hist.ratio / hist.season.map(season)).to_numpy()
n, f = 20_000, fc.forecast_logs.to_numpy()
level = season.to_numpy()[rng.integers(len(season), size=n)]
demand = np.round(f * level[:, None] * resid[rng.integers(len(resid), size=(n, len(f)))])

# A: every store on its own
qa = np.array([np.ceil(q_empirical(fi * hist.ratio, ratio)) for fi in f])
sold_a = np.minimum(demand, qa)
profit_a = (price * sold_a - cost * qa + salvage * (qa - sold_a)).sum(axis=1)


# B: one chain order, shared out by forecast, then moved to the stores that run short
def chain(q_total):
    alloc = np.floor(q_total * f / f.sum())
    alloc[: int(q_total - alloc.sum())] += 1
    short, spare = np.maximum(demand - alloc, 0).sum(axis=1), np.maximum(alloc - demand, 0).sum(axis=1)
    moved = np.minimum(short, spare)
    sold = np.minimum(demand.sum(axis=1), q_total)
    return price * sold - cost * q_total + salvage * (q_total - sold) - move * moved, moved


results = {q: chain(q)[0].mean() for q in range(int(f.sum() * 0.9), int(f.sum() * 1.4), 5)}
qb = max(results, key=results.get)
profit_b, moved = chain(qb)
rows = [("A: each store its own newsvendor", int(qa.sum()), profit_a.mean(), np.quantile(profit_a, 0.05),
         (qa - sold_a).sum(axis=1).mean(), 0.0),
        ("B: chain order + moves", qb, profit_b.mean(), np.quantile(profit_b, 0.05),
         np.maximum(qb - demand.sum(axis=1), 0).mean(), moved.mean())]
print(pd.DataFrame(rows, columns=["option", "logs_made", "expected_profit", "p5_profit", "left_over", "logs_moved"])
      .round(1).to_string(index=False))
print(f"forecast total {f.sum()}; B gains ${profit_b.mean() - profit_a.mean():,.2f} on average")
a log short loses $20.50, a log left over $1.90: critical ratio 0.915
average error by season (demand / forecast): 2023 1.050, 2024 1.016, 2025 1.022; store-level spread 0.321
                          option  logs_made  expected_profit  p5_profit  left_over  logs_moved
A: each store its own newsvendor       3055          37969.0    34358.7     1100.8         0.0
          B: chain order + moves       2143          39881.5    36168.7      169.3       171.3
forecast total 1921; B gains $1,912.56 on average
  • The ratio is very high (0.915): a missed sale loses $20.50, and a leftover only $1.90 after Boxing Day.
  • Option A has to cover each store's own 91st percentile, and a store's demand varies by about 32%. It bakes 3,055 logs and throws or discounts about 1,100.
  • Option B pools the stores. The chain's demand varies much less than each store's, because the store errors partly cancel. It needs only 2,143 logs, moves about 170, and earns about $1,900 more.
  • B doesn't pool perfectly: the scenarios keep each season's chain-wide level (all stores high in 2023), and that part doesn't cancel (Days 44 and 45).

Memo: "Bake 2,140 yule logs for the chain (forecast 1,921) and plan to move about 170 between stores on December 22–23. It earns about $1,900 more than letting each store order on its own, and leaves 900 fewer logs for Boxing Day."

Commit

git add .
git commit -m "Day 51: the newsvendor"
git push

Day 51 checklist

  • I can derive the critical ratio from the cost of one unit too few and one too many.
  • I use the empirical quantile when the distribution's shape is in doubt.
  • I include salvage and lost goodwill in the ratio.
  • I know the profit curve is flat at the top and steeper on the short side.
  • I can explain why pooling demand needs less stock, and why correlation limits it.