Monte Carlo Simulation¶
Every December, Qahwa House orders its Ramadan gift boxes (a box of dates, a bag of the house blend and two cups) from a supplier, once, for the whole season. Nothing can be reordered once Ramadan starts, and boxes left after Eid are cleared at a loss. Order too few and customers leave empty-handed; order too many and the boxes pile up in the back room. Ramadan 2026 starts on about 18 February. How many boxes should each branch order?
The answer depends on a number nobody knows in December: the season’s demand. This reading builds a Monte Carlo simulation: it replaces the unknown input by a distribution, plays the season thousands of times, and reads the distribution of profit, not a single number. Then it uses the same method on a second decision: what price to bid for a catering contract against competitors whose bids are unknown.
After this reading you can:
describe an uncertain input by a distribution estimated from data;
write a simulation model in NumPy and read its output as a distribution;
find the best order quantity by simulation and check it with the critical ratio (the newsvendor model);
read risk from a simulation: the probability of a loss, percentiles, value at risk;
choose the number of runs from the standard error, and compare plans with common random numbers;
choose a bid that balances the chance of winning, the margin and the risk.
The data¶
One row per season and branch (qahwa_giftbox_demand.csv, 40 rows): the nine seasons from 2016 to 2025 (there was no season in 2020, when the shops were closed) and the 2026 season, which is the decision.
| Column | Meaning |
|---|---|
season, ramadan_start | the year and the first day of Ramadan |
branch, city | where |
forecast | the marketing team’s forecast of the branch’s demand, made in December |
ordered | boxes ordered from the supplier |
sold, leftover | boxes sold, and boxes left after Eid |
demand | boxes customers asked for: sales plus the requests logged after a sell-out |
The 2026 rows hold only the forecast.
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")
boxes[boxes["season"] >= 2025]How have past orders worked out? In 2016 and 2017 each branch ordered exactly its forecast. In 2017 three branches sold out, and from 2018 the chain added a safety margin: it orders the forecast plus 20%.
past = boxes[boxes["season"] < 2026].copy()
past[["ordered", "sold", "leftover", "demand"]] = past[["ordered", "sold", "leftover", "demand"]].astype(int)
past["turned_away"] = past["demand"] - past["sold"]
by_season = past.groupby("season")[["forecast", "ordered", "demand", "sold", "leftover", "turned_away"]].sum()
by_season["leftover %"] = (100 * by_season["leftover"] / by_season["ordered"]).round(1)
by_seasonsince_2018 = by_season.loc[2018:]
print(f"since 2018: {since_2018['ordered'].sum():,} boxes ordered, {since_2018['leftover'].sum():,} left over "
f"({since_2018['leftover'].sum() / since_2018['ordered'].sum():.0%}), "
f"{since_2018['turned_away'].sum()} requests turned away")since 2018: 11,880 boxes ordered, 2,490 left over (21%), 51 requests turned away
The safety margin did its job too well: since 2018, one box in five was left over (2,490 boxes), while only 51 customer requests went unserved. Is that a good trade? It depends on what a leftover box and a missed sale each cost, and on how uncertain demand really is. A simulation answers both at once.
1. Inputs as distributions¶
A simulation model has three parts:
inputs: the decision (here, the order) and the uncertain quantities (here, demand), each uncertain input described by a distribution;
the model: the formulas that turn the inputs into an output (here, the season’s profit);
outputs: the model is run many times with random draws of the inputs, and the outputs form a distribution of their own.
Where does the demand distribution come from? In December the branch has a forecast, and the data show how wrong past forecasts were. The ratio demand / forecast measures it: 1.10 means demand came in 10% above the forecast.
past["ratio"] = past["demand"] / past["forecast"]
r_mean, r_sd = past["ratio"].mean(), past["ratio"].std()
print(f"{len(past)} seasons and branches: demand / forecast has mean {r_mean:.3f}, standard deviation {r_sd:.3f}, "
f"from {past['ratio'].min():.2f} to {past['ratio'].max():.2f}")
x = np.linspace(0.4, 1.6, 300)
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.hist(past["ratio"], bins=np.arange(0.55, 1.40, 0.1), density=True, color="#4C9BC9", edgecolor="white", label="36 past seasons")
ax.plot(x, stats.norm.pdf(x, r_mean, r_sd), color="#D2691E", lw=2.5, label=f"normal({r_mean:.3f}, {r_sd:.3f})")
ax.axvline(1, color="black", ls="--", lw=1)
ax.set_xlabel("demand / forecast")
ax.set_yticks([])
ax.legend(loc="upper right")
plt.show()36 seasons and branches: demand / forecast has mean 0.955, standard deviation 0.187, from 0.61 to 1.29

Two facts stand out:
The forecasts run high. On average demand reached 95.5% of the forecast: marketing is a little optimistic, every year.
They miss by about 19% (the standard deviation of the ratio), in both directions, and the histogram is roughly symmetric, so a normal distribution with the same mean and standard deviation is a reasonable model.
So for the Olaya branch, whose 2026 forecast is 640 boxes, demand is modelled as with :
FORECAST = 640 # Olaya, 2026
mu, sigma = FORECAST * r_mean, FORECAST * r_sd
print(f"Olaya 2026 demand: mean {mu:.0f} boxes, standard deviation {sigma:.0f}")Olaya 2026 demand: mean 611 boxes, standard deviation 120
2. A simulation model of one season¶
The economics of a box, from the supplier’s quote and last year’s prices:
| SAR per box | |
|---|---|
| selling price | 150 |
| supplier’s price | 95 |
| value of a box left after Eid (sold to staff and partners) | 20 |
So each box sold earns SAR, and each box left over loses SAR. The profit of a season is
PRICE, COST, LEFTOVER_VALUE = 150, 95, 20
def season_profit(order, demand):
# Profit of a season for an order and a demand (numbers or NumPy arrays).
sold = np.minimum(order, demand)
leftover = order - sold
return PRICE * sold + LEFTOVER_VALUE * leftover - COST * order
for d in [500, 640, 750]:
print(f"order 640, demand {d}: profit {season_profit(640, d):,} SAR")order 640, demand 500: profit 17,000 SAR
order 640, demand 640: profit 35,200 SAR
order 640, demand 750: profit 35,200 SAR
A single run tells us little: demand could be anything around 611. So we draw 10,000 seasons of demand from the distribution, and compute the profit of each. Fixing the generator’s seed makes the results reproducible.
rng = np.random.default_rng(14)
N = 10_000
demand = np.maximum(np.round(FORECAST * rng.normal(r_mean, r_sd, N)), 0) # 10,000 possible seasons at Olaya
profit_640 = season_profit(640, demand)
print(f"order 640: mean profit {profit_640.mean():,.0f} SAR, standard deviation {profit_640.std():,.0f}, "
f"from {profit_640.min():,.0f} to {profit_640.max():,.0f}")
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.hist(profit_640 / 1000, bins=50, color="#4C9BC9", edgecolor="white")
ax.axvline(profit_640.mean() / 1000, color="#D2691E", lw=2.5, label="mean")
ax.set_xlabel("profit of the season (thousand SAR), order 640")
ax.set_ylabel("simulated seasons")
ax.legend(loc="upper left")
plt.show()order 640: mean profit 27,034 SAR, standard deviation 10,225, from -23,950 to 35,200

The output is a distribution with a striking shape. Whenever demand reaches 640, every box sells and the profit hits its ceiling, SAR: that is the tall bar on the right, about 41% of the seasons. Below the ceiling, profit falls with demand, down to losses in the worst seasons. The mean, about 27,000 SAR, is one summary of this picture, and not the only one we need.
3. The newsvendor problem: how many to order?¶
A decision made once, before an uncertain demand, with a cost for each unit too many and each unit too few, is called a newsvendor problem (after a newspaper seller who buys papers in the morning). The simulation solves it directly: try every order quantity on the same 10,000 seasons and keep the one with the highest mean profit.
orders = np.arange(400, 801, 5)
mean_profit = np.array([season_profit(q, demand).mean() for q in orders])
best = orders[mean_profit.argmax()]
print(f"best order: {best} boxes, mean profit {mean_profit.max():,.0f} SAR")
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.plot(orders, mean_profit / 1000, color="#4C9BC9", lw=2.5)
for q, lab, col in [(best, "best", "#2E8B57"), (640, "forecast", "#555555"), (768, "forecast + 20%", "#C0392B")]:
ax.axvline(q, color=col, ls="--", lw=1.2)
ax.text(q + 4, 15.5, lab, color=col, fontsize=9)
ax.set_ylim(15, 29)
ax.set_xlabel("boxes ordered")
ax.set_ylabel("mean profit (thousand SAR)")
plt.show()best order: 590 boxes, mean profit 27,594 SAR

The best order is about 590 boxes: below the forecast of 640, and far below the 768 boxes the chain’s habit would order. Why below?
The critical ratio. Think about the last box of the order. It sells if demand is larger than the order, with probability , and then earns the underage cost we avoided, SAR. Otherwise it is left over and loses the overage cost SAR. Adding boxes pays as long as , so the best order is the quantity with
the 42nd percentile of demand. A leftover box costs more than a missed sale, so the best order is below the middle of the distribution.
cu, co = PRICE - COST, 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* = the {critical_ratio:.3f} quantile of demand = {q_star} boxes "
f"({q_star / FORECAST:.2f} x the forecast)")critical ratio 0.423: q* = the 0.423 quantile of demand = 588 boxes (0.92 x the forecast)
The formula gives 588 boxes, and the simulation’s 590 agrees (it only tried multiples of 5). The simulation needed no formula, which is its strength: it still works when the model is too complicated for one.
Now compare three plans on the same 10,000 seasons:
def summary(order, demand):
p = season_profit(order, demand)
return {"mean profit": p.mean(), "std dev": p.std(), "P(loss)": (p < 0).mean(),
"5th percentile": np.percentile(p, 5), "P(sell out)": (demand > order).mean(),
"boxes left (mean)": np.maximum(order - demand, 0).mean()}
plans = {"critical ratio (588)": q_star, "the forecast (640)": 640, "forecast + 20% (768)": 768}
compare = pd.DataFrame({name: summary(q, demand) for name, q in plans.items()}).T
compare.style.format({"mean profit": "{:,.0f}", "std dev": "{:,.0f}", "P(loss)": "{:.1%}", "5th percentile": "{:,.0f}",
"P(sell out)": "{:.1%}", "boxes left (mean)": "{:.1f}"})Three lessons in one table:
The habit is expensive. Ordering the forecast plus 20% earns about 6,300 SAR less per season at Olaya alone than the critical-ratio order (21,300 against 27,600 SAR), with four times as many boxes left over.
The top of the curve is flat. Ordering the forecast (640) loses only about 560 SAR against the best order. What matters most is erring on the right side: here, the low side.
Selling out is not a failure. The best plan sells out in 58% of seasons. Each sell-out costs a few missed sales at 55 SAR, which is cheaper than many leftover boxes at 75 SAR.
Would the rule have worked in the past? A back-test applies each policy to the real seasons since 2018, when the chain started its safety margin:
test = past[past["season"] >= 2018].copy()
policies = {"forecast + 20%": 1.2, "the forecast": 1.0, "0.92 x forecast": 0.92}
backtest = pd.Series({name: season_profit((test["forecast"] * k).round(), test["demand"]).sum()
for name, k in policies.items()}, name="profit 2018-2025 (SAR)")
backtest.map("{:,.0f}".format)forecast + 20% 329,700
the forecast 425,420
0.92 x forecast 434,585
Name: profit 2018-2025 (SAR), dtype: strOver the seven seasons from 2018 to 2025 and the four branches, ordering the forecast would have earned 434,585 SAR, against 329,700 SAR for the habit: about 105,000 SAR more. The rule is not a lucky draw of the simulation; it would have worked on the real seasons.
4. Reading risk, not just the mean¶
Two plans with the same mean can carry very different risks. A simulation measures them directly from the simulated outcomes:
the probability of a loss, : the share of simulated seasons that lose money;
percentiles: the 5th percentile is the profit that only the worst 5% of seasons fall below;
value at risk (VaR): the loss, against the mean, that is exceeded only with a small probability (5% here).
p_best, p_habit = season_profit(q_star, demand), season_profit(768, demand)
# the share of simulated seasons with a profit below each value (a cumulative distribution)
fig, ax = plt.subplots(figsize=(7, 3.6))
for p, lab, col in [(p_habit, "forecast + 20% (768)", "#C0392B"), (p_best, f"critical ratio ({q_star})", "#4C9BC9")]:
xs = np.sort(p) / 1000
ax.plot(xs, np.arange(1, len(xs) + 1) / len(xs), color=col, lw=2.5, label=lab)
ax.axvline(0, color="black", lw=1)
ax.axhline(0.05, color="#555555", lw=1, ls=":")
ax.text(-29, 0.07, "5% of seasons", fontsize=9, color="#555555")
ax.set_xlim(-30, 45)
ax.set_xlabel("profit of the season (thousand SAR)")
ax.set_ylabel("share of seasons below")
ax.legend(loc="upper left")
plt.show()
for name, p in [(f"order {q_star}", p_best), ("order 768", p_habit)]:
p5 = np.percentile(p, 5)
print(f"{name}: mean {p.mean():,.0f}, 5th percentile {p5:,.0f}, 5% value at risk {p.mean() - p5:,.0f} SAR, "
f"P(loss) {(p < 0).mean():.1%}")
order 588: mean 27,594, 5th percentile 10,240, 5% value at risk 17,354 SAR, P(loss) 1.1%
order 768: mean 21,333, 5th percentile -3,260, 5% value at risk 24,593 SAR, P(loss) 7.9%
Each curve shows, for every profit level, the share of simulated seasons that end below it: where a curve crosses the vertical line at 0 is its probability of a loss, and where it crosses the dotted line is its 5th percentile. The habit’s curve starts much further left: it earns more in a great season (it does not sell out until demand reaches 768 boxes) but its bad seasons are much worse. In one season out of twenty it falls below −3,260 SAR, a loss, while the critical-ratio order still earns at least 10,240 SAR. Its chance of a loss is 7.9% against 1.1%. Here the better plan is also the safer one; in the next section that is not the case.
5. How many runs?¶
A simulated mean is itself an estimate from a sample of simulated seasons. Its precision is measured, as in Week 5, by the standard error: the standard deviation of the output divided by .
for n in [100, 1_000, 10_000]:
p = p_best[:n]
se = p.std(ddof=1) / np.sqrt(n)
print(f"{n:>6,} runs: mean profit {p.mean():>7,.0f} SAR, standard error {se:5,.0f}, "
f"95% interval ± {1.96 * se:,.0f}") 100 runs: mean profit 27,366 SAR, standard error 831, 95% interval ± 1,630
1,000 runs: mean profit 27,635 SAR, standard error 255, 95% interval ± 500
10,000 runs: mean profit 27,594 SAR, standard error 79, 95% interval ± 155
With 100 runs the mean is only known to within about ±1,630 SAR; with 10,000, within about ±155 SAR. A hundred times as many runs make the interval ten times narrower.
Comparing plans: common random numbers. To compare two orders, we want the difference of their mean profits. If each plan is simulated with its own random seasons, the difference carries the noise of both samples. If both plans face the same simulated seasons, most of that noise cancels, because a good season is good for both. This is why the sweep in section 3 used one demand array for every order.
other = np.maximum(np.round(FORECAST * np.random.default_rng(99).normal(r_mean, r_sd, N)), 0) # independent seasons
same = season_profit(q_star, demand) - season_profit(640, demand)
se_same = same.std(ddof=1) / np.sqrt(N)
diff_indep = season_profit(q_star, demand).mean() - season_profit(640, other).mean()
se_indep = np.sqrt(season_profit(q_star, demand).var(ddof=1) / N + season_profit(640, other).var(ddof=1) / N)
print(f"order {q_star} minus order 640, same seasons: {same.mean():6,.0f} SAR, standard error {se_same:4,.0f}")
print(f"order {q_star} minus order 640, independent seasons: {diff_indep:6,.0f} SAR, standard error {se_indep:4,.0f}")order 588 minus order 640, same seasons: 560 SAR, standard error 32
order 588 minus order 640, independent seasons: 597 SAR, standard error 130
Both estimates say the critical-ratio order earns a few hundred SAR more than ordering the forecast, but with common random numbers the standard error is about four times smaller. To reach the same precision with independent draws, we would need about sixteen times as many runs.
6. A second model: bidding for a catering contract¶
A corporate client in Riyadh invites sealed bids for a year of coffee service at its offices in 2026. The lowest bid wins, provided it is within the client’s budget of 300,000 SAR. What should Qahwa House bid?
The uncertain inputs, from the manager’s estimates and past tenders:
| Input | Distribution |
|---|---|
| Qahwa House’s cost of serving the contract | triangular: minimum 180, most likely 200, maximum 260 thousand SAR (overruns are likelier than savings) |
| number of competitors who bid | each of 4 known caterers bids with probability 0.5 |
| a competitor’s bid | triangular: 210, 245, 290 thousand SAR |
The profit is bid − cost if Qahwa House wins and 0 if it loses. A higher bid earns more when it wins, but wins less often. We simulate 10,000 tenders once, and evaluate every bid on the same tenders (common random numbers again).
rng = np.random.default_rng(15)
T = 10_000
cost = rng.triangular(180, 200, 260, T) # thousand SAR
enters = rng.random((T, 4)) < 0.5 # which of the 4 competitors bid
their_bids = rng.triangular(210, 245, 290, (T, 4))
lowest_rival = np.where(enters, their_bids, np.inf).min(axis=1) # inf when nobody else bids
rows = []
for bid in range(215, 265, 5):
win = (bid < lowest_rival) & (bid <= 300)
profit = np.where(win, bid - cost, 0.0)
rows.append({"bid (k SAR)": bid, "P(win)": win.mean(), "mean profit (k SAR)": profit.mean(),
"P(loss)": (profit < 0).mean(), "5th percentile (k SAR)": np.percentile(profit, 5)})
bids = pd.DataFrame(rows).set_index("bid (k SAR)")
bids.style.format({"P(win)": "{:.1%}", "mean profit (k SAR)": "{:.1f}", "P(loss)": "{:.1%}", "5th percentile (k SAR)": "{:.1f}"})fig, ax = plt.subplots(figsize=(7, 3.4))
ax.plot(bids.index, bids["mean profit (k SAR)"], color="#4C9BC9", lw=2.5, marker="o", label="mean profit (k SAR)")
ax.set_xlabel("Qahwa House's bid (thousand SAR)")
ax.set_ylabel("mean profit (k SAR)")
ax2 = ax.twinx()
ax2.plot(bids.index, 100 * bids["P(loss)"], color="#C0392B", lw=2, ls="--", marker="s", label="P(loss) (%)")
ax2.axhline(5, color="#C0392B", lw=1, ls=":")
ax2.set_ylabel("P(loss) (%)")
ax2.text(258, 6, "5% limit", fontsize=9, color="#C0392B", ha="right")
fig.legend(loc="lower center", ncol=2, frameon=False)
fig.subplots_adjust(bottom=0.27)
plt.show()
best_bid = bids["mean profit (k SAR)"].idxmax()
safe_bid = bids[bids["P(loss)"] <= 0.05]["mean profit (k SAR)"].idxmax()
print(f"highest mean profit: bid {best_bid}k, mean {bids.loc[best_bid, 'mean profit (k SAR)']:.1f}k, P(loss) {bids.loc[best_bid, 'P(loss)']:.1%}")
print(f"best bid with P(loss) <= 5%: bid {safe_bid}k, mean {bids.loc[safe_bid, 'mean profit (k SAR)']:.1f}k, P(loss) {bids.loc[safe_bid, 'P(loss)']:.1%}")
print(f"the safety costs {1000 * (bids.loc[best_bid, 'mean profit (k SAR)'] - bids.loc[safe_bid, 'mean profit (k SAR)']):,.0f} SAR of mean profit")
highest mean profit: bid 235k, mean 13.3k, P(loss) 8.4%
best bid with P(loss) <= 5%: bid 240k, mean 13.0k, P(loss) 4.2%
the safety costs 309 SAR of mean profit
The bid with the highest mean profit is 235,000 SAR (a mean of about 13,300 SAR). But it loses money in 8.4% of tenders: it wins often, and in the seasons when the cost runs to the top of its range, the contract costs more than it pays.
The owner’s rule is that a contract may have at most a 5% chance of losing money. The best bid within that limit is 240,000 SAR: it wins half the tenders, its mean profit is about 13,000 SAR, and its chance of a loss is 4.2%. Safety costs about 300 SAR of mean profit, a price most owners would pay. The mean alone would have picked the riskier bid; the simulation shows the trade-off, and the decision maker sets the limit.
Summary¶
| Step | What we did | Qahwa House result |
|---|---|---|
| Inputs | a distribution for each uncertain input, from data | demand = forecast × normal(0.955, 0.187) |
| Model | profit as a function of the decision and the inputs | season_profit(order, demand) |
| Outputs | 10,000 runs; the output is a distribution | order 640: mean about 27,000 SAR, sells out in 41% of seasons |
| Newsvendor | sweep the decision; check with the critical ratio | 0.423: order 588 boxes, not 768 |
| Risk | P(loss), percentiles, value at risk | 768 boxes: P(loss) 7.9%; 588 boxes: 1.1% |
| Precision | standard error, common random numbers | ±155 SAR with 10,000 runs; differences 4 × sharper on the same seasons |
| Bidding | the highest mean is not always acceptable | 235k has the best mean but an 8.4% risk of loss; bid 240k |
A simulation does not make the decision. It shows each plan’s full range of outcomes, so that the decision maker can choose with the risks in view.
Next week: decisions with several criteria (AHP and TOPSIS), and how to use analytics and AI responsibly.