Lab 8: Demand Forecast App¶
In this lab you forecast the coffee beans of each Qahwa House branch, test your forecasts fairly, and put the result in a Streamlit app the manager can use to place the order.
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 = ...
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())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]:
... # plot the 52 values of year y against range(1, 53), with 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()Your answer here (double-click to edit).
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 = ...
test = ...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")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):
... # the mean of the last k weeks, repeated h times
def same_week_last_year(s, h, m=52):
... # the h weeks that started m weeks before the end: s.iloc[-m:-m + h].values
def holt_winters(s, h):
model = ... # ExponentialSmoothing with an additive trend and an additive 52-week season, fitted
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)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 = ...
rmse = ...
mape = ...
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())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)})Your answer here (double-click to edit).
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 = ... # a selectbox with the branches (the columns of kg)
method = st.sidebar.radio("Method", ["Holt-Winters", "Same week last year", "Last week"])
z = ... # a slider "Service level (z)" from 0.0 to 2.5, default 1.28, step 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 = ... # mean absolute error
rmse = ... # root mean squared error
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 = ... # the 8-week total plus z * rmse * sqrt(8), rounded up to a whole kg
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())# 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")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.
Write your recommendation here (double-click to edit).
★ 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# E2# E3# E4AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.