You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定蜡烛数量拆分xts格式OHLC数据

按指定蜡烛数量合并K线的实现方法

现有数据生成代码

先看生成原始5分钟K线的代码:

len <- 10000
times <- seq(as.POSIXct("2016-01-01 00:00:00"), length = len, by = "sec")
prices <- cumsum(rnorm(len))+1000

library(xts)
xp <- xts(x = prices,order.by = times)
xp <- to.minutes5(xp)

生成的xp数据样例:

xp.Open   xp.High   xp.Low xp.Close
2016-01-01 00:04:59 1001.8097 1004.7440 986.8783 986.8783
2016-01-01 00:09:59  986.7830  995.0656 960.4920 966.7475
2016-01-01 00:14:59  965.9071  979.9402 965.2857 975.6030
2016-01-01 00:19:59  973.5659  988.7293 965.7774 983.4846
2016-01-01 00:24:59  982.7731  982.7731 945.9951 946.5125
2016-01-01 00:29:59  946.3951  949.1420 925.5131 936.8539
2016-01-01 00:34:59  935.7039  954.8570 935.7039 948.0653
2016-01-01 00:39:59  949.0397  951.8483 928.8650 942.4658
2016-01-01 00:44:59  943.3805  963.3857 939.1387 947.9653

执行chart_Series(xp)即可绘制原始K线图。

需求说明

目前可以用to.period()按时间周期合并K线,但需要实现按指定蜡烛数量合并(比如将现有数据合并为5根蜡烛),预期的分割逻辑参考以下标记代码:

n <- 5  # 设置目标蜡烛数量
breaks <- seq(1, nrow(xp), length.out = n+1)
abline(v=breaks,col=4,lty=2,lwd=2)

解决方案

通过分组聚合的方式实现,具体步骤如下:

通用均分方案(自动处理余数)

library(xts)

# 设置目标蜡烛数量
n_target <- 5

# 生成分组索引:将原始数据均匀分成n_target组,自动处理最后一组数量不足的情况
group_ids <- cut(1:nrow(xp), breaks = n_target, labels = FALSE)

# 按组聚合计算新K线的OHLC
xp_agg <- aggregate(xp, by = group_ids, FUN = function(x) {
  c(
    Open = as.numeric(x[1, "xp.Open"]),   # 组内首根K线开盘价
    High = max(x[, "xp.High"]),           # 组内最高价
    Low = min(x[, "xp.Low"]),             # 组内最低价
    Close = as.numeric(x[nrow(x), "xp.Close"])  # 组内最后一根K线收盘价
  )
})

# 转换为xts对象,时间索引取每组最后一根K线的时间
xp_agg_xts <- xts(xp_agg, order.by = index(xp)[cumsum(table(group_ids))])

# 查看合并后的K线数据
xp_agg_xts

# 绘制合并后的K线图
chart_Series(xp_agg_xts)

严格均分方案(忽略末尾不足组)

如果需要每组蜡烛数量完全一致,可舍弃最后不足一组的原始K线:

library(xts)

n_target <- 5
# 计算每组的蜡烛数量
k <- nrow(xp) %/% n_target
# 生成严格均分的分组索引
group_ids <- rep(1:n_target, each = k)
# 截取刚好能均分的前n_target*k根K线
xp_sub <- xp[1:(n_target*k), ]

# 按组聚合
xp_agg_strict <- aggregate(xp_sub, by = group_ids, FUN = function(x) {
  c(
    Open = as.numeric(x[1, "xp.Open"]),
    High = max(x[, "xp.High"]),
    Low = min(x[, "xp.Low"]),
    Close = as.numeric(x[nrow(x), "xp.Close"])
  )
})

# 转换为xts对象,时间索引取每组最后一根K线的时间
xp_agg_strict_xts <- xts(xp_agg_strict, order.by = index(xp_sub)[seq(k, n_target*k, by = k)])

内容的提问来源于stack exchange,提问作者mr.T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:17:57