问题描述
解决方案
在 QMT (Quantitative Trading Platform) 中,获取某个行业的股票列表主要有以下几种方法,具体取决于您需要的行业分类标准(如证监会行业、申万行业)或板块类型。
以下是详细的说明和代码示例。
1. 获取证监会 (CSRC) 行业成分股
如果您需要获取证监会行业分类(如“CSRC金融业”、“CSRC医药制造业”)的成分股,应使用 ContextInfo.get_industry 函数。
- 函数:
ContextInfo.get_industry(industry) - 参数:
industry(string) - 行业名称,例如'CSRC金融业'。 - 注意: 行业名称必须严格匹配 QMT 文档附录中的名称(通常带有
CSRC前缀)。
2. 获取板块或概念成分股
如果您需要获取客户端左侧板块列表中的任意板块(包括指数成分、概念板块、地区板块或自定义板块),应使用 ContextInfo.get_stock_list_in_sector 函数。
- 函数:
ContextInfo.get_stock_list_in_sector(sectorname, realtime) - 参数:
sectorname(string) - 板块名称,如'沪深300'、'锂电池'。realtime(number) - 可选,毫秒级时间戳。如果不填,默认取最新。
3. 获取指数成分股 (特定)
虽然 get_stock_list_in_sector 通用性更强,但 QMT 也提供了专门针对指数成分股的接口 ContextInfo.get_sector。
- 函数:
ContextInfo.get_sector(sector, realtime) - 参数:
sector(string) - 指数代码,如'000300.SH'。
代码示例
以下代码展示了如何在 init 函数中调用这几种方法并打印结果:
# -*- coding: gbk -*-
def init(ContextInfo):
# 方法一:获取证监会行业 (CSRC) 成分股
# 行业名称请参考文档附录,通常以 CSRC 开头
industry_name = 'CSRC金融业'
stock_list_csrc = ContextInfo.get_industry(industry_name)
print(f"========== {industry_name} 成分股示例 ==========")
print(f"股票数量: {len(stock_list_csrc)}")
print(f"前5只股票: {stock_list_csrc[:5]}")
# 方法二:获取通用板块/概念成分股
# 支持客户端左侧列表中的板块名,如 '沪深300', '酿酒' 等
sector_name = '沪深300'
stock_list_sector = ContextInfo.get_stock_list_in_sector(sector_name)
print(f"========== {sector_name} 成分股示例 ==========")
print(f"股票数量: {len(stock_list_sector)}")
print(f"前5只股票: {stock_list_sector[:5]}")
# 方法三:通过指数代码获取成分股
index_code = '000016.SH' # 上证50
stock_list_index = ContextInfo.get_sector(index_code)
print(f"========== {index_code} 成分股示例 ==========")
print(f"股票数量: {len(stock_list_index)}")
print(f"前5只股票: {stock_list_index[:5]}")
def handlebar(ContextInfo):
pass
常见行业名称参考 (CSRC)
根据 QMT 文档,常用的证监会行业名称包括但不限于:
CSRC金融业CSRC房地产业CSRC医药制造业CSRC计算机、通信和其他电子设备制造业CSRC农、林、牧、渔业
Q&A
Q: get_industry 和 get_stock_list_in_sector 有什么区别?
A: get_industry 专门用于获取证监会 (CSRC) 标准行业分类的股票列表,输入参数必须是标准的 CSRC 行业名。而 get_stock_list_in_sector 更加通用,它可以获取 QMT 客户端界面上能看到的各种板块,包括概念板块(如“锂电池”)、地区板块、指数板块以及用户自定义的板块。
Q: 如何获取某个股票属于哪个行业?
A: 可以使用 get_industry_name_of_stock(industryType, stockcode) 函数。例如 get_industry_name_of_stock('SW', '600000.SH') 可以获取浦发银行的申万行业名称,使用 'CSRC' 作为第一个参数则获取证监会行业名称。
Q: 获取到的股票代码是什么格式?
A: 获取到的列表是包含股票代码的 List,格式通常为 code.market,例如 '600000.SH' (上海) 或 '000001.SZ' (深圳)。
Q: 为什么我输入的行业名称返回空列表?
A: 请检查行业名称是否完全匹配。对于 get_industry,名称必须包含 CSRC 前缀(如 CSRC银行业 可能是不存在的,应该是 CSRC金融业 下的细分,或者直接使用 CSRC金融业)。对于 get_stock_list_in_sector,请确保该板块在 QMT 客户端的板块列表中存在。