- Value at risk (VaR): how bad the worst weeks get.
- Conditional value at risk (CVaR): how bad they are on average. CVaR fits into a linear program.
Today you measure both, put CVaR into the two-stage model, trace the trade-off between the average and the tail, and check that it holds a year later.
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 59–60:
mdp_settings: olive oil from an overnight wholesaler.replenishment_scenarios: stress tests for the capstone.
58.1 VaR and CVaR of a plan
For a level α (say 5%):
- VaR is the profit the worst α of weeks fall below.
- CVaR is the average profit in those worst α of weeks.
VaR says where the tail starts; CVaR says how deep it is. CVaR also has the properties a risk measure should have: diversifying never makes it look worse, and VaR doesn't always pass that test. Create day58/cvar.py:
"""Day 58: risk measures. Value at risk (VaR) and conditional value at risk (CVaR) of weekly profit, and CVaR inside
the two-stage bakery model (Rockafellar and Uryasev's linear formulation).
Import it: from cvar import var_cvar, add_cvar
"""
import numpy as np
import pyomo.environ as pyo
def var_cvar(profits, alpha=0.05, weights=None):
"""VaR: the profit the worst alpha of weeks fall below. CVaR: the average profit in those worst alpha of weeks
(the fraction of a week at the boundary counts in part). Equal weights unless given."""
x = np.asarray(profits, dtype=float)
w = np.full(len(x), 1 / len(x)) if weights is None else np.asarray(weights, dtype=float)
order = np.argsort(x)
x, w = x[order], w[order]
cum = np.cumsum(w)
k = int(np.searchsorted(cum, alpha - 1e-12)) # the week where the worst alpha ends
var = x[k]
take = np.minimum(w, np.maximum(alpha - (cum - w), 0)) # how much of each week is in the tail
return var, float((take * x).sum() / alpha)
def add_cvar(m, alpha=0.05, weight=0.5):
"""Replace a two-stage model's objective by (1 - weight) x expected profit + weight x CVaR_alpha(profit).
CVaR_alpha = max over eta of eta - (1 / alpha) E[(eta - profit)+] (linear with one extra variable per week)."""
n = len(m.W)
m.eta = pyo.Var() # at the optimum: the VaR
m.below = pyo.Var(m.W, within=pyo.NonNegativeReals) # how far each week falls below eta
m.tail = pyo.Constraint(m.W, rule=lambda m, w: m.below[w] >= m.eta - m.week_profit[w])
m.cvar = pyo.Expression(expr=m.eta - sum(m.below[w] for w in m.W) / (alpha * n))
m.mean = pyo.Expression(expr=sum(m.week_profit[w] for w in m.W) / n)
m.expected_profit.deactivate()
m.risk_objective = pyo.Objective(expr=(1 - weight) * m.mean + weight * m.cvar, sense=pyo.maximize)
return m
Then day58/run_cvar.py:
# ---------- 58.1 VaR and CVaR of a plan ----------
print("--- var and cvar")
rp = build_two_stage(d, econ, st, demand, weeks)
solve(rp)
prof = scenario_profits(rp)
for a in (0.05, 0.10, 0.20):
v, c = var_cvar(prof, a)
print(f"alpha {a:.0%}: VaR ${v:,.2f} (the worst {a:.0%} of weeks earn less), CVaR ${c:,.2f} (their average)")
worst = pd.Series(prof, index=weeks).nsmallest(6)
print("the worst weeks: " + ", ".join(f"{w} ${p:,.0f}" for w, p in worst.items()))
--- var and cvar
alpha 5%: VaR $111,962.72 (the worst 5% of weeks earn less), CVaR $98,574.43 (their average)
alpha 10%: VaR $112,636.39 (the worst 10% of weeks earn less), CVaR $105,481.90 (their average)
alpha 20%: VaR $113,109.97 (the worst 20% of weeks earn less), CVaR $109,179.07 (their average)
the worst weeks: 2025-01-06 $79,043, 2026-01-05 $83,584, 2026-07-06 $106,916, 2025-07-07 $109,635, 2025-06-30 $111,687, 2025-05-19 $111,963
The VaR at 5% is $111,963, barely below the average: on most weeks the plan does fine. But two weeks, the first weeks of January 2025 and 2026, earn $79,000 and $84,000, and they drag the CVaR down to $98,574. VaR doesn't see how bad those two weeks are; CVaR does.
58.2 CVaR in the model
Rockafellar and Uryasev showed that CVaR is the optimum of a small problem:
The positive part becomes one variable per week, , so the problem is linear and fits inside the two-stage model. At the optimum, is the VaR. The objective weights expected profit against CVaR:
# ---------- 58.2 CVaR in the model ----------
print("--- cvar model")
def solve_risk(weight, alpha=0.05, dem=demand, wk=weeks):
m = add_cvar(build_two_stage(d, econ, st, dem, wk), alpha, weight)
solve(m)
return m
m = solve_risk(1.0)
print(f"maximize CVaR 5%: eta = ${pyo.value(m.eta):,.2f} (the VaR), CVaR ${pyo.value(m.cvar):,.2f}, "
f"mean ${pyo.value(m.mean):,.2f}")
print(f"check from its weeks: VaR, CVaR = " + ", ".join(f"${x:,.2f}" for x in var_cvar(scenario_profits(m), 0.05)))
--- cvar model
maximize CVaR 5%: eta = $107,461.63 (the VaR), CVaR $103,807.19, mean $107,278.91
check from its weeks: VaR, CVaR = $107,461.63, $103,807.19
The model's CVaR matches the one computed from its own weeks: the formulation is right.
58.3 The mean-CVaR frontier
# ---------- 58.3 The mean-CVaR frontier ----------
print("--- frontier")
rows, plans = [], {}
for weight in (0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0):
m = solve_risk(weight)
p = scenario_profits(m)
plans[weight] = {q: max(0.0, pyo.value(m.x[q])) for q in m.P}
rows.append((weight, round(p.mean(), 2), round(var_cvar(p, 0.05)[1], 2), round(p.min(), 2),
round(sum(plans[weight].values()), 1)))
front = pd.DataFrame(rows, columns=["cvar_weight", "mean", "cvar_5", "worst_week", "batches_planned"])
print(front.to_string(index=False))
change = pd.DataFrame({"risk_neutral": pd.Series(plans[0.0]), "max_cvar": pd.Series(plans[1.0])}).round(2)
change["change"] = (change.max_cvar - change.risk_neutral).round(2)
print("largest changes, risk-neutral -> max CVaR:")
print(change[change.change.abs() > 1].sort_values("change").to_string())
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.plot(front.cvar_5, front["mean"], "o-", color="#3b82f6")
for r in front.itertuples():
ax.annotate(f"w={r.cvar_weight:g}", (r.cvar_5, r.mean), textcoords="offset points", xytext=(5, 4), fontsize=7,
color="#6b7280")
ax.set(xlabel="CVaR 5%: average of the worst 5% of weeks ($)", ylabel="expected profit a week ($)",
title="The mean-CVaR frontier of the bakery's week")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("figures/day58_cvar.png", dpi=150)
print("saved figures/day58_cvar.png")
--- frontier
cvar_weight mean cvar_5 worst_week batches_planned
0.00 112600.11 98574.43 79042.69 429.2
0.10 112510.87 100537.09 83038.36 426.2
0.25 112340.22 101545.08 84484.10 425.7
0.50 111967.78 102179.33 85095.31 423.7
0.75 109657.44 103597.52 91938.58 414.9
0.90 108897.13 103766.97 93499.06 413.7
1.00 107278.91 103807.19 96206.33 409.6
largest changes, risk-neutral -> max CVaR:
risk_neutral max_cvar change
BK-03 21.37 1.46 -19.91
BK-18 28.40 19.73 -8.67
BK-13 26.40 17.76 -8.64
BK-14 24.86 17.10 -7.76
BK-23 19.14 13.15 -5.99
BK-29 18.08 12.50 -5.58
BK-CR 30.11 24.65 -5.46
BK-12 14.50 9.87 -4.63
BK-WW 44.11 39.51 -4.60
BK-25 14.99 10.52 -4.47
BK-16 8.76 5.92 -2.84
BK-10 19.71 17.62 -2.09
BK-04 17.81 15.86 -1.95
BK-22 7.40 5.61 -1.79
BK-07 7.79 12.38 4.59
BK-15 0.00 4.99 4.99
BK-21 0.00 11.23 11.23
BK-20 0.00 14.94 14.94
BK-08 0.00 16.24 16.24
BK-24 0.00 16.66 16.66
saved figures/day58_cvar.png

- The frontier is steep at first: a weight of 0.5 gives up $632 a week on average and gains $3,605 in the worst 5% of weeks. Most of the tail can be protected cheaply. The last bit costs a lot: going from 0.5 to CVaR alone gives up another $4,689 a week for $1,628 more CVaR.
- How the plan protects itself: it bakes less of the products that fall furthest in January (rye BK-03, croissants, BK-13, BK-14, BK-18), and spreads into products the risk-neutral plan didn't make at all (BK-08, BK-20, BK-21, BK-24). This is diversification, as in a portfolio.
- Which point to choose is a judgement about risk appetite, not a calculation. The frontier shows management what each choice costs.
58.4 First year in, second year out
Each year in the history has one Christmas and one January. Plan on the first year, then test on the second:
# ---------- 58.4 First year in, second year out ----------
print("--- year out")
first, second = list(range(52)), list(range(52, len(weeks)))
pick = lambda idx: ({(p, k): demand[p, w] for p in d["products"] for k, w in enumerate(idx)}, [weeks[w] for w in idx])
d1, w1 = pick(first)
d2, w2 = pick(second)
rows = []
for weight in (0.0, 0.5, 1.0):
m = solve_risk(weight, dem=d1, wk=w1)
plan = {q: max(0.0, pyo.value(m.x[q])) for q in m.P}
ev = build_two_stage(d, econ, st, d2, w2, plan=plan)
solve(ev)
p_in, p_out = scenario_profits(m), scenario_profits(ev)
rows.append((weight, round(p_in.mean(), 2), round(var_cvar(p_in, 0.05)[1], 2), round(p_out.mean(), 2),
round(var_cvar(p_out, 0.05)[1], 2)))
print(f"trained on {w1[0]}..{w1[-1]}, tested on {w2[0]}..{w2[-1]}")
print(pd.DataFrame(rows, columns=["cvar_weight", "mean_train", "cvar_train", "mean_test", "cvar_test"]).to_string(index=False))
--- year out
trained on 2024-12-02..2025-11-24, tested on 2025-12-01..2026-11-16
cvar_weight mean_train cvar_train mean_test cvar_test
0.0 112588.33 98366.96 112598.93 98692.36
0.5 112006.62 101807.24 112021.45 102260.56
1.0 107772.35 103298.80 107833.23 103311.92
The trade-off holds a year later: the risk-averse plans keep their better CVaR on weeks they have never seen, at the same cost in mean. The tail has repeating causes here (the January drop happens every year), so protecting it generalizes. Tails with unique causes would not; check before trusting a CVaR plan.
Decision it supports: plans that trade a little average profit for much better bad weeks, at a price everyone can see.
Other decisions you can support the same way: portfolio allocation (CVaR is a standard risk limit) · capacity plans that must survive a bad season · energy contracts against price spikes · insurance purchases.
The planted bug
day58/bug_tail.py adds CVaR to the model by hand. Run it.
alpha, n = 0.05, len(weeks)
m.eta = pyo.Var()
m.below = pyo.Var(m.W, within=pyo.NonNegativeReals)
m.tail = pyo.Constraint(m.W, rule=lambda m, w: m.below[w] >= m.eta - m.week_profit[w])
m.expected_profit.deactivate()
m.risk = pyo.Objective(expr=m.eta - sum(m.below[w] for w in m.W) / n, sense=pyo.maximize)
solve(m)
p = scenario_profits(m)
print(f"the model's 'CVaR 5%': ${pyo.value(m.risk):,.2f} (eta ${pyo.value(m.eta):,.2f})")
print(f"the plan's mean ${p.mean():,.2f}; its real CVaR 5% ${var_cvar(p, 0.05)[1]:,.2f}; worst week ${p.min():,.2f}")
What happens, and why
the model's 'CVaR 5%': $112,600.11 (eta $114,269.81)
the plan's mean $112,600.11; its real CVaR 5% $98,574.43; worst week $79,042.69
The "CVaR" equals the mean, $112,600, and the plan is the risk-neutral one: its real CVaR is $98,574. The objective forgot to divide by α:
- Without , raising always pays until reaches the best week, so the formula collapses to the expected profit.
- With , each unit of costs times the share of weeks below it. then stops at the α-quantile, the VaR.
Check a risk model by recomputing its risk measure from its own scenario profits, as 58.2 does.
Mini-project: the CFO's risk limit
The CFO sets a limit: "the worst 5% of weeks must average at least $X". Maximize expected profit subject to , for X = $100,000, $102,000, $103,000 and $103,500. What does each limit cost a year? Does it still hold in the second year if the plan is made on the first?
Solution
"""Day 58 mini-project: the CFO sets a risk limit: "the worst 5% of weeks must average at least $X". Maximize expected
profit subject to CVaR_5% >= X for X = $100,000, $102,000, $103,000 and $103,500. What does each limit cost a year?
Does the limit still hold in the second year if the plan is made on the first?
Run from the repository root (after day06/load_tables.py): python day58/mini_project_cfo.py
"""
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
for folder in ("day06", "day42", "day44", "day53", "day58"):
sys.path.insert(0, folder)
from bakery import solve
from cvar import add_cvar, var_cvar
from two_stage import build_two_stage, load_two_stage, scenario_profits
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
d, econ, st, demand, weeks = load_two_stage(con)
idx1, idx2 = range(52), range(52, len(weeks))
pick = lambda idx: ({(p, k): demand[p, w] for p in d["products"] for k, w in enumerate(idx)}, [weeks[w] for w in idx])
rows, base = [], None
for limit in (None, 100_000, 102_000, 103_000, 103_500):
m = add_cvar(build_two_stage(d, econ, st, demand, weeks), 0.05, weight=0.0) # objective: expected profit
if limit:
m.cfo_limit = pyo.Constraint(expr=m.cvar >= limit)
solve(m)
p = scenario_profits(m)
base = base or p.mean()
# the same limit, planned on the first year and checked on the second
d1, w1 = pick(idx1)
m1 = add_cvar(build_two_stage(d, econ, st, d1, w1), 0.05, weight=0.0)
if limit:
m1.cfo_limit = pyo.Constraint(expr=m1.cvar >= limit)
try:
solve(m1)
d2, w2 = pick(idx2)
ev = build_two_stage(d, econ, st, d2, w2, plan={q: max(0.0, pyo.value(m1.x[q])) for q in m1.P})
solve(ev)
second = round(var_cvar(scenario_profits(ev), 0.05)[1], 2)
except RuntimeError:
second = "no plan meets it in year 1"
rows.append(("none" if limit is None else f"${limit:,}", round(p.mean(), 2), round(var_cvar(p, 0.05)[1], 2),
round((base - p.mean()) * 52), second))
print(pd.DataFrame(rows, columns=["cvar_limit", "expected_profit", "cvar_5", "cost_a_year", "cvar_5_second_year"])
.to_string(index=False))
cvar_limit expected_profit cvar_5 cost_a_year cvar_5_second_year
none 112600.11 98574.43 0 98692.36
$100,000 112548.37 100000.00 2690 100361.2
$102,000 112118.18 102000.00 25060 102502.19
$103,000 110776.65 103000.00 94820 103277.06
$103,500 109866.47 103500.00 142149 no plan meets it in year 1
- A $100,000 limit costs only $2,690 a year, and $102,000 costs $25,000. Both hold in the second year.
- $103,000 costs $95,000 a year. $103,500 costs $142,000, and no plan meets it using the first year alone: it is at the edge of what is possible.
- A CVaR constraint is easier to agree on than a weight. Executives can set a floor in dollars; the model finds the cheapest way to keep it.
Memo to the CFO: "A floor of $102,000 on the average of the worst 5% of weeks (today: $98,600) costs about $25,000 a year in expected profit and held up on a year of data the plan hadn't seen. Floors above $103,000 cost $95,000 a year or more."
Commit
git add .
git commit -m "Day 58: risk measures and CVaR"
git push
Day 58 checklist
- I can compute VaR and CVaR from scenario profits, and explain why CVaR sees the depth of the tail.
- I can add CVaR to an LP with Rockafellar and Uryasev's formulation.
- I can draw a mean-CVaR frontier and describe how the plan diversifies.
- I can impose a CVaR floor as a constraint, and check it out of sample.
- I verify a risk model by recomputing its measure from its scenarios.