****************************************
* PROGRAM: 771Fall08_Rec1_STATAexample
* PROGRAMMER: Simone Schaner
* PURPOSE: Example to illustrate nonparametric
*	regression techniques and the effects
*	of measurement error
* DATE CREATED: 9/5/08
*****************************************


*************************************************************************
* NONPARAMETRIC REGRESSION
*************************************************************************

clear

set mem 100m
set more off
set seed 2681


set obs 10000

* SIMULATE SOME NONLINEAR DATA
g x=_n/10000
g y= 150*x^5+ln(x)+300*cos(x)+invnorm(uniform())

* GRAPH IT
sort x
twoway scatter y x

* GENERATE POLYNOMIALS FOR SERIES REGRESSION
forval i=1/15 {
	g x`i'=x^`i'
	}

* DEGREE TWO
reg y x1-x2
predict xhat1, xb
sort x
twoway scatter y x || line xhat1 x

* DEGREE THREE
reg y x1-x3
predict xhat3, xb
sort x
twoway scatter y x || line xhat3 x

* DEGREE 5
reg y x1-x5
predict xhat2, xb
sort x
twoway scatter y x || line xhat2 x

* KERNEL AND LOCAL LINEAR REGRESSION
locpoly y x , degree(0)  lcolor(red) name(kreg1) title("Kernel Regression") nodraw
locpoly y x , degree(1)  lcolor(red) name(kreg2) title("Local Linear Regression") nodraw

* COMBINE THEM ON ONE GRAPH TO ILLUSTRATE BIAS OF KERNEL
gr combine kreg1 kreg2,  rows(2) cols(1) xsize(7) ysize(8.5)


*********************************************************************
* MEASUREMENT ERROR
**********************************************************************

clear
set obs 10000

* SIMULATE DATA
g x_star=uniform()
g y_star=2+3*x_star+invnorm(uniform())

g x=x_star+invnorm(uniform())
g y=y_star+invnorm(uniform())

* TRUE REGRESSION
reg y_star x_star

* ME ON BOTH SIDES
reg y x

* ME ON LHS
reg y x_star

* ME ON RHS
reg y_star x

* IV IS A SOLUTION
g x2= x_star+invnorm(uniform())
ivreg y_star (x=x2)