价格Xts的多列累积回报

时间:2017-10-09 09:58:00

标签: r xts

我有以下数据并尝试计算复合回报。

sample_data <- data.frame(Date = c ("2017-01-31","2017-02-28", "2017-03-31", "2017-04-30"), 
              stock1 = c(9,12,13,14), stock2 = c(5,6,8,9), stock3 = c(4,4.5,5,4), stock4 = c(6,7.8,8,8.5), stock5 = c(5,5.5,6.2,7))

使用xts包我在尝试运行此代码时遇到错误:

Return.calculate(sample_data[,c(2:9)], method = c("compound"))

1 个答案:

答案 0 :(得分:1)

您的sample_data不是xts个对象。这是data.frame。您可以执行以下操作来克服:

sample_data <- data.frame(Date = c ("2017-01-31","2017-02-28",
                                    "2017-03-31", "2017-04-30"), 
                          stock1 = c(9,12,13,14), stock2 = c(5,6,8,9),
                          stock3 = c(4,4.5,5,4), stock4 = c(6,7.8,8,8.5),
                          stock5 = c(5,5.5,6.2,7))

class(sample_data)  ## check the structure of your data
x = xts(sample_data[, -1], order.by=as.Date(sample_data$Date))
Return.calculate(x, method = c("compound"))

结果如下:

> Return.calculate(x, method = c("compound"))
               stock1    stock2     stock3     stock4     stock5
2017-01-31         NA        NA         NA         NA         NA
2017-02-28 0.28768207 0.1823216  0.1177830 0.26236426 0.09531018
2017-03-31 0.08004271 0.2876821  0.1053605 0.02531781 0.11980120
2017-04-30 0.07410797 0.1177830 -0.2231436 0.06062462 0.12136086