如何在Pandas中合并历史与实时股票价格数据
合并历史1分钟OHLCV数据与实时重采样数据的解决方案
刚好做过类似的行情数据合并需求,给你分享下实操的解决方案,核心就是搞定时间对齐和重叠分钟的数据合并这俩事儿,具体步骤如下:
1. 先统一数据格式:把时间列转为索引
不管是历史数据还是实时重采样数据,第一步都要把date列转成datetime类型,并且设置为DataFrame的索引——这是后续时间匹配和合并的基础。
import pandas as pd # 处理历史数据 historical_df['date'] = pd.to_datetime(historical_df['date']) historical_df = historical_df.set_index('date') # 处理实时重采样得到的1分钟数据 realtime_df['date'] = pd.to_datetime(realtime_df['date']) realtime_df = realtime_df.set_index('date')
2. 检测并处理重叠的分钟数据
历史数据的最后一分钟,大概率会和实时重采样的第一分钟重叠(因为实时数据是从历史结束的时间点继续接收tick并采样的)。这时候需要把这两个时间段的OHLCV数据按照行情规则合并:
- 开盘价(
open)取历史数据的(因为历史数据记录的是该分钟最早的开盘价) - 最高价(
high)取两者的最大值 - 最低价(
low)取两者的最小值 - 收盘价(
close)取实时数据的(因为实时数据是该分钟最新的收盘价) - 成交量(
volume)取两者的总和
代码实现如下:
# 获取历史数据最后一条和实时数据第一条的时间索引 last_hist_time = historical_df.index[-1] first_real_time = realtime_df.index[0] if last_hist_time == first_real_time: # 合并重叠行 merged_row = pd.Series( data={ "open": historical_df.loc[last_hist_time, "open"], "high": max(historical_df.loc[last_hist_time, "high"], realtime_df.loc[first_real_time, "high"]), "low": min(historical_df.loc[last_hist_time, "low"], realtime_df.loc[first_real_time, "low"]), "close": realtime_df.loc[first_real_time, "close"], "volume": historical_df.loc[last_hist_time, "volume"] + realtime_df.loc[first_real_time, "volume"] }, name=last_hist_time ) # 删除历史数据的最后一行和实时数据的第一行 historical_df = historical_df.iloc[:-1] realtime_df = realtime_df.iloc[1:] # 将合并后的行添加到历史数据中 historical_df = pd.concat([historical_df, merged_row.to_frame().T])
3. 合并剩余的实时数据
处理完重叠部分后,直接把剩下的实时数据追加到历史数据后面即可,记得确保索引唯一:
# 合并处理后的实时数据到历史数据 combined_df = pd.concat([historical_df, realtime_df]) # 保险起见,去重(保留最新的那条) combined_df = combined_df[~combined_df.index.duplicated(keep="last")]
额外提醒
- 如果是实时持续更新的场景(比如每生成一条新的1分钟实时数据就合并一次),可以把上述逻辑封装成一个函数,每次新数据进来时调用即可。
- 务必保证历史数据和实时数据的时间频率完全一致(都是1分钟),否则会出现时间对齐混乱的问题。
内容的提问来源于stack exchange,提问作者quantllama
相关产品推荐
相关产品推荐

