Dear all,

I'm trying to calculate the standard deviation of the regression residual where I require at least 3 firm-years of historical data (year t, year t-1, and year t-2) for the maximum of 5 years (year t, year t-1 until year t-4). I use the following code in Stata 16.1:

Code:
gen sdresidualstore=.
gen count=.
sort firm fyear
by firm: gen nr=_n
egen firmid=group(firm)
sum firmid
local m=r(max)
forvalues i=1(1)`m'{
    qui sum nr if firmid==`i'
    local n=r(min)+2
    local p=r(max)
    if maxnr>2 {
        forvalues j=`n'(1)`p'{
            qui gen helpvar=1 if firmid==`i' & nr<=`j' & nr>`j'-5
            qui sum residual if hulpvar==1
            qui replace sdresidualstore=r(sd) if firmid==`i' & nr==`j'
            qui replace count=r(N) if firmid==`i' & nr==`j'
            qui drop hulpvar
            di `i' " / " `j' " / " `m'
        }
    }
}

To elucidate, the variable "sdresidualstore" should store the 3-5 firm-years standard deviation of the residual that I want to calculate; and the variable "count" should store the number of observations used to compute the standard deviation (i.e., minimum of 3, and maximum of 5).

Stata does not recognize the code marked in red. I've also tried:

Code:
max(nr)>2 {
and,

Code:
nr>2 {
Both codes do not seem to work. Does anyone know what I did wrong here?

Any help is much appreciated!

Kind regards,

Dennis