我有一个数据框,在一段时间内有各种股票回报。收益率为百分比收益或损失(.02表示2%收益或102%之前的收益率值)。
我正在寻找一个函数或方法来累积显示每个时期的回报(百分比)。例如,这将显示stock1的累积/复合增益为前3个时段的.02,.0404,.09242 ......(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 =
答案 0 :(得分:4)
这将为您提供按期间累积的回报:
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
或者如果你想要一些更具人类可读性的东西:
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%"
答案 1 :(得分:3)
您可以使用dplyr
:
mydf %>%
mutate_each(funs(
paste0(formatC(100 * (cumprod(1 + .) - 1), format = "f", 2), "%")), -period)
给出了:
# period stock1 stock2
#1 a 2.00% 0.00%
#2 b 4.04% 1.00%
#3 c 9.24% 1.00%
#4 d 3.78% 4.03%
#5 e -1.41% 9.23%
#6 f -1.41% 10.32%