问题描述
解决方案
在 QMT 量化交易平台中,查询期货合约乘数和股票上市日期分别有对应的专用 API 函数。以下是具体的实现方法和代码示例。
1. 查询期货合约乘数
使用 ContextInfo.get_contract_multiplier(contractcode) 函数。
- 参数:
contractcode(string),合约代码,格式为代码.市场(例如'IF2306.IF')。 - 返回值:
number,返回该合约的乘数。
2. 查询股票上市日期
使用 ContextInfo.get_open_date(stockcode) 函数。
- 参数:
stockcode(string),股票代码,格式为代码.市场(例如'000001.SZ')。 - 返回值:
number,返回上市日期,格式通常为YYYYMMDD(例如19910403)。
3. 综合查询(获取合约详细信息)
除了上述专用函数外,还可以使用 ContextInfo.get_instrumentdetail(stockcode) 获取合约的详细信息字典,其中包含了合约乘数(VolumeMultiple)和上市日期(OpenDate)。
代码示例
您可以将以下代码复制到 QMT 的策略编辑器中运行,查看输出结果。
# -*- coding: gbk -*-
def init(ContextInfo):
# 示例 1: 查询期货合约乘数
# 以中金所沪深300股指期货主力合约为例 (IF.IF 代表主力)
future_code = 'IF.IF'
multiplier = ContextInfo.get_contract_multiplier(future_code)
print(f"期货合约 {future_code} 的合约乘数是: {multiplier}")
# 示例 2: 查询股票上市日期
# 以平安银行为例
stock_code = '000001.SZ'
open_date = ContextInfo.get_open_date(stock_code)
print(f"股票 {stock_code} 的上市日期是: {open_date}")
# 示例 3: 使用 get_instrumentdetail 获取详细信息
# 获取某只股票的详细信息
detail = ContextInfo.get_instrumentdetail(stock_code)
if detail:
print(f"--- {stock_code} 详细信息 ---")
print(f"上市日期 (OpenDate): {detail.get('OpenDate')}")
print(f"合约乘数 (VolumeMultiple): {detail.get('VolumeMultiple')}")
print(f"前收盘价 (PreClose): {detail.get('PreClose')}")
def handlebar(ContextInfo):
# 该函数在回测或实时运行时会在每根K线调用,此处不需要执行逻辑
pass
Q&A
Q: get_open_date 返回的日期格式是什么?
A: 该函数返回的是一个整数(number)类型,格式为 YYYYMMDD(年月日),例如 20230101。
Q: 如果查询的代码不存在或输入错误,函数会返回什么?
A: 如果代码无效,get_contract_multiplier 通常返回 0 或 None(取决于具体版本实现),get_instrumentdetail 可能会返回空字典或 None。建议在实盘代码中增加对返回值的非空判断。
Q: get_instrumentdetail 还能查询哪些信息?
A: 该函数返回一个字典,包含非常丰富的信息,如:ExchangeID(市场代码)、InstrumentName(合约名称)、ExpireDate(到期日/退市日)、UpStopPrice(涨停价)、DownStopPrice(跌停价)、LongMarginRatio(多头保证金率)等。
Q: 如何查询期货合约的到期日?
A: 可以使用 ContextInfo.get_contract_expire_date(codemarket) 函数,或者通过 ContextInfo.get_instrumentdetail(codemarket)['ExpireDate'] 获取。