Note that you can do this with rangestat (from SSC): far simpler to code and much much faster! To install rangestat, type in Stata's Command window:
Just as a proof of concept, here's some synthetic data that has the correct structure. I copied Clyde's code from #12 (altered slightly to remove all the output):
Note that there are may ways to code the interval() option. Within groups of ticker year, the year does not change so all observations in the group are included. Since all observations within the group have the same interval bounds, the regression is calculated once and the results are carried over to the other observations in the group.
Code:
ssc install rangestat
Code:
clear all set obs 50 gen ticker = string(_n) expand 10 bysort ticker: gen year = 2006 + _n expand 365 bysort ticker year: gen Date = mdy(1,1,year) + _n - 1 sort ticker year Date format %td Date gen company_stock_return = runiform() gen sp_500_return = runiform() drop year * Clyde's code gen int year = yofd(Date) gen beta = . levelsof ticker, local(firms) qui foreach f of local firms { levelsof year if ticker == `"`f'"', local(years) foreach y of local years { capture regress company_stock_return sp_500_return if year == `y' /// & ticker ==`"`f'"' if c(rc) == 0 { // SUCCESSFUL REGRESSION, STORE RESULTS replace beta = _b[sp_500_return] if year == `y' & ticker == `"`f'"' } else if !inlist(c(rc), 2000, 2001) { // SOME PROBLEM OTHER THAN TOO FEW OBSERVATIONS display in red `"Unexpected error with ticker = `f' and year = `y'"' exit c(rc) } } } * compare with rangestat (from SSC). rangestat (reg) company_stock_return sp_500_return, interval(year 0 0) by(ticker year) assert beta == float(b_sp_500_return)
Comment