Lab 14: Simulation App¶
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.
You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.
# 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 = ...
past["ratio"] = ...
r_mean, r_sd = ..., ...
print(f"demand / forecast: mean {r_mean:.3f}, standard deviation {r_sd:.3f}")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)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 = ..., ...
print(f"Corniche 2026 demand: mean {mu:.1f}, standard deviation {sigma:.1f}")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)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 = ...
leftover = ...
return ...check("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]))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 = ...
print(f"simulated demand: mean {demand.mean():.1f}, from {demand.min():.0f} to {demand.max():.0f}")check("B2 10,000 seasons", demand.shape == (10_000,))
check("B2 mean simulated demand about 498", abs(demand.mean() - 497.6) < 0.5)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 = ... # one mean profit per order
best = ...
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()check("B3 71 orders tried", len(mean_profit) == 71)
check("B3 the best order is below the forecast (520)", 470 <= best <= 490)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 = ...
co = ...
critical_ratio = ...
q_star = ...
print(f"critical ratio {critical_ratio:.3f}, q* = {q_star}")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)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(loss)": ..., "5th percentile": ..., "P(sell out)": ...}
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)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?
Your answer here (double-click to edit).
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 = ...
profit = ...
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)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 = ...
safe_bid = ...
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%})")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)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 = ... # a selectbox "Branch" with the branches (the index of forecasts)
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 = ... # a slider "Boxes to order" from 0 to 2 * forecast, starting at 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 = ... # the profit of each simulated season with this order
# 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)", ...) # the share of seasons with a loss, as a percentage with one decimal, e.g. "1.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)")# 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}")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.
Your answer here (double-click to edit).
★ 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# E2# E3# E4AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.