问题描述
用 get_stock_list_in_sector 函数获取沪深 300 历史数据,返回值为空,但是当前沪深 300 的成分股可以完整返回,不知道错误出在哪里,请大佬帮忙看下
def init(ContextInfo):
return
def after_init(ContextInfo):
sector_name = '沪深 300'
adjusted_time = '20230612'
# 不传参数,返回最新的板块成分数据
newest_sector_list = ContextInfo.get_stock_list_in_sector(sector_name)
print(f'板块最新成分股: {newest_sector_list}')
# 根据历史时间,返回历史成分数据
history_sector_stock_list = ContextInfo.get_stock_list_in_sector(sector_name, '20230612')
print(f'板块历史成分股: {history_sector_stock_list}')
def handlebar(ContextInfo):
return
image.png
上图可见,最新板块成分股可以返回,但历史成分股返回为空(本地数据是齐全的)
请大佬们帮忙看一下,谢谢
解决方案
您好!出现这个问题的原因在于 get_stock_list_in_sector 函数的第二个参数 realtime 需要传入的是「毫秒级时间戳」(整数类型),而不是日期字符串(如 '20230612')。
当您不传第二个参数时,系统默认获取最新的成分股,所以能正常返回;但当您传入 '20230612' 这个字符串时,系统无法将其识别为有效的时间戳,因此返回了空列表。
解决方法
您需要使用 Python 的 time 和 datetime 模块,将日期字符串转换为毫秒级时间戳。以下是修改后的正确代码示例:
import time
import datetime
def init(ContextInfo):
pass
# 注意:QMT 标准回调函数主要是 init 和 handlebar,如果您在自定义函数中调用,请确保它被正确触发
def after_init(ContextInfo):
sector_name = '沪深300'
adjusted_time_str = '20230612'
# 不传参数,返回最新的板块成分数据
newest_sector_list = ContextInfo.get_stock_list_in_sector(sector_name)
print(f'板块最新成分股数量: {len(newest_sector_list)}')
# 将日期字符串转换为毫秒级时间戳
# 1. 字符串转 datetime 对象
dt = datetime.datetime.strptime(adjusted_time_str, '%Y%m%d')
# 2. datetime 转时间戳(秒)并乘以 1000 转为毫秒
timetag = int(time.mktime(dt.timetuple()) * 1000)
# 根据历史时间戳,返回历史成分数据
history_sector_stock_list = ContextInfo.get_stock_list_in_sector(sector_name, timetag)
print(f'板块历史成分股数量: {len(history_sector_stock_list)}')
print(f'板块历史成分股: {history_sector_stock_list}')
def handlebar(ContextInfo):
pass
补充说明
- 获取指数成分股的专用函数:如果您专门为了获取指数(如沪深300)的成分股,QMT 还提供了一个更直接的函数
ContextInfo.get_sector(sector, realtime)。用法类似,但第一个参数传入的是指数代码(如'000300.SH')。# 获取沪深300历史成分股 history_index_stocks = ContextInfo.get_sector('000300.SH', timetag) - 在 handlebar 中获取当前 K 线的时间戳:如果您是在盘中或回测的
handlebar函数中动态获取当前 K 线对应的成分股,可以直接使用ContextInfo.get_bar_timetag(ContextInfo.barpos)获取当前 K 线的毫秒时间戳,直接传入即可。def handlebar(ContextInfo): timetag = ContextInfo.get_bar_timetag(ContextInfo.barpos) stocks = ContextInfo.get_stock_list_in_sector('沪深300', timetag) - 数据下载:获取历史成分股需要依赖本地的历史数据,请确保在 QMT 的【数据管理】中已经下载了对应时间段的板块/指数成分股数据。