Announcement

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

  • Calculating yearly cumulative returns

    Hi all,

    I have generated normally distributed data of monthly stock returns for 30,000,000 observations and I want to calculate cumulative returns for the first 12 observations (1-12), the next 12 observation (13-24) and so on, so I can calculate e.g. the median of all yearly returns. So far my code looks like this however I can’t figure it out to be working. Any help would be appreciated.

    Code:
    clear
    set seed 1307
    set obs 30000000
    gen ret_02 = rnormal(0.005, 0.02)
    gen ln_ret_02 = ln(1+ret_02)
    local chunk_size 12
    gen sum_ln_ret_02 = .
    forval i = 1 ('chunk_size') 30000000 {
        local start_obs `i'
        local end_obs `i' + `chunk_size' - 1
        replace sum_ln_ret_02 = sum(ln_ret_02[`start_obs'/`end_obs'])
    }
    gen cum_ret_02 = exp(sum_ln_ret_02)-1

  • #2
    Looping over observations is almost never necessary in Stata. Moreover, the approach using logarithms is computationally inefficient: it is a relic of the days when these things were done by hand or on a pocket calculator. For a programmed computer, calculating iterated products is much faster.

    Code:
    clear
    set seed 1307
    set obs 30000000
    gen ret_02 = rnormal(0.005, 0.02)
    gen growth = 1 + ret_02
    local chunk_size 12
    
    gen `c(obs_t)' chunk = ceil(_n/`chunk_size')
    sort chunk, stable
    by chunk: gen double wanted = growth if _n == 1
    by chunk: replace wanted = wanted[_n-1]*growth if _n > 1
    by chunk: replace wanted = wanted[_N] - 1

    Comment


    • #3
      Thank you, Mr. Schechter! This has helped a lot.

      Comment

      Working...
      X