提问人:sg08 提问时间:9/24/2023 更新时间:9/28/2023 访问量:88
如何使用 TimeScaleDB 将具有 OHLCV 的 1 分钟蜡烛数据聚合为更高的时间框架蜡烛(例如 5 分钟、30 分钟、1 小时等)?
How to aggregate 1 minute candle data having OHLCV into higher timeframe candles (say 5 min, 30 min, 1 hr etc.) using TimeScaleDB?
问:
我正在将这些数据存储在 TimescaleDB 中。我的 1 分钟蜡烛数据不是 24x7,而是一个连续的块,它在一天中的某个地方(市场开盘 - 收盘)。此外,假设这个市场时机不规律,如果我回顾历史,可能会有所不同。
因此,我需要一种方法,最好使用sql查询来聚合此数据!
例如:
对于 2023/09/11,我有上午 8:00 - 11:10 的数据。
- 那么 30 分钟的蜡烛应该是 8:00 - 8:30, 8:30 - 9:00, .... , 11:00-11:10
- 同样,1小时蜡烛应该是8:00-9:00,...,11:00-11:10
对于 2023/09/12,我有上午 7:40 - 10:15 的数据。
- 那么 30 分钟的蜡烛应该是 7:40 - 8:10, 8:10 - 8:40, .... , 11:10-11:15
- 同样,1小时蜡烛应该是7:40-8:40,...,10:40-11:15
我的聚合应如下所示: 30 分钟
2023-09-11 8:00 o h l c v 2023-09-11 8:30 o h l c v .. .. 2023-09-11 11:00 o h l c v
2023-09-12 7:40 o h l c v 2023-09-12 8:10 o h l c v
我尝试了聚合,但它会用自己的 30 分钟桶来存储它,从一天的开始
2023-09-12 00:00 o h l c v 2023-09-12 00:30 o h l c v 2023-09-12 01:00 o h l c v ... ... ..
答:
0赞
jonatasdp
9/28/2023
#1
您可以使用candlestick_agg构建聚合,然后将其汇总到更大的时间范围。
例:
\echo
drop materialized view candlestick_1d cascade;
drop materialized view candlestick_1h cascade;
drop materialized view candlestick_1m cascade;
DROP TABLE "ticks" CASCADE;
CREATE TABLE "ticks" ("time" timestamp with time zone not null, "symbol" text, "price" decimal, "volume" float);
SELECT create_hypertable('ticks', 'time', chunk_time_interval => INTERVAL '1 day');
ALTER TABLE ticks SET (
timescaledb.compress,
timescaledb.compress_orderby = 'time',
timescaledb.compress_segmentby = 'symbol'
);
CREATE MATERIALIZED VIEW candlestick_1m
WITH (timescaledb.continuous) AS
SELECT time_bucket('1m', time),
"ticks"."symbol",
candlestick_agg(time, price, volume) as candlestick
FROM "ticks"
GROUP BY 1, 2
ORDER BY 1
WITH DATA;
您可以汇总到更大的时间范围:
CREATE MATERIALIZED VIEW candlestick_1h
WITH (timescaledb.continuous ) AS
SELECT time_bucket('1 hour', "time_bucket"),
symbol,
rollup(candlestick) as candlestick
FROM "candlestick_1m"
GROUP BY 1, 2
ORDER BY 1
WITH NO DATA;
CREATE MATERIALIZED VIEW candlestick_1d
WITH (timescaledb.continuous) AS
SELECT time_bucket('1 day', "time_bucket"),
symbol,
rollup(candlestick) as candlestick
FROM "candlestick_1h"
GROUP BY 1, 2
ORDER BY 1
WITH DATA;
对于time_bucket问题,请尝试使用参数。origin
评论