diff --git a/CITATION.cff b/CITATION.cff index 1493676..64fc457 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,7 +2,7 @@ cff-version: 1.2.0 message: "If you use this teaching material, or the models in it, please cite it as below." title: "Teaching notebooks for IE 3315, IE 5301 and REE 4301" abstract: >- - Eighteen executed teaching notebooks and an accompanying Python package, + Nineteen executed teaching notebooks and an accompanying Python package, organised by subject across three courses in industrial engineering and energy systems modelling. Each notebook builds its model by hand and then asserts agreement with the packaged implementation, so the two cannot drift apart diff --git a/CLAUDE.md b/CLAUDE.md index 07e88fa..bbfe2f0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -136,7 +136,7 @@ They belong with the repository. Moved twice so far: to `C:\dev\` on 2026-09-05, ## Status, measured 2026-09-05 -Eighteen notebooks (seventeen as of 2026-09-05) across twelve subjects (`02` empty on purpose), sixteen package modules, thirty- +Nineteen notebooks (seventeen as of 2026-09-05) across twelve subjects (`02` empty on purpose), sixteen package modules, thirty- odd tables in `data/raw/`, 170 tests, and `tools/check_notebooks.py`. README.md has the table. **What to run before believing anything:** `python -m pytest tests/ -q`, diff --git a/README.md b/README.md index 423e7dd..67e784d 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ ahead of LP formulation, which is backwards. ## What is here, measured 2026-09-05 -Eighteen teaching notebooks in twelve subjects, each with its package module, its tables and its +Nineteen teaching notebooks in twelve subjects, each with its package module, its tables and its tests. `02_simplex_and_bases` is empty on purpose. Every notebook ships executed, ends in the agreement assertion, and passes `tools/check_notebooks.py`. @@ -136,7 +136,7 @@ agreement assertion, and passes `tools/check_notebooks.py`. | 04 | `transportation`, `assignment` | `transportation`, `assignment` | | 05 | `facility_location` | `facility_location` | | 06 | `curve_fit_lifting`, `pooling` | `nonconvex` | -| 07 | `newsvendor` | `newsvendor`, `data` | +| 07 | `newsvendor`, `risk_measures` | `newsvendor`, `data` | | 08 | `monte_carlo` | `montecarlo` | | 09 | `markov_and_queues` | `markov`, `queueing` | | 10 | `zero_sum_game`, `saddle_points` | `games` | diff --git a/notebooks/07_stochastic_and_newsvendor/risk_measures.ipynb b/notebooks/07_stochastic_and_newsvendor/risk_measures.ipynb new file mode 100644 index 0000000..309b3a5 --- /dev/null +++ b/notebooks/07_stochastic_and_newsvendor/risk_measures.ipynb @@ -0,0 +1,778 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cf596430", + "metadata": {}, + "source": [ + "# Risk, not just the average: VaR and CVaR for the newsvendor\n", + "\n", + "`newsvendor.ipynb` in this folder chose one order to maximise average profit, and ended by asking\n", + "what happens if you guard the worst scenario instead. The worst single scenario is a blunt thing to\n", + "guard. This notebook guards the worst quarter of them, two ways.\n", + "\n", + "**Value at Risk** at 75% is the profit you beat in three scenarios out of four: a threshold.\n", + "**Conditional Value at Risk** at 75% is the average profit across the worst quarter: the tail\n", + "itself. One of them is a linear program and the other needs an integer variable per scenario." + ] + }, + { + "cell_type": "markdown", + "id": "5cf949d6", + "metadata": {}, + "source": [ + "## Setup: where the package lives\n", + "\n", + "This notebook builds its models by hand and then checks them against `orteach`, the package in\n", + "`src/`. Run from a clone of the repository, `../../src` is right there. On Colab there is no clone\n", + "until this cell makes one, and no `gurobipy` until it installs it. Nothing here needs a secret." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "f4fb3bd9", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.160335Z", + "iopub.status.busy": "2026-10-27T13:50:50.160163Z", + "iopub.status.idle": "2026-10-27T13:50:50.172993Z", + "shell.execute_reply": "2026-10-27T13:50:50.172459Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "package: src\\orteach\n" + ] + } + ], + "source": [ + "import os, subprocess, sys\n", + "\n", + "REPO_URL = \"https://github.com/sear-labs/teaching-code\"\n", + "REF = \"v1.0.0\" # the release this notebook ships in: Colab clones THIS\n", + "\n", + "try:\n", + " import google.colab # noqa: F401 - succeeds only on Colab\n", + " ON_COLAB = True\n", + "except ImportError:\n", + " ON_COLAB = False\n", + "\n", + "if ON_COLAB:\n", + " if not os.path.isdir(\"/content/teaching-code\"):\n", + " subprocess.run([\"git\", \"clone\", \"--quiet\", \"--depth\", \"1\", \"--branch\", REF, REPO_URL, \"/content/teaching-code\"], check=True)\n", + " os.chdir(\"/content/teaching-code/notebooks/07_stochastic_and_newsvendor\")\n", + " subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"gurobipy>=11,<14\"], check=True)\n", + "\n", + "sys.path.insert(0, os.path.abspath(os.path.join(\"..\", \"..\", \"src\")))\n", + "try:\n", + " import orteach # noqa: F401\n", + "except ImportError:\n", + " raise SystemExit(\"orteach not found: run this notebook from its own folder inside the repository, \"\n", + " \"so that ../../src exists.\")\n", + "root = os.path.abspath(os.path.join(\"..\", \"..\"))\n", + "print(\"package:\", os.path.relpath(os.path.dirname(orteach.__file__), root))" + ] + }, + { + "cell_type": "markdown", + "id": "82706f3e", + "metadata": {}, + "source": [ + "## Licence setup\n", + "\n", + "Nothing here needs a key. `pip install gurobipy` ships a licence limited to two thousand variables\n", + "and constraints, and every model below is built to fit inside it (the next section says how). A machine\n", + "with its own licence file uses that instead, and on Colab three secrets read from the key icon in\n", + "the left sidebar are used when they are there. The environment starts silent, so no licence number\n", + "lands in an output cell." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "3ea4d2eb", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.175104Z", + "iopub.status.busy": "2026-10-27T13:50:50.174929Z", + "iopub.status.idle": "2026-10-27T13:50:50.235571Z", + "shell.execute_reply": "2026-10-27T13:50:50.235064Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "licence: local gurobi.lic\n" + ] + } + ], + "source": [ + "import gurobipy as gp\n", + "from gurobipy import GRB\n", + "\n", + "env = gp.Env(empty=True)\n", + "env.setParam(\"OutputFlag\", 0) # start silent: the licence banner, and its licence number, stay out of the outputs\n", + "try:\n", + " from google.colab import userdata\n", + " try:\n", + " env.setParam(\"WLSACCESSID\", userdata.get(\"GRB_WLSACCESSID\"))\n", + " env.setParam(\"WLSSECRET\", userdata.get(\"GRB_WLSSECRET\"))\n", + " env.setParam(\"LICENSEID\", int(userdata.get(\"GRB_LICENSEID\")))\n", + " licence = \"Colab Secrets (WLS)\"\n", + " except (userdata.SecretNotFoundError, userdata.NotebookAccessError):\n", + " licence = \"the size-limited licence pip ships\" # no key needed; see the note above\n", + "except ImportError:\n", + " licence = \"local gurobi.lic\"\n", + "env.start()\n", + "print(\"licence:\", licence)" + ] + }, + { + "cell_type": "markdown", + "id": "b1763a22", + "metadata": {}, + "source": [ + "## The economics and the scenarios\n", + "\n", + "The same newspaper as `newsvendor.ipynb`: each copy costs 2, sells for 15, and an unsold copy costs 3\n", + "to dispose of. The demand scenarios are that notebook's table, but only the first 400 of them. Every\n", + "model here has about four variables per scenario, so 400 keeps the largest under the free\n", + "licence's two thousand; a full licence can raise `SCENARIOS`. With `ALPHA` at 0.75 the tail is exactly\n", + "100 scenarios, so \"the worst quarter\" means a whole number of them." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "328fad37", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.237841Z", + "iopub.status.busy": "2026-10-27T13:50:50.237631Z", + "iopub.status.idle": "2026-10-27T13:50:50.252997Z", + "shell.execute_reply": "2026-10-27T13:50:50.252507Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "400 scenarios, demand from 33.4 to 731.2, mean 398.8\n", + "ALPHA 0.75: the worst quarter is 100 scenarios\n" + ] + } + ], + "source": [ + "from statistics import mean\n", + "from orteach import tolerance\n", + "from orteach.data import load_demand\n", + "\n", + "COST, RETAIL, RECOVER = 2, 15, -3\n", + "ALPHA = 0.75\n", + "SCENARIOS = 400\n", + "\n", + "demand = load_demand()[:SCENARIOS]\n", + "TAIL = round((1 - ALPHA) * SCENARIOS)\n", + "print(f\"{len(demand)} scenarios, demand from {min(demand):.1f} to {max(demand):.1f}, mean {mean(demand):.1f}\")\n", + "print(f\"ALPHA {ALPHA}: the worst quarter is {TAIL} scenarios\")" + ] + }, + { + "cell_type": "markdown", + "id": "28d53277", + "metadata": {}, + "source": [ + "## Two numbers for the tail, for an order you pick\n", + "\n", + "Score an order of 400 copies against every scenario, then sort the profits. VaR is the profit in\n", + "position `TAIL` of the sorted list (beaten in three scenarios out of four); CVaR is the mean of the\n", + "`TAIL` profits below it. Predict before running: which is larger, and by roughly how much?" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "7db07f2a", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.255046Z", + "iopub.status.busy": "2026-10-27T13:50:50.254867Z", + "iopub.status.idle": "2026-10-27T13:50:50.259489Z", + "shell.execute_reply": "2026-10-27T13:50:50.259001Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "order 400: mean 4495.20 VaR 4024.31 CVaR 2894.04\n" + ] + } + ], + "source": [ + "ORDER_GUESS = 400\n", + "guess_profits = [RETAIL * min(ORDER_GUESS, d) - COST * ORDER_GUESS + RECOVER * max(0, ORDER_GUESS - d)\n", + " for d in demand]\n", + "ranked = sorted(guess_profits)\n", + "guess_var, guess_cvar = ranked[TAIL], mean(ranked[:TAIL])\n", + "print(f\"order {ORDER_GUESS}: mean {mean(guess_profits):.2f} VaR {guess_var:.2f} CVaR {guess_cvar:.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "2db39308", + "metadata": {}, + "source": [ + "## CVaR as a linear program\n", + "\n", + "The average of the worst 100 profits looks like it needs sorting, which no LP can do. The way round\n", + "it (Rockafellar and Uryasev): CVaR is the largest value of $\\nu - \\frac{1}{100}\\sum_i \\max(0,\\ \\nu -\n", + "\\text{profit}_i)$ over all $\\nu$. Give each scenario an `excess` variable at least $\\nu -\n", + "\\text{profit}_i$ and at least zero, and the max disappears.\n", + "\n", + "The rest is the newsvendor skeleton: one `order` with no scenario index (decided before demand is\n", + "seen), and `sales` and `discount` per scenario (decided after). `BETA` weighs the average against\n", + "the tail: 1 is pure CVaR, 0 is the average alone." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "eda8ac22", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.261490Z", + "iopub.status.busy": "2026-10-27T13:50:50.261321Z", + "iopub.status.idle": "2026-10-27T13:50:50.297483Z", + "shell.execute_reply": "2026-10-27T13:50:50.296915Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1602 variables, 1200 constraints\n" + ] + } + ], + "source": [ + "mc = gp.Model(\"CVaR\", env=env)\n", + "tolerance.apply(mc)\n", + "order = mc.addVar(name=\"order\")\n", + "profit = mc.addVars(SCENARIOS, lb=-GRB.INFINITY, name=\"profit\")\n", + "sales = mc.addVars(SCENARIOS, ub=demand, name=\"sales\")\n", + "discount = mc.addVars(SCENARIOS, name=\"discount\")\n", + "mc.addConstrs((profit[i] == RETAIL * sales[i] - COST * order + RECOVER * discount[i] for i in range(SCENARIOS)), name=\"profit\")\n", + "mc.addConstrs((sales[i] + discount[i] == order for i in range(SCENARIOS)), name=\"demand\")\n", + "\n", + "nu = mc.addVar(lb=-GRB.INFINITY, name=\"nu\")\n", + "excess = mc.addVars(SCENARIOS, name=\"excess\") # >= 0 by default\n", + "mc.addConstrs((excess[i] >= nu - profit[i] for i in range(SCENARIOS)), name=\"excess\")\n", + "\n", + "BETA = 1.0\n", + "mc.setObjective((1 - BETA) * profit.sum() / SCENARIOS + BETA * (nu - excess.sum() / TAIL), GRB.MAXIMIZE)\n", + "mc.update()\n", + "print(mc.NumVars, \"variables,\", mc.NumConstrs, \"constraints\")" + ] + }, + { + "cell_type": "markdown", + "id": "04688756", + "metadata": {}, + "source": [ + "Predict before running: will the CVaR order be larger or smaller than the 400 you scored by hand,\n", + "and will its average profit be higher or lower?" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "80453201", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.299760Z", + "iopub.status.busy": "2026-10-27T13:50:50.299574Z", + "iopub.status.idle": "2026-10-27T13:50:50.311621Z", + "shell.execute_reply": "2026-10-27T13:50:50.311136Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "CVaR order 306.6096 objective 3285.4101\n", + "scored: mean 3810.80 VaR 3985.92 CVaR 3285.41\n" + ] + } + ], + "source": [ + "mc.optimize()\n", + "cvar_order = order.X\n", + "cvar_objective = mc.ObjVal\n", + "cvar_profits = [RETAIL * min(cvar_order, d) - COST * cvar_order + RECOVER * max(0, cvar_order - d) for d in demand]\n", + "ranked = sorted(cvar_profits)\n", + "print(f\"CVaR order {cvar_order:.4f} objective {cvar_objective:.4f}\")\n", + "print(f\"scored: mean {mean(cvar_profits):.2f} VaR {ranked[TAIL]:.2f} CVaR {mean(ranked[:TAIL]):.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "8fb4230d", + "metadata": {}, + "source": [ + "The profits were scored again from the order rather than read off `profit[i].X`. Hold that thought;\n", + "the VaR model below is where it matters.\n", + "\n", + "## Turning the dial\n", + "\n", + "The same model with `BETA` at 0 is the risk-neutral newsvendor; at one half it splits the\n", + "difference. Only the objective changes, so set a new one and solve again." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "f0b1c186", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.313632Z", + "iopub.status.busy": "2026-10-27T13:50:50.313457Z", + "iopub.status.idle": "2026-10-27T13:50:50.329018Z", + "shell.execute_reply": "2026-10-27T13:50:50.328484Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "BETA 0: order 459.7374 BETA 0.5: order 391.1796 BETA 1: order 306.6096\n" + ] + } + ], + "source": [ + "mc.setObjective(profit.sum() / SCENARIOS, GRB.MAXIMIZE) # BETA = 0\n", + "mc.optimize()\n", + "neutral_order = order.X\n", + "mc.setObjective(0.5 * profit.sum() / SCENARIOS + 0.5 * (nu - excess.sum() / TAIL), GRB.MAXIMIZE) # BETA = 0.5\n", + "mc.optimize()\n", + "mix_order = order.X\n", + "print(f\"BETA 0: order {neutral_order:.4f} BETA 0.5: order {mix_order:.4f} BETA 1: order {cvar_order:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "ceeec6a2", + "metadata": {}, + "source": [ + "Now sweep it: eleven settings of the dial, the same two lines each time, which is what a loop is\n", + "for. Predict the shape first: does the order fall evenly as the dial turns?" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "a09b0490", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:50.331119Z", + "iopub.status.busy": "2026-10-27T13:50:50.330941Z", + "iopub.status.idle": "2026-10-27T13:50:51.393843Z", + "shell.execute_reply": "2026-10-27T13:50:51.393169Z" + } + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAmoAAAE1CAYAAABX4szAAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjYsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvq6yFwwAAAAlwSFlzAAAPYQAAD2EBqD+naQAAVkdJREFUeJzt3XlYVHX/PvD7MCzKjsoqiCiKoqCAS7gEKu64IamJO/k8Zo9KWq71dcm0h3JBS0vDJTcKhEpLE0kQ05Q1QQxNQdFAzIVFBXTm/P7wYX5NoAIyzAHu13XNdcWZz5zzPr0dvTnbRxBFUQQRERERSY6WpgsgIiIiosoxqBERERFJFIMaERERkUQxqBERERFJFIMaERERkUQxqBERERFJFIMaERERkURpa7oAKVAoFPjzzz9hZGQEQRA0XQ4RERE1YKIooqioCDY2NtDSev4xMwY1AH/++Sfs7Ow0XQYRERE1Ijk5ObC1tX3uGAY1AEZGRgCe/g8zNjZWyzYUCgVu374Nc3PzF6ZnUh/2QTrYC2lgH6SDvZAOdfeisLAQdnZ2yvzxPAxqgPJ0p7GxsVqDWkl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0xO+vr7w8fFB79690bFjxwrXyj2PtrY2Nm3ahC+++AI2NjYYNWpUpeNatmyJH3/8EefOnUOXLl0wa9YsBAYG4r333qvytipjZmaGX3/9FZMmTcLq1avh5uaGvn374sCBA/j4448rHE0MDAzEvXv3MGHCBJXT0xs2bICZmRl69eqFESNGYPDgwXB3d3/h9nV1dfGf//wHwcHBylD43XffoVWrVujbt+9L7RtRYyGIlV10QUQkMeUPaP3iiy80sv0HDx6gZcuWWLduXYVrrqjqevTogaCgIEycOFHTpRDVCzyiRkT1wrJly2Bvb//C671qS0pKCg4cOIArV64gOTkZAQEBAPDMo2L0Yvn5+fD398frr7+u6VKI6g0eUSMiqkRKSgreeOMNZGZmQldXFx4eHli/fj1cXFw0XRoRNSIMakREREQSxVOfRERERBLFoEZEREQkUQxqRERERBLFoEZEREQkUQxqRERERBLFoEZEREQkUQxqRERERBLFoEZEREQkUf8Ptr2RIRExG4oAAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Figure: the order falls from 459.7 at BETA 0 to 306.6 at BETA 1; the drop at each step of 0.1 is [6.5, 8.9, 17.5, 15.3, 20.3, 40.0, 21.8, 7.0, 7.9, 7.9].\n" + ] + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "DIAL = [b / 10 for b in range(11)]\n", + "dial_orders = []\n", + "for b in DIAL:\n", + " mc.setObjective((1 - b) * profit.sum() / SCENARIOS + b * (nu - excess.sum() / TAIL), GRB.MAXIMIZE)\n", + " mc.optimize()\n", + " dial_orders.append(order.X)\n", + "\n", + "plt.figure(figsize=(7, 3.2))\n", + "plt.plot(DIAL, dial_orders, \"o-\", color=\"black\")\n", + "plt.xlabel(\"BETA (weight on CVaR)\")\n", + "plt.ylabel(\"order\")\n", + "plt.grid(alpha=0.3)\n", + "plt.show()\n", + "steps = [round(a - b, 1) for a, b in zip(dial_orders, dial_orders[1:])]\n", + "print(f\"Figure: the order falls from {dial_orders[0]:.1f} at BETA 0 to {dial_orders[-1]:.1f} at BETA 1; \"\n", + " f\"the drop at each step of 0.1 is {steps}.\")" + ] + }, + { + "cell_type": "markdown", + "id": "db1e854a", + "metadata": {}, + "source": [ + "## VaR as an integer program\n", + "\n", + "VaR is a threshold `worst` that profit must beat in all but 100 scenarios. Which 100 is the\n", + "model's choice, so each scenario gets a binary `excused`; an excused scenario's constraint is\n", + "switched off by a big-M term, and at most `TAIL` may be excused. That is one binary per scenario: a\n", + "MIP, where CVaR was an LP." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "53d0152c", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:51.396085Z", + "iopub.status.busy": "2026-10-27T13:50:51.395845Z", + "iopub.status.idle": "2026-10-27T13:50:51.431685Z", + "shell.execute_reply": "2026-10-27T13:50:51.431181Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1602 variables, 400 of them binary, 1201 constraints\n" + ] + } + ], + "source": [ + "BIG_M = RETAIL * max(demand) - (RECOVER - COST) * max(demand) # wider than any two profits apart\n", + "mv = gp.Model(\"VaR\", env=env)\n", + "tolerance.apply(mv)\n", + "v_order = mv.addVar(name=\"order\")\n", + "v_profit = mv.addVars(SCENARIOS, lb=-GRB.INFINITY, name=\"profit\")\n", + "v_sales = mv.addVars(SCENARIOS, ub=demand, name=\"sales\")\n", + "v_discount = mv.addVars(SCENARIOS, name=\"discount\")\n", + "mv.addConstrs((v_profit[i] == RETAIL * v_sales[i] - COST * v_order + RECOVER * v_discount[i] for i in range(SCENARIOS)), name=\"profit\")\n", + "mv.addConstrs((v_sales[i] + v_discount[i] == v_order for i in range(SCENARIOS)), name=\"demand\")\n", + "\n", + "worst = mv.addVar(lb=-GRB.INFINITY, name=\"worst\")\n", + "excused = mv.addVars(SCENARIOS, vtype=GRB.BINARY, name=\"excused\")\n", + "mv.addConstrs((worst - BIG_M * excused[i] <= v_profit[i] for i in range(SCENARIOS)), name=\"worst\")\n", + "mv.addConstr(excused.sum() <= TAIL, name=\"budget\")\n", + "mv.setObjective(worst, GRB.MAXIMIZE)\n", + "mv.update()\n", + "print(mv.NumVars, \"variables,\", mv.NumIntVars, \"of them binary,\", mv.NumConstrs, \"constraints\")" + ] + }, + { + "cell_type": "markdown", + "id": "a08191b4", + "metadata": {}, + "source": [ + "Predict before running: will the VaR order land above or below the CVaR order?\n", + "\n", + "Then read the tail two ways: from the model's own `profit` variables, and by scoring the order\n", + "against every scenario, as for CVaR." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "46e72cad", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:51.433785Z", + "iopub.status.busy": "2026-10-27T13:50:51.433606Z", + "iopub.status.idle": "2026-10-27T13:50:51.764564Z", + "shell.execute_reply": "2026-10-27T13:50:51.764040Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "VaR order 334.6840 objective (the threshold) 4350.8916 MIP gap 0.0e+00\n", + "tail CVaR from the model's profit variables -456.49\n", + "tail CVaR from scoring the order 3220.62\n" + ] + } + ], + "source": [ + "mv.optimize()\n", + "var_order = v_order.X\n", + "var_objective = mv.ObjVal\n", + "model_says = sorted(v_profit[i].X for i in range(SCENARIOS))\n", + "var_profits = [RETAIL * min(var_order, d) - COST * var_order + RECOVER * max(0, var_order - d) for d in demand]\n", + "scored = sorted(var_profits)\n", + "print(f\"VaR order {var_order:.4f} objective (the threshold) {var_objective:.4f} MIP gap {mv.MIPGap:.1e}\")\n", + "print(f\"tail CVaR from the model's profit variables {mean(model_says[:TAIL]):10.2f}\")\n", + "print(f\"tail CVaR from scoring the order {mean(scored[:TAIL]):10.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "b6f6f9ee", + "metadata": {}, + "source": [ + "Same order, two very different tails. Which one is true, and why does the model's own number\n", + "disagree? Count the scenarios where the two profits differ, and check whether they are the ones\n", + "the model excused." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "988119c8", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:51.766612Z", + "iopub.status.busy": "2026-10-27T13:50:51.766415Z", + "iopub.status.idle": "2026-10-27T13:50:51.771831Z", + "shell.execute_reply": "2026-10-27T13:50:51.771342Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "75 scenarios where the model's profit differs from the scored profit\n", + "100 scenarios excused; 75 of the differing ones are excused\n" + ] + } + ], + "source": [ + "differ = [i for i in range(SCENARIOS) if abs(v_profit[i].X - var_profits[i]) > tolerance.FEASIBILITY_ATOL]\n", + "excused_ones = [i for i in range(SCENARIOS) if excused[i].X > 0.5]\n", + "print(f\"{len(differ)} scenarios where the model's profit differs from the scored profit\")\n", + "print(f\"{len(excused_ones)} scenarios excused; {len(set(differ) & set(excused_ones))} of the differing ones are excused\")" + ] + }, + { + "cell_type": "markdown", + "id": "d20307f6", + "metadata": {}, + "source": [ + "## Four orders, side by side\n", + "\n", + "The risk-neutral order, the half-and-half mix, CVaR and VaR, each scored against the same 400\n", + "scenarios. Before running, say which order you expect to win each column." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "562384dc", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:51.773935Z", + "iopub.status.busy": "2026-10-27T13:50:51.773759Z", + "iopub.status.idle": "2026-10-27T13:50:51.780383Z", + "shell.execute_reply": "2026-10-27T13:50:51.779907Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " order mean VaR CVaR worst\n", + "risk-neutral 459.74 4620.83 3725.62 2595.35 -1698.36\n", + "mix 391.18 4453.98 4068.41 2938.14 -1355.57\n", + "CVaR 306.61 3810.80 3985.92 3285.41 -932.72\n", + "VaR 334.68 4068.32 4350.89 3220.62 -1073.09\n" + ] + } + ], + "source": [ + "compare = {\"risk-neutral\": neutral_order, \"mix\": mix_order, \"CVaR\": cvar_order, \"VaR\": var_order}\n", + "print(f\"{'':13} {'order':>9} {'mean':>9} {'VaR':>9} {'CVaR':>9} {'worst':>9}\")\n", + "for name, q in compare.items():\n", + " pr = sorted(RETAIL * min(q, d) - COST * q + RECOVER * max(0, q - d) for d in demand)\n", + " print(f\"{name:13} {q:9.2f} {mean(pr):9.2f} {pr[TAIL]:9.2f} {mean(pr[:TAIL]):9.2f} {pr[0]:9.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "c63dbda6", + "metadata": {}, + "source": [ + "Does each order win the column it was built for? Which order would you give a vendor who can\n", + "survive a bad quarter but not a bad day, and which number in the table would you show them?\n", + "\n", + "---\n", + "\n", + "# Now the streamlined version\n", + "\n", + "The same models, built in the package once: `newsvendor.solve_cvar` for the dial (any `beta`),\n", + "`newsvendor.solve_var` for the MIP, and `newsvendor.tail_stats` for the two tail numbers. Both\n", + "solvers score the order against every scenario before returning profits, for the reason found\n", + "above." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "9ad2d3d3", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:51.782314Z", + "iopub.status.busy": "2026-10-27T13:50:51.782113Z", + "iopub.status.idle": "2026-10-27T13:50:52.208128Z", + "shell.execute_reply": "2026-10-27T13:50:52.207606Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "risk-neutral order 459.7374 mean 4620.83 VaR 3725.62 CVaR 2595.35\n", + "mix order 391.1796 mean 4453.98 VaR 4068.41 CVaR 2938.14\n", + "CVaR order 306.6096 mean 3810.80 VaR 3985.92 CVaR 3285.41\n", + "VaR order 334.6840 mean 4068.32 VaR 4350.89 CVaR 3220.62\n" + ] + } + ], + "source": [ + "from orteach import newsvendor as nv\n", + "from orteach.tolerance import AGREEMENT_RTOL, rel_diff\n", + "\n", + "pkg = {\"risk-neutral\": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=0.0, env=env),\n", + " \"mix\": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=0.5, env=env),\n", + " \"CVaR\": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=1.0, env=env),\n", + " \"VaR\": nv.solve_var(demand, COST, RETAIL, RECOVER, ALPHA, env=env)}\n", + "for name, r in pkg.items():\n", + " v, c = nv.tail_stats(r.profits, ALPHA)\n", + " print(f\"{name:13} order {r.order:9.4f} mean {r.expected_profit:9.2f} VaR {v:9.2f} CVaR {c:9.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "5ccb7f3e", + "metadata": {}, + "source": [ + "## The agreement assertion\n", + "\n", + "Every optimal order here is unique (checked when this was written, by minimising and maximising the\n", + "order over each optimal set), so the orders are compared directly. So are the two objective values,\n", + "each against the package's honestly scored tail number, which is the claim that the model's\n", + "objective, unlike its profit variables, is true." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "2aba2c45", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:50:52.210427Z", + "iopub.status.busy": "2026-10-27T13:50:52.210253Z", + "iopub.status.idle": "2026-10-27T13:50:52.653097Z", + "shell.execute_reply": "2026-10-27T13:50:52.652582Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "19 comparisons\n", + " risk-neutral order hand 459.7374 package 459.7374 rel 0.00e+00\n", + " mix order hand 391.1796 package 391.1796 rel 0.00e+00\n", + " CVaR order hand 306.6096 package 306.6096 rel 0.00e+00\n", + " VaR order hand 334.6840 package 334.6840 rel 0.00e+00\n", + " CVaR objective = scored CVaR hand 3285.4101 package 3285.4101 rel 1.38e-16\n", + " VaR objective = scored VaR hand 4350.8916 package 4350.8916 rel 0.00e+00\n", + " ...\n", + "\n", + "notebook and package agree to 1.4e-16\n" + ] + } + ], + "source": [ + "cvar_v, cvar_c = nv.tail_stats(pkg[\"CVaR\"].profits, ALPHA)\n", + "var_v, var_c = nv.tail_stats(pkg[\"VaR\"].profits, ALPHA)\n", + "checks = [(\"risk-neutral order\", neutral_order, pkg[\"risk-neutral\"].order),\n", + " (\"mix order\", mix_order, pkg[\"mix\"].order),\n", + " (\"CVaR order\", cvar_order, pkg[\"CVaR\"].order),\n", + " (\"VaR order\", var_order, pkg[\"VaR\"].order),\n", + " (\"CVaR objective = scored CVaR\", cvar_objective, cvar_c),\n", + " (\"VaR objective = scored VaR\", var_objective, var_v),\n", + " (\"hand-scored CVaR\", mean(sorted(cvar_profits)[:TAIL]), cvar_c),\n", + " (\"hand-scored VaR\", sorted(var_profits)[TAIL], var_v)]\n", + "for b, q in zip(DIAL, dial_orders):\n", + " checks.append((f\"dial {b:.1f}\", q, nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=b, env=env).order))\n", + "\n", + "worst = max(rel_diff(h, k) for _, h, k in checks)\n", + "print(f\"{len(checks)} comparisons\")\n", + "for name, hand, packaged in checks[:6]:\n", + " print(f\" {name:30} hand {hand:10.4f} package {packaged:10.4f} rel {rel_diff(hand, packaged):.2e}\")\n", + "print(\" ...\")\n", + "assert worst < AGREEMENT_RTOL, f\"notebook and package disagree by {worst:.2e}\"\n", + "print(f\"\\nnotebook and package agree to {worst:.1e}\")" + ] + }, + { + "cell_type": "markdown", + "id": "a13df22c", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## Where to take this next\n", + "\n", + "- Set `ALPHA` to 0.95. The tail is now 20 scenarios. Predict which orders move most, then check.\n", + "- With a full licence, set `SCENARIOS` to 1000. Does the CVaR order settle, or keep moving?\n", + "- Give the VaR model's objective a tiny positive weight on average profit, so selling a copy is\n", + " never worth nothing to it. Does the model's own tail now agree with the scored one, and does the\n", + " VaR order change?\n", + "- Add the worst-case order from `newsvendor.ipynb` to the comparison table. Which column does it\n", + " win, and at what cost in the others?" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/src/orteach/newsvendor.py b/src/orteach/newsvendor.py index 2d537c3..18c3e44 100644 --- a/src/orteach/newsvendor.py +++ b/src/orteach/newsvendor.py @@ -17,6 +17,8 @@ solve_expected_value one order quantity, chosen as if demand were certain solve_perfect_information one order quantity PER scenario - a clairvoyant solve_max_worst_case the order that makes the worst scenario least bad + solve_cvar best average of the worst (1 - alpha) share, mixed with the mean + solve_var best (1 - alpha) quantile: a MIP, one binary per scenario The gaps between them are the content: EVPI is what clairvoyance would be worth, VSS is what modelling uncertainty is worth. @@ -174,6 +176,92 @@ def solve_max_worst_case(demand, cost, retail, recover, env=None) -> NewsvendorR return NewsvendorResult(order.X, [profit[i].X for i in range(n)], "max worst case") +# --------------------------------------------- tail risk (risk_measures.ipynb, 2026-10-27) +# +# VaR and CVaR at level alpha are defined here on a sample whose tail is a whole number of +# scenarios, (1 - alpha) * n. Then there is no fractional-tail convention to argue about: +# CVaR is the mean of the worst k profits, VaR the (k+1)-th worst, and the LP and MIP below +# return exactly those numbers. A sample that does not divide is refused, not rounded. + +def _tail_size(n: int, alpha: float) -> int: + k = round((1 - alpha) * n) + if k < 1 or abs((1 - alpha) * n - k) > 1e-9: + raise ValueError("(1 - alpha) * n = %g is not a whole number of scenarios; choose n and alpha " + "so it is (e.g. n = 400, alpha = 0.75 gives a tail of 100)" % ((1 - alpha) * n)) + return k + + +def tail_stats(profits, alpha: float) -> tuple[float, float]: + """(VaR, CVaR) of a profit sample at level alpha: the (k+1)-th worst profit, and the mean of + the k worst, where k = (1 - alpha) * n.""" + k = _tail_size(len(profits), alpha) + s = sorted(profits) + return s[k], sum(s[:k]) / k + + +def solve_cvar(demand, cost, retail, recover, alpha, beta=1.0, env=None) -> NewsvendorResult: + """Maximise (1 - beta) * mean profit + beta * CVaR_alpha(profit). beta = 0 is the + risk-neutral order (solve_stochastic); beta = 1 is pure CVaR. An LP, by the + Rockafellar-Uryasev form: CVaR = max over nu of nu - E[(nu - profit)^+] / (1 - alpha). + + Profits are re-scored from the order: a scenario above nu does not reach the objective, so + the solver may leave its sales short and its profit variable is not the order's profit.""" + _check_economics(cost, retail, recover) + n = len(demand) + k = _tail_size(n, alpha) + lo, hi = _bounds(demand, cost, retail, recover) + with gp.Model(env=env) as m: + tolerance.apply(m) + m.ModelSense = gp.GRB.MAXIMIZE + order = m.addVar(name="order") + profit = m.addVars(n, lb=lo, ub=hi, name="profit") + sales = m.addVars(n, ub=demand, name="sales") + discount = m.addVars(n, name="discount") + m.addConstrs((profit[i] == -order * cost + sales[i] * retail + + recover * discount[i] for i in range(n)), name="profit") + m.addConstrs((sales[i] + discount[i] == order for i in range(n)), name="demand") + nu = m.addVar(lb=-hi, ub=hi, name="nu") + excess = m.addVars(n, ub=hi - lo, name="excess") + m.addConstrs((excess[i] >= nu - profit[i] for i in range(n)), name="excess") + m.setObjective((1 - beta) * profit.sum() / n + beta * (nu - excess.sum() / k)) + m.optimize() + if m.Status != gp.GRB.OPTIMAL: + raise RuntimeError("CVaR model ended with status %d" % m.Status) + result = evaluate_order(demand, cost, retail, recover, order.X) + result.label = "CVaR mix, beta %g" % beta + return result + + +def solve_var(demand, cost, retail, recover, alpha, env=None) -> NewsvendorResult: + """Maximise VaR_alpha(profit): the largest w such that profit >= w in all but (1 - alpha) * n + scenarios. A MIP, one binary per scenario excusing it via a big-M term. Profits re-scored + from the order, because an excused scenario's profit variable is unconstrained from above.""" + _check_economics(cost, retail, recover) + n = len(demand) + k = _tail_size(n, alpha) + lo, hi = _bounds(demand, cost, retail, recover) + with gp.Model(env=env) as m: + tolerance.apply(m) + m.ModelSense = gp.GRB.MAXIMIZE + order = m.addVar(name="order") + profit = m.addVars(n, lb=lo, ub=hi, name="profit") + sales = m.addVars(n, ub=demand, name="sales") + discount = m.addVars(n, name="discount") + m.addConstrs((profit[i] == -order * cost + sales[i] * retail + + recover * discount[i] for i in range(n)), name="profit") + m.addConstrs((sales[i] + discount[i] == order for i in range(n)), name="demand") + worst = m.addVar(lb=lo, ub=hi, obj=1.0, name="worst") + excused = m.addVars(n, vtype=gp.GRB.BINARY, name="excused") + m.addConstrs((worst - (hi - lo) * excused[i] <= profit[i] for i in range(n)), name="worst") + m.addConstr(excused.sum() <= k, name="budget") + m.optimize() + if m.Status != gp.GRB.OPTIMAL: + raise RuntimeError("VaR model ended with status %d" % m.Status) + result = evaluate_order(demand, cost, retail, recover, order.X) + result.label = "VaR" + return result + + def evpi(stochastic: NewsvendorResult, perfect: NewsvendorResult) -> float: """Expected Value of Perfect Information — what clairvoyance would be worth.""" return perfect.expected_profit - stochastic.expected_profit diff --git a/tests/test_risk_measures.py b/tests/test_risk_measures.py new file mode 100644 index 0000000..eda658d --- /dev/null +++ b/tests/test_risk_measures.py @@ -0,0 +1,74 @@ +"""VaR and CVaR for the newsvendor, pinned (notebooks/07_stochastic_and_newsvendor/risk_measures.ipynb). + +The invariants are the theory: each model is the best of all of them on its own measure, the +dial with beta = 0 is the risk-neutral order, and turning the dial toward CVaR never raises +the order. Every model here is under the size-limited licence's 2,000 variables (400 scenarios: +at most 4 * 400 + 2), so these run in CI. +""" +import os +import sys + +import pytest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))), "src")) + +from orteach import data, newsvendor as nv # noqa: E402 +from orteach.tolerance import AGREEMENT_RTOL, FEASIBILITY_ATOL, rel_diff # noqa: E402 + +COST, RETAIL, RECOVER, ALPHA, SCENARIOS = 2, 15, -3, 0.75, 400 + + +@pytest.fixture(scope="module") +def demand(): + return data.load_demand()[:SCENARIOS] + + +@pytest.fixture(scope="module") +def sols(demand): + return {"mean": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=0.0), + "mix": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=0.5), + "cvar": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=1.0), + "var": nv.solve_var(demand, COST, RETAIL, RECOVER, ALPHA)} + + +def test_a_tail_that_is_not_whole_scenarios_is_refused(): + with pytest.raises(ValueError, match="whole number"): + nv.tail_stats(list(range(10)), 0.75) + + +def test_tail_stats_are_the_kth_worst_and_the_mean_below_it(): + profits = list(range(1, 9)) # alpha 0.75 on 8 -> tail of 2 + assert nv.tail_stats(profits, 0.75) == (3, 1.5) + + +def test_beta_zero_is_the_risk_neutral_order(demand, sols): + st = nv.solve_stochastic(demand, COST, RETAIL, RECOVER) + assert rel_diff(sols["mean"].order, st.order) < AGREEMENT_RTOL + + +def test_each_model_wins_on_its_own_measure(sols): + stats = {k: nv.tail_stats(s.profits, ALPHA) for k, s in sols.items()} + for k in sols: + assert stats["cvar"][1] >= stats[k][1] - FEASIBILITY_ATOL, k # CVaR best on CVaR + assert stats["var"][0] >= stats[k][0] - FEASIBILITY_ATOL, k # VaR best on VaR + assert sols["mean"].expected_profit >= sols[k].expected_profit - FEASIBILITY_ATOL, k + + +def test_the_var_order_beats_the_risk_neutral_order_on_both_tail_measures(sols): + """Scored honestly from its order. Read off the VaR model's own profit variables instead, + its tail looks catastrophic (excused scenarios' profits are left wherever the solver put + them); that was this file's first draft of the claim, and it was false.""" + var_v, var_c = nv.tail_stats(sols["var"].profits, ALPHA) + mean_v, mean_c = nv.tail_stats(sols["mean"].profits, ALPHA) + assert var_v > mean_v and var_c > mean_c + + +def test_the_dial_never_raises_the_order(demand): + orders = [nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=b / 10).order for b in range(11)] + assert all(b <= a + FEASIBILITY_ATOL for a, b in zip(orders, orders[1:])), orders + + +def test_the_orders_the_notebook_prints(sols): + for k, want in {"mean": 459.7374, "mix": 391.1796, "cvar": 306.6096, "var": 334.6840}.items(): + assert abs(sols[k].order - want) < 1e-3, (k, sols[k].order) diff --git a/tools/seeds/seed_risk.py b/tools/seeds/seed_risk.py new file mode 100644 index 0000000..9f8d13f --- /dev/null +++ b/tools/seeds/seed_risk.py @@ -0,0 +1,375 @@ +"""Seed for the newsvendor risk-measures notebook (07). Writes the notebook without outputs; execute it afterwards (README.md here).""" +import json +import os + +REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +OUT = os.path.join(REPO, "notebooks", "07_stochastic_and_newsvendor", "risk_measures.ipynb") +cells = [] + + +def md(t): + cells.append({"cell_type": "markdown", "metadata": {}, "source": t.strip("\n").splitlines(keepends=True)}) + + +def code(t): + cells.append({"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], + "source": t.strip("\n").splitlines(keepends=True)}) + + +md(r""" +# Risk, not just the average: VaR and CVaR for the newsvendor + +`newsvendor.ipynb` in this folder chose one order to maximise average profit, and ended by asking +what happens if you guard the worst scenario instead. The worst single scenario is a blunt thing to +guard. This notebook guards the worst quarter of them, two ways. + +**Value at Risk** at 75% is the profit you beat in three scenarios out of four: a threshold. +**Conditional Value at Risk** at 75% is the average profit across the worst quarter: the tail +itself. One of them is a linear program and the other needs an integer variable per scenario. +""") + +md(r""" +## Setup: where the package lives + +This notebook builds its models by hand and then checks them against `orteach`, the package in +`src/`. Run from a clone of the repository, `../../src` is right there. On Colab there is no clone +until this cell makes one, and no `gurobipy` until it installs it. Nothing here needs a secret. +""") +code(r''' +import os, subprocess, sys + +REPO_URL = "https://github.com/sear-labs/teaching-code" +REF = "v1.0.0" # the release this notebook ships in: Colab clones THIS + +try: + import google.colab # noqa: F401 - succeeds only on Colab + ON_COLAB = True +except ImportError: + ON_COLAB = False + +if ON_COLAB: + if not os.path.isdir("/content/teaching-code"): + subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", REF, REPO_URL, "/content/teaching-code"], check=True) + os.chdir("/content/teaching-code/notebooks/07_stochastic_and_newsvendor") + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "gurobipy>=11,<14"], check=True) + +sys.path.insert(0, os.path.abspath(os.path.join("..", "..", "src"))) +try: + import orteach # noqa: F401 +except ImportError: + raise SystemExit("orteach not found: run this notebook from its own folder inside the repository, " + "so that ../../src exists.") +root = os.path.abspath(os.path.join("..", "..")) +print("package:", os.path.relpath(os.path.dirname(orteach.__file__), root)) +''') + +md(r""" +## Licence setup + +Nothing here needs a key. `pip install gurobipy` ships a licence limited to two thousand variables +and constraints, and every model below is built to fit inside it (the next section says how). A machine +with its own licence file uses that instead, and on Colab three secrets read from the key icon in +the left sidebar are used when they are there. The environment starts silent, so no licence number +lands in an output cell. +""") +code(r''' +import gurobipy as gp +from gurobipy import GRB + +env = gp.Env(empty=True) +env.setParam("OutputFlag", 0) # start silent: the licence banner, and its licence number, stay out of the outputs +try: + from google.colab import userdata + try: + env.setParam("WLSACCESSID", userdata.get("GRB_WLSACCESSID")) + env.setParam("WLSSECRET", userdata.get("GRB_WLSSECRET")) + env.setParam("LICENSEID", int(userdata.get("GRB_LICENSEID"))) + licence = "Colab Secrets (WLS)" + except (userdata.SecretNotFoundError, userdata.NotebookAccessError): + licence = "the size-limited licence pip ships" # no key needed; see the note above +except ImportError: + licence = "local gurobi.lic" +env.start() +print("licence:", licence) +''') + +md(r""" +## The economics and the scenarios + +The same newspaper as `newsvendor.ipynb`: each copy costs 2, sells for 15, and an unsold copy costs 3 +to dispose of. The demand scenarios are that notebook's table, but only the first 400 of them. Every +model here has about four variables per scenario, so 400 keeps the largest under the free +licence's two thousand; a full licence can raise `SCENARIOS`. With `ALPHA` at 0.75 the tail is exactly +100 scenarios, so "the worst quarter" means a whole number of them. +""") +code(r''' +from statistics import mean +from orteach import tolerance +from orteach.data import load_demand + +COST, RETAIL, RECOVER = 2, 15, -3 +ALPHA = 0.75 +SCENARIOS = 400 + +demand = load_demand()[:SCENARIOS] +TAIL = round((1 - ALPHA) * SCENARIOS) +print(f"{len(demand)} scenarios, demand from {min(demand):.1f} to {max(demand):.1f}, mean {mean(demand):.1f}") +print(f"ALPHA {ALPHA}: the worst quarter is {TAIL} scenarios") +''') + +md(r""" +## Two numbers for the tail, for an order you pick + +Score an order of 400 copies against every scenario, then sort the profits. VaR is the profit in +position `TAIL` of the sorted list (beaten in three scenarios out of four); CVaR is the mean of the +`TAIL` profits below it. Predict before running: which is larger, and by roughly how much? +""") +code(r''' +ORDER_GUESS = 400 +guess_profits = [RETAIL * min(ORDER_GUESS, d) - COST * ORDER_GUESS + RECOVER * max(0, ORDER_GUESS - d) + for d in demand] +ranked = sorted(guess_profits) +guess_var, guess_cvar = ranked[TAIL], mean(ranked[:TAIL]) +print(f"order {ORDER_GUESS}: mean {mean(guess_profits):.2f} VaR {guess_var:.2f} CVaR {guess_cvar:.2f}") +''') + +md(r""" +## CVaR as a linear program + +The average of the worst 100 profits looks like it needs sorting, which no LP can do. The way round +it (Rockafellar and Uryasev): CVaR is the largest value of $\nu - \frac{1}{100}\sum_i \max(0,\ \nu - +\text{profit}_i)$ over all $\nu$. Give each scenario an `excess` variable at least $\nu - +\text{profit}_i$ and at least zero, and the max disappears. + +The rest is the newsvendor skeleton: one `order` with no scenario index (decided before demand is +seen), and `sales` and `discount` per scenario (decided after). `BETA` weighs the average against +the tail: 1 is pure CVaR, 0 is the average alone. +""") +code(r''' +mc = gp.Model("CVaR", env=env) +tolerance.apply(mc) +order = mc.addVar(name="order") +profit = mc.addVars(SCENARIOS, lb=-GRB.INFINITY, name="profit") +sales = mc.addVars(SCENARIOS, ub=demand, name="sales") +discount = mc.addVars(SCENARIOS, name="discount") +mc.addConstrs((profit[i] == RETAIL * sales[i] - COST * order + RECOVER * discount[i] for i in range(SCENARIOS)), name="profit") +mc.addConstrs((sales[i] + discount[i] == order for i in range(SCENARIOS)), name="demand") + +nu = mc.addVar(lb=-GRB.INFINITY, name="nu") +excess = mc.addVars(SCENARIOS, name="excess") # >= 0 by default +mc.addConstrs((excess[i] >= nu - profit[i] for i in range(SCENARIOS)), name="excess") + +BETA = 1.0 +mc.setObjective((1 - BETA) * profit.sum() / SCENARIOS + BETA * (nu - excess.sum() / TAIL), GRB.MAXIMIZE) +mc.update() +print(mc.NumVars, "variables,", mc.NumConstrs, "constraints") +''') + +md(r""" +Predict before running: will the CVaR order be larger or smaller than the 400 you scored by hand, +and will its average profit be higher or lower? +""") +code(r''' +mc.optimize() +cvar_order = order.X +cvar_objective = mc.ObjVal +cvar_profits = [RETAIL * min(cvar_order, d) - COST * cvar_order + RECOVER * max(0, cvar_order - d) for d in demand] +ranked = sorted(cvar_profits) +print(f"CVaR order {cvar_order:.4f} objective {cvar_objective:.4f}") +print(f"scored: mean {mean(cvar_profits):.2f} VaR {ranked[TAIL]:.2f} CVaR {mean(ranked[:TAIL]):.2f}") +''') + +md(r""" +The profits were scored again from the order rather than read off `profit[i].X`. Hold that thought; +the VaR model below is where it matters. + +## Turning the dial + +The same model with `BETA` at 0 is the risk-neutral newsvendor; at one half it splits the +difference. Only the objective changes, so set a new one and solve again. +""") +code(r''' +mc.setObjective(profit.sum() / SCENARIOS, GRB.MAXIMIZE) # BETA = 0 +mc.optimize() +neutral_order = order.X +mc.setObjective(0.5 * profit.sum() / SCENARIOS + 0.5 * (nu - excess.sum() / TAIL), GRB.MAXIMIZE) # BETA = 0.5 +mc.optimize() +mix_order = order.X +print(f"BETA 0: order {neutral_order:.4f} BETA 0.5: order {mix_order:.4f} BETA 1: order {cvar_order:.4f}") +''') + +md(r""" +Now sweep it: eleven settings of the dial, the same two lines each time, which is what a loop is +for. Predict the shape first: does the order fall evenly as the dial turns? +""") +code(r''' +import matplotlib.pyplot as plt + +DIAL = [b / 10 for b in range(11)] +dial_orders = [] +for b in DIAL: + mc.setObjective((1 - b) * profit.sum() / SCENARIOS + b * (nu - excess.sum() / TAIL), GRB.MAXIMIZE) + mc.optimize() + dial_orders.append(order.X) + +plt.figure(figsize=(7, 3.2)) +plt.plot(DIAL, dial_orders, "o-", color="black") +plt.xlabel("BETA (weight on CVaR)") +plt.ylabel("order") +plt.grid(alpha=0.3) +plt.show() +steps = [round(a - b, 1) for a, b in zip(dial_orders, dial_orders[1:])] +print(f"Figure: the order falls from {dial_orders[0]:.1f} at BETA 0 to {dial_orders[-1]:.1f} at BETA 1; " + f"the drop at each step of 0.1 is {steps}.") +''') + +md(r""" +## VaR as an integer program + +VaR is a threshold `worst` that profit must beat in all but 100 scenarios. Which 100 is the +model's choice, so each scenario gets a binary `excused`; an excused scenario's constraint is +switched off by a big-M term, and at most `TAIL` may be excused. That is one binary per scenario: a +MIP, where CVaR was an LP. +""") +code(r''' +BIG_M = RETAIL * max(demand) - (RECOVER - COST) * max(demand) # wider than any two profits apart +mv = gp.Model("VaR", env=env) +tolerance.apply(mv) +v_order = mv.addVar(name="order") +v_profit = mv.addVars(SCENARIOS, lb=-GRB.INFINITY, name="profit") +v_sales = mv.addVars(SCENARIOS, ub=demand, name="sales") +v_discount = mv.addVars(SCENARIOS, name="discount") +mv.addConstrs((v_profit[i] == RETAIL * v_sales[i] - COST * v_order + RECOVER * v_discount[i] for i in range(SCENARIOS)), name="profit") +mv.addConstrs((v_sales[i] + v_discount[i] == v_order for i in range(SCENARIOS)), name="demand") + +worst = mv.addVar(lb=-GRB.INFINITY, name="worst") +excused = mv.addVars(SCENARIOS, vtype=GRB.BINARY, name="excused") +mv.addConstrs((worst - BIG_M * excused[i] <= v_profit[i] for i in range(SCENARIOS)), name="worst") +mv.addConstr(excused.sum() <= TAIL, name="budget") +mv.setObjective(worst, GRB.MAXIMIZE) +mv.update() +print(mv.NumVars, "variables,", mv.NumIntVars, "of them binary,", mv.NumConstrs, "constraints") +''') + +md(r""" +Predict before running: will the VaR order land above or below the CVaR order? + +Then read the tail two ways: from the model's own `profit` variables, and by scoring the order +against every scenario, as for CVaR. +""") +code(r''' +mv.optimize() +var_order = v_order.X +var_objective = mv.ObjVal +model_says = sorted(v_profit[i].X for i in range(SCENARIOS)) +var_profits = [RETAIL * min(var_order, d) - COST * var_order + RECOVER * max(0, var_order - d) for d in demand] +scored = sorted(var_profits) +print(f"VaR order {var_order:.4f} objective (the threshold) {var_objective:.4f} MIP gap {mv.MIPGap:.1e}") +print(f"tail CVaR from the model's profit variables {mean(model_says[:TAIL]):10.2f}") +print(f"tail CVaR from scoring the order {mean(scored[:TAIL]):10.2f}") +''') + +md(r""" +Same order, two very different tails. Which one is true, and why does the model's own number +disagree? Count the scenarios where the two profits differ, and check whether they are the ones +the model excused. +""") +code(r''' +differ = [i for i in range(SCENARIOS) if abs(v_profit[i].X - var_profits[i]) > tolerance.FEASIBILITY_ATOL] +excused_ones = [i for i in range(SCENARIOS) if excused[i].X > 0.5] +print(f"{len(differ)} scenarios where the model's profit differs from the scored profit") +print(f"{len(excused_ones)} scenarios excused; {len(set(differ) & set(excused_ones))} of the differing ones are excused") +''') + +md(r""" +## Four orders, side by side + +The risk-neutral order, the half-and-half mix, CVaR and VaR, each scored against the same 400 +scenarios. Before running, say which order you expect to win each column. +""") +code(r''' +compare = {"risk-neutral": neutral_order, "mix": mix_order, "CVaR": cvar_order, "VaR": var_order} +print(f"{'':13} {'order':>9} {'mean':>9} {'VaR':>9} {'CVaR':>9} {'worst':>9}") +for name, q in compare.items(): + pr = sorted(RETAIL * min(q, d) - COST * q + RECOVER * max(0, q - d) for d in demand) + print(f"{name:13} {q:9.2f} {mean(pr):9.2f} {pr[TAIL]:9.2f} {mean(pr[:TAIL]):9.2f} {pr[0]:9.2f}") +''') + +md(r""" +Does each order win the column it was built for? Which order would you give a vendor who can +survive a bad quarter but not a bad day, and which number in the table would you show them? + +--- + +# Now the streamlined version + +The same models, built in the package once: `newsvendor.solve_cvar` for the dial (any `beta`), +`newsvendor.solve_var` for the MIP, and `newsvendor.tail_stats` for the two tail numbers. Both +solvers score the order against every scenario before returning profits, for the reason found +above. +""") +code(r''' +from orteach import newsvendor as nv +from orteach.tolerance import AGREEMENT_RTOL, rel_diff + +pkg = {"risk-neutral": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=0.0, env=env), + "mix": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=0.5, env=env), + "CVaR": nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=1.0, env=env), + "VaR": nv.solve_var(demand, COST, RETAIL, RECOVER, ALPHA, env=env)} +for name, r in pkg.items(): + v, c = nv.tail_stats(r.profits, ALPHA) + print(f"{name:13} order {r.order:9.4f} mean {r.expected_profit:9.2f} VaR {v:9.2f} CVaR {c:9.2f}") +''') + +md(r""" +## The agreement assertion + +Every optimal order here is unique (checked when this was written, by minimising and maximising the +order over each optimal set), so the orders are compared directly. So are the two objective values, +each against the package's honestly scored tail number, which is the claim that the model's +objective, unlike its profit variables, is true. +""") +code(r''' +cvar_v, cvar_c = nv.tail_stats(pkg["CVaR"].profits, ALPHA) +var_v, var_c = nv.tail_stats(pkg["VaR"].profits, ALPHA) +checks = [("risk-neutral order", neutral_order, pkg["risk-neutral"].order), + ("mix order", mix_order, pkg["mix"].order), + ("CVaR order", cvar_order, pkg["CVaR"].order), + ("VaR order", var_order, pkg["VaR"].order), + ("CVaR objective = scored CVaR", cvar_objective, cvar_c), + ("VaR objective = scored VaR", var_objective, var_v), + ("hand-scored CVaR", mean(sorted(cvar_profits)[:TAIL]), cvar_c), + ("hand-scored VaR", sorted(var_profits)[TAIL], var_v)] +for b, q in zip(DIAL, dial_orders): + checks.append((f"dial {b:.1f}", q, nv.solve_cvar(demand, COST, RETAIL, RECOVER, ALPHA, beta=b, env=env).order)) + +worst = max(rel_diff(h, k) for _, h, k in checks) +print(f"{len(checks)} comparisons") +for name, hand, packaged in checks[:6]: + print(f" {name:30} hand {hand:10.4f} package {packaged:10.4f} rel {rel_diff(hand, packaged):.2e}") +print(" ...") +assert worst < AGREEMENT_RTOL, f"notebook and package disagree by {worst:.2e}" +print(f"\nnotebook and package agree to {worst:.1e}") +''') + +md(r""" +--- + +## Where to take this next + +- Set `ALPHA` to 0.95. The tail is now 20 scenarios. Predict which orders move most, then check. +- With a full licence, set `SCENARIOS` to 1000. Does the CVaR order settle, or keep moving? +- Give the VaR model's objective a tiny positive weight on average profit, so selling a copy is + never worth nothing to it. Does the model's own tail now agree with the scored one, and does the + VaR order change? +- Add the worst-case order from `newsvendor.ipynb` to the comparison table. Which column does it + win, and at what cost in the others? +""") + +nb = {"cells": cells, "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, + "language_info": {"name": "python", "version": "3.13"}}, "nbformat": 4, "nbformat_minor": 5} +os.makedirs(os.path.dirname(OUT), exist_ok=True) +with open(OUT, "w", encoding="utf-8") as f: + json.dump(nb, f, indent=1, ensure_ascii=False) + f.write("\n") +print("wrote %s (%d cells)" % (OUT, len(cells)))