合并Pandas历史和实时股价数据

2024-04-19 04:26:24 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我创建一个熊猫数据框,其中包含当天的1min OHLCV历史数据,例如:

                    open    high    low close   volume
date                    
2019-10-30 07:55:00 3034.00 3034.25 3033.75 3034.00 209
2019-10-30 07:56:00 3034.00 3034.25 3033.75 3034.00 315
2019-10-30 07:57:00 3034.25 3034.50 3033.75 3034.25 432
2019-10-30 07:58:00 3034.00 3034.25 3033.75 3033.75 329
2019-10-30 07:59:00 3034.00 3034.25 3033.75 3034.00 231

下一刻,我使用监听器类订阅了一个实时tick提要,并将其重新采样到一个持续更新的1min OHLCV数据帧中,例如:

                    open    high    low close   volume
date                    
2019-10-30 07:59:00 3033.75 3034.00 3033.75 3034.00 35
2019-10-30 08:00:00 3033.75 3034.25 3033.25 3033.75 117
2019-10-30 08:01:00 3033.75 3034.00 3033.75 3034.00 78

如何合并这两个数据,以便将每一行新的实时数据(标记重采样为1min行)附加到历史数据中?另一个问题是历史数据的最后一分钟和实时数据的第一分钟之间的重叠——这些需要结合起来。你知道吗


Tags: 数据标记closedateopenlow历史数据ohlcv
3条回答
# isolate the new indexes, (present in live_df but not in hist_df)
new_locs = ~live_df.index.isin(hist_df.index)

# append just the new entries in the live_df
new_df = hist_df.append(live_df.loc[new_locs])

如果你的历史数据增长异常长,这可能会随着时间的推移变得缓慢。如果将数据帧按升序时间排序,可以简化new_locs检查,只查看最近的几行。与.iloc()

首次使用:

for i in live_df.index:
    if i in historical_df.index:
        new_live_df = live_df.drop(i)

这样就删除了实时数据的第一行,因为它已经在历史数据中了。你知道吗

然后使用:

df_total = historical_df.append(new_live_df)

相关问题 更多 >