title: R programming cumulative returns period calculations using data table
body: <p>I would like to request some help on how to create new columns of cumulative returns of stock data. My data is structured as follows:</p>
  <pre><code>Month      Stock    Ret
      
  Jan-2001    A       0.01    
  Feb-2001    B       0.02    
  Jan-2002    B       0.01    
  Feb-2002    B       0.03
  </code></pre>
  <p>The data is for 10 years. I want to calculate cumulative returns in 12 month increments for each stock.</p>
  <p>For example, the first period of returns would cover Jan-2001 until Dec-2001. The second period would be from February 2001 until
  Jan-2002 and so forth.</p>
  <p>These calculations would be done per stock and would use non-cumulative returns for each period calculation. Since I have a lot of stocks for a lot of years, I wanted to see if there is a more efficient way to do these calculations than a for loop.</p>
  <p>I have been searching for ways to try and do it with data.table package, but I am unsure how to do this.</p>
  <h1>Edit:</h1>
  <p>Perhaps my loop function can better explain what I want to achieve.</p>
  <pre><code>my.data &lt;- data.frame(Date = seq.Date(as.Date('2001-01-01'), by ='month', length = 24), stock = factor(c(rep('A', 2*12), rep('B', 2*12))), Ret = c(rep(c(.02,.01,0,.03,.02,.01,02,.01,0,.03,.02,.01), 2)))  
  
  final_table &lt;- list()
  num_periods &lt;- 2*12-12
  
  
  for(i in unique(my.data$stock)){
  
    ts_i = ts(my.data[my.data$stock==i, 'Ret'])
  
    table_i = matrix(nrow=length(ts_i), ncol=15)
  
    num_periods = length(ts_i)-12
  
    table_i[,1] = ts_i
  
    table_i[,14] = i
  
    table_i[,15] = ts(my.data[my.data$stock==i,'Date'])
  
    for(j in 1:num_periods){
       myperiod = cumprod(ts_i[j:(j+11)]+1)-1
       table_i[12+j,2:13] = myperiod
    }
   colnames(table_i) = c('original', paste0('p',-12:-2),'p1','stock','Date')
   final_table[[i]] = table_i
  }
  
  new.my.data = do.call('rbind',final_table)
  
  new.my.data = na.omit(new.my.data)
  </code></pre>