set more off
capt log close
cd "/Users/baum/Documents/Courses 2009-2010/EC771 S2010"
log using 771reg, replace

// EC771reg  cfb 0122
// illustration of regression by OLS, MM, ML

sysuse auto, clear
g gpm = 1 / mpg
replace weight = weight / 1000

// solution by OLS regression
regress gpm foreign weight
estat vce

// solution by method of moments
// GMM criterion will be minimized to zero as the model
// is exactly identified (3 moment conditions, 3 parameters)
gmm (gpm - {xb:foreign weight} - {b0}), ///
    instruments(foreign weight) wmatrix(unadjusted) nolog
// note that the VCE estimates are large-sample
// and thus do not agree with those of OLS
estat vce

// solution by maximum likelihood
// For linear regression assuming normally distributed errors,
// ln L = sum [ ln phi( (y_i - x_i b) / sigma ) - ln sigma ]
// where phi( ) is the density of N(0, 1)
// The three-parameter form of Stata's normalden(x, m, s) function
// returns [ phi((x-m)/s) / s ], so we may call it directly
// to evaluate the likelihood of each observation
program drop _all
program mynormalreg_lf 
	version 11 
	args lnf mu sigma 
	quietly replace `lnf' = ///
	ln(normalden( $ML_y1, `mu', `sigma' ) ) 
	end
	
ml model lf mynormalreg_lf (gpm = foreign weight) /sigma
ml maximize, nolog
// estimate of /sigma may be compared with RMS Error from OLS
// but degrees of freedom differ
// note that the VCE estimates, based on /sigma, are large-sample
estat vce

log close
translate 771reg.smcl 771reg.pdf, replace
log2html 771reg.smcl 771reg.html, replace