Search code examples
stata

How to take maximum of rolling window without SSC packages


How can I create a variable in Stata that contains the maximum of a dynamic rolling window applied to another variable? The rolling window must be able to change iteratively within a loop.

max(numvar, L1.numvar, L2.numvar) will give me what I want for a single window size, but how can I change the window size iteratively within the loop?

My current code for calculating the rolling sum (credit to @Nick Cox for the algorithm):

generate var1lagged = 0

forval k = -2(1)2 {
    if `k' < 0 {
        local k1 = -(`k')
        replace var1lagged = var1lagged + L`k1'.var1
}
    else replace var1lagged = var1lagged + F`k'.var1
}

How would I achieve the same sort of flexibility but with the maximum, minimum, or average of the window?


Solution

  • In the simplest case suppose K at least 1 is given as the number of lags in the window

    local arg L1.numvar
    
    forval k = 2/`K' { 
          local arg `arg', L`k'.numvar 
    }
    
    gen wanted = max(`arg') 
    

    If the window includes the present value, that is just a twist

    local arg numvar 
    
    forval k = 1/`K' {
        local arg `arg', L`k'.numvar 
    } 
    
    gen wanted = max(`arg') 
    

    More generally, numvar would not be a specific variable name, but would be a local macro including such a name.

    EDIT 1

    This returns missing as a result only if all arguments are missing. If you wanted to insist on missing as a result if any argument is missing, then go

    gen wanted = cond(missing(`arg'), ., max(`arg')) 
    

    EDIT 2

    Check out rolling more generally. Otherwise for a rolling mean you calculate directly you need to work out (1) the sum as in the question (2) the number of non-missing values.

    The working context of the OP evidently rules out installing community-contributed commands; otherwise I would recommend rangestat and rangerun (SSC). Note that many community-contributed commands have been published via the Stata Journal, GitHub or user sites.