Last Update: March 22, 2022
My online video tutorials are hosted at YouTube channel.
For learning this concept, you can view my online video tutorials: Instrumental Variables: Two Stage Least Squares in Python (Spyder) and Instrumental Variables: Two Stage Least Squares in Python (Jupyter).
Videos Code
1. Packages
import statsmodels.api as sm
import statsmodels.formula.api as smf
import linearmodels.iv.model as lm
2. Data
houseprices_object = sm.datasets.get_rdataset(dataname="HousePrices",
package="AER", cache=True)
houseprices = houseprices_object.data
print(houseprices.head())
print(houseprices_object.__doc__)
3. Model
mlr1 = smf.ols(formula="price ~ lotsize + bedrooms",
data=houseprices).fit()
4. Instrumental Variables
Two Stage Least Squares
mdatac = sm.add_constant(data=houseprices, prepend=False)
mlr2 = lm.IV2SLS(dependent=mdatac["price"],
exog=mdatac[["const", "bedrooms"]],
endog=mdatac["lotsize"],
instruments=mdatac[["driveway", "garage"]]).fit(
cov_type="homoskedastic", debiased=True)
print(mlr1.params, mlr2.params)
print(mlr1.tvalues, mlr2.tstats)
print(mlr1.pvalues, mlr2.pvalues)
print(mlr1.fvalue, mlr1.f_pvalue)
print(mlr2.f_statistic)
Courses
My online courses are hosted at Teachable website.
For more details on this concept, you can view my Linear Regression in Python Course.