我想计算一个xts对象的半年聚合。我以为我可以使用to.period
,但输出仍然是xts,每年有4个数据点,而我只想要两个。
data(edhec, package="PerformanceAnalytics")
xts::to.period(edhec[,1],period="quarters",k=2,OHLC=FALSE)
我想修改此to.period
函数以包含半年度输出。有什么建议?代码对我来说有点过于复杂。我认为它必须与endpoints
有关,这是xts包中的第二个函数。
function (x, period = "months", k = 1, indexAt = NULL, name = NULL,
OHLC = TRUE, ...)
{
if (missing(name))
name <- deparse(substitute(x))
xo <- x
x <- try.xts(x)
if (NROW(x) == 0 || NCOL(x) == 0)
stop(sQuote("x"), " contains no data")
if (any(is.na(x))) {
x <- na.omit(x)
warning("missing values removed from data")
}
if (!OHLC) {
xx <- x[endpoints(x, period, k), ]
}
else {
if (!is.null(indexAt)) {
index_at <- switch(indexAt, startof = TRUE, endof = FALSE,
FALSE)
}
else index_at <- FALSE
cnames <- c("Open", "High", "Low", "Close")
if (has.Vo(x))
cnames <- c(cnames, "Volume")
if (has.Ad(x) && is.OHLC(x))
cnames <- c(cnames, "Adjusted")
cnames <- paste(name, cnames, sep = ".")
if (is.null(name))
cnames <- NULL
xx <- .Call("toPeriod", x, endpoints(x, period, k), has.Vo(x),
has.Vo(x, which = TRUE), has.Ad(x) && is.OHLC(x),
index_at, cnames, PACKAGE = "xts")
}
if (!is.null(indexAt)) {
if (indexAt == "yearmon" || indexAt == "yearqtr")
indexClass(xx) <- indexAt
if (indexAt == "firstof") {
ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
if (period %in% c("years", "months", "quarters",
"days"))
index(xx) <- firstof(ix$year + 1900, ix$mon +
1)
else index(xx) <- firstof(ix$year + 1900, ix$mon +
1, ix$mday, ix$hour, ix$min, ix$sec)
}
if (indexAt == "lastof") {
ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
if (period %in% c("years", "months", "quarters",
"days"))
index(xx) <- as.Date(lastof(ix$year + 1900, ix$mon +
1))
else index(xx) <- lastof(ix$year + 1900, ix$mon +
1, ix$mday, ix$hour, ix$min, ix$sec)
}
}
reclass(xx, xo)
}
答案 0 :(得分:0)
这看起来像xts::endpoints()
中的错误。在period = "months"
和k > 1
的情况下,endpoints()
会进行此调整:
if (k > 1) ep[seq(1, length(ep), k)] else ep
to.period()
OHLC = FALSE
只有endpoints()
的输出对输入对象进行子集化。所以它相当于:
data(edhec, package="PerformanceAnalytics")
ep <- endpoints(edhec[,1], "quarters", 2)
edhec[ep, 2]
查看此错误的修复是否与添加与period = "months"
时相同的调整一样简单:
data(edhec, package="PerformanceAnalytics")
ep <- endpoints(edhec[,1], "quarters", 1)
ep <- ep[seq(1, length(ep), 2)]
edhec[ep, 2]