r语言 - 修改为 .period 以包含"semi-annual"



我想计算 xts 对象的半年聚合。我以为我可以使用to.period,但输出仍然是一个 xts,每年有 4 个数据点,而我只想要两个。

data(edhec, package="PerformanceAnalytics")
xts::to.period(edhec[,1],period="quarters",k=2,OHLC=FALSE)

我想修改这个to.period函数,以包括半年产量。有什么建议吗?代码对我来说有点太复杂了。我认为它一定与 xts 包中的第二个函数endpoints有关。

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)
}

这看起来像是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]

最新更新