【问题标题】:Merging historical and live stock price data in pandas在 pandas 中合并历史和实时股票价格数据
【发布时间】:2019-10-30 15:29:49
【问题描述】:

首先,我创建一个 Pandas 数据框,其中包含当天的 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

下一刻,我使用侦听器类订阅实时报价,并将其重新采样为持续更新的 1 分钟 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

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

【问题讨论】:

    标签: python pandas resampling stock ohlc


    【解决方案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 增长得特别长,随着时间的推移,这可能会变慢。如果您保持数据框按升序排序,您可以简化new_locs 检查以仅查看最近的几行。 .iloc()

    【讨论】:

      【解决方案2】:

      第一次使用:

      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)
      

      【讨论】:

      • 如果它在更新之前运行,它可能会创建 UnboundLocalError: local variable 'new_live_df' referenced before assignment
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2020-08-09
      相关资源
      最近更新 更多