Improving Stata Newey-West Command Output
Published:
Stata’s built-in newey
command does not output ( R^2 ) and adjusted ( R^2 ) by default. Notably, the ( R^2 ) from newey
is the same as that from OLS. To facilitate exporting these statistics, particularly for use with reg2docx
, I’ve created a custom command.
First, remove any existing program by the same name:
cap program drop newey_r2
Define the new command that will calculate and display ( R^2 ) and adjusted ( R^2 ):
cap program drop newey_r2
program define newey_r2, eclass
syntax varlist [if] [in], [lag(string) otheropt(string)]
marksample touse
qui count if `touse'
local N = r(N)
if "`lag'" == ""{
local lag = floor(4 * (`N' / 100)^(2 / 9))
}
qui reg `varlist' if `touse'
local r2 = e(r2)
local r2_a = e(r2_a)
dis as text "Newey-West regression using newey_r2" _c
dis as text _column(49) "R-squared" _c
dis as text _column(67) "=" _c
dis as result %11.4f `r2'
dis as text _column(49) "Adj R-squared" _c
dis as text _column(67) "=" _c
dis as result %11.4f `r2_a' _c
newey `varlist' if `touse' , force lag(`lag') `otheropt'
ereturn scalar r2 = `r2'
ereturn scalar r2_a = `r2_a'
end
Reference for calculating lag: MathWorks HAC documentation.
To implement this custom command, follow these steps based on your operating system:
- On Ubuntu: Go to
/home/USERNAME/STATA_DIR/ado/base/n
(replace USERNAME with your username and STATA_DIR with your Stata directory) - On Mac: Go to
/Applications/Stata/ado/base/n
Use sudo vim to open or create newey_r2.ado
, and paste the above code into this file.
sudo vim newey_r2.ado
Testing the Command
To ensure the command works correctly, test it with some sample data:
eststo clear
webuse idle2 , clear
tset time
eststo: newey usr idle , lag(3) force
est store m1
// I enforced the force option in the program code
eststo: newey_r2 usr idle , lag(3)
est store m2
// I enforced the force option in the program code
eststo: newey_r2 usr idle // lag is calculated using the formula 4 * (N / 100)^(2 / 9)
est store m3
// not regularly spaced data
webuse idle2 , clear
tset time
drop if time==2
eststo: newey usr idle , lag(3) force
est store m1
// I enforced the force option in the program code
eststo: newey_r2 usr idle , lag(3)
est store m2
// I enforced the force option in the program code
eststo: newey_r2 usr idle // lag is calculated using the formula floor(4 * (N / 100)^(2 / 9))
est store m3
esttab using ./test.csv, b(3) t(2) ar2(3) star(* 0.10 ** 0.05 *** 0.01) nogaps nonotes replace
eststo clear
This script demonstrates the enhanced functionality of newey_r2
, including the automatic calculation of optimal lags and exporting of ( R^2 ) and adjusted ( R^2 ) statistics, which are crucial for robust regression analysis and documentation.