我有兴趣使用xts对象计算日期可变的多个实体的总回报。
我尝试了来自quantmod的periodReturn函数和来自PerformanceAnalytics包的Return.cumulative函数。这些都不为我提供所需的答案。我玩弄了使用Apply和编写函数的概念。我遇到了一个问题,因为我找不到该系列的第一个和最后一个实例。我不知道NA是否会影响无法找到起点和终点。
if(!require(data.table)) {install.packages("data.table"); require(data.table)}
if(!require(lubridate)) {install.packages("lubridate"); require(lubridate)}
if(!require(quantmod)) {install.packages("quantmod"); require(quantmod)}
if(!require(xts)) {install.packages("xts"); require(xts)}
x<-data.table::data.table(
date = c("2009-01-01", "2009-01-04", "2009-01-05", "2009-01-06",
"2009-01-07", "2009-01-08", "2009-01-11", "2009-01-12",
"2009-01-13", "2009-01-14", "2009-01-15", "2009-01-18", "2009-01-19",
"2009-01-20", "2009-01-21", "2009-01-22", "2009-01-26",
"2009-01-27", "2009-01-28", "2009-01-29", "2009-02-01", "2009-02-02",
"2009-02-03", "2009-02-04", "2009-02-05", "2009-02-08",
"2009-02-09", "2009-02-10", "2009-02-11", "2009-02-12", "2009-02-15",
"2009-02-16", "2009-02-17", "2009-02-18", "2009-02-19",
"2009-02-22", "2009-02-23", "2009-02-24", "2009-02-25", "2009-02-26",
"2009-03-01", "2009-03-02", "2009-03-03", "2009-03-04", "2009-03-05",
"2009-03-08", "2009-03-09", "2009-03-10", "2009-03-11",
"2009-03-12", "2009-03-15", "2009-03-16", "2009-03-17", "2009-03-18",
"2009-03-19", "2009-03-22", "2009-03-23", "2009-03-24",
"2009-03-25", "2009-03-26", "2009-03-29", "2009-03-30", "2009-03-31",
"2009-04-01", "2009-04-02"),
A = c(0.195, 0.195, 0.19, 0.185, 0.185, 0.19, 0.2, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA),
B = c(NA, NA, NA, NA, NA, NA, NA, 0.2, 0.21, 0.22, 0.23, 0.24,
0.185, 0.185, 0.2, 0.2, 0.18, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA),
C = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 0.18, 0.165, 0.17, 0.18, 0.175, 0.21, 0.2, 0.19, 0.19,
0.2, 0.2, 0.2, 0.185, 0.19, 0.195, 0.19, 0.185, 0.16, 0.17,
0.17, 0.175, 0.19, 0.19, 0.185, 0.19, 0.18, 0.185, 0.18, 0.18,
0.165, 0.18, 0.185, 0.185, 0.185, 0.17, 0.165, 0.17, 0.19, 0.19,
0.19, 0.22, 0.25, 0.25, 0.285, 0.265, 0.29, 0.29, 0.3)
)
setkey(x,"date")
x$date<-as_date(x$date)
x<-as.xts(x)
ReturnsA<-allReturns(x[,"A"])
ReturnsB<-allReturns(x[,"B"])
ReturnsC<-allReturns(x[,"C"])
我期望以下输出:
ReturnsTot <- data.table(returnsTotA = 2.5641, returnsTotA = -10.0,returnsTotA = 66.6667)
(as.single(lapply(lapply(x, na.omit, x[1,]), tail, 1))-as.single(lapply(lapply(x, na.omit, x[1,]), head, 1))) / as.single(lapply(lapply(x, na.omit, x[1,]), head, 1))
我得到0.02564 -0.10000 0.66667