from _api_doc_utils import *TwoSLS
Closed-form linear IV / two-stage least squares
1 Where it fits
Group: Causal inference
TwoSLS estimates linear instrumental-variables models. With endogenous regressors \(X_e\), exogenous controls \(X_c\), instruments \(Z\), and outcome \(y\), it runs the projection of the second-stage design on the instrument span and then estimates
\[ y = \alpha + X_e\beta_e + X_c\beta_c + u. \]
It supports multiple endogenous regressors and excluded instruments.
2 Python API
Constructor: cm.TwoSLS
Call fit(x_endog, x_exog, z, y). The predict(x) method expects a second-stage design matrix matching the fitted endogenous+exogenous columns. The robust linear covariance options match OLS: vanilla, hc1, newey_west, and cluster.
print(inspect.signature(cm.TwoSLS))()
cls = cm.TwoSLS
display(HTML(html_table(["Public method"], public_methods(cls))))| Public method |
|---|
bootstrap(self, /, n_bootstrap, seed=None) |
fit(self, /, x_endog, x_exog, z, y) |
fit_sketch(self, /, x_endog, x_exog, z, y, sketch_size, seed=None) |
fit_weighted(self, /, x_endog, x_exog, z, y, sample_weight) |
predict(self, /, x) |
summary(self, /, vcov='hc1', lags=None, clusters=None) |
3 Minimal example
rng=np.random.default_rng(9); n=400
z=rng.normal(size=(n,2)); x_exog=rng.normal(size=(n,1)); v=rng.normal(size=(n,1)); u=.6*v[:,0]+rng.normal(scale=.4,size=n)
x_endog=z@np.array([[.8],[-.4]])+.2*x_exog+v; y=.5+1.2*x_endog[:,0]-.7*x_exog[:,0]+u
model=cm.TwoSLS(); model.fit(x_endog,x_exog,z,y)
print(model.summary()["coef"])
print(model.summary(vcov="newey_west", lags=3)["coef_se"])[ 1.22456127 -0.6589091 ]
[0.04054546 0.03621148]
4 summary() contract
The table below is generated by fitting the live class in this repository and then inspecting summary(). Shapes are shown because most values are plain NumPy arrays or scalars.
rng=np.random.default_rng(109); n=120; z=rng.normal(size=(n,2)); x_exog=rng.normal(size=(n,1)); v=rng.normal(size=(n,1)); x_endog=z@np.array([[.8],[-.4]])+.2*x_exog+v; y=.5+1.2*x_endog[:,0]-.7*x_exog[:,0]+.6*v[:,0]+rng.normal(size=n)*.4
model=cm.TwoSLS(); model.fit(x_endog,x_exog,z,y)
summary = model.summary()
display(HTML(html_table(["summary() key", "shape"], summary_shape_rows(summary))))| summary() key | shape |
|---|---|
intercept |
() |
coef |
(2,) |
intercept_se |
() |
coef_se |
(2,) |
vcov_type |
() |