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

Inventory Policies and Safety Stock

The newsvendor orders once. A distribution centre orders again and again, and each order arrives after a lead time that varies. DC-MTL keeps six ambient items (pasta, canned tomatoes, coffee, olive oil, rice, cereal) and orders them weekly today, by habit.

▶
Video for Day 52 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
52.1 What the history says
0:45–1:45
52.2 How much to order, and when
1:45–2:00
Break
2:00–2:45
52.3 Check it by simulation
2:45–3:45
52.4 Ordering once a week; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: a faster supplier?
4:45–5:00
Commit with Git + checklist

Three questions decide its stock:

  • How much to order each time?
  • When to order (the reorder point)?
  • How much extra to keep for bad luck (safety stock)?

Today you answer them with the classic formulas, then check the formulas with a simulation built on the DC's own history.

52.1 What the history says

Create day52/inventory.py:

"""Day 52: inventory policies for the ambient items at DC-MTL. EOQ, safety stock, reorder points, and a simulation
to check them. Unmet demand is lost (the stores are short-shipped).

Import it:  from inventory import load_items, eoq, sigma_lead_time, k_for_fill_rate, simulate_policy
"""
import numpy as np
import pandas as pd
from scipy import optimize, stats


def load_items(con):
    """One row per item: demand a day (mean, sd), lead time in days from the purchase orders (mean, sd), costs."""
    settings = dict(con.sql("SELECT * FROM inventory_settings").fetchall())
    items = con.sql("""
        SELECT i.*, q.quoted_lead_days, d.mean_day, d.sd_day, l.lead_mean, l.lead_sd
        FROM dc_items i
        JOIN dc_suppliers q USING (supplier_id)
        JOIN (SELECT item_id, avg(cases) AS mean_day, stddev_samp(cases) AS sd_day FROM dc_daily_demand GROUP BY ALL) d
             USING (item_id)
        JOIN (SELECT item_id, avg(received_on - ordered_on) AS lead_mean, stddev_samp(received_on - ordered_on) AS lead_sd
              FROM purchase_orders GROUP BY ALL) l USING (item_id)
        ORDER BY item_id""").df().set_index("item_id")
    items["hold_per_case_year"] = items.cost_per_case * settings["holding_rate_per_year"]
    return items, settings


def demand_history(con, item):
    return con.sql(f"SELECT cases FROM dc_daily_demand WHERE item_id = '{item}' ORDER BY demand_date").df().cases.to_numpy()


def lead_history(con, item):
    return con.sql(f"""SELECT received_on - ordered_on AS days FROM purchase_orders WHERE item_id = '{item}'""").df().days.to_numpy()


def eoq(annual_demand, order_cost, hold_per_year):
    """Economic order quantity: balances ordering (K D / Q) against holding (h Q / 2)."""
    return np.sqrt(2 * annual_demand * order_cost / hold_per_year)


def sigma_lead_time(mean_day, sd_day, lead_mean, lead_sd):
    """Spread of demand over a random lead time: sqrt(L sd_d^2 + d^2 sd_L^2)."""
    return np.sqrt(lead_mean * sd_day ** 2 + mean_day ** 2 * lead_sd ** 2)


def normal_loss(k):
    """Expected units short per unit of sd when stock covers mean + k sd: L(k) = pdf(k) - k (1 - cdf(k))."""
    return stats.norm.pdf(k) - k * stats.norm.sf(k)


def k_for_fill_rate(fill, q, sigma):
    """The safety factor k that gives fill rate `fill` with order quantity q: sigma L(k) = (1 - fill) q."""
    target = (1 - fill) * q / sigma
    return optimize.brentq(lambda k: normal_loss(k) - target, -4, 6)


def simulate_policy(demand_pool, lead_pool, rng, days, reorder_point=None, order_qty=None, review=None, order_up_to=None,
                    start=None):
    """Day by day: orders arrive, demand is met from stock (the rest is lost), then the policy looks at the
    inventory position (on hand + on order). (s, Q): when the position is at or below s, order Q.
    (R, S): every R days, order up to S. Demand and lead times are resampled from history."""
    on_hand = start if start is not None else (order_up_to or reorder_point + order_qty)
    pipeline = {}                                                   # arrival day -> cases
    demand_total = shipped = orders = 0.0
    stock_days = 0.0
    for day in range(days):
        on_hand += pipeline.pop(day, 0)
        d = demand_pool[rng.integers(len(demand_pool))]
        ship = min(d, on_hand)
        on_hand -= ship
        demand_total += d
        shipped += ship
        stock_days += on_hand
        position = on_hand + sum(pipeline.values())
        qty = 0
        if review is None and position <= reorder_point:
            qty = order_qty
        elif review is not None and day % review == 0:
            qty = max(0, order_up_to - position)
        if qty > 0:
            arrive = day + int(lead_pool[rng.integers(len(lead_pool))])
            pipeline[arrive] = pipeline.get(arrive, 0) + qty
            orders += 1
    return {"fill_rate": shipped / demand_total, "avg_on_hand": stock_days / days, "orders": orders,
            "lost": demand_total - shipped}

Then day52/run_inventory.py:

# ---------- 52.1 What the history says ----------
print("--- history")
print(items[["item_name", "supplier_id", "mean_day", "sd_day", "quoted_lead_days", "lead_mean", "lead_sd"]]
      .round(2).to_string())
--- history
                           item_name supplier_id  mean_day  sd_day  quoted_lead_days  lead_mean  lead_sd
item_id
AM-01               Pasta 500 g (12)       SUP-A    119.34   36.17                 5       5.96     1.11
AM-02    Canned tomatoes 796 ml (24)       SUP-A     87.04   26.30                 5       6.00     1.06
AM-03               Coffee 900 g (6)       SUP-B     26.37   11.40                10      10.65     2.77
AM-04              Olive oil 1 L (6)       SUP-B     17.74    8.72                10      11.77     3.50
AM-05          Basmati rice 2 kg (6)       SUP-C     42.62   13.57                 7       8.19     1.60
AM-06          Oat cereal 500 g (12)       SUP-C     61.93   17.59                 7       8.08     1.62

The suppliers are late: SUP-A quotes 5 days and takes 6, SUP-B quotes 10 and takes 11–12 with a spread of 3 days, SUP-C quotes 7 and takes 8. The lead time that matters is the one in the purchase orders, not the contract.

52.2 How much to order, and when

A continuous-review (s, Q) policy: whenever the inventory position (stock on hand plus stock on order) falls to ss, order QQ.

  • How much, the economic order quantity, balances the cost of ordering (KK per order, D/QD/Q orders a year) against the cost of holding (hh per case per year, Q/2Q/2 cases on average): Q∗=2DK/hQ^* = \sqrt{2DK/h}.
  • When: ss covers the demand expected during the lead time plus a safety stock. Demand over a random lead time has spread

σLT=Lˉ σd2+dˉ 2 σL2\sigma_{LT} = \sqrt{\bar L\,\sigma_d^2 + \bar d^{\,2}\,\sigma_L^2}

The second term is the lead time's own variation, which is large for SUP-B.

  • How much safety: two service measures are common.

    • Cycle service level: the chance of no stock-out in an order cycle, Φ(k)\Phi(k).
    • Fill rate: the share of demand shipped.

    The fill rate is what the stores feel. With kk the safety factor, each cycle is short by σLTL(k)\sigma_{LT}L(k) on average, so a fill rate β\beta needs σLTL(k)=(1−β) Q\sigma_{LT}L(k) = (1-\beta)\,Q.

# ---------- 52.2 How much to order, and when ----------
print("--- policy")
pol = pd.DataFrame(index=items.index)
pol["Q"] = np.round(eoq(items.mean_day * YEAR, K, items.hold_per_case_year))
pol["sigma_LT"] = sigma_lead_time(items.mean_day, items.sd_day, items.lead_mean, items.lead_sd)
pol["k"] = [k_for_fill_rate(fill, q, s) for q, s in zip(pol.Q, pol.sigma_LT)]
pol["safety_stock"] = np.round(pol.k * pol.sigma_LT)
pol["s"] = np.round(items.mean_day * items.lead_mean + pol.safety_stock)
pol["cycle_service"] = stats.norm.cdf(pol.k)
pol["orders_a_year"] = items.mean_day * YEAR / pol.Q
print(pol.round(2).to_string())
--- policy
              Q  sigma_LT     k  safety_stock      s  cycle_service  orders_a_year
item_id
AM-01    1990.0    159.49  0.35          55.0  766.0           0.64          21.89
AM-02    1293.0    112.41  0.40          45.0  567.0           0.66          24.57
AM-03     443.0     81.98  0.86          70.0  351.0           0.81          21.73
AM-04     393.0     68.94  0.83          57.0  266.0           0.80          16.47
AM-05     861.0     78.49  0.43          34.0  383.0           0.67          18.07
AM-06     828.0    112.26  0.68          76.0  576.0           0.75          27.30

A 98% fill rate needs only a small safety factor for pasta (kk = 0.35, a cycle service level of 64%). Each pasta order is big (1,990 cases, 17 days of demand), so stock-outs are rare in relative terms. Coffee and olive oil need more (k≈0.85k \approx 0.85): smaller orders, and a late, erratic supplier. Cycle service and fill rate are very different targets. Say which one you mean.

52.3 Check it by simulation

The formulas assume normal demand during the lead time and orders that don't cross. The simulation assumes neither: it resamples the DC's own daily demand and its own purchase-order lead times, for two years, 20 times.

# ---------- 52.3 Check it by simulation ----------
print("--- simulation (s, Q)")


def run(item, reps=20, seed=52, **policy):
    dem, lead = demand_history(con, item), lead_history(con, item)
    rng = np.random.default_rng(seed)
    sims = pd.DataFrame([simulate_policy(dem, lead, rng, DAYS, **policy) for _ in range(reps)]).mean()
    i = items.loc[item]
    sims["cost_a_year"] = (sims.avg_on_hand * i.hold_per_case_year + sims.orders / DAYS * YEAR * K
                           + sims.lost / DAYS * YEAR * i.margin_per_case)
    return sims


rows = []
for item in items.index:
    r = pol.loc[item]
    s = run(item, reorder_point=r.s, order_qty=r.Q)
    rows.append((item, r.s, r.Q, round(s.fill_rate, 4), round(s.avg_on_hand, 1), round(s.orders / DAYS * YEAR, 1),
                 round(s.cost_a_year, 0)))
sq = pd.DataFrame(rows, columns=["item", "s", "Q", "fill_rate", "avg_on_hand", "orders_a_year", "cost_a_year"])
print(sq.to_string(index=False))
--- simulation (s, Q)
 item     s      Q  fill_rate  avg_on_hand  orders_a_year  cost_a_year
AM-01 766.0 1990.0     0.9883       1077.4           21.4       8957.0
AM-02 567.0 1293.0     0.9885        710.1           23.9      10146.0
AM-03 351.0  443.0     0.9866        301.2           21.2       9867.0
AM-04 266.0  393.0     0.9881        265.3           15.9       6885.0
AM-05 383.0  861.0     0.9852        477.4           17.5       7381.0
AM-06 576.0  828.0     0.9866        504.1           26.6      12602.0

Every item reaches 98.5–98.9% against the 98% target. The formula is slightly conservative here, because the DC loses unmet demand rather than backordering it, and the formula counts backorders. The policies are right; the simulation is the check that makes you trust them.

52.4 Ordering once a week: (R, S)

Purchasing orders every item weekly today. A periodic-review (R, S) policy: every RR days, order up to SS. It must protect over the review period plus the lead time:

S=dˉ (R+Lˉ)+k σR+LS = \bar d\,(R + \bar L) + k\,\sigma_{R+L}

# ---------- 52.4 Ordering once a week: (R, S) ----------
print("--- simulation (R, S)")
rows = []
for item in items.index:
    i = items.loc[item]
    sigma = sigma_lead_time(i.mean_day, i.sd_day, i.lead_mean + R, i.lead_sd)      # protect over review + lead time
    q = i.mean_day * R                                                              # a week's demand per order
    S = np.round(i.mean_day * (R + i.lead_mean) + k_for_fill_rate(fill, q, sigma) * sigma)
    s = run(item, review=R, order_up_to=S)
    rows.append((item, S, round(s.fill_rate, 4), round(s.avg_on_hand, 1), round(s.orders / DAYS * YEAR, 1),
                 round(s.cost_a_year, 0)))
rs = pd.DataFrame(rows, columns=["item", "S", "fill_rate", "avg_on_hand", "orders_a_year", "cost_a_year"])
print(rs.to_string(index=False))
print(f"total cost a year: (s, Q) ${sq.cost_a_year.sum():,.0f}; weekly (R, S) ${rs.cost_a_year.sum():,.0f}; "
      f"stock (s, Q) {sq.avg_on_hand.sum():,.0f} cases, (R, S) {rs.avg_on_hand.sum():,.0f}")
--- simulation (R, S)
 item      S  fill_rate  avg_on_hand  orders_a_year  cost_a_year
AM-01 1725.0     0.9945        665.9           52.5      11095.0
AM-02 1257.0     0.9959        486.5           52.5      11535.0
AM-03  582.0     0.9929        228.5           52.5      12434.0
AM-04  437.0     0.9957        181.7           52.5      10586.0
AM-05  742.0     0.9938        272.2           52.5      10325.0
AM-06 1065.0     0.9945        389.2           52.5      13212.0
total cost a year: (s, Q) $55,838; weekly (R, S) $69,187; stock (s, Q) 3,336 cases, (R, S) 2,224

The weekly policy holds less stock (2,224 cases against 3,336) but places 52 orders a year per item, against 16–27. At $150 an order it costs about $13,000 a year more across the six items. Two practical notes:

  • Joint ordering: pasta and tomatoes come from the same supplier. One weekly order for both halves the order cost, which narrows the gap. This is an exercise worth doing.
  • Weekly ordering is simpler to run. Use the numbers to decide whether the simplicity is worth $13,000.

Decision it supports: how much and when to reorder, and how much safety stock a service target needs.

Other decisions you can support the same way: spare parts for the fleet · hospital supplies · raw materials at a plant · cash kept in ATMs.

The planted bug

day52/bug_quoted_lead.py sets the reorder points from the suppliers' quoted lead times, with no lead-time variation ("that's what the contract says"). Run it.

rows = []
for item, i in items.iterrows():
    q = np.round(eoq(i.mean_day * 365, settings["order_cost_per_po"], i.hold_per_case_year))
    sigma = sigma_lead_time(i.mean_day, i.sd_day, i.quoted_lead_days, 0.0)          # quoted, and never late
    s = np.round(i.mean_day * i.quoted_lead_days + k_for_fill_rate(settings["target_fill_rate"], q, sigma) * sigma)
    rng = np.random.default_rng(52)
    sims = [simulate_policy(demand_history(con, item), lead_history(con, item), rng, 730, reorder_point=s, order_qty=q)
            for _ in range(20)]
    rows.append((item, s, q, round(np.mean([x["fill_rate"] for x in sims]), 4)))
print(pd.DataFrame(rows, columns=["item", "s", "Q", "fill_rate"]).to_string(index=False))
What happens, and why
 item     s      Q  fill_rate
AM-01 583.0 1990.0     0.9491
AM-02 431.0 1293.0     0.9460
AM-03 277.0  443.0     0.9500
AM-04 184.0  393.0     0.9228
AM-05 293.0  861.0     0.9461
AM-06 438.0  828.0     0.9318

The fill rate falls to 92–95%, against the 98% promised. Two errors compound: the suppliers are a day or more late on average, so even the expected lead-time demand is too low; and the lead time's spread, dˉ 2σL2\bar d^{\,2}\sigma_L^2, is left out of σLT\sigma_{LT}. Olive oil (SUP-B: 1.8 days late, with a 3.5-day spread) suffers most. Measure lead times from receipts; contracts describe what suppliers promise, not what they do.

Mini-project: a faster supplier?

SUP-D offers coffee (AM-03) and olive oil (AM-04) with a lead time of 4 ± 1 days, instead of SUP-B's 11–12 ± 3, at 2% more per case. Set a 98% fill-rate (s, Q) policy for each supplier and compare the full cost a year: purchases, holding, orders and lost margin.

Solution
"""Day 52 mini-project: supplier SUP-D offers coffee (AM-03) and olive oil (AM-04) with a lead time of 4 +/- 1 days
instead of SUP-B's 10 (11-12 in practice, +/- 3), at 2% more per case. Set a 98% fill-rate (s, Q) policy for each
supplier and compare the full cost a year: purchases, holding, orders and lost margin. Check with the simulation.

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

import duckdb
import numpy as np
import pandas as pd

sys.path.insert(0, "day52")
from inventory import demand_history, eoq, k_for_fill_rate, lead_history, load_items, sigma_lead_time, simulate_policy

pd.set_option("display.width", 180)
con = duckdb.connect("northbound.duckdb", read_only=True)
items, settings = load_items(con)
K, fill = settings["order_cost_per_po"], settings["target_fill_rate"]
offers = con.sql("SELECT * FROM dc_supplier_offers").df().set_index("item_id")
rows = []
for item, o in offers.iterrows():
    i = items.loc[item]
    dem = demand_history(con, item)
    for supplier, lead_mean, lead_sd, premium, leads in [
            (i.supplier_id, i.lead_mean, i.lead_sd, 0.0, lead_history(con, item)),
            (o.supplier_id, o.lead_mean_days, o.lead_sd_days, o.price_premium,
             np.clip(np.round(np.random.default_rng(7).normal(o.lead_mean_days, o.lead_sd_days, 500)), 1, None))]:
        cost = i.cost_per_case * (1 + premium)
        hold = cost * settings["holding_rate_per_year"]
        q = np.round(eoq(i.mean_day * 365, K, hold))
        sigma = sigma_lead_time(i.mean_day, i.sd_day, lead_mean, lead_sd)
        s = np.round(i.mean_day * lead_mean + k_for_fill_rate(fill, q, sigma) * sigma)
        rng = np.random.default_rng(520)                          # the same demand days for both suppliers
        sims = pd.DataFrame([simulate_policy(dem, leads, rng, 730, reorder_point=s, order_qty=q) for _ in range(20)]).mean()
        year = 365 / 730
        purchases = (i.mean_day * 365 - sims.lost * year) * cost          # cases shipped a year, at the price
        rows.append((item, supplier, s, q, round(sims.fill_rate, 4), round(sims.avg_on_hand, 1),
                     round(purchases), round(sims.avg_on_hand * hold), round(sims.orders * year * K),
                     round(sims.lost * year * i.margin_per_case)))
t = pd.DataFrame(rows, columns=["item", "supplier", "s", "Q", "fill_rate", "avg_on_hand", "purchases", "holding",
                                "ordering", "lost_margin"])
t["total"] = t[["purchases", "holding", "ordering", "lost_margin"]].sum(axis=1)
print(t.to_string(index=False))
for item, g in t.groupby("item"):
    print(f"{item}: switching to {g.supplier.iloc[1]} changes the cost by ${g.total.iloc[1] - g.total.iloc[0]:+,.0f} a year "
          f"(stock {g.avg_on_hand.iloc[1] - g.avg_on_hand.iloc[0]:+,.0f} cases)")
    other = g[["holding", "ordering", "lost_margin"]].sum(axis=1)
    print(f"    break-even premium: {(other.iloc[0] - other.iloc[1]) / g.purchases.iloc[0]:.2%} "
          f"(the faster supplier saves ${other.iloc[0] - other.iloc[1]:,.0f} a year before the price)")
 item supplier     s     Q  fill_rate  avg_on_hand  purchases  holding  ordering  lost_margin  total
AM-03    SUP-B 351.0 443.0     0.9853        297.9     557488     4379      3191         2522 567580
AM-03    SUP-D 117.0 439.0     0.9874        237.2     569863     3556      3229         2162 578810
AM-04    SUP-B 266.0 393.0     0.9874        259.8     322135     3273      2415         1241 329064
AM-04    SUP-D  76.0 389.0     0.9876        205.3     328651     2638      2434         1219 334942
AM-03: switching to SUP-D changes the cost by $+11,230 a year (stock -61 cases)
    break-even premium: 0.21% (the faster supplier saves $1,145 a year before the price)
AM-04: switching to SUP-D changes the cost by $+5,878 a year (stock -54 cases)
    break-even premium: 0.20% (the faster supplier saves $638 a year before the price)
  • The faster supplier cuts the reorder point by two-thirds and the stock by 54–61 cases. But holding costs only 25% a year, so that saves about $1,100 (coffee) and $640 (olive oil) a year.
  • The 2% premium adds about $12,400 and $6,500 a year to the purchases. Decline the offer.
  • The break-even premium is about 0.2%. A shorter lead time is worth exactly the stock it saves, and stock is cheap for items that don't spoil.

Note to Purchasing: "Stay with SUP-B for coffee and olive oil. SUP-D's faster delivery would save about $1,800 a year in stock and lost sales, but its 2% price premium adds about $18,900: $17,100 a year more in all. It would be worth it at a premium of 0.2% or less. Instead, raise SUP-B's late deliveries with them: they average 1–2 days beyond the quote."

Commit

git add .
git commit -m "Day 52: inventory policies and safety stock"
git push

Day 52 checklist

  • I can compute an EOQ, a safety stock and a reorder point.
  • I include lead-time variation, measured from receipts, in the safety stock.
  • I know the difference between cycle service level and fill rate.
  • I can set an (R, S) policy and compare it with (s, Q).
  • I check inventory formulas with a simulation on the real history.