R 中的 xts 和 zoo 库中有几个函数,它们试图将金融 OHLC(V) 数据从低粒度聚合到更高粒度,以及新来的 tibbletime::to_period,它对 tibble 执行相同的任务。然而,所有这些都遭受同样的低效率:当我们说一小时聚合时,它们将循环时间作为间隔的起点和终点,即边界将是上午 8 点、上午 9 点、上午 10 点,... 如果我有 15 分钟蜡烛的数据,我如何聚合 OHLC(V),以便按 1 H 间隔而不是轮次聚合?
Time <- seq(from = as.POSIXct("2018-12-28 12:00:00"), to = as.POSIXct("2019-01-02 13:30:00"), by = 900)
Price_Data <- tibble::tibble(Time = Time,
Open = 100 + rnorm(n = length(Time)),
High = 100 + rnorm(n = length(Time)),
Low = 100 + rnorm(n = length(Time)),
Close = 100 + rnorm(n = length(Time)),
Volume = rpois(n = length(Time), lambda = 5000))
tail(Price_Data)
1 2019-01-02 12:15:00 99.7 5074
2 2019-01-02 12:30:00 99.9 4925
3 2019-01-02 12:45:00 101. 5070
4 2019-01-02 13:00:00 98.6 4919
5 2019-01-02 13:15:00 98.6 4925
6 2019-01-02 13:30:00 99.5 5046
如何将上述小标题聚合为 30M、1H、2H 和 4H,以便组具有所需的长度?例如,按 1H 汇总的最后一组将从 12:45:00 到 13:30:00 拿 4 支蜡烛,从 11:45:00 拿 2H,......我试过了
purrr::map(c("30 M","1 H","2 H","4 H")), function(Period) Price_Data %>%
na.omit() %>% tibbletime::tbl_time(., index = Time) %>%
tibbletime::collapse_by(Period, side = "end", clean = T) %>%
dplyr::group_by(Time) %>%
dplyr::mutate(Open = dplyr::first(Open),
High = max(High),
Low = min(Low),
Close = dplyr::last(Close),
Volume = sum(Volume)) %>%
dplyr::slice(n = n()) %>% dplyr::ungroup())
具有各种参数组合,但没有产生所需的结果。此外,按特定间隔内的蜡烛数分组也无济于事,因为现实世界的数据存在差距。