求助:彭博终端零日期权交易量查询代码仅返回常规到期结果
问题:无法获取SPX零日期权(0DTE)数据
本人拥有彭博终端访问权限,尝试用Python代码获取交易量最高的零日期权,但当前代码仅能返回常规到期期权结果,无法抓取零日期权数据,请求技术支持。
当前代码
import pandas as pd import matplotlib.pyplot as plt from xbbg import blp def inspect_options_data(specific_day='2023-8-17'): try: # Fetch bulk options data for S&P 500 Index options_data = blp.bds(tickers='SPX Index', flds=['OPT_EXIRE_DT'== specific_day, 'OPT_CHAIN']) # Filter for call options with the specified expiration date call_options = options_data[options_data['security_description'].str.contains(f'{specific_day} C')].copy() # Filter for put options with the specified expiration date put_options = options_data[options_data['security_description'].str.contains(f'{specific_day} P')].copy() # Extract the strike price from the 'security_description' column call_options['strike'] = call_options['security_description'].str.extract(f'C(\d+) ').astype(float) call_options['type'] = 'Call' # Extract the strike price from the 'security_description' column put_options['strike'] = put_options['security_description'].str.extract(f'P(\d+) ').astype(float) put_options['type'] = 'Put' # Fetch volume data for each option and ensure it's a scalar value put_options['px_volume'] = put_options['security_description'].apply(lambda x: blp.bdp(tickers=x, flds=['PX_VOLUME']).iloc[0, 0]) call_options['px_volume'] = call_options['security_description'].apply(lambda x: blp.bdp(tickers=x, flds=['PX_VOLUME']).iloc[0, 0]) # Combine puts and calls data combined_data = pd.concat([put_options, call_options]) # Sort by volume in descending order and select the top 10 top_10_options = combined_data.sort_values(by='px_volume', ascending=False).head(10) # Visualization plt.figure(figsize=(12, 6)) plt.bar(top_10_options['security_description'], top_10_options['px_volume'], color=['red' if t == 'Put' else 'green' for t in top_10_options['type']]) plt.xticks(rotation=45, ha='right') plt.xlabel('Option Description') plt.ylabel('Volume') plt.title(f'Top 10 Options for {specific_day}') plt.tight_layout() plt.show() except Exception as e: print(f"Error: {e}") # Inspect the options data inspect_options_data()
问题分析与修复方案
核心问题1:BDS调用参数错误
原代码中blp.bds的flds参数写法完全错误:['OPT_EXIRE_DT'== specific_day, 'OPT_CHAIN']会生成一个布尔值和字段名的无效列表,根本不符合彭博API的参数要求。正确做法是用overrides参数筛选指定到期日的期权链。
核心问题2:零日期权筛选逻辑不当
零日期权(0DTE)的到期日为当日,但原代码通过security_description字符串匹配日期,容易因格式不匹配漏掉数据。应直接利用彭博返回的OPT_EXIRE_DT字段进行精准筛选。
核心问题3:请求效率低下
原代码用apply逐个调用bdp获取成交量,不仅速度慢,还容易触发彭博的请求频率限制,改用批量bds请求能大幅提升效率。
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt from xbbg import blp def inspect_zero_day_options(specific_day='2023-08-17'): try: # 1. 获取指定到期日的SPX期权链,用overrides筛选到期日 options_chain = blp.bds( tickers='SPX Index', flds=['OPT_CHAIN', 'OPT_EXIRE_DT', 'OPT_STRIKE_PX', 'OPT_CALL_PUT'], overrides={'OPT_EXIRE_DT': specific_day} ) # 2. 筛选零日期权(确保到期日完全匹配) zero_day_options = options_chain[options_chain['opt_exire_dt'] == pd.to_datetime(specific_day)].copy() if zero_day_options.empty: print(f"没有找到{specific_day}的零日期权数据") return # 3. 批量获取所有期权的成交量,避免逐个请求 option_tickers = zero_day_options['security'].tolist() volume_data = blp.bds( tickers=option_tickers, flds=['PX_VOLUME'] ).reset_index().rename(columns={'index': 'security', 'px_volume': 'px_volume'}) # 4. 合并数据并整理字段 combined_data = pd.merge(zero_day_options, volume_data, on='security') combined_data['type'] = combined_data['opt_call_put'].map({'C': 'Call', 'P': 'Put'}) combined_data['strike'] = combined_data['opt_strike_px'].astype(float) # 5. 按交易量排序取前10 top_10_options = combined_data.sort_values(by='px_volume', ascending=False).head(10) # 6. 可视化 plt.figure(figsize=(12, 6)) colors = ['red' if t == 'Put' else 'green' for t in top_10_options['type']] plt.bar(top_10_options['security'], top_10_options['px_volume'], color=colors) plt.xticks(rotation=45, ha='right') plt.xlabel('期权代码') plt.ylabel('交易量') plt.title(f'{specific_day} 交易量Top10零日期权') plt.tight_layout() plt.show() except Exception as e: print(f"错误信息: {e}") # 执行查询 inspect_zero_day_options()
关键修改说明
- 用
overrides={'OPT_EXIRE_DT': specific_day}替代错误的字段参数,精准筛选指定到期日的期权链。 - 直接通过
opt_exire_dt字段匹配日期,避免字符串匹配的误差,确保零日期权不会被遗漏。 - 批量调用
bds获取所有期权的成交量,减少请求次数,提升效率并规避彭博限制。 - 利用彭博返回的
OPT_CALL_PUT和OPT_STRIKE_PX字段直接提取期权类型和行权价,无需从描述字符串中解析,更可靠。
内容的提问来源于stack exchange,提问作者Eli Sakkal
相关产品推荐
相关产品推荐

