3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT (Quantitative Trading Platform) 中,查询指数在过去某一天(历史时刻)的成分股列表,主要使用 ContextInfo.get_sector 函数,并配合毫秒级时间戳参数来实现。
ContextInfo.get_sector(sector, realtime)
'000300.SH' (沪深300)。以下是一个完整的 Python 策略代码示例,展示了如何将日期字符串转换为时间戳,并查询指定日期的沪深300成分股。
# -*- coding: gbk -*-
import datetime
import time
def init(ContextInfo):
# 1. 设置要查询的指数代码(例如:沪深300)
index_code = '000300.SH'
# 2. 设置要查询的历史日期(格式:YYYYMMDD)
target_date_str = '20210104'
# 3. 将日期字符串转换为毫秒级时间戳
# 先转换为 datetime 对象
dt_obj = datetime.datetime.strptime(target_date_str, "%Y%m%d")
# 转换为秒级时间戳,再乘以 1000 变为毫秒
timetag = int(time.mktime(dt_obj.timetuple()) * 1000)
# 4. 调用 get_sector 获取历史成分股
# 注意:第二个参数传入计算好的 timetag
component_list = ContextInfo.get_sector(index_code, timetag)
# 5. 输出结果
print(f"查询日期: {target_date_str}")
print(f"指数代码: {index_code}")
print(f"成分股数量: {len(component_list)}")
print(f"成分股列表 (前10个): {component_list[:10]}")
def handlebar(ContextInfo):
pass
time.time() 返回的是秒(10位数字),因此务必乘以 1000。ContextInfo.get_sector。ContextInfo.get_stock_list_in_sector(sectorname, realtime),用法类似,也支持时间戳参数。Q: 如果我只输入指数代码而不输入时间参数,会发生什么?
A: 如果省略 realtime 参数,ContextInfo.get_sector 将默认返回该指数当前最新的成分股列表,而不是历史列表。
Q: get_sector 返回的股票代码是什么格式?
A: 返回的是一个列表(List),包含字符串格式的股票代码,形式为 code.market,例如 ['600000.SH', '000001.SZ', ...]。
Q: 如何查询某个行业(如“银行”)在历史上的成分股?
A: 对于行业板块,建议使用 ContextInfo.get_stock_list_in_sector(sectorname, realtime)。例如 ContextInfo.get_stock_list_in_sector('申万银行', timetag)。
Q: 为什么我查询出来的列表是空的?
A: 可能有两个原因:一是该日期是非交易日或该指数在该日期尚未发布;二是本地缺少该指数的历史基础数据,请尝试在客户端补充下载数据。