我有以下样本数据并尝试从以下价格计算复合回报。
sample_data <- data.frame(Date = c ("2017-01-31", "2017-02-28", "2017-03-31",
"2017-04-30", "2017-05-31", "2017-06-30"),
stock = c("a", "a", "a","a", "a", "a"),
Price = c(10, 11, 17, 12, 13, 14))
我使用Return.calculate包:
Return.calculate(sample_data$Price, method = "compound")
但是收到以下错误:
没有适用于'xtsAttributes&lt; - '的方法适用于。的对象 “动物园”课程
答案 0 :(得分:2)
您需要将数据作为xts
对象传递。转换为xts
时要小心,只包含数字变量 - reason here - 这就是为什么只能转换sample_data$Price
library(xts)
library(PerformanceAnalytics)
sample_data$Date <- as.Date(sample_data$Date)
sample_data_xts <- xts(sample_data$Price, order.by = sample_data$Date)
Return.calculate(sample_data_xts, method = "compound")
# [,1]
# 2017-01-31 NA
# 2017-02-28 0.09531018
# 2017-03-31 0.43531807
# 2017-04-30 -0.34830669
# 2017-05-31 0.08004271
# 2017-06-30 0.07410797