Lab 6: Linear Regression with statsmodels¶
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 = ...
heat.params.round(2)check("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)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 = ...
print(round(slope_by_hand, 4), round(heat.rsquared, 3))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)A3. Cups and price¶
Now fit cups on price_sar and store the model in naive.
naive = ...
naive.params.round(2)check("A3 the slope is positive (!)", naive.params["price_sar"] > 0)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().
Your answer here (double-click to edit).
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 = ...
print(full.params.round(2))
print(round(full.rsquared, 3))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)B2. Reading a dummy¶
Store the University branch’s coefficient in uni.
uni = ...
round(float(uni), 2)check("B2 University sells fewer cups than the baseline", uni < -100)B3. Which branch is the baseline? Write one sentence that explains uni to the manager, saying what is held fixed.
Your answer here (double-click to edit).
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 = ...
pred = ...
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])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 = ...
print(inter.params.filter(like="promo").round(2))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)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"]
promo_effect = ...
promo_effect.round(1)check("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")C3. In two sentences: what would the manager have concluded from the model of B1, and why is it misleading?
Your answer here (double-click to edit).
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 = ...
slope = inter.params["price_sar"]
price_change = ...
price_change.round(1)check("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"])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 = ...
promo_change.round(1)check("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())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.
Write your recommendation here (double-click to edit).
★ 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# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.