如何将 1 分钟的开盘-高-低-收数据转换为 Python 中的另一个时间范围(fx:5 分钟,1 小时)?

How do you convert 1 minute open-high-low-close data to another timeframe(fx: 5 minute, 1 hour) in Python?

我是 Python 和 Whosebug 的新手,所以如果我在 post 中犯了错误,请多多包涵。

我有一个 Pandas 数据框,其中包含 1 分钟的开盘价、最高价、最低价和收盘价数据,以时间为索引,用于一种货币。我如何将它变成一个数据框,例如,5 分钟的开盘价、最高价、最低价、收盘价数据,并使时间戳也合适?这是打印出的 1 分钟数据的示例:

                   ZARJPY_open  ZARJPY_high  ZARJPY_low  ZARJPY_close
time                                                            
201901011700        7.589        7.589       7.589         7.589
201901011701        7.590        7.590       7.590         7.590
201901011702        7.589        7.590       7.589         7.589
201901011703        7.590        7.593       7.590         7.593
201901011705        7.592        7.593       7.592         7.593

我想把它变成:

                  ZARJPY_open  ZARJPY_high  ZARJPY_low  ZARJPY_close
time                                                            
201901011700        7.589        7.593       7.589         7.593
201901011706                  -next 5 minutes-                     

感谢任何帮助:)

编辑:时间戳采用 YYYYMMDDHHmm(年、月、日、小时、分钟)格式

您可以使用 5 分钟的石斑鱼对象:

# parse the time. 
df.time = pd.to_datetime(df.time, format="%Y%m%d%H%M")

#make the time the index. 
df = df.set_index("time")

# group in 5-minute chunks. 
t = df.groupby(pd.Grouper(freq='5Min')).agg({"ZARJPY_open": "first", 
                                             "ZARJPY_close": "last", 
                                             "ZARJPY_low": "min", 
                                             "ZARJPY_high": "max"})
t.columns = ["open", "close", "low", "high"]
print(t)

结果是:

                      open  close    low   high
time                                           
2019-01-01 17:00:00  7.589  7.593  7.589  7.593
2019-01-01 17:05:00  7.592  7.593  7.592  7.593