# Chapter 15: Regression and Econometrics with Python
# Fundamentals of Python for Financial Econometrics - Regression and Econometrics with Python
# Dataset: Ceteris Lab teaching sample

# Regression and Econometrics with Python
#
# **Opening question:** What does a regression coefficient mean, and which assumptions are needed before it can support an economic claim?

# %% Cell 2
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(15)
x = np.linspace(0, 10, 120)
y = 1.5 + 0.8*x + rng.normal(0, 0.4 + 0.08*x)
df = pd.DataFrame({"y": y, "x": x})
model = smf.ols("y ~ x", data=df).fit(cov_type="HC3")
print(round(model.params["x"], 3), round(model.bse["x"], 3))

# **Interpretation check:** Interpretation. The slope is close to the data-generating value. HC3 standard errors account for heteroskedasticity in a large-sample approximation.

# %% Cell 4
df["group"] = (df["x"] > 5).astype(int)
interaction = smf.ols("y ~ x * group", data=df).fit(cov_type="HC3")
print(interaction.params.round(3).to_dict())

# **Interpretation check:** Interpretation. The interaction allows the slope to differ after x exceeds five. Here the estimated difference is small because the simulated process has one common slope.

# %% Cell 6
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(15)
x = np.linspace(0, 10, 120)
y = 1.5 + 0.8*x + rng.normal(0, 0.4 + 0.08*x)

# Verified source output
#
# ```text
# 0.848 0.028
# ```
#
# ```text
# {'Intercept': 1.503, 'x': 0.809, 'group': -0.565, 'x:group': 0.099}
# ```
