xts :: period.apply和cumprod

时间:2012-10-31 22:47:41

标签: r finance xts

我正在尝试计算xts对象子集的累积产品。这是我想要的一个例子,以及使用period.apply或其他一些基于c ++的快速函数可以更快/更优雅的问题吗?

# install.packages("qmao", repos="http://R-Forge.R-project.org")
require(qmao) # for do.call.rbind()

# I need something like cumprod over xts but by endpoints (subsets of xts)
test <- xts(rep(0.01, length(as.Date(13514:13523, origin="1970-01-01"))), as.Date(13514:13523, origin="1970-01-01"))
ep <- c(0, 5, NROW(test))
# This does not do the trick
period.prod(test, INDEX=ep)
# So, try the obvious, but it does not do the trick
period.apply(test, INDEX=ep, FUN=function(x) cumprod(1 + x))

# Well, write your own
# Hm, there is no split.xts that takes ep (endpoints) as parameter...
# OK, split it manually
test.list <- list(length(ep) - 1)
k <- 1:(length(ep) - 1)
test.list <- lapply(k, function(x) test[(ep[x] + 1):ep[x + 1], ])
# This is what I want...
do.call.rbind(lapply(test.list, function(x) cumprod(1 + x)))
# Is there a better/faster way to do this?

1 个答案:

答案 0 :(得分:5)

period.apply和朋友们一起工作是因为他们每个时期只返回一次观察。你想要更像ave

的东西
dep <- diff(ep)
out.ave <- ave(test+1, rep(ep, c(0,dep)), FUN=cumprod)