[英]Merging historical and live stock price data in pandas
首先,我创建一个 Pandas dataframe 包含当天的 1 分钟 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
下一刻,我使用监听器 class 订阅实时报价,并将其重新采样为持续更新的 1 分钟 OHLCV 数据 dataframe,例如:
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
如何合并这两者,以便将每一行新的实时数据(重新采样为 1 分钟行的刻度)附加到历史数据中? 另一个问题是最后一分钟的历史数据和第一分钟的实时数据之间的重叠——这些需要结合起来。
# 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])
如果你的历史 df 增长得特别长,随着时间的推移,这可能会变慢。 如果您将 dataframe 保持按升序排序,则可以简化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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.