3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
get_result_records 的 historysums 统计历史个股交易胜率在量化策略回测中,除了观察整体的资金曲线和夏普比率外,对个股维度的交易表现(如单只股票的累计交易次数、累计盈亏、持仓天数以及胜率)进行深度分析,是评估策略优劣的关键步骤。QMT 平台提供了强大的 get_result_records 接口,允许我们在回测运行过程中或回测结束后,通过代码直接提取这些精细化的统计数据。
get_result_recordsget_result_records 函数用于获取模型回测面板中的记录结果。要统计个股的历史交易汇总,我们需要将 recordtype 参数设置为 'historysums'。
get_result_records(recordtype, index, ContextInfo)
recordtype (string): 记录类型。统计历史汇总时固定为 'historysums'。index (number): 当前主图对应 K 线的索引,通常传入当前 K 线位置 ContextInfo.barpos。ContextInfo: 策略运行环境对象。'historysums' 返回对象的核心属性当 recordtype 为 'historysums' 时,返回的 List 中包含多个 Python 对象,每个对象代表一只股票的历史交易汇总,其常用属性如下:
stockcode: 合约代码(如 '000001.SZ')market: 市场代码(如 'SZ')profit: 累计盈亏(元)trade_balance: 累计成交额buy_sell_times: 累计交易次数holding_periods: 累计持仓天数benefit_weight: 盈利占比权重以下是一个完整的 QMT 策略示例。我们在 handlebar 的最后一根 K 线上调用 get_result_records,提取 'historysums' 数据,并使用 pandas 进行格式化输出与胜率/盈亏分析。
#coding:gbk
import pandas as pd
def init(ContextInfo):
# 设定股票池
ContextInfo.set_universe(['000001.SZ', '000002.SZ', '600000.SH'])
# 设定初始资金
ContextInfo.capital = 1000000
def handlebar(ContextInfo):
# 简单的双均线或金叉买入卖出逻辑(此处省略具体信号代码,仅作交易示意)
# 策略运行过程中会产生买卖交易...
# 判定是否为最后一根 K 线,在回测结束时进行统计
if ContextInfo.is_last_bar():
index = ContextInfo.barpos
# 获取历史汇总记录
records = get_result_records('historysums', index, ContextInfo)
if not records:
print("没有历史交易汇总记录!")
return
# 解析数据并构建 DataFrame
data_list = []
for r in records:
data_list.append({
'证券代码': r.stockcode,
'市场': r.market,
'累计盈亏(元)': r.profit,
'累计交易次数': r.buy_sell_times,
'累计持仓天数': r.holding_periods,
'成交额/市值': r.trade_balance
})
df = pd.DataFrame(data_list)
# 计算整体指标
total_profit = df['累计盈亏(元)'].sum()
profitable_trades = df[df['累计盈亏(元)'] > 0]
win_rate = len(profitable_trades) / len(df) if len(df) > 0 else 0
print("\n=========== 个股历史交易汇总 ===========")
print(df.to_string(index=False))
print("========================================")
print(f"交易总只数: {len(df)} | 盈利个股只数: {len(profitable_trades)}")
print(f"个股胜率 (盈利个股数/总交易个股数): {win_rate * 100:.2f}%")
print(f"个股累计总盈亏: {total_profit:.2f} 元")
数据管理 补充对应品种和周期的历史行情数据,确保回测能够正常撮合并产生交易记录。recordtype 设置为 'dealdetails'(交易明细),对每一笔买卖的平仓盈亏进行配对统计。get_result_records 接口仅在回测模式下有效,实盘或模拟盘运行中无法通过此接口获取历史汇总,实盘请使用 get_trade_detail_data 接口查询实时资金与持仓。