3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
is_sector_stock 快速判断股票归属板块在 QMT(迅投量化交易系统)策略开发过程中,我们经常需要对股票池中的标的进行动态筛选,比如判断某只股票是否属于“沪深300”、“上证50”或自定义板块,从而执行不同的买卖逻辑。
QMT Python API 提供了高效的内置函数 is_sector_stock,可以在 handlebar 函数中快速完成这一判定。
is_sector_stock 函数说明is_sector_stock 用于判定给定股票代码是否存在于指定的板块中。
is_sector_stock(sectorname, market, stockcode)
sectorname (string):板块名称,例如 '沪深300'、'上证50'、'中证500' 等。market (string):市场简称,例如 'SH'(上交所)或 'SZ'(深交所)。stockcode (string):不带市场后缀的股票代码,例如 '600000'。True:股票在指定板块中。False:股票不在指定板块中。handlebar 中使用的示例代码以下是一个简单的 Python 策略示例,演示如何在逐 Bar 运行的 handlebar 函数中,对当前运行标的或全市场标的进行板块归属判断:
#coding:gbk
def init(ContextInfo):
# 初始化全局变量与股票池
ContextInfo.set_universe(['600000.SH', '000001.SZ'])
def handlebar(ContextInfo):
# 获取当前主图股票代码与市场
code = ContextInfo.stockcode
market = ContextInfo.market
# 快速判定 600000 是否属于沪深300板块
is_hs300 = is_sector_stock('沪深300', market, code)
if is_hs300:
print(f"当前BarPos: {ContextInfo.barpos}, 股票 {code}.{market} 属于 沪深300 板块")
else:
print(f"当前BarPos: {ContextInfo.barpos}, 股票 {code}.{market} 不属于 沪深300 板块")
is_sector_stock 传参时,股票代码与市场是分开传递的(如 'SH' 与 '600000'),而某些其他 API 接口(如 get_market_data)使用的是联合格式(如 '600000.SH')。handlebar 中频繁轮询大批量股票,建议只在最新的 Bar(ContextInfo.is_last_bar())或新 Bar 产生时(ContextInfo.is_new_bar())触发判断,以提升策略回测和实盘运行的性能。is_typed_stock(stocktypenum, market, stockcode) 函数。