Hello,

I need to do some operations over all the lags up to the current value, but the loop I wrote takes forever, could you please tell me how to speed it up?

levelsof permno, local(levels)
foreach lev of local levels {
gen l1_new=(retex-b_cons-b_mktrf*mktrf)*(mktrf-mktrf_mean)^2
local lag=_n
forval i=1/`lag'-1{
replace l1_new=l1_new+(l`i'.retex-b_cons-b_mktrf*l`i'.mktrf)*(l`i'.mktrf-mktrf_mean)^2
}
}

Thank you in advance,
Alina

Later edit: I am also getting errors in the code, but I don't know why.