gpt4 book ai didi

r - 将价格数据聚合到 R data.table 中的不同时间范围

转载 作者:行者123 更新时间:2023-12-04 12:35:36 25 4
gpt4 key购买 nike

您好,我希望将 data.table 中的每分钟数据汇总到每 5 分钟(或每 10 分钟)的范围内。我知道这很容易通过使用 xts 和 to.minutes5 函数来完成,但我不想在这种情况下使用 xts,因为数据集相当大。在 data.table 中是否有一种简单的方法可以做到这一点?

数据示例:在此示例中,21.30 到 21.34(包括两者)之间的时间段只有一行,t = 21.30,open = 0.88703,high = 0.88799,low = 0.88702,close = 0.88798,volume = 43(注意来自 21.35 本身的数据被忽略)。

                      t    open    high     low   close volume
1: 2010-01-03 21:27:00 0.88685 0.88688 0.88685 0.88688 2
2: 2010-01-03 21:28:00 0.88688 0.88688 0.88686 0.88688 5
3: 2010-01-03 21:29:00 0.88688 0.88704 0.88687 0.88703 7
4: 2010-01-03 21:30:00 0.88703 0.88795 0.88702 0.88795 10
5: 2010-01-03 21:31:00 0.88795 0.88795 0.88774 0.88778 7
6: 2010-01-03 21:32:00 0.88778 0.88778 0.88753 0.88760 8
7: 2010-01-03 21:33:00 0.88760 0.88781 0.88760 0.88775 11
8: 2010-01-03 21:34:00 0.88775 0.88799 0.88775 0.88798 7
9: 2010-01-03 21:35:00 0.88798 0.88803 0.88743 0.88782 8
10: 2010-01-03 21:36:00 0.88782 0.88782 0.88770 0.88778 6

根据 GSee 的要求从 dput(head(myData)) 输出。我想使用 data.table 来存储一些基于原始数据的派生字段。因此,即使我确实使用 xts 来汇总这些价格条,我也必须以某种方式将它们放入数据表中,因此我将不胜感激关于正确保存 data.table 和 xts 项目的任何提示。

structure(list(t = structure(c(1241136000, 1241136060, 1241136120, 
1241136180, 1241136240, 1241136300), class = c("POSIXct", "POSIXt"
), tzone = "Europe/London"), open = c(0.89467, 0.89467, 0.89472,
0.89473, 0.89504, 0.895), high = c(0.89481, 0.89475, 0.89473,
0.89506, 0.8951, 0.895), low = c(0.89457, 0.89465, 0.89462, 0.89473,
0.89486, 0.89486), close = c(0.89467, 0.89472, 0.89473, 0.89504,
0.895, 0.89488), volume = c(96L, 14L, 123L, 49L, 121L, 36L)), .Names = c("t",
"open", "high", "low", "close", "volume"), class = c("data.table",
"data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x0000000000100788>)

最佳答案

您可以在 POSIXt 向量上使用 xts 中的 endpoints 函数(用 C 语言编写)。 endpoints 查找某个时间段的最后一个元素的位置。按照惯例,1:05 不会包含在与 1:00 相同的小节中。因此,您为 dput 提供的数据(与上面打印的数据不同)将有 2 个条。

假设 dt 是您的 data.table:

library(data.table)
library(xts)

setkey(dt, t) # make sure the data.table is sorted by time.
ep <- endpoints(dt$t, "minutes", 5)[-1] # remove the first value, which is 0
dt[ep, grp:=seq_along(ep)] # create a column to group by
dt[, grp:=na.locf(grp, fromLast=TRUE)] # fill in NAs

dt[, list(t=last(t), open=open[1], high=max(high), low=min(low),
close=last(close), volume=sum(volume)), by=grp]

grp t open high low close volume
1: 1 2009-05-01 01:04:00 0.89467 0.8951 0.89457 0.89500 403
2: 2 2009-05-01 01:05:00 0.89500 0.8950 0.89486 0.89488 36

关于r - 将价格数据聚合到 R data.table 中的不同时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com