3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT 极简量化交易平台中,进行期权策略开发时,获取期权合约的静态基本信息(如行权价、到期日、期权类型)以及计算期权的理论价格是构建交易模型的基础。QMT 提供了专门的期权数据接口和内置的 BSM(Black-Scholes-Merton)计算函数,帮助开发者快速实现这些需求。
QMT 提供了 ContextInfo.get_option_detail_data(optioncode) 接口,通过传入期权合约代码,可以获取包含行权价、到期日、标的证券等在内的详细字典数据。
ContextInfo.get_option_detail_data(optioncode)OptExercisePrice:期权行权价ExpireDate:到期日(格式如 20231025)optType:期权类型(CALL 或 PUT)VolumeMultiple:合约乘数OptUndlCode:期权标的证券代码QMT 内置了 ContextInfo.bsm_price 函数,支持直接输入标的价格、行权价、无风险利率、波动率等参数,计算欧式期权的理论价格。
ContextInfo.bsm_price(optionType, objectPrices, strikePrice, riskFree, sigma, days, dividend)optionType:期权类型,认购为 'C',认沽为 'P'objectPrices:期权标的价格(支持单个价格或价格列表)strikePrice:期权行权价riskFree:无风险收益率(如 0.03 代表 3%)sigma:标的年化波动率(如 0.23 代表 23%)days:距离到期的剩余天数dividend:标的分红率以下示例展示了如何在 QMT 策略中获取指定期权合约(如 '10001506.SHO')的详细信息,并计算其当前的 BSM 理论价格:
#coding:gbk
import datetime
def init(ContextInfo):
# 设定需要查询的期权合约代码
ContextInfo.option_code = '10001506.SHO'
def handlebar(ContextInfo):
if not ContextInfo.is_last_bar():
return
# 1. 获取期权合约详细信息
detail = ContextInfo.get_option_detail_data(ContextInfo.option_code)
if not detail:
print("未获取到期权合约信息,请检查合约代码是否正确或数据是否下载完整。")
return
opt_type = detail['optType'] # CALL 或 PUT
strike_price = detail['OptExercisePrice'] # 行权价
expire_date_str = str(detail['ExpireDate']) # 到期日
print(f"期权合约: {ContextInfo.option_code}")
print(f"期权类型: {opt_type}")
print(f"行权价格: {strike_price}")
print(f"到期日期: {expire_date_str}")
# 2. 计算剩余天数
today = datetime.datetime.now().date()
expire_date = datetime.datetime.strptime(expire_date_str, '%Y%m%d').date()
remaining_days = (expire_date - today).days
print(f"剩余天数: {remaining_days} 天")
# 3. 获取标的最新价格(以50ETF为例)
undl_code = detail['OptUndlCode'] + '.' + detail['OptUndlMarket']
tick_data = ContextInfo.get_full_tick([undl_code])
if undl_code in tick_data:
underlying_price = tick_data[undl_code]['lastPrice']
print(f"标的最新价 ({undl_code}): {underlying_price}")
# 4. 使用 BSM 模型计算理论价格
# 假设无风险利率为 3%,标的年化波动率为 20%,分红率为 0
bsm_opt_type = 'C' if opt_type == 'CALL' else 'P'
theoretical_price = ContextInfo.bsm_price(
optionType=bsm_opt_type,
objectPrices=underlying_price,
strikePrice=strike_price,
riskFree=0.03,
sigma=0.20,
days=max(remaining_days, 1), # 避免剩余天数为0导致计算异常
dividend=0.0
)
print(f"BSM 理论价格: {theoretical_price:.4f}")
SHO 上交所期权、SZO 深交所期权)的过期合约列表与历史行情数据。ContextInfo.get_bar_timetag(ContextInfo.barpos),而非当前系统时间 datetime.datetime.now()。