3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
您好!出现这个问题的原因在于 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
ContextInfo.get_sector(sector, realtime)。用法类似,但第一个参数传入的是指数代码(如 '000300.SH')。# 获取沪深300历史成分股
history_index_stocks = ContextInfo.get_sector('000300.SH', timetag)
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)