Hello! This is my first post on the forum, so please bare with me!

I have a panel data set from 2003-2016 for 5 different stock portfolios, and would like to generate rolling betas with a 6 month window for each portfolio over time (starting from Jan 2004).

Portfolio Year_Month x y N
1 2003m7 x1 y1 1
1 2003m8 x2 y2 2
... ... ... ...
1 2016m12 x162 y162 162
2 2003m7 x163 y163 163
... ... ... ...
5 2016m12 x810 y810 810

I have understood that this needs to be done through a loop, and have tried the following code:

local begin_m = 7
local end_m = 810
use Monthly_Data.dta

forvalues i=`begin_m'(1)`end_m' {

keep if monthyear<=`i' & monthyear>`i'-7
statsby _b _se e(N) e(r2_a), by(Portfolio) clear: reg x y
gen month=`i'

if `i'==`begin_m' {
save "Betas_Rolling.dta", replace
}
else {
append using "Betas_Rolling.dta"
sort Portfolio Year_Month
save "Betas_Rolling.dta", replace
}
use Monthly_Data.dta
}


However, whenever I run it, Stata deletes all the 810 observations, and returns "no observations / an error occurred when statsby executed regress"

Any ideas on how to get this code to work, or an alternative way to generate the rolling betas? All help would be so dearly appreciated.

Thank you so much.

Best,
Adam