Chapter 3 quiz
Ten questions to bring the chapter together.
Work from question 1 to 10. Edit your Python box, click Run Code, review the result, then click Submit attempt. Reference answers unlock after all ten attempts are submitted. This records completion, not correctness. Each box runs independently. Progress is saved in this browser.
Question 1
Print the correlation between LocationOffset and TravelCost. Compare it with correlation between squared LocationOffset and TravelCost. Explain whether the first result justifies ignoring location.
Write your answer, then run it.
Question 2
Fit Revenue on Ads with an intercept and print coefficients.
Write your answer, then run it.
Question 3
Print the first week’s observed, fitted, and residual revenues.
Write your answer, then run it.
Question 4
Print the SPY slope and its 95% confidence interval for NVDA return.
Write your answer, then run it.
Question 5
Test whether the SPY slope equals 1 against a two-sided alternative. Print its p-value.
Write your answer, then run it.
Question 6
At retail Ads=5, print a mean CI and individual PI.
Write your answer, then run it.
Question 7
Print the retail record with the largest absolute residual.
Write your answer, then run it.
Question 8
For the full pharmacy model, print the fitted annual-profit difference for US$1,000 higher disposable income while holding the other five inputs fixed.
Write your answer, then run it.
Question 9
For the retail SLR, print SST, SSR, SSE, R-squared and regression RMSE using n-2; state one limitation of using training fit to select predictors.
Write your answer, then run it.
Question 10
Predict NVDA returns, as percentages, for supplied SPY returns of -1% and +1%. State the required prediction input.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
Question 1
import pandas as pd
visits = pd.DataFrame({"LocationOffset": [-3, -2, -1, 0, 1, 2, 3]})
visits["TravelCost"] = 5 + visits["LocationOffset"] ** 2
print(round(visits["LocationOffset"].corr(visits["TravelCost"]), 3))
print(round((visits["LocationOffset"] ** 2).corr(visits["TravelCost"]), 3))
print(
"Location matters through a U-shaped cost relationship even though its Pearson correlation is zero."
)Expected output
0.0
1.0
Location matters through a U-shaped cost relationship even though its Pearson correlation is zero.A single correlation summarises linear association and can miss a curved relationship.
Question 2
import pandas as pd
sales = pd.DataFrame({
"Ads": [1, 2, 3, 4, 5, 6, 7, 8],
"Revenue": [12, 15, 14, 20, 19, 24, 25, 27],
"Price": [9, 8, 10, 7, 9, 6, 7, 6]
})
import statsmodels.api as sm
X = sm.add_constant(sales[["Ads"]])
model = sm.OLS(sales["Revenue"], X).fit()
print(model.params.round(3))Expected output
const 9.643
Ads 2.190
dtype: float64The intercept is explicitly included.
Question 3
import pandas as pd
sales = pd.DataFrame({
"Ads": [1, 2, 3, 4, 5, 6, 7, 8],
"Revenue": [12, 15, 14, 20, 19, 24, 25, 27],
"Price": [9, 8, 10, 7, 9, 6, 7, 6]
})
import statsmodels.api as sm
X = sm.add_constant(sales[["Ads"]])
model = sm.OLS(sales["Revenue"], X).fit()
print(
round(sales.loc[0, "Revenue"], 3),
round(model.fittedvalues.loc[0], 3),
round(model.resid.loc[0], 3),
)Expected output
12 11.833 0.167Residual is observed minus fitted.
Question 4
import pandas as pd
prices = pd.read_csv(
"https://busanalytics-book.pages.dev/data/nvda_spy_daily_2023_2024.csv",
index_col="Date", parse_dates=True).sort_index()
data = prices[["SPY", "NVDA"]].pct_change().dropna()
cut = int(len(data) * 0.8)
train = data.iloc[:cut].copy()
test = data.iloc[cut:].copy()
import statsmodels.api as sm
X = sm.add_constant(train[["SPY"]])
Y = train["NVDA"]
model = sm.OLS(Y, X).fit()
print(model.params["SPY"])
print(model.conf_int().loc["SPY"])Expected output
2.3320290464037203
0 2.005432
1 2.658626
Name: SPY, dtype: float64The slope describes a change in fitted NVDA return for a change in SPY return.
Question 5
import pandas as pd
prices = pd.read_csv(
"https://busanalytics-book.pages.dev/data/nvda_spy_daily_2023_2024.csv",
index_col="Date", parse_dates=True).sort_index()
data = prices[["SPY", "NVDA"]].pct_change().dropna()
cut = int(len(data) * 0.8)
train = data.iloc[:cut].copy()
test = data.iloc[cut:].copy()
import statsmodels.api as sm
X = sm.add_constant(train[["SPY"]])
Y = train["NVDA"]
model = sm.OLS(Y, X).fit()
from scipy import stats
t_stat = (model.params["SPY"] - 1) / model.bse["SPY"]
print(2 * stats.t.sf(abs(t_stat), model.df_resid))Expected output
1.208846915869949e-14Subtract the null slope of 1 and count both tails.
Question 6
import pandas as pd
sales = pd.DataFrame({
"Ads": [1, 2, 3, 4, 5, 6, 7, 8],
"Revenue": [12, 15, 14, 20, 19, 24, 25, 27],
"Price": [9, 8, 10, 7, 9, 6, 7, 6]
})
import statsmodels.api as sm
X = sm.add_constant(sales[["Ads"]])
model = sm.OLS(sales["Revenue"], X).fit()
new = pd.DataFrame({"const": [1], "Ads": [5]})
p = model.get_prediction(new).summary_frame()
print(p[["mean_ci_lower", "mean_ci_upper", "obs_ci_lower", "obs_ci_upper"]].round(3))Expected output
mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
0 19.318 21.872 16.843 24.348The individual interval includes additional outcome variation.
Question 7
import pandas as pd
sales = pd.DataFrame({
"Ads": [1, 2, 3, 4, 5, 6, 7, 8],
"Revenue": [12, 15, 14, 20, 19, 24, 25, 27],
"Price": [9, 8, 10, 7, 9, 6, 7, 6]
})
import statsmodels.api as sm
X = sm.add_constant(sales[["Ads"]])
model = sm.OLS(sales["Revenue"], X).fit()
print(sales.loc[model.resid.abs().idxmax()])Expected output
Ads 3
Revenue 14
Price 10
Name: 2, dtype: int64Investigate context before excluding an observation.
Question 8
import pandas as pd
import statsmodels.api as sm
raw = pd.read_csv("https://busanalytics-book.pages.dev/data/profit.csv")
features = [
"Income", "Disposable Income", "Birth Rate (per 1,000)",
"Soc Security (per 1,000)", "CV Death (per 100,000)", "% 65 or Older"
]
# The proposed Kansas City location has no observed Profit.
observed = raw.dropna(subset=["Profit"]).copy()
X = sm.add_constant(observed[features])
model = sm.OLS(observed["Profit"], X).fit()
print(model.params["Disposable Income"] * 1000)Expected output
2535.0336858778187The partial slope multiplied by 1,000 gives the fitted annual Profit-dollar difference. This is conditional association rather than a causal claim.
Question 9
import pandas as pd
sales = pd.DataFrame({
"Ads": [1, 2, 3, 4, 5, 6, 7, 8],
"Revenue": [12, 15, 14, 20, 19, 24, 25, 27],
"Price": [9, 8, 10, 7, 9, 6, 7, 6]
})
import statsmodels.api as sm
X = sm.add_constant(sales[["Ads"]])
model = sm.OLS(sales["Revenue"], X).fit()
import numpy as np
y = sales["Revenue"]
sst = ((y - y.mean()) ** 2).sum()
ssr = ((model.fittedvalues - y.mean()) ** 2).sum()
sse = (model.resid**2).sum()
print(round(sst, 3), round(ssr, 3), round(sse, 3))
print(round(1 - sse / sst, 4), round(np.sqrt(sse / (len(y) - 2)), 3))
print(
"Extra predictors can improve training fit while worsening prediction on new records."
)Expected output
214.0 201.524 12.476
0.9417 1.442
Extra predictors can improve training fit while worsening prediction on new records.The decomposition uses OLS with an intercept. Held-out error is needed to judge transfer to new records.
Question 10
import pandas as pd
prices = pd.read_csv(
"https://busanalytics-book.pages.dev/data/nvda_spy_daily_2023_2024.csv",
index_col="Date", parse_dates=True).sort_index()
data = prices[["SPY", "NVDA"]].pct_change().dropna()
cut = int(len(data) * 0.8)
train = data.iloc[:cut].copy()
test = data.iloc[cut:].copy()
import statsmodels.api as sm
X = sm.add_constant(train[["SPY"]])
Y = train["NVDA"]
model = sm.OLS(Y, X).fit()
new = pd.DataFrame({"const": [1, 1], "SPY": [-0.01, 0.01]})
print(model.predict(new) * 100)
print("The SPY return must be supplied for each scenario.")Expected output
0 -1.996343
1 2.667715
dtype: float64
The SPY return must be supplied for each scenario.The model gives a conditional stock-return prediction, given the SPY return.