R xts包 - 每天一分钟到

时间:2017-07-14 10:41:26

标签: r xts

我在xts中有一分钟的时间序列。我想知道是否有一种优雅的方式让OHLC从一天开始到我的时间序列的每一分钟。例如2017-07-14 12:29分钟2017-07-14 08:00开放,2017-07-14 12:29收盘,2017-07期间最低/最高14 08:00至2017-07-14 12:29。 我的时间从08:00到22:00(841分钟)完全充满。 我正在考虑做一个循环,但我想有更优雅的方式。

由于

皮尔

1 个答案:

答案 0 :(得分:1)

您可以分别使用cummax()cummin()计算累积最大值/分钟数。您只需要在白天应用这些功能。您可以{{1}将您的数据分组到每日组中,将以下功能应用于每个组,然后split()将数据重新组合在一起。

以下是使用xts包中每日数据的可重现示例。

rbind()

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

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))
相关问题