Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Compute rolling lagged statistics (St.Dev.) within group

    Dear Statalist users,

    I have a data set of stock returns. The data set contains returns, dates and firm identifiers. For each observation (uniquiley identified by date and firm identifier), I want to compute the standard deviation of returns of the firm from t= -205 to t= -6 before the current return t=0.

    I was looking into "rolling", "mvsumm"and "rollstat" but did not figure out how to solve this.

    It would be really kind if someone could help me with this, I have been trying to find a solution for about 2 hours.

    Thanks

    Jean-Marie

  • #2
    We'll there's a new command called tsegen (from SSC) that was designed to handle this type of problem. To install it, type in the command window

    Code:
    ssc install tsegen
    Unfortunately, this is such a long rolling window of time that it exceeds the capacity of tsrevar, the command used internally to generate the temporary variables that substitute for the time-series variable list. This does not mean that you can't get there. Here's some toy data and how to calculate the rolling sd

    Code:
    set seed 1235321
    clear
    
    * generate data on 100 stocks
    set obs 100
    gen firmid = _n
    
    * over time
    expand 500
    bysort firmid: gen time = _n
    
    * random returns
    by firmid: gen return = runiform() * 1000
    by firmid: replace return = return[1] + runiform() * 10
    
    * some missing observations
    drop if runiform() < .1
    
    tsset firmid time
    
    * workaround for limit in -tsrevar-
    tsrevar L(6/100).return
    local vlist `r(varlist)'
    tsrevar L(101/200).return
    local vlist `vlist' `r(varlist)'
    tsrevar L(201/205).return
    local vlist `vlist' `r(varlist)'
    
    
    egen rollsd = rowsd(`vlist')
    
    drop `vlist'
    
    * spot check for observation at time 400
    sum return if inrange(time,195,394) & firmid == 1
    sum return if inrange(time,195,394) & firmid == 2
    list if time == 400 & inlist(firmid,1,2)
    See the help file for tsegen for more information about this approach.

    Comment


    • #3
      Thanks a lot for your help Robert! It works!
      Best,
      Jean-Marie

      Comment


      • #4
        Thanks for the closure. I'll see if we can figure out a workaround for tsegen. If not, we'll update the help file to flag this limitation and indicate the workaround.

        Comment

        Working...
        X