*! version 30aug2024

Partially-linear IV model - Basic example with pystacked

The model has three conditional expectations: E[Y|X], E[D|X] and E[Z|X].
For each reduced form equation, we use pystacked's default learners:
OLS, cross-validated lasso, and gradient boosting.
Since the data set is very small, we consider 30 cross-fitting folds.
NB: The model specification and results will be stored on a Mata object
with the default name "m0".

. use https://statalasso.github.io/dta/AJR.dta, clear

. global Y logpgp95

. global D avexpr

. global Z logem4

. global X lat_abst edes1975 avelf temp* humid* steplow-oilres

. set seed 42

. ddml init iv, kfolds(30)

. ddml E[Y|X]: pystacked $Y $X

. ddml E[D|X]: pystacked $D $X

. ddml E[Z|X]: pystacked $Z $X

. ddml crossfit

. ddml estimate

Replicate the ddml estimate results for the 1st cross-fit estimation (resample 1) by hand,
using the estimated conditional expectations generated by ddml and pystacked;
"_1" means resample 1.
Compare using ddml estimate, replay.

. cap drop Yresid

. cap drop Dresid

. cap drop Zresid

. gen double Yresid = $Y - Y1_pystacked_1

. gen double Dresid = $D - D1_pystacked_1

. gen double Zresid = $Z - Z1_pystacked_1

. ivreg Yresid (Dresid=Zresid)

. ddml estimate, mname(m0) spec(st) rep(1) notable replay