【问题标题】:Calculating Compounded Return by ID in R在 R 中按 ID 计算复合回报
【发布时间】:2016-07-11 17:13:55
【问题描述】:

我正在尝试计算 CAGR 值,定义为 (Ending/Beginning)^(1/number of years)-1。

我有一个 df,其中包含“Stock”、“date”、“Annual.Growth.Rate”列。快速注意:我试图使用滞后函数来做到这一点,但是,我无法在每只股票的开头更改递归公式。查看 dput 会更有意义:

structure(list(Stock = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"), 
    date = structure(c(6L, 2L, 3L, 4L, 5L, 1L, 12L, 8L, 9L, 10L, 
    11L, 7L), .Label = c("3/28/16", "3/29/12", "3/29/13", "3/29/14", 
    "3/29/15", "3/30/11", "6/28/16", "6/29/12", "6/29/13", "6/29/14", 
    "6/29/15", "6/30/11"), class = "factor"), Annual.Growth.Rate = c(0.1, 
    0.2, 0.1, 0.1, 0.1, 0.1, 0.3, 0.2, 0.14, 0.14, 0.14, 0.14
    ), Growth = c(110, 132, 145.2, 159.72, 175.692, 193.2612, 
    130, 156, 177.84, 202.7376, 231.120864, 263.477785), CAGR = c(0.098479605, 
    0.098479605, 0.098479605, 0.098479605, 0.098479605, 0.098479605, 
    0.125, 0.125, 0.125, 0.125, 0.125, 0.125)), .Names = c("Stock", 
"date", "Annual.Growth.Rate", "Growth.on.100", "CAGR"), class = "data.frame", row.names = c(NA, 
-12L)) 

这是预期的输出。在存量、日期和增长之前)。 100 的增长并不全是以前的“滞后”。由于第一个可用日期乘以给定的起始日期,在本例中为 100,(1+.1)*100,然后后面的增长值是未来值 (110) * 下一个增长率。我可以弄清楚如何使用 dplyr 进行 CAGR,但我真的被困在 100 的增长上。

【问题讨论】:

    标签: r dplyr summary split-apply-combine


    【解决方案1】:

    您可以在 mutate 中使用 cumprod。起始 100 值也是任意的。这都是一个产品。您可以计算产品的其余部分,然后乘以启动器。

    starter <- 100
    my.data <- data.frame(stock=c('a','a','a','b','b','b'), growth = c(.1,.2,.1,.1,.1,.1), date = c(1,2,3,1,2,3)) #example Data
    my.data
    my.data %>%
      group_by(stock) %>%
      mutate(growth.unit =  order_by(date,cumprod(1+growth)),
             growth = growth.unit*starter) -> new.data
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      相关资源
      最近更新 更多