* wald_2sls.do

clear
capture log close

use https://raw.github.com/scunning1975/mixtape/master/card.dta, clear

* Calculate the Wald estimator manually as the ratio fo two covariances, then 2SLS, then appropriate tests on weak instrument first stage.

* 1. Wald IV as a ratio of two covariances: Cov(lwage,nearc4)/Cov(educ,nearc4)
* Cov(Y,Z) = E[YZ] - E[Y]E[Z]
* Cov(S,Z) = E[SZ] - E[S]E[Z]

egen mean_wage = mean(lwage)
egen mean_iv = mean(nearc4)
egen mean_educ = mean(educ)
gen yz_product = mean_wage*mean_iv
gen sz_product = mean_educ*mean_iv

gen yz = lwage*nearc4
gen sz = educ*nearc4

egen mean_yz = mean(yz)
egen mean_sz = mean(sz)

* Wald estimator: Cov(Y,Z) / Cov(S,Z)
gen cov_yz = mean_yz - yz_product
gen cov_sz = mean_sz - sz_product

gen wald_iv1 = cov_yz/cov_sz


* 2. Wald IV as a ratio of two OLS regression coefficients
regress lwage nearc4, robust
gen rf = _b[nearc4]

regress educ nearc4, robust
gen fs = _b[nearc4]

gen wald_iv2 = rf/fs
su wald_iv2


* 3. Wald IV as Twostage least squares
regress educ  nearc4, robust
predict shat

regress lwage  shat, robust
gen wald_2sls1 = _b[shat]


* 4. Wald IV as Twostage least squares
ivregress 2sls lwage (educ=nearc4), first robust
gen wald_2sls2 = _b[educ]

su wald*