Forecasting Demand¶
Every order a business places is a bet on the future: how many kilograms of beans, how many cups, how many staff next month. A forecast turns the history of a number into an estimate of its next values, and a good one says how far off it is likely to be. This reading builds forecasts for Qahwa House’s coffee beans, from the simplest rules to Holt-Winters exponential smoothing, and shows how to test them fairly before trusting them with an order.
After this reading you can:
describe a time series by its level, trend, seasonality and noise;
produce naive, average, moving-average and seasonal-naive forecasts;
explain how exponential smoothing weights the past, and fit a Holt-Winters model with statsmodels;
test forecasts on a holdout period and compare them with MAE, RMSE and MAPE;
turn a forecast and its error into an order quantity.
Textbook: Albright & Winston, Business Analytics: Data Analysis and Decision Making, Chapter 12.
The decision¶
It is the end of July 2025. Each Qahwa House branch orders its coffee beans from the roaster for the next 8 weeks at once. Order too little and a branch runs out of its signature blend; order too much and the beans go stale (roasted beans lose their flavour within about two months). The manager asks: how many kilograms should each branch order?
The data: the beans used by each branch every week for three years, from 1 August 2022 to the week of 21 July 2025.
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"]
demand.head()| Column | Meaning |
|---|---|
week_start | the Monday that starts the week |
branch, city | where |
beans_kg | coffee beans used that week (kg) |
ramadan_days | how many days of the week fall in Ramadan (0 to 7) |
holiday | a public holiday in that week, if any |
A time series is easiest to handle with one column per branch and one row per week, indexed by date. asfreq("W-MON") tells pandas that the rows are weekly, starting on Mondays, which statsmodels needs later.
kg = demand.pivot(index="week_start", columns="branch", values="beans_kg")[BRANCHES].asfreq("W-MON")
print(kg.shape, "from", kg.index[0].date(), "to", kg.index[-1].date())
fig, ax = plt.subplots(figsize=(9, 3.8))
kg.plot(ax=ax, lw=1.4)
ax.set_ylabel("Beans used (kg per week)")
ax.set_xlabel("")
ax.set_title("Three years of coffee beans, by branch")
ax.legend(title="", loc="center left", bbox_to_anchor=(1.0, 0.5), fontsize=9)
ax.grid(alpha=0.3)
plt.show()(156, 4) from 2022-08-01 to 2025-07-21

1. What a time series is made of¶
A time series is a variable measured at regular intervals. Four components describe most business series:
Level: where the series is now.
Trend: a steady rise or fall. Each branch uses more beans every year.
Seasonality: a pattern that repeats with a fixed period, here every 52 weeks. The cool months are busy, the hot summer is quiet (customers travel or stay indoors), and the University branch follows the academic calendar: a deep dip during the summer break, a smaller one in the winter break, and busy exam weeks.
Noise: what is left, the week-to-week ups and downs that no model can predict.
Plotting each year on top of the others separates the season from the trend: the shape repeats, and every year sits a little higher.
year = np.repeat(["Aug 2022 – Jul 2023", "Aug 2023 – Jul 2024", "Aug 2024 – Jul 2025"], 52)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), sharex=True)
for ax, b in zip(axes, ["Olaya", "University"]):
for y in np.unique(year):
ax.plot(range(1, 53), kg.loc[year == y, b].values, label=y, lw=1.4)
ax.set_title(b)
ax.set_xlabel("Week of the year (week 1 starts in early August)")
ax.grid(alpha=0.3)
axes[0].set_ylabel("kg per week")
axes[1].legend(fontsize=8)
plt.tight_layout()
plt.show()
yearly = kg.groupby(year).mean()
print("Mean kg per week, by year\n", yearly.round(1), "\n")
print("Growth over two years (%)\n", ((yearly.iloc[2] / yearly.iloc[0] - 1) * 100).round(1))
Mean kg per week, by year
branch Olaya Corniche Al Faisaliyah University
Aug 2022 – Jul 2023 90.0 79.2 60.0 40.3
Aug 2023 – Jul 2024 95.1 82.4 61.8 41.7
Aug 2024 – Jul 2025 102.6 87.9 65.0 43.2
Growth over two years (%)
branch
Olaya 14.0
Corniche 10.9
Al Faisaliyah 8.4
University 7.2
dtype: float64
Olaya grew by 14% in two years and the University branch by 7%. At the University branch the summer break (weeks 47 to 4) cuts bean use to about 18 kg a week, from about 50 kg during term, and the winter break makes a smaller dip around week 25. One dip does not stay in place: Ramadan (somewhere in weeks 31 to 38) follows the lunar calendar and starts about 11 days earlier every year, so its dip slides to the left from one year to the next. A forecast that ignores the season will be badly wrong at exactly the moments that matter: when the season turns.
2. A fair test: the holdout¶
A forecast should be judged on weeks it has not seen. We hide the last 8 weeks (2 June to 21 July 2025), the same length as the decision’s horizon, fit every method on the weeks before, forecast the hidden weeks, and compare. This is the time-series version of last week’s train/test split: the test period always comes after the training period, never shuffled, because the future is what we forecast.
H = 8 # the decision's horizon, in weeks
train, test = kg.iloc[:-H], kg.iloc[-H:]
print("train:", train.index[0].date(), "to", train.index[-1].date(), f"({len(train)} weeks)")
print("test: ", test.index[0].date(), "to", test.index[-1].date(), f"({len(test)} weeks)")train: 2022-08-01 to 2025-05-26 (148 weeks)
test: 2025-06-02 to 2025-07-21 (8 weeks)
3. Simple forecasts¶
Four rules need no model at all, and every serious forecast should beat them:
| Method | Forecast for every future week |
|---|---|
| Naive | the last observed week |
| Average | the mean of all past weeks |
| Moving average ( weeks) | the mean of the last weeks |
| Seasonal naive | the same week one season (52 weeks) earlier |
Each one is a single line of pandas. Every function takes a series s and a horizon h, and returns h forecasts.
def naive(s, h):
return np.repeat(s.iloc[-1], h)
def average(s, h):
return np.repeat(s.mean(), 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 # the h weeks that started one season ago
print("University, last week:", train["University"].iloc[-1], "kg")
print("naive forecast: ", naive(train["University"], 3))
print("4-week moving average:", moving_average(train["University"], 3).round(1))
print("same week last year: ", same_week_last_year(train["University"], 3))University, last week: 55.9 kg
naive forecast: [55.9 55.9 55.9]
4-week moving average: [51.9 51.9 51.9]
same week last year: [53.4 41.2 28.5]
The last training week at the University branch was an exam week (55.9 kg). The naive and moving-average forecasts carry that level into June, when the students leave; only the seasonal naive forecast “knows” that the break is coming.
4. Exponential smoothing¶
A moving average gives the last weeks equal weight and ignores everything older. Exponential smoothing gives every past week some weight, and the weight shrinks the further back the week is. With a smoothing constant between 0 and 1, the level is updated every week:
Unrolled, the weights on the last weeks are , , , ...: a large reacts fast to recent weeks, a small one smooths more.
for alpha in (0.3, 0.8):
w = [alpha * (1 - alpha) ** k for k in range(6)]
print(f"alpha = {alpha}: weights on the last 6 weeks", np.round(w, 3))alpha = 0.3: weights on the last 6 weeks [0.3 0.21 0.147 0.103 0.072 0.05 ]
alpha = 0.8: weights on the last 6 weeks [0.8 0.16 0.032 0.006 0.001 0. ]
Simple exponential smoothing tracks only the level, so its forecast is flat, like a moving average. Two extensions add the other components, each with its own smoothing constant:
Holt’s method also smooths a trend (), so the forecast can rise or fall;
Holt-Winters also smooths a seasonal index for each of the periods of the season (), so the forecast repeats the seasonal pattern on top of the trend.
statsmodels fits all three: it chooses the smoothing constants that make the one-step-ahead errors on the training data as small as possible. With a 52-week season, it needs at least two full seasons of history; we have nearly three.
from statsmodels.tsa.holtwinters import ExponentialSmoothing
def holt_winters(s, h):
model = ExponentialSmoothing(s, trend="add", seasonal="add", seasonal_periods=52).fit()
return model.forecast(h).values
print("University, Holt-Winters:", holt_winters(train["University"], H).round(1))
print("University, actual: ", test["University"].values)University, Holt-Winters: [55.9 45.6 26.7 18.6 19.9 19.8 20.8 20.6]
University, actual: [47.8 50.2 36.4 18.2 18.5 18.1 18.9 18.5]
trend="add" and seasonal="add" make the trend and the seasonal effects additive (so many kilograms up or down); "mul" would make the seasonal effects multiplicative (so many percent), which suits series whose swings grow with their level. The forecast catches the University branch’s summer drop almost exactly.
5. Measuring forecast error¶
For each week, the error is (actual minus forecast). Three summaries are standard:
| Measure | Formula | Reads as |
|---|---|---|
| MAE, mean absolute error | the typical miss, in kg | |
| RMSE, root mean squared error | in kg, but big misses count more (they are squared) | |
| MAPE, mean absolute percentage error | the typical miss, in % of the actual |
We forecast the 8 hidden weeks of every branch with each method, then pool the 32 errors.
methods = {
"Last week (naive)": naive,
"Average": average,
"Moving average (4 weeks)": 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()}
def scores(actual, forecast):
e = (actual - forecast).stack() # every branch and week in one column
a = actual.stack()
return pd.Series({"MAE": e.abs().mean(), "RMSE": np.sqrt((e ** 2).mean()), "MAPE": (e.abs() / a).mean() * 100})
results = pd.DataFrame({name: scores(test, f) for name, f in forecasts.items()}).T
results.round(2)The three rules that ignore the season miss by 10 to 16 kg a week on average, and the naive forecast by 47% of the actual: they all carried the spring level into the summer. The two seasonal methods miss by about 5 kg, and Holt-Winters is best on all three measures.
The chart shows why, at two branches.
import matplotlib.dates as mdates
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
for ax, b in zip(axes, ["Olaya", "University"]):
ax.plot(kg[b].iloc[-30:], color="black", lw=1.6, label="actual")
for name, style in [("Last week (naive)", ":"), ("Same week last year", "--"), ("Holt-Winters", "-")]:
ax.plot(forecasts[name][b], style, lw=2, label=name)
ax.axvline(test.index[0], color="grey", lw=1)
ax.set_title(b)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
ax.tick_params(axis="x", labelsize=8)
ax.grid(alpha=0.3)
axes[0].set_ylabel("kg per week")
axes[1].legend(fontsize=8)
plt.tight_layout()
plt.show()
6. Which measure?¶
Look at the two seasonal methods again. On MAPE they are level (7.89% against 7.92%), on MAE Holt-Winters is ahead by less than a kilogram, but on RMSE it wins clearly (5.72 against 7.65 kg). RMSE squares the errors, so a few big misses weigh heavily, and the copy of last year makes some big misses. Here is the largest, at Olaya:
olaya = pd.DataFrame({"actual": test["Olaya"],
"same week last year": forecasts["Same week last year"]["Olaya"],
"Holt-Winters": forecasts["Holt-Winters"]["Olaya"].round(1)})
olaya["holiday"] = demand.loc[demand["branch"] == "Olaya"].set_index("week_start")["holiday"].reindex(olaya.index).fillna("")
print(olaya.head(3), "\n")
print(demand.loc[(demand["branch"] == "Olaya") & (demand["holiday"] == "Eid al-Adha"), ["week_start", "holiday"]]) actual same week last year Holt-Winters holiday
week_start
2025-06-02 91.5 89.8 100.3 Eid al-Adha
2025-06-09 105.0 80.0 92.8
2025-06-16 91.3 85.1 93.2
week_start holiday
47 2023-06-26 Eid al-Adha
97 2024-06-10 Eid al-Adha
148 2025-06-02 Eid al-Adha
In the week of 9 June 2025, Olaya used 105.0 kg; the copy forecast 80.0 kg, a 25 kg miss. Last year that week held Eid al-Adha, when many customers travel. But Eid al-Adha, like Ramadan and Eid al-Fitr, follows the lunar calendar and comes about 11 days earlier every year: in 2025 it fell in the week of 2 June. Copying last year put the holiday dip in the wrong week. Holt-Winters averages its seasonal pattern over several years, so it spreads that dip thinly and misses less.
The measure also changes which branch looks hardest to forecast:
by_branch = pd.DataFrame({b: scores(test[[b]], forecasts["Holt-Winters"][[b]]) for b in BRANCHES}).T
by_branch.round(2)In kilograms, Olaya, the biggest branch, has the largest errors (MAE 6.05 kg). In percent, the University branch does (11.71%): its summer weeks use only about 18 kg, so a 2 kg miss is already 11%. MAPE is useful for comparing series of different sizes, but it blows up when the actual values are small, and it cannot be computed at all when one is zero.
Choose the measure that matches the cost of being wrong. Beans are bought by the kilogram, and running out of them in a busy week is much worse than a small miss, so for this decision we compare in kilograms and prefer RMSE.
7. From forecast to order¶
We refit Holt-Winters on all three years and forecast the next 8 weeks, 28 July to 15 September 2025. A forecast is never exact, so the order adds a safety buffer. If the weekly errors are roughly normal and independent, with a standard deviation close to the holdout RMSE, the error of an 8-week total has a standard deviation of (Week 5). Adding 1.28 of those standard deviations covers the 8 weeks in about 90% of cases.
future = pd.DataFrame({b: ExponentialSmoothing(kg[b], trend="add", seasonal="add", seasonal_periods=52).fit().forecast(H)
for b in BRANCHES})
print("Weekly forecasts (kg)\n", future.round(1), "\n")
rmse = by_branch["RMSE"]
order = pd.DataFrame({
"forecast, 8 weeks": future.sum(),
"buffer (90%)": 1.28 * rmse * np.sqrt(H),
})
order["order (kg)"] = np.ceil(order["forecast, 8 weeks"] + order["buffer (90%)"])
order["naive: last week x 8"] = kg.iloc[-1] * H
order.round(1)Weekly forecasts (kg)
Olaya Corniche Al Faisaliyah University
2025-07-28 85.5 82.8 53.4 20.4
2025-08-04 84.1 83.2 53.0 19.9
2025-08-11 86.3 84.6 54.3 20.4
2025-08-18 95.5 88.6 59.4 31.0
2025-08-25 99.2 90.1 64.3 50.3
2025-09-01 110.7 94.8 66.3 49.6
2025-09-08 110.5 91.5 69.4 49.7
2025-09-15 116.6 97.6 73.4 54.0
fig, ax = plt.subplots(figsize=(9, 3.6))
for b in BRANCHES:
line, = ax.plot(kg[b].iloc[-40:], lw=1.4, label=b)
ax.plot(future[b], "--", lw=2, color=line.get_color())
ax.axvline(future.index[0], color="grey", lw=1)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
ax.set_ylabel("kg per week")
ax.set_title("The last 40 weeks and the next 8 (dashed)")
ax.legend(fontsize=8, ncol=4)
ax.grid(alpha=0.3)
plt.show()
The order is 814 kg for Olaya, 735 kg for Corniche, 512 kg for Al Faisaliyah and 314 kg for the University branch. The naive rule (“order what we used last week, times eight”) would have ordered only 148 kg for the University branch: its last week was a summer week, and the students come back in late August. The forecast rises from 20 kg to about 50 kg a week when term starts.
Two cautions before sending the order:
A model only knows the calendar of the past. Holidays that move (Ramadan, the two Eids) and one-off events (a new branch nearby, a promotion, a supply problem) are not in the seasonal pattern. Check the coming weeks yourself and adjust, or add them to the model: a regression with a holiday variable, as in Week 6, handles them directly.
The buffer is only as good as its assumptions. Errors that run in the same direction for several weeks (as they do when the trend changes) make the 8-week total less certain than suggests.
In the lab you put this analysis in a Streamlit app, so the manager can choose a branch, a method and a service level, and read off the order.
Check your understanding¶
Why must the holdout come at the end of the series rather than be a random sample of weeks?
A moving average of 4 weeks and exponential smoothing with : which reacts faster to a sudden change? Which forgets the past entirely after 4 weeks?
Method A has a lower MAE than method B but a higher RMSE. What does that tell you about A’s errors?
Why can MAPE make a small branch look like the hardest to forecast?
Name one situation in which the forecast for the coming 8 weeks should be adjusted by hand.