Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 14 Solutions: Simulation App

Open In Colab

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.

Loading...

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.

demand / forecast: mean 0.955, standard deviation 0.187
✅ 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.

Corniche 2026 demand: mean 496.6, standard deviation 97.1
✅ 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).

✅ 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.

simulated demand: mean 497.6, from 151 to 869
✅ 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.

best order 480, mean profit 22,419 SAR
<Figure size 700x340 with 1 Axes>
✅ 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).

critical ratio 0.423, q* = 478
✅ 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.

Loading...
✅ 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.

Loading...
✅ 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.

highest mean: 120.0k (P(loss) 7.2%); within the 5% limit: 122.5k (P(loss) 4.0%)
✅ 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.

Writing giftbox_app.py
✅ 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:

  1. Put giftbox_app.py in a folder, open a terminal there and run pip install streamlit pandas scipy.

  2. Run streamlit run giftbox_app.py; a browser tab opens at http://localhost:8501. Move the order slider and watch the histogram and the chance of a loss.

  3. 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.

best order: bootstrap 480, normal model 480
the empirical 0.423 quantile of the ratio x 520 = 478.2
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
difference 455 SAR a season
common random numbers: about 123 runs
independent seasons:   about 2,066 runs
leftover value 58 SAR: critical ratio 0.598, recommended order 521 > 520