Lab 14 Solutions: Simulation App¶
These are the worked solutions of Lab 14, with the outputs. Try the lab yourself first.
In this lab you build a Monte Carlo simulation of Qahwa House’s Ramadan gift-box season for the Corniche branch in Jeddah, read its risks, simulate a bid for a catering contract, and put the gift-box model in a Streamlit app the manager can use.
The question. It is December 2025. Each branch orders its gift boxes for Ramadan 2026 once, from a supplier; nothing can be reordered during the season. A box sells for 150 SAR, costs 95 SAR, and a box left after Eid is worth 20 SAR. Corniche’s forecast is 520 boxes, and the chain’s habit is to order the forecast plus 20%. How many boxes should Corniche order, and what risk comes with that order?
How this lab works
Run the cells from top to bottom with Shift + Enter. Replace every
...with your code, then run the check cell under it.Extended track: after Part D, try the ★ challenges.
Submit before the next lab session: File → Download → Download .ipynb, plus your
giftbox_app.py.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
# Read a course dataset from the website, or from a local copy of the repository.
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
boxes = load("qahwa_giftbox_demand.csv")
PRICE, COST, LEFTOVER_VALUE = 150, 95, 20
boxes.tail(8)boxes has one row per season and branch: the marketing forecast made in December, the boxes ordered, sold and leftover, and the demand (sales plus the requests logged after a sell-out). The 2026 rows hold only the forecast.
Part A: The uncertain input¶
A1. How wrong were past forecasts?¶
Keep the past seasons (before 2026) in past, add a column ratio = demand / forecast, and store its mean and standard deviation in r_mean and r_sd.
past = boxes[boxes["season"] < 2026].copy()
past["ratio"] = past["demand"] / past["forecast"]
r_mean, r_sd = past["ratio"].mean(), past["ratio"].std()
print(f"demand / forecast: mean {r_mean:.3f}, standard deviation {r_sd:.3f}")demand / forecast: mean 0.955, standard deviation 0.187
check("A1 36 past seasons and branches", len(past) == 36)
check("A1 the forecasts run high: mean ratio about 0.955", abs(r_mean - 0.955) < 0.001)
check("A1 standard deviation about 0.187", abs(r_sd - 0.187) < 0.001)✅ A1 36 past seasons and branches
✅ A1 the forecasts run high: mean ratio about 0.955
✅ A1 standard deviation about 0.187
A2. Corniche’s demand in 2026¶
Model Corniche’s 2026 demand as forecast × ratio, with the ratio normal(r_mean, r_sd). Compute the mean mu and the standard deviation sigma of that demand.
FORECAST = 520
mu, sigma = FORECAST * r_mean, FORECAST * r_sd
print(f"Corniche 2026 demand: mean {mu:.1f}, standard deviation {sigma:.1f}")Corniche 2026 demand: mean 496.6, standard deviation 97.1
check("A2 mean demand about 497 boxes, below the forecast", abs(mu - 496.6) < 0.5)
check("A2 standard deviation about 97 boxes", abs(sigma - 97.1) < 0.5)✅ A2 mean demand about 497 boxes, below the forecast
✅ A2 standard deviation about 97 boxes
Part B: Simulate the season¶
B1. The model¶
Write season_profit(order, demand): 150 SAR for each box sold, 20 SAR for each box left over, minus 95 SAR for each box ordered. It must work when demand is a NumPy array (use np.minimum).
def season_profit(order, demand):
sold = np.minimum(order, demand)
leftover = order - sold
return PRICE * sold + LEFTOVER_VALUE * leftover - COST * ordercheck("B1 demand below the order", season_profit(500, 450) == 21_000)
check("B1 demand above the order", season_profit(500, 600) == 27_500)
check("B1 works on an array", np.array_equal(season_profit(500, np.array([450, 600])), [21_000, 27_500]))✅ B1 demand below the order
✅ B1 demand above the order
✅ B1 works on an array
B2. 10,000 seasons¶
Draw 10,000 values of the ratio from normal(r_mean, r_sd) with the generator rng, multiply by the forecast, round to whole boxes and replace any negative value by 0. Store the result in demand.
rng = np.random.default_rng(14)
N = 10_000
demand = np.maximum(np.round(FORECAST * rng.normal(r_mean, r_sd, N)), 0)
print(f"simulated demand: mean {demand.mean():.1f}, from {demand.min():.0f} to {demand.max():.0f}")simulated demand: mean 497.6, from 151 to 869
check("B2 10,000 seasons", demand.shape == (10_000,))
check("B2 mean simulated demand about 498", abs(demand.mean() - 497.6) < 0.5)✅ B2 10,000 seasons
✅ B2 mean simulated demand about 498
B3. Sweep the order¶
Compute the mean profit of every order from 350 to 700 boxes in steps of 5, on the same simulated seasons, and plot it. Store the best order in best.
orders = np.arange(350, 701, 5)
mean_profit = np.array([season_profit(q, demand).mean() for q in orders])
best = orders[mean_profit.argmax()]
print(f"best order {best}, mean profit {mean_profit.max():,.0f} SAR")
plt.figure(figsize=(7, 3.4))
plt.plot(orders, mean_profit)
plt.xlabel("boxes ordered")
plt.ylabel("mean profit (SAR)")
plt.show()best order 480, mean profit 22,419 SAR

check("B3 71 orders tried", len(mean_profit) == 71)
check("B3 the best order is below the forecast (520)", 470 <= best <= 490)✅ B3 71 orders tried
✅ B3 the best order is below the forecast (520)
B4. Check it with the critical ratio¶
Compute the underage cost cu (profit lost on a box we could have sold), the overage cost co (loss on a box left over), the critical ratio, and the order q_star it gives with the normal model (rounded to a whole box).
cu = PRICE - COST
co = COST - LEFTOVER_VALUE
critical_ratio = cu / (cu + co)
q_star = round(stats.norm.ppf(critical_ratio, mu, sigma))
print(f"critical ratio {critical_ratio:.3f}, q* = {q_star}")critical ratio 0.423, q* = 478
check("B4 critical ratio 55 / 130", abs(critical_ratio - 55 / 130) < 1e-9)
check("B4 q* = 478 boxes", q_star == 478)
check("B4 the simulation agrees within 5 boxes", abs(best - q_star) <= 5)✅ B4 critical ratio 55 / 130
✅ B4 q* = 478 boxes
✅ B4 the simulation agrees within 5 boxes
B5. Read the risk¶
For the three plans below, compute on the same simulated seasons the mean profit, the probability of a loss, the 5th percentile of profit and the probability of selling out. Store them in a table risk with one row per plan.
plans = {"critical ratio": q_star, "the forecast": 520, "forecast + 20%": 624}
rows = {}
for name, q in plans.items():
p = season_profit(q, demand)
rows[name] = {"mean profit": p.mean(), "P(loss)": (p < 0).mean(), "5th percentile": np.percentile(p, 5),
"P(sell out)": (demand > q).mean()}
risk = pd.DataFrame(rows).T
risk.round(3)check("B5 three plans, four measures", risk.shape == (3, 4))
check("B5 the habit has the lowest mean profit", risk["mean profit"].idxmin() == "forecast + 20%")
check("B5 ... and the highest chance of a loss", risk["P(loss)"].idxmax() == "forecast + 20%")
check("B5 the critical-ratio order sells out in more than half the seasons", risk.loc["critical ratio", "P(sell out)"] > 0.5)✅ B5 three plans, four measures
✅ B5 the habit has the lowest mean profit
✅ B5 ... and the highest chance of a loss
✅ B5 the critical-ratio order sells out in more than half the seasons
B6. In two or three sentences for the manager: why is the best order below the forecast, and why is selling out in more than half the seasons acceptable?
A box left over loses 75 SAR (95 − 20), while a box we could have sold loses only 55 SAR of profit, so the critical ratio is 55 / 130 = 0.42: the best order is the 42nd percentile of demand, below its middle. On top of that, the forecasts run high (demand has averaged 95.5% of the forecast), so Corniche’s expected demand is about 497 boxes, not 520, and the best order is 478. Selling out in 58% of seasons means turning away a few customers near the end of Ramadan, at 55 SAR each, which is cheaper than the 75 SAR each extra leftover box would cost: 478 boxes earn 22,420 SAR on average, against 17,333 SAR for the habit’s 624 boxes.
Part C: Bidding for a contract¶
A private university in Al-Kharj invites sealed bids to run its campus coffee kiosks in 2026. The lowest bid wins, if it is within the university’s budget of 150,000 SAR. The manager’s estimates (all in thousand SAR):
Qahwa House’s cost of running the kiosks: triangular, minimum 90, most likely 100, maximum 135;
3 rival caterers, each bidding with probability 0.6;
a rival’s bid: triangular, 105, 120, 150.
The next cell simulates 10,000 tenders once. Complete the loop: for each bid, Qahwa House wins when its bid is below the lowest rival bid and within the budget; its profit is bid − cost when it wins and 0 otherwise.
rng = np.random.default_rng(16)
T = 10_000
cost = rng.triangular(90, 100, 135, T)
enters = rng.random((T, 3)) < 0.6
lowest_rival = np.where(enters, rng.triangular(105, 120, 150, (T, 3)), np.inf).min(axis=1)
rows = []
for bid in np.arange(105, 141, 2.5):
win = (bid < lowest_rival) & (bid <= 150)
profit = np.where(win, bid - cost, 0.0)
rows.append({"bid": bid, "P(win)": win.mean(), "mean profit": profit.mean(), "P(loss)": (profit < 0).mean()})
bids = pd.DataFrame(rows).set_index("bid")
bids.round(3)check("C1 15 bids", len(bids) == 15)
check("C1 a bid of 120k wins about half the tenders", abs(bids.loc[120, "P(win)"] - 0.507) < 0.01)
check("C1 higher bids never win more often", bids["P(win)"].is_monotonic_decreasing)✅ C1 15 bids
✅ C1 a bid of 120k wins about half the tenders
✅ C1 higher bids never win more often
C2. Choose the bid¶
Find best_bid, the bid with the highest mean profit, and safe_bid, the bid with the highest mean profit among those with at most a 5% chance of a loss.
best_bid = bids["mean profit"].idxmax()
safe_bid = bids[bids["P(loss)"] <= 0.05]["mean profit"].idxmax()
print(f"highest mean: {best_bid}k (P(loss) {bids.loc[best_bid, 'P(loss)']:.1%}); "
f"within the 5% limit: {safe_bid}k (P(loss) {bids.loc[safe_bid, 'P(loss)']:.1%})")highest mean: 120.0k (P(loss) 7.2%); within the 5% limit: 122.5k (P(loss) 4.0%)
check("C2 the highest mean profit is at 117.5k or 120k", best_bid in (117.5, 120.0))
check("C2 that bid's chance of a loss is above 5%", bids.loc[best_bid, "P(loss)"] > 0.05)
check("C2 the best bid within the limit is 122.5k", safe_bid == 122.5)✅ C2 the highest mean profit is at 117.5k or 120k
✅ C2 that bid's chance of a loss is above 5%
✅ C2 the best bid within the limit is 122.5k
Part D: The simulation app¶
D1. Fill in the app¶
The next cell writes a Streamlit app to giftbox_app.py: the manager chooses a branch and an order; the app simulates the season and shows the recommended order (critical ratio), the mean profit, the chance of a loss, the 5th percentile and a histogram of profit. Fill in the four gaps marked ..., run the cell, then run the test cell under it.
%%writefile giftbox_app.py
import numpy as np
import pandas as pd
import streamlit as st
from scipy import stats
URL = "https://chebil.github.io/BusinessDecision/data/qahwa_giftbox_demand.csv"
PRICE, COST, LEFTOVER_VALUE = 150, 95, 20
@st.cache_data
def load():
try:
return pd.read_csv(URL)
except Exception:
return pd.read_csv("../data/qahwa_giftbox_demand.csv")
def season_profit(order, demand):
sold = np.minimum(order, demand)
return PRICE * sold + LEFTOVER_VALUE * (order - sold) - COST * order
boxes = load()
past = boxes[boxes["season"] < 2026]
ratio = past["demand"] / past["forecast"]
forecasts = boxes[boxes["season"] == 2026].set_index("branch")["forecast"]
st.title("Qahwa House · gift-box simulator")
# 1. Inputs in the sidebar
branch = st.sidebar.selectbox("Branch", list(forecasts.index))
forecast = int(forecasts[branch])
mu, sigma = forecast * ratio.mean(), forecast * ratio.std()
critical_ratio = (PRICE - COST) / (PRICE - LEFTOVER_VALUE)
recommended = round(stats.norm.ppf(critical_ratio, mu, sigma))
order = st.sidebar.slider("Boxes to order", 0, 2 * forecast, recommended)
runs = st.sidebar.select_slider("Simulated seasons", [1_000, 10_000, 50_000], value=10_000)
# 2. Simulate the seasons
rng = np.random.default_rng(14)
demand = np.maximum(np.round(forecast * rng.normal(ratio.mean(), ratio.std(), runs)), 0)
profit = season_profit(order, demand)
# 3. Results
c1, c2, c3, c4 = st.columns(4)
c1.metric("Recommended order", f"{recommended}")
c2.metric("Mean profit (SAR)", f"{profit.mean():,.0f}")
c3.metric("P(loss)", f"{(profit < 0).mean():.1%}")
c4.metric("5th percentile (SAR)", f"{np.percentile(profit, 5):,.0f}")
counts, edges = np.histogram(profit / 1000, bins=40)
st.bar_chart(pd.DataFrame({"seasons": counts}, index=edges[:-1].round(1)), x_label="profit (thousand SAR)")Writing giftbox_app.py
# Run the app in the notebook without a browser: Streamlit's AppTest executes it like a visitor would.
import importlib.util, subprocess, sys
if importlib.util.find_spec("streamlit") is None: # Colab does not ship Streamlit
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "streamlit"], check=True)
import logging
from pathlib import Path
from streamlit.testing.v1 import AppTest
for name in ("streamlit", "streamlit.runtime.scriptrunner_utils.script_run_context"):
logging.getLogger(name).setLevel(logging.ERROR) # quiet "missing ScriptRunContext" notices
at = AppTest.from_file(str(Path("giftbox_app.py").resolve()), default_timeout=90).run()
check("D1 the app runs without an error", not at.exception)
if at.exception:
print(at.exception[0].message)
else:
labels = [m.label for m in at.metric]
check("D1 four metrics", labels == ["Recommended order", "Mean profit (SAR)", "P(loss)", "5th percentile (SAR)"])
at.selectbox[0].select("Corniche").run()
values = {m.label: m.value for m in at.metric}
print(values)
check("D1 Corniche: recommended order 478", values["Recommended order"] == "478")
check("D1 Corniche: P(loss) about 1.1%", values["P(loss)"] == "1.1%")
for b in ["Olaya", "Corniche", "Al Faisaliyah", "University"]:
at.selectbox[0].select(b).run()
print(f"{b}: recommended order {at.metric[0].value}")✅ D1 the app runs without an error
✅ D1 four metrics
{'Recommended order': '478', 'Mean profit (SAR)': '22,420', 'P(loss)': '1.1%', '5th percentile (SAR)': '8,220'}
✅ D1 Corniche: recommended order 478
✅ D1 Corniche: P(loss) about 1.1%
Olaya: recommended order 588
Corniche: recommended order 478
Al Faisaliyah: recommended order 349
University: recommended order 239
D2. See it in a browser¶
Colab cannot show a Streamlit page, so open it in GitHub Codespaces (free with GitHub Education) or on your own computer:
Put
giftbox_app.pyin a folder, open a terminal there and runpip install streamlit pandas scipy.Run
streamlit run giftbox_app.py; a browser tab opens athttp://localhost:8501. Move the order slider and watch the histogram and the chance of a loss.To share it, push the file and a
requirements.txt(streamlit, pandas, scipy) to a GitHub repository and deploy it on Streamlit Community Cloud (share.streamlit.io).
The course’s finished version, with the prices as inputs, the standard error, all four branches and the catering bid, is week14/app/app.py in the course repository.
D3. Your recommendation¶
Write three sentences for the manager: how many boxes each branch should order for Ramadan 2026 (use your app), what that order risks (with a number from the simulation), and which bid Qahwa House should submit for the university kiosks, and why.
Order 588 boxes at Olaya, 478 at Corniche, 349 at Al Faisaliyah and 239 at the University branch (about 0.92 × each forecast), not the forecast plus 20%. At Corniche this order earns 22,420 SAR on average over 10,000 simulated seasons, loses money in only 1.1% of them and earns at least 8,220 SAR in 19 seasons out of 20, while the habit (624 boxes) earns 17,333 SAR on average with a 7.8% chance of a loss. For the university kiosks, bid 122,500 SAR: a bid of 120,000 SAR has a slightly higher mean profit (5,894 against 5,551 SAR) but a 7.2% chance of losing money, above the 5% limit, while 122,500 SAR wins 39% of the tenders and loses money in 4.0% of them.
★ Extended challenges¶
E1. Without the normal model. Instead of drawing the ratio from a normal distribution, resample the 36 past ratios with replacement (rng.choice(past["ratio"].to_numpy(), N)), a bootstrap. Does Corniche’s best order change?
E2. Pooling the branches. Suppose the four branches could share one stock, kept at the roastery and delivered daily. Simulate the four branches together: for each simulated season, draw one season factor from the nine past seasons’ mean ratios (a good year is good for every branch) and, for each branch, a deviation from the 36 past values of ratio ÷ that season’s mean. Compare the best pooled order (one stock for the total demand) with the sum of the four branches’ best orders (each with its own stock), and their mean profits. Why does pooling raise the profit, and why does it move the order up? (Hint: what happens to the spread of total demand, and where is the critical ratio?)
E3. How many runs? With independent random seasons for each plan, how many runs are needed to be 95% sure that ordering 478 beats ordering 520 at Corniche? And with common random numbers?
E4. The app. Add sliders for the price, the cost and the leftover value. At what leftover value does the recommended order for Corniche rise above the forecast? Explain with the critical ratio.
# E1: a bootstrap: resample the 36 past ratios instead of drawing from a normal distribution
rng_b = np.random.default_rng(14)
demand_b = np.round(FORECAST * rng_b.choice(past["ratio"].to_numpy(), N))
mean_b = np.array([season_profit(q, demand_b).mean() for q in orders])
print(f"best order: bootstrap {orders[mean_b.argmax()]}, normal model {best}")
print(f"the empirical {critical_ratio:.3f} quantile of the ratio x 520 = {FORECAST * np.quantile(past['ratio'], critical_ratio):.1f}")best order: bootstrap 480, normal model 480
the empirical 0.423 quantile of the ratio x 520 = 478.2
# E2: one shared stock against four separate stocks
forecasts = boxes[boxes["season"] == 2026].set_index("branch")["forecast"]
season_mean = past.groupby("season")["ratio"].transform("mean")
factors = past.groupby("season")["ratio"].mean().to_numpy() # 9 season factors
deviations = (past["ratio"] / season_mean).to_numpy() # 36 branch deviations
rng_p = np.random.default_rng(21)
f = rng_p.choice(factors, N)
D4 = np.round(forecasts.to_numpy() * f[:, None] * rng_p.choice(deviations, (N, 4))) # N seasons x 4 branches
separate_orders, separate_profit = [], np.zeros(N)
for j, b in enumerate(forecasts.index):
grid = np.arange(0.6, 1.3, 0.005) * forecasts[b]
means = [season_profit(q, D4[:, j]).mean() for q in grid]
q = round(grid[int(np.argmax(means))])
separate_orders.append(q)
separate_profit += season_profit(q, D4[:, j])
total = D4.sum(axis=1)
grid = np.arange(0.6, 1.3, 0.005) * forecasts.sum()
means = [season_profit(q, total).mean() for q in grid]
pooled = round(grid[int(np.argmax(means))])
print(f"four stocks: {dict(zip(forecasts.index, separate_orders))}, total {sum(separate_orders)} boxes, "
f"mean profit {separate_profit.mean():,.0f} SAR")
print(f"one stock: {pooled} boxes, mean profit {season_profit(pooled, total).mean():,.0f} SAR")four stocks: {'Olaya': 573, 'Corniche': 465, 'Al Faisaliyah': 342, 'University': 233}, total 1613 boxes, mean profit 77,751 SAR
one stock: 1647 boxes, mean profit 81,389 SAR
# E3: runs needed so that the 95% interval of the difference (478 minus 520) excludes 0
d_same = season_profit(478, demand) - season_profit(520, demand)
other = np.maximum(np.round(FORECAST * np.random.default_rng(99).normal(r_mean, r_sd, N)), 0)
var_indep = season_profit(478, demand).var(ddof=1) + season_profit(520, other).var(ddof=1)
diff = d_same.mean()
print(f"difference {diff:,.0f} SAR a season")
print(f"common random numbers: about {int(np.ceil((1.96 * d_same.std(ddof=1) / diff) ** 2)):,} runs")
print(f"independent seasons: about {int(np.ceil(1.96 ** 2 * var_indep / diff ** 2)):,} runs")difference 455 SAR a season
common random numbers: about 123 runs
independent seasons: about 2,066 runs
# E4: the leftover value at which the recommended order rises above the forecast
for value in range(20, 81, 2):
cr = (PRICE - COST) / (PRICE - value)
q = round(stats.norm.ppf(cr, mu, sigma))
if q > FORECAST:
print(f"leftover value {value} SAR: critical ratio {cr:.3f}, recommended order {q} > {FORECAST}")
break
# The course app week14/app/app.py has sliders for the price, the cost and the leftover value.leftover value 58 SAR: critical ratio 0.598, recommended order 521 > 520