▼
Sunday, August 12, 2012
Mata: program your own IV Estimator
* Mata: program your own IV Estimator
* First let see how we could program an IV estimator without matrices.
version 11
clear
set obs 1000
gen z = rnormal()
gen u= rnormal()
gen x = u + z + rnormal()
gen y = 2 + 2*x + 15*u
reg y x
foreach v in x y z {
foreach vv in x y z {
gen `v'`vv' = `v'*`vv'
qui sum
local `v'`vv' = r(mean)*r(N)
}
}
di "IVhat = " (`xz'*(`zz')^-1*`zx')^-1 * (`xz'*(`zz')^-1*`zy')
ivreg y (x=z)
* Looks pretty close. However, there is some divergence due to the above estimator not allowing for a constant.
ivreg y (x=z), nocon
* Now let's see how to do it in Mata.
mata
x = st_data(.,("x"))
z = st_data(.,("z"))
y = st_data(.,("y"))
IVhat1 = invsym((x'*z)*invsym(z'*z)*(z'*x))*(x'*z)*invsym(z'*z)*(z'*y)
"IV estimate without constant"
IVhat1
"Create a constant vector of length x"
cons = J(rows(x), 1, 1)
X = (x, cons)
Z = (z, cons)
IVhat2 = invsym((X'*Z)*invsym(Z'*Z)*(Z'*X))*(X'*Z)*invsym(Z'*Z)*(Z'*y)
"IV estimate with constant"
IVhat2
end
* End is necessary with mata do files to indicate when the mata subsystem is completed.
No comments:
Post a Comment