Lab 8 Solutions: Demand Forecast App¶
These are the worked solutions of Lab 8, with the outputs. Try the lab yourself first.
The question. It is the end of July 2025, and each branch orders its beans for the next 8 weeks at once. Too few and the branch runs out; too many and the beans go stale. How many kilograms should each branch order, and which forecasting method should the app use?
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 C, try the ★ challenges.
Submit before the next lab session: File → Download → Download .ipynb, plus your
forecast_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
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, parse_dates=["week_start"])
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name, parse_dates=["week_start"])
demand = load("qahwa_weekly_demand.csv")
BRANCHES = ["Olaya", "Corniche", "Al Faisaliyah", "University"]
from statsmodels.tsa.holtwinters import ExponentialSmoothing
kg = demand.pivot(index="week_start", columns="branch", values="beans_kg")[BRANCHES].asfreq("W-MON")
kg.tail()kg has one row per week (156 weeks, 1 August 2022 to 21 July 2025) and one column per branch: the kilograms of beans used that week. The original table demand also has ramadan_days (days of the week in Ramadan) and holiday.
Part A: Look before you forecast¶
A1. Trend¶
Compute the mean kg per week of each branch in each of the three years. The rows of kg are in order, 52 weeks per year, so the year number is np.repeat([1, 2, 3], 52). Store the table in yearly (3 rows, 4 branches).
year = np.repeat([1, 2, 3], 52)
yearly = kg.groupby(year).mean()
yearly.round(1)check("A1 three years, four branches", yearly.shape == (3, 4))
check("A1 every branch grows from year 1 to year 3", (yearly.iloc[2] > yearly.iloc[0]).all())✅ A1 three years, four branches
✅ A1 every branch grows from year 1 to year 3
A2. Seasonality¶
Plot the University branch’s three years on top of each other (one line per year, x = week 1 to 52). Which weeks are the summer break? Is there a second, smaller dip?
fig, ax = plt.subplots(figsize=(8, 3.5))
for y in [1, 2, 3]:
ax.plot(range(1, 53), kg.loc[year == y, "University"].values, label=f"year {y}")
ax.set_xlabel("Week of the year (week 1 starts in early August)")
ax.set_ylabel("kg per week")
ax.legend()
plt.show()
The summer break is the deep dip at the start and the end of each year line (weeks 47 to 4, late June to late August): bean use falls from about 50 kg to under 20 kg. There are two smaller dips: the winter break around week 25 (mid-January), which stays in place, and Ramadan in weeks 31 to 38, which comes earlier every year. The peaks just before the summer and in December are exam weeks.
Part B: A fair test¶
B1. Split¶
Hide the last 8 weeks: train is every week but the last 8, test the last 8.
H = 8
train = kg.iloc[:-H]
test = kg.iloc[-H:]check("B1 148 training weeks", len(train) == 148)
check("B1 the test starts on 2 June 2025", str(test.index[0].date()) == "2025-06-02")✅ B1 148 training weeks
✅ B1 the test starts on 2 June 2025
B2. Four forecasting methods¶
Complete the functions. Each takes a series s (one branch) and a horizon h and returns an array of h forecasts.
def naive(s, h):
return np.repeat(s.iloc[-1], h)
def moving_average(s, h, k=4):
return np.repeat(s.iloc[-k:].mean(), h)
def same_week_last_year(s, h, m=52):
return s.iloc[-m:-m + h].values
def holt_winters(s, h):
model = ExponentialSmoothing(s, trend="add", seasonal="add", seasonal_periods=52).fit()
return model.forecast(h).valuesu = train["University"]
check("B2 moving average of the last 4 weeks", abs(moving_average(u, 2)[0] - u.iloc[-4:].mean()) < 1e-9)
check("B2 same week last year", np.allclose(same_week_last_year(u, 8), kg["University"].iloc[-60:-52].values))
check("B2 Holt-Winters forecasts the summer drop at University", holt_winters(u, 8)[-1] < 25)✅ B2 moving average of the last 4 weeks
✅ B2 same week last year
✅ B2 Holt-Winters forecasts the summer drop at University
B3. Score them¶
Write scores(actual, forecast) that returns a Series with the MAE, RMSE and MAPE (in %) of all the errors of a table of actuals and a table of forecasts (stack() puts every branch and week in one column). Then score the four methods over the four branches.
def scores(actual, forecast):
e = (actual - forecast).stack()
a = actual.stack()
mae = e.abs().mean()
rmse = np.sqrt((e ** 2).mean())
mape = (e.abs() / a).mean() * 100
return pd.Series({"MAE": mae, "RMSE": rmse, "MAPE": mape})
methods = {"Last week": naive, "Moving average": moving_average,
"Same week last year": same_week_last_year, "Holt-Winters": holt_winters}
forecasts = {name: pd.DataFrame({b: f(train[b], H) for b in BRANCHES}, index=test.index) for name, f in methods.items()}
results = pd.DataFrame({name: scores(test, f) for name, f in forecasts.items()}).T
results.round(2)check("B3 naive MAE is about 15.7 kg", abs(results.loc["Last week", "MAE"] - 15.73) < 0.05)
check("B3 Holt-Winters has the lowest RMSE", results["RMSE"].idxmin() == "Holt-Winters")
check("B3 RMSE is never below MAE", (results["RMSE"] >= results["MAE"]).all())✅ B3 naive MAE is about 15.7 kg
✅ B3 Holt-Winters has the lowest RMSE
✅ B3 RMSE is never below MAE
B4. In two or three sentences: why do the first two methods miss so badly on these 8 weeks? And why does the gap between the two seasonal methods look small on MAE and MAPE but large on RMSE? (Hint: compare both forecasts with the actual values at Olaya, week by week, and look at the holiday column of demand.)
pd.DataFrame({"actual": test["Olaya"],
"same week last year": forecasts["Same week last year"]["Olaya"],
"Holt-Winters": forecasts["Holt-Winters"]["Olaya"].round(1)})The test weeks are the start of the summer and of the campus break; the last week and the moving average carry the busy spring level forward, so they over-forecast every week (by 47% on average for the naive rule). The two seasonal methods are close on most weeks, but copying last year makes a few large misses, the largest at Olaya in the week of 9 June: 80.0 kg forecast against 105.0 kg, because Eid al-Adha fell in that week in 2024 but a week earlier in 2025. RMSE squares the errors, so those few big misses weigh heavily (7.65 against 5.72 kg), while MAE and MAPE treat every kilo or percent the same.
Part C: The demand forecast app¶
C1. Fill in the app¶
The next cell writes a Streamlit app to forecast_app.py: the manager chooses a branch, a method and a service level; the app tests the method on the last 8 weeks, forecasts the next 8 and computes the order, forecast total + z × RMSE × √8, as in the reading. Fill in the five gaps marked ..., run the cell, then run the test cell under it.
%%writefile forecast_app.py
import numpy as np
import pandas as pd
import streamlit as st
from statsmodels.tsa.holtwinters import ExponentialSmoothing
URL = "https://chebil.github.io/BusinessDecision/data/qahwa_weekly_demand.csv"
H = 8
@st.cache_data
def load():
try:
df = pd.read_csv(URL, parse_dates=["week_start"])
except Exception:
df = pd.read_csv("../data/qahwa_weekly_demand.csv", parse_dates=["week_start"])
return df.pivot(index="week_start", columns="branch", values="beans_kg").asfreq("W-MON")
def forecast(s, h, method):
if method == "Last week":
return np.repeat(s.iloc[-1], h)
if method == "Same week last year":
return s.iloc[-52:-52 + h].values
model = ExponentialSmoothing(s, trend="add", seasonal="add", seasonal_periods=52).fit()
return model.forecast(h).values
kg = load()
st.title("Qahwa House · bean order planner")
# 1. Inputs in the sidebar
branch = st.sidebar.selectbox("Branch", list(kg.columns))
method = st.sidebar.radio("Method", ["Holt-Winters", "Same week last year", "Last week"])
z = st.sidebar.slider("Service level (z)", 0.0, 2.5, 1.28, 0.01)
s = kg[branch]
train, test = s.iloc[:-H], s.iloc[-H:]
# 2. Test the method on the last 8 weeks
pred = forecast(train, H, method)
err = test.values - pred
mae = np.abs(err).mean()
rmse = np.sqrt((err ** 2).mean())
c1, c2 = st.columns(2)
c1.metric("Holdout MAE (kg)", f"{mae:.2f}")
c2.metric("Holdout RMSE (kg)", f"{rmse:.2f}")
# 3. Forecast the next 8 weeks and the order
future_index = pd.date_range(s.index[-1] + pd.Timedelta(weeks=1), periods=H, freq="W-MON")
future = pd.Series(forecast(s, H, method), index=future_index)
order = np.ceil(future.sum() + z * rmse * np.sqrt(H))
st.metric("Order for the next 8 weeks (kg)", f"{order:,.0f}")
# 4. Chart: the last 52 weeks and the forecast
chart = pd.DataFrame({"actual": s.iloc[-52:], "forecast": future})
st.line_chart(chart)
st.dataframe(future.round(1).rename("kg").to_frame())Overwriting forecast_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("forecast_app.py").resolve()), default_timeout=90).run()
check("C1 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("C1 holdout MAE and RMSE metrics", "Holdout MAE (kg)" in labels and "Holdout RMSE (kg)" in labels)
check("C1 an order metric", "Order for the next 8 weeks (kg)" in labels)
at.selectbox[0].select("University").run()
order = next(m.value for m in at.metric if m.label.startswith("Order"))
print("University order:", order, "kg")
check("C1 the University order is about 314 kg with Holt-Winters and z = 1.28", order.replace(",", "") == "314")✅ C1 the app runs without an error
✅ C1 holdout MAE and RMSE metrics
✅ C1 an order metric
University order: 314 kg
✅ C1 the University order is about 314 kg with Holt-Winters and z = 1.28
C2. 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
forecast_app.pyin a folder, open a terminal there and runpip install streamlit pandas statsmodels.Run
streamlit run forecast_app.py; a browser tab opens athttp://localhost:8501.To share it, push the file and a
requirements.txt(streamlit, pandas, statsmodels) to a GitHub repository and deploy it on Streamlit Community Cloud (share.streamlit.io).
The course’s finished version, with all branches at once and more methods, is week08/app/app.py in the course repository.
C3. Your recommendation¶
Use your app with each branch and method. Then write three sentences for the manager: how much each branch should order (with the method and service level you chose), why you trust that method (with a number from the holdout), and one thing in the coming 8 weeks the model cannot know about.
Order 814 kg for Olaya, 735 kg for Corniche, 512 kg for Al Faisaliyah and 314 kg for the University branch: the Holt-Winters forecast for 28 July to 15 September plus a buffer of 1.28 × RMSE × √8, about 90% sure to cover the 8 weeks. On the last 8 weeks, which we hid from the model, Holt-Winters missed by 4.7 kg a week on average and had the lowest RMSE (5.7 kg), against 15.7 kg for repeating last week, which would order only 148 kg for the University branch just before the students come back. The model only knows the calendar of past years, so check the coming weeks for anything new, such as a promotion, a supply delay or a change in the university’s term dates, and adjust the order by hand.
★ Extended challenges¶
E1. Multiplicative seasonality. Refit Holt-Winters with seasonal="mul" and score it on the holdout. Which branches gain, and why might multiplicative seasonality suit the University branch?
E2. Rolling-origin test. One holdout of 8 weeks is a small test. Repeat the split with the test ending 4, 8 and 12 weeks earlier, and average the MAE of each method. Does the ranking hold?
E3. Moving holidays. In the coming 8 weeks there is no Eid, but in February 2026 Ramadan starts on about 18 February, 11 days earlier than in 2025. Using ramadan_days, estimate how much bean use falls per Ramadan day at Olaya (compare Ramadan weeks with the weeks just before), and describe how you would correct a Holt-Winters forecast for the weeks of February and March 2026.
E4. The app. Add the moving average and the average to your app’s methods, and show a table of the holdout MAE, RMSE and MAPE of every method for the chosen branch.
# E1: multiplicative seasonality
def holt_winters_mul(s, h):
return ExponentialSmoothing(s, trend="add", seasonal="mul", seasonal_periods=52).fit().forecast(h).values
mul = pd.DataFrame({b: holt_winters_mul(train[b], H) for b in BRANCHES}, index=test.index)
pd.DataFrame({"additive": {b: scores(test[[b]], forecasts["Holt-Winters"][[b]])["MAE"] for b in BRANCHES},
"multiplicative": {b: scores(test[[b]], mul[[b]])["MAE"] for b in BRANCHES}}).round(2)# E2: rolling-origin test (the test window ends 0, 4, 8 and 12 weeks before the last week)
rows = []
for back in [0, 4, 8, 12]:
end = len(kg) - back
tr, te = kg.iloc[:end - H], kg.iloc[end - H:end]
for name, f in methods.items():
fc = pd.DataFrame({b: f(tr[b], H) for b in BRANCHES}, index=te.index)
rows.append({"origin": str(te.index[0].date()), "method": name, "MAE": scores(te, fc)["MAE"]})
rolling = pd.DataFrame(rows).pivot(index="origin", columns="method", values="MAE")
print(rolling.round(2), "\n")
print("mean MAE\n", rolling.mean().sort_values().round(2))method Holt-Winters Last week Moving average Same week last year
origin
2025-03-10 8.97 11.69 8.07 7.43
2025-04-07 5.46 3.39 13.12 6.20
2025-05-05 4.69 5.82 5.93 6.54
2025-06-02 4.67 15.73 14.93 5.35
mean MAE
method
Holt-Winters 5.95
Same week last year 6.38
Last week 9.16
Moving average 10.51
dtype: float64
# E3: the Ramadan effect at Olaya, Ramadan weeks against the 4 weeks just before each Ramadan
ol = demand[demand["branch"] == "Olaya"].reset_index(drop=True)
effects = []
for start in ol.index[(ol["ramadan_days"] > 0) & (ol["ramadan_days"].shift(1, fill_value=0) == 0)]:
before = ol.loc[start - 4:start - 1, "beans_kg"].mean()
full = ol.loc[start:start + 5]
full = full[full["ramadan_days"] == 7]
effects.append((full["beans_kg"].mean() / before - 1) * 100 / 7)
print(ol.loc[start, "week_start"].date(), f"full Ramadan weeks vs the 4 weeks before: {full['beans_kg'].mean() / before - 1:+.1%}")
print(f"about {np.mean(effects):.1f}% per Ramadan day")
# To correct a forecast for February-March 2026: multiply each week's forecast by (1 + effect x ramadan_days of that week),
# after removing the Ramadan dip that Holt-Winters copied from March 2025 (divide those weeks by the same factor).2023-03-20 full Ramadan weeks vs the 4 weeks before: -26.5%
2024-03-11 full Ramadan weeks vs the 4 weeks before: -25.1%
2025-02-24 full Ramadan weeks vs the 4 weeks before: -29.4%
about -3.9% per Ramadan day
# E4: see week08/app/app.py in the course repository for a version with every method and a score table