[英]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.