3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT(迅投量化交易系统)中,扩展数据(ext_data)常用于存储横截面指标或自定义因子。如果逐根 Bar 在 handlebar 中频繁调用 ext_data_rank 获取截面排名,会导致严重的计算性能瓶颈。
为了提高计算效率,QMT 提供了 ContextInfo.get_ext_all_data 接口,支持在策略初始化阶段(init)一次性将全市场历史时间区域内的扩展数据**数值(value)和排名(rank)**全部提取到内存中,极大提升策略的回测和运行速度。
ContextInfo.get_ext_all_data(extdataname, start_time='19720101', end_time='22010101')
| 参数名 | 类型 | 说明 | 默认值 |
|---|---|---|---|
extdataname |
str |
扩展数据名称(必须与QMT客户端中设置的名称一致) | 无(必填) |
start_time |
str |
起始时间(格式 YYYYMMDD) |
'19720101' |
end_time |
str |
截止时间(格式 YYYYMMDD) |
'22010101' |
返回一个 pandas.Panel(或多维数据结构),其维度组织如下:
'600000.SH')'value'(实际数值)和 'rank'(全市场排名)最佳实践说明:
强烈建议在init(ContextInfo)初始化函数中一次性取出数据并赋值给ContextInfo的全局变量,避免在handlebar中重复检索。
以下示例展示了如何在 init 中读取名为 'mycci' 的扩展数据,并在 handlebar 中快速调取当前 Bar 对应的排名与数值:
#encoding:gbk
import pandas as pd
def init(ContextInfo):
print("=== 开始初始化策略及加载扩展数据 ===")
# 设置股票池
ContextInfo.set_universe(['600000.SH', '000001.SZ'])
# 一次性获取全市场历史扩展数据及排名
ext_name = 'mycci'
try:
# 提取 2020年至今的全市场扩展数据(数值 + 排名)
ContextInfo.ext_panel = ContextInfo.get_ext_all_data(ext_name, start_time='20200101', end_time='20231231')
print(f"成功加载扩展数据 [{ext_name}]")
except Exception as e:
print(f"加载扩展数据失败, 请检查扩展数据名称及本地数据补充情况: {e}")
ContextInfo.ext_panel = None
def handlebar(ContextInfo):
# 如果扩展数据获取失败,直接跳过
if ContextInfo.ext_panel is None:
return
# 获取当前 Bar 的毫秒级时间戳
bar_time = ContextInfo.get_bar_timetag(ContextInfo.barpos)
# 检查当前时间戳是否存在于扩展数据 Panel 的 Items 中
if bar_time in ContextInfo.ext_panel.items:
# 提取当前时间戳下的所有股票的数据框 (DataFrame: Index=股票代码, Columns=['value', 'rank'])
df_current = ContextInfo.ext_panel[bar_time]
# 查看当前主图股票的数值和排名
stock = ContextInfo.stockcode
if stock in df_current.index:
val = df_current.loc[stock, 'value']
rank = df_current.loc[stock, 'rank']
print(f"BarPos: {ContextInfo.barpos} | 代码: {stock} | 扩展数值: {val} | 全市场排名: {rank}")
pandas 0.22.0,原生支持 pandas.Panel 结构。通过 panel[time] 或 panel.loc[time, stock, 'rank'] 可以快速索引数据。get_ext_all_data 载入的数据量会较大。建议按需传入具体的 start_time 和 end_time,避免占用过多内存。