Saturday, May 5, 2012

Program your own quantile regression v1 - Maximum Likelihood

* Stata estimation and maximum likelihood


* Clear old data
clear
* Set observations to 1000
set obs 10000

* Specify the quartile
gl tau=.5

gen x1=runiform()*4-2
gen y=3*x1+rnormal()

* Drop the program if it already is in the memory
cap program drop my_qreg1

* Define the ML program
program my_qreg1
* Tell stata what version to run in
  version 11
* Define the arguments used in the ML command
  args lnfj xb sigma
* Specify the log likelihood function return values (lnfj)
* The quantile estimator can be found by maximizing the asymetric Laplace probability density function
  quietly replace `lnfj'=log($tau*(1-$tau)/`sigma')-$tau*($ML_y1-`xb')/`sigma'     if `xb'< $ML_y1
  quietly replace `lnfj'=log($tau*(1-$tau)/`sigma')-($tau-1)*($ML_y1-`xb')/`sigma' if `xb'>=$ML_y1
end

* Tell stata which model to use
ml model lf my_qreg1 (y = x1) ()
* Search for starting values
ml search
* Maximize the log likelihood function using the Newtonian/Ralphson algorithm
* Sometimes this algorithm does not always converge.  It is not as efficiently
* programmed as the stata built in qreg command.
ml maximize

* Pretty close but not exactly the same.
qreg y x1

No comments:

Post a Comment