3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在进行ETF(交易型开放式指数基金)套利交易时,折溢价率是最核心的监控指标。折溢价率是指ETF的二级市场交易价格与其**盘中份额参考净值(IOPV)**之间的偏差。当偏差足够大并能覆盖交易成本时,就存在套利机会。
QMT平台提供了极其便利的内置函数 get_etf_iopv,让开发者能够实时获取ETF的官方IOPV,从而精准捕捉盘中套利机会。
get_etf_iopvget_etf_iopv(stockcode)stockcode(string,如 '510050.SH')IOPV(float,基金份额参考净值)get_full_tickget_full_tick(stock_code)lastPrice 的字典。$$\text{折溢价率} = \frac{\text{ETF二级市场最新价} - \text{IOPV}}{\text{IOPV}} \times 100%$$
以下是一个在QMT中实时监控华夏上证50ETF(510050.SH)折溢价并打印套利信号的完整策略模版:
#coding:gbk
import time
def init(ContextInfo):
# 设定监控的ETF代码
ContextInfo.etf_code = '510050.SH'
ContextInfo.set_universe([ContextInfo.etf_code])
# 设定套利阈值(例如 0.2%)
ContextInfo.threshold = 0.002
# 设定交易账号
ContextInfo.account = '6000000248' # 请替换为您的实际资金账号
ContextInfo.set_account(ContextInfo.account)
print(f"ETF折溢价监控启动,目标: {ContextInfo.etf_code}, 触发阈值: {ContextInfo.threshold*100}%")
def handlebar(ContextInfo):
# 仅在最新Tick/Bar上运行
if not ContextInfo.is_last_bar():
return
# 1. 获取实时IOPV
iopv = get_etf_iopv(ContextInfo.etf_code)
# 2. 获取二级市场最新价格
tick_data = ContextInfo.get_full_tick([ContextInfo.etf_code])
if ContextInfo.etf_code not in tick_data:
return
market_price = tick_data[ContextInfo.etf_code]['lastPrice']
if iopv <= 0 or market_price <= 0:
return
# 3. 计算折溢价率
diff_rate = (market_price - iopv) / iopv
print(f"时间: {time.strftime('%H:%M:%S')} | 市场价: {market_price:.3f} | IOPV: {iopv:.3f} | 折溢价率: {diff_rate*100:.3f}%")
# 4. 套利逻辑判定
if diff_rate > ContextInfo.threshold:
print(f"【触发溢价套利】折溢价率 {diff_rate*100:.3f}% 超过上限 {ContextInfo.threshold*100}%")
# 执行溢价套利逻辑:此处可调用 passorder 卖出二级市场ETF,并配合一篮子股票申购
# passorder(24, 1101, ContextInfo.account, ContextInfo.etf_code, 5, -1, 10000, ContextInfo)
elif diff_rate < -ContextInfo.threshold:
print(f"【触发折价套利】折溢价率 {diff_rate*100:.3f}% 低于下限 {-ContextInfo.threshold*100}%")
# 执行折价套利逻辑:此处可调用 passorder 买入二级市场ETF,并进行赎回
# passorder(23, 1101, ContextInfo.account, ContextInfo.etf_code, 5, -1, 10000, ContextInfo)
ContextInfo.threshold 的设定必须大于综合交易成本。get_etf_info(stockcode) 获取成分股清单及现金替代溢价比例。