r 中的累积百分比 return
cumulative percentage return in r
我有一个数据框,其中包含一段时间内各种股票 return。 return 以百分比收益或损失表示(.02 表示 2% return 或前一期间值的 102%)。
我正在寻找一种函数或方法来累积显示每个时期的 returns(以百分比表示)。例如,这将显示 stock1 的前 3 个周期的 cumulative/compounding 收益为 .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 =
这将为您提供按期间的累计 return:
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%"
您可以使用 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%
我有一个数据框,其中包含一段时间内各种股票 return。 return 以百分比收益或损失表示(.02 表示 2% return 或前一期间值的 102%)。
我正在寻找一种函数或方法来累积显示每个时期的 returns(以百分比表示)。例如,这将显示 stock1 的前 3 个周期的 cumulative/compounding 收益为 .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 =
这将为您提供按期间的累计 return:
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%"
您可以使用 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%