PostgreSQL将1分钟OHLCV烛光数据重采样为5分钟OHLCV烛光数据

c0vxltue  于 2023-03-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(140)

我有一个PostgreSQL数据库,其中包含以下列:

timestamp <bigint> - Unix timestamp in milliseconds
open      <float>  - The first traded price
high      <float>  - The highest traded price
low       <float>  - THe lowest traded price
close     <float>  - The last traded price
volume    <float>  - The total volumed transacted during the time period

有时我会查询30天以上的数据(43.2k行)。这些查询需要很长时间,所以我想每当我有〉30天的数据时,我会获取5分钟蜡烛,而不是将行数减少5倍。
基本上,我正在寻找一个函数来实现这一点(伪代码):

SELECT 
first_value(timestamp),
first_value(open),
max(high),
min(low),
last_value(close),
sum(volume)
WHERE timestamp > {some timestamp in the past} AND timestamp < {current time}
GROUP BY floor((timestamp / 1000) / (60*5)) * 5
ORDER BY timestamp

任何帮助都将不胜感激,我在这件事上耽搁了一段时间

7fyelxc5

7fyelxc51#

使用subquery获取列:minute5。在它上面生成groupingsorting。为了获得第一个值,'open'使用array_agg进行排序,并将值通过方括号。'close'也是如此,但方向相反。

SELECT 
min(timestamp) AS timestamp, 
(array_agg(open ORDER BY timestamp))[1] AS open, 
max(high) AS high, 
min(low) AS low,  
(array_agg(close ORDER BY timestamp DESC))[1] AS close, 
sum(volume) volume
FROM
(SELECT*, floor((timestamp/1000) / (60*5)) * 5 AS minute5
FROM stock
ORDER BY timestamp
) t
GROUP BY
minute5
ORDER BY
minute5
;

以下是link:创建一个表并获取数据(添加了一个dt列,该列带有一个类型,可以直观地查看每行的日期和时间)。

相关问题