如何加速Bloomberg xbbg的日内Bar数据请求?
优化Bloomberg xbbg数据拉取速度的解决方案
当前代码通过嵌套循环逐个请求合约和日期,共发起372次API调用,导致拉取8.9k行数据耗时60秒。以下是针对新版xbbg的高效优化方案:
1. 批量请求替代循环(核心优化)
利用xbbg的bdib接口支持批量合约和日期范围的特性,将多次请求合并为少数几次,大幅减少API交互开销:
import pandas as pd from xbbg import blp cl_chain = [ 'CL1 Comdty', 'CL2 Comdty', 'CL3 Comdty', 'CL4 Comdty', 'CL5 Comdty', 'CL6 Comdty', 'CL7 Comdty', 'CL8 Comdty', 'CL9 Comdty', 'CL10 Comdty', 'CL11 Comdty', 'CL12 Comdty' ] date_range = pd.bdate_range(end='today', periods=31) # 一次性传入所有合约和日期范围 cl_hist = blp.bdib(tickers=cl_chain, dt=date_range, interval=60, ref='CME')
此方案将请求次数从372次降至1次(或按日期分片的少量请求),Bloomberg批量API的处理效率远高于单次请求,能直接将耗时压缩至数秒级别。
2. 并行请求日期(备选方案)
若批量日期范围请求存在兼容性问题,可采用线程池并行处理单日期的批量合约请求,避免串行等待:
import pandas as pd from xbbg import blp from concurrent.futures import ThreadPoolExecutor cl_chain = [ 'CL1 Comdty', 'CL2 Comdty', 'CL3 Comdty', 'CL4 Comdty', 'CL5 Comdty', 'CL6 Comdty', 'CL7 Comdty', 'CL8 Comdty', 'CL9 Comdty', 'CL10 Comdty', 'CL11 Comdty', 'CL12 Comdty' ] date_range = pd.bdate_range(end='today', periods=31) def fetch_day_data(dt): return blp.bdib(tickers=cl_chain, dt=dt, interval=60, ref='CME') # 控制线程数避免触发Bloomberg API限制,建议设为3-5 with ThreadPoolExecutor(max_workers=4) as executor: daily_dfs = list(executor.map(fetch_day_data, date_range)) cl_hist = pd.concat(daily_dfs, sort=True)
3. 减少不必要的数据传输
若仅需特定字段(如收盘价),在请求时指定fields参数,减少返回的数据量:
cl_hist = blp.bdib( tickers=cl_chain, dt=date_range, interval=60, ref='CME', fields=['close'] # 仅获取收盘价,按需修改 )
内容的提问来源于stack exchange,提问作者Analyst
相关产品推荐
相关产品推荐

