R xts 包 - to.period 一天一分钟

R xts package - to.period by minute over a day

我在 xts 中有一个分钟的时间序列。我想知道是否有一种优雅的方法可以让 OHLC 从一天开始直到我的时间序列的每一分钟。例如,对于 2017-07-14 12:29 分钟,我将在 2017-07-14 08:00、2017-07-14 12:29 和 min/max 开盘] 2017-07-14 08:00 至 2017-07-14 12:29 期间。 我的时间序列从 08:00 到 22:00(841 分钟点)完全填满。 我正在考虑做一个循环,但我想有更优雅的方法。

谢谢

皮埃尔

您可以分别使用 cummax()cummin() 计算累积 max/min。您只需要每天应用这些功能。您可以通过 split() 将数据分成每日组,将下面的函数应用于每个组,然后 rbind() 将数据重新组合在一起来实现。

这是一个使用 xts 包中的每日数据的可重现示例。

library(xts)
set.seed(21)
tm <- timeBasedSeq('2017-07-14/2017-07-15/M')
x <- xts(20*cumprod(1+rnorm(length(tm), 0, 0.0025)), tm)
colnames(x) <- "price"

aggfun <- function(x) {
  stopifnot(ncol(x) > 0)
  # remove potential column name
  colnames(x) <- NULL
  r <- xts(cbind(Open = rep(x[1], nrow(x)),
                 High = cummax(x),
                 Low = cummin(x),
                 Close = x), index(x))
  r
}
y <- do.call(rbind, lapply(split(x, "day"), aggfun))

一天到下一天的输出如下:

y[1439:1442]
#                         Open     High      Low    Close
# 2017-07-14 23:58:00 20.03965 25.02193 19.60128 23.73810
# 2017-07-14 23:59:00 20.03965 25.02193 19.60128 23.71598
# 2017-07-15 00:00:00 23.73816 23.73816 23.73816 23.73816
# 2017-07-15 00:01:00 23.73816 23.73816 23.71164 23.71164