No need to adjust the Mata code. rangestat returns first the number of observations (as myreg1). Then as many variables as there are independent variables. So if you have 2, rangestat will store the coefficients in myreg2 myreg3. Finally, since a constant is added in the Mata code, it's coefficient is returned in myreg4. Here's an updated example:
Code:
* test data; use variable names in the thread webuse grunfeld, clear rename company permno rename invest stockexcessret rename mvalue mktrf gen mktrf_lag1 = L.mktrf save "test_data.dta", replace * ------------ regressions over a window of 6 periods using -rangestat- -------- * define a linear regression in Mata using quadcross() - help mata cross(), example 2 mata: mata clear mata set matastrict on real rowvector myreg(real matrix Xall) { real colvector y, b, Xy real matrix X, XX y = Xall[.,1] // dependent var is first column of Xall X = Xall[.,2::cols(Xall)] // the remaining cols are the independent variables X = X,J(rows(X),1,1) // add a constant XX = quadcross(X, X) // linear regression, see help mata cross(), example 2 Xy = quadcross(X, y) b = invsym(XX) * Xy return(rows(X), b') } end * regressions with a constant over a rolling window of 6 periods by permno rangestat (myreg) stockexcessret mktrf mktrf_lag1, by(permno) interval(time -5 0) casewise * the Mata function returns first the number of observations and then as many * variables as there are independent variables (plus the constant) for the betas rename (myreg1 myreg2 myreg3 myreg4) (nobs rs_mktrf rs_mktrfl1 rs_cons) * reject results if the window is less than 6 or if the number of obs < 4 isid permno year by permno: replace rs_mktrf = . if _n < 6 | nobs < 4 by permno: replace rs_cons = . if _n < 6 | nobs < 4 by permno: replace rs_mktrfl1 = . if _n < 6 | nobs < 4 save "rangestat_results.dta", replace * ----------------- replicate using -rolling- ---------------------------------- use "test_data.dta", clear levelsof permno, local(permno) foreach s of local permno { rolling _b, window(6) saving(betas_`s', replace) reject(e(N) < 4): /// regress stockexcessret mktrf mktrf_lag1 if permno == `s' } clear save "betas.dta", replace emptyok foreach s of local permno { append using "betas_`s'.dta" } rename end year merge 1:1 permno year using "rangestat_results.dta" isid permno year, sort gen diff_mktrf = abs(_b_mktrf - float(rs_mktrf)) gen diff_mktrfl1 = abs(_b_mktrf_lag1 - float(rs_mktrfl1)) gen diff_cons = abs(_b_cons - float(rs_cons)) summ diff*
Comment