Lab 6 Solutions: Linear Regression with statsmodels¶
These are the worked solutions, with outputs. Try the lab yourself first.
In this lab you build regression models of Qahwa House’s daily sales and use them to answer two questions from the manager.
The questions. Should we raise drink prices by 1 SAR? and Should every branch keep the “second cup half price” promotion?
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.
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
import statsmodels.formula.api as smf
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)
daily = load("qahwa_daily_2025.csv")
daily.head()| Column | Meaning |
|---|---|
date, weekday, month | the day |
weekend | 1 on Friday and Saturday |
branch, city | where |
temp_c | the day’s highest temperature (°C) |
price_sar | the average price of a cup that day (SAR); each branch tested a different price every month |
promo | 1 on a second cup half price day |
cups | drinks sold that day |
revenue_sar | drink revenue that day (SAR) |
Part A: Simple regression¶
A1. Cups and temperature¶
Fit the simple regression of cups on temp_c with smf.ols(...).fit(). Store the fitted model in heat.
heat = smf.ols("cups ~ temp_c", data=daily).fit()
heat.params.round(2)Intercept 308.19
temp_c 3.34
dtype: float64check("A1 a positive slope: hotter days sell more", heat.params["temp_c"] > 0)
check("A1 the slope is between 3 and 4 cups per degree", 3 < heat.params["temp_c"] < 4)✅ A1 a positive slope: hotter days sell more
✅ A1 the slope is between 3 and 4 cups per degree
A2. The slope by hand¶
The least-squares slope of a simple regression is . Compute it with pandas and store it in slope_by_hand. Then print (heat.rsquared).
slope_by_hand = daily["temp_c"].cov(daily["cups"]) / daily["temp_c"].var()
print(round(slope_by_hand, 4), round(heat.rsquared, 3))3.3372 0.068
check("A2 same slope as statsmodels", abs(slope_by_hand - heat.params["temp_c"]) < 1e-9)
check("A2 the temperature alone explains less than 10% of the variation", heat.rsquared < 0.10)✅ A2 same slope as statsmodels
✅ A2 the temperature alone explains less than 10% of the variation
A3. Cups and price¶
Now fit cups on price_sar and store the model in naive.
naive = smf.ols("cups ~ price_sar", data=daily).fit()
naive.params.round(2)Intercept -71.61
price_sar 31.59
dtype: float64check("A3 the slope is positive (!)", naive.params["price_sar"] > 0)✅ A3 the slope is positive (!)
A4. Taken at face value, this slope says that raising prices sells more cups. In two sentences, give the most likely explanation. Hint: daily.groupby("branch")[["price_sar", "cups"]].mean().
Answer. The simple regression compares days across branches, and the busiest branch, Olaya, is also the most expensive (17.46 SAR and 513 cups on average) while University is the cheapest and quietest (12.97 SAR, 321 cups). The branch drives both the price and the sales, so the slope of +31.59 measures the difference between branches, not the effect of a price change.
Part B: Multiple regression and dummy variables¶
B1. The full model¶
Fit cups on price_sar, temp_c, weekend, promo and the branch (as C(branch)). Store it in full and print the coefficients.
full = smf.ols("cups ~ price_sar + temp_c + weekend + promo + C(branch)", data=daily).fit()
print(full.params.round(2))
print(round(full.rsquared, 3))Intercept 645.01
C(branch)[T.Corniche] 72.20
C(branch)[T.Olaya] 159.15
C(branch)[T.University] -147.41
price_sar -25.57
temp_c 3.77
weekend 69.18
promo 54.37
dtype: float64
0.881
check("B1 the price slope is now negative", full.params["price_sar"] < 0)
check("B1 three branch dummies (one branch is the baseline)", sum(k.startswith("C(branch)") for k in full.params.index) == 3)
check("B1 R-squared above 0.85", full.rsquared > 0.85)✅ B1 the price slope is now negative
✅ B1 three branch dummies (one branch is the baseline)
✅ B1 R-squared above 0.85
B2. Reading a dummy¶
Store the University branch’s coefficient in uni.
uni = full.params["C(branch)[T.University]"]
round(float(uni), 2)-147.41check("B2 University sells fewer cups than the baseline", uni < -100)✅ B2 University sells fewer cups than the baseline
B3. Which branch is the baseline? Write one sentence that explains uni to the manager, saying what is held fixed.
Answer. The baseline is Al Faisaliyah, the first branch in alphabetical order. On a day with the same price, temperature, weekday or weekend and promotion status, the University branch sells about 147 cups fewer than Al Faisaliyah.
B4. A prediction¶
Predict the cups sold at Olaya on a Saturday at 40 °C, with a price of 17 SAR and no promotion. Build a one-row DataFrame new_day with the five columns the model uses, then store full.get_prediction(new_day).summary_frame(alpha=0.05) in pred.
new_day = pd.DataFrame({"price_sar": [17.0], "temp_c": [40.0], "weekend": [1], "promo": [0], "branch": ["Olaya"]})
pred = full.get_prediction(new_day).summary_frame(alpha=0.05)
pred.round(1)check("B4 between 550 and 650 cups", 550 < pred["mean"].iloc[0] < 650)
check("B4 the interval for one day is wider than the interval for the mean",
(pred["obs_ci_upper"] - pred["obs_ci_lower"]).iloc[0] > (pred["mean_ci_upper"] - pred["mean_ci_lower"]).iloc[0])✅ B4 between 550 and 650 cups
✅ B4 the interval for one day is wider than the interval for the mean
Part C: An interaction¶
C1. Does the promotion work the same everywhere?¶
Fit the model of B1 with promo * C(branch) in place of promo + C(branch). Store it in inter.
inter = smf.ols("cups ~ price_sar + temp_c + weekend + promo * C(branch)", data=daily).fit()
print(inter.params.filter(like="promo").round(2))promo 41.24
promo:C(branch)[T.Corniche] -4.41
promo:C(branch)[T.Olaya] -25.58
promo:C(branch)[T.University] 85.65
dtype: float64
check("C1 three interaction terms", sum(":" in k for k in inter.params.index) == 3)
check("C1 a better fit than the full model", inter.rsquared > full.rsquared)✅ C1 three interaction terms
✅ C1 a better fit than the full model
C2. The promotion’s effect in each branch¶
The promotion’s effect in the baseline branch is inter.params["promo"]; in another branch, add its promo:C(branch)[T.<branch>] term. Store the four effects in a Series promo_effect, indexed by branch name.
branches = ["Olaya", "Corniche", "Al Faisaliyah", "University"]
b = inter.params
promo_effect = pd.Series({br: b["promo"] + (0 if br == "Al Faisaliyah" else b[f"promo:C(branch)[T.{br}]"]) for br in branches})
promo_effect.round(1)Olaya 15.7
Corniche 36.8
Al Faisaliyah 41.2
University 126.9
dtype: float64check("C2 four branches", len(promo_effect) == 4)
check("C2 the promotion works best at University", promo_effect.idxmax() == "University")
check("C2 and worst at Olaya", promo_effect.idxmin() == "Olaya")✅ C2 four branches
✅ C2 the promotion works best at University
✅ C2 and worst at Olaya
C3. In two sentences: what would the manager have concluded from the model of B1, and why is it misleading?
Answer. The model of B1 has one promotion coefficient, so it tells the manager that a promotion day adds about 54 cups in every branch and suggests keeping it everywhere. With the interaction, the promotion adds about 127 cups at University but only about 16 at Olaya: the 54 is an average that describes no branch.
Part D: The decision¶
D1. What is one riyal on the price worth?¶
For each branch, take the mean cups and price_sar of non-promotion days (a DataFrame normal, one row per branch). With the price slope of inter, the revenue changes from to . Store the change per day in a Series price_change, indexed by branch.
normal = daily[daily["promo"] == 0].groupby("branch")[["cups", "price_sar"]].mean().loc[branches]
slope = inter.params["price_sar"]
price_change = (normal["cups"] + slope) * (normal["price_sar"] + 1) - normal["cups"] * normal["price_sar"]
price_change.round(1)branch
Olaya 25.5
Corniche -12.9
Al Faisaliyah -41.7
University -62.3
dtype: float64check("D1 four branches", len(price_change) == 4)
check("D1 small changes: under 100 SAR a day in every branch", price_change.abs().max() < 100)
check("D1 Olaya gains, University loses", price_change["Olaya"] > 0 > price_change["University"])✅ D1 four branches
✅ D1 small changes: under 100 SAR a day in every branch
✅ D1 Olaya gains, University loses
D2. Where does the promotion pay?¶
On a promotion day the average cup sells 18% below its price. With promo_effect extra cups, the revenue of a promotion day is . Store the change against a normal day, , in a Series promo_change.
promo_change = (normal["cups"] + promo_effect) * normal["price_sar"] * 0.82 - normal["cups"] * normal["price_sar"]
promo_change.round(1)branch
Olaya -1381.8
Corniche -836.4
Al Faisaliyah -581.2
University 637.9
dtype: float64check("D2 the promotion pays at University", promo_change["University"] > 0)
check("D2 and loses revenue in the three other branches", (promo_change.drop("University") < 0).all())✅ D2 the promotion pays at University
✅ D2 and loses revenue in the three other branches
D3. Your recommendation¶
Write three sentences for the manager: one on the price (with numbers), one on the promotion (with numbers), and one on what the regression cannot tell you.
Recommendation. A price 1 SAR higher costs about 26 cups a day in every branch, so revenue barely changes (+25.5 SAR a day at Olaya, −12.9 to −62.3 SAR elsewhere): I would not raise prices for revenue’s sake. Keep the second cup half price promotion only at University, where it brings about 127 extra cups and +637.9 SAR a day, and stop it in the other three branches, where it loses 581 to 1,382 SAR per promotion day. The model only covers prices between 12 and 18.5 SAR and the factors it includes; it says nothing about costs or about how customers would react to a lasting price rise, so the change should be tested for a month in one branch first.
★ Extended challenges¶
E1. Is the weekend effect the same everywhere? Add a weekend:C(branch) interaction to inter and look at the p-values of the new terms (model.pvalues). Should the model keep them?
E2. Elasticity. Fit np.log(cups) ~ np.log(price_sar) + temp_c + weekend + promo * C(branch). The coefficient of np.log(price_sar) is the price elasticity: the % change in cups for a 1% change in price. What does its value say about revenue?
E3. Revenue directly. Fit revenue_sar on the same variables as inter. Compute the promotion’s effect on revenue in each branch and compare it with D2.
e1 = smf.ols("cups ~ price_sar + temp_c + weekend + promo * C(branch) + weekend:C(branch)", data=daily).fit()
print(e1.pvalues.filter(like="weekend:").round(3))weekend:C(branch)[T.Corniche] 0.530
weekend:C(branch)[T.Olaya] 0.480
weekend:C(branch)[T.University] 0.283
dtype: float64
E1. All three p-values are well above 0.05 (0.283 to 0.530): the data show no difference in the weekend lift between branches, so the extra terms only add noise. Keep the simpler model.
e2 = smf.ols("np.log(cups) ~ np.log(price_sar) + temp_c + weekend + promo * C(branch)", data=daily).fit()
round(float(e2.params["np.log(price_sar)"]), 3)-0.987E2. The elasticity is about −0.99: a price 1% higher sells about 1% fewer cups. Revenue, price times cups, then hardly changes, which is what D1 found branch by branch.
e3 = smf.ols("revenue_sar ~ price_sar + temp_c + weekend + promo * C(branch)", data=daily).fit()
r = e3.params
pd.Series({br: r["promo"] + (0 if br == "Al Faisaliyah" else r[f"promo:C(branch)[T.{br}]"]) for br in branches}).round(1)Olaya -1374.4
Corniche -836.5
Al Faisaliyah -609.7
University 659.9
dtype: float64E3. The revenue model gives the same picture: the promotion adds about 660 SAR a day at University and loses about 610 to 1,374 SAR elsewhere, close to D2’s figures, which were computed from the cups model and the 18% discount.