Search code examples
rfinance

cumulative percentage return in r


I have a data frame with a variety of stock returns over a period of time. The returns are in percent gain or loss (.02 for 2% return or 102% of the previous periods value).

I am looking for either a function or method to cumulatively show the returns for each period (in percentages). For example, this would show the cumulative/compounding gains for stock1 to be .02, .0404, .09242 for the first 3 periods.... (1.02*1.02*1.05).

   mydf = data.frame(period = c('a','b','c','d','e','f'), stock1=c(.02, .02, .05,-.05,-.05,0), stock2=c(0, .01,0,.03,.05,.01))
   mydf
   #help mydf$stk1_percentgain =

Solution

  • This will give you the cumulative return by period:

    sapply(mydf[,-1], function(x) cumprod(1 + x) - 1)
    
              stock1    stock2
    [1,]  0.02000000 0.0000000
    [2,]  0.04040000 0.0100000
    [3,]  0.09242000 0.0100000
    [4,]  0.03779900 0.0403000
    [5,] -0.01409095 0.0923150
    [6,] -0.01409095 0.1032382
    

    Or if you want something that's more human-readable:

    sapply(mydf[,-1], function(x) paste0(sprintf("%0.2f", (cumprod(1 + x) - 1)*100, 2),"%"))
    
         stock1   stock2  
    [1,] "2.00%"  "0.00%" 
    [2,] "4.04%"  "1.00%" 
    [3,] "9.24%"  "1.00%" 
    [4,] "3.78%"  "4.03%" 
    [5,] "-1.41%" "9.23%" 
    [6,] "-1.41%" "10.32%"