3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT 量化交易平台中,策略回测和实盘监控时清晰的图表标注能够帮助开发者快速校验交易信号。利用 ContextInfo.draw_icon 和 ContextInfo.draw_vertline 函数,我们可以在 K 线图上精确绘制买卖信号图标及关键突破的垂直时间线。
ContextInfo.draw_icon(cond, height, type)cond: 触发绘制的逻辑条件(True/False)。height: 绘制图标的高度位置(通常设为对应 Bar 的最高价或最低价)。type: 图标类型,0 表示矩形,1 表示椭圆。ContextInfo.draw_vertline(cond, number1, number2, color='', limit='')cond: 触发绘制垂直线的逻辑条件(True/False)。number1: 垂直线的起点高度(如最低价或 0)。number2: 垂直线的终点高度(如最高价或高位数值)。color: 颜色名称,例如 'red', 'green', 'cyan', 'yellow', 'magenta' 等。limit: 画线控制,如 'noaxis'(不影响坐标轴标尺)。以下策略实现了一个简单的均线突破逻辑:当短期均线上穿长期均线时,判定为关键突破,绘制天蓝色垂直线,并在最低价位置标记矩形买入图标;当短期均线下穿长期均线时,绘制红色垂直线,并在最高价位置标记椭圆卖出图标。
#coding:gbk
import numpy as np
def init(ContextInfo):
# 设置全局参数
ContextInfo.short_period = 5
ContextInfo.long_period = 20
ContextInfo.set_universe(['600000.SH'])
def handlebar(ContextInfo):
# 获取当前Bar位置
pos = ContextInfo.barpos
if pos < ContextInfo.long_period:
return
# 获取历史收盘价
close_prices = ContextInfo.get_history_data(ContextInfo.long_period + 1, '1d', 'close')
stock_code = ContextInfo.stockcode
if stock_code not in close_prices or len(close_prices[stock_code]) < ContextInfo.long_period + 1:
return
prices = close_prices[stock_code]
# 计算均线
ma_short_prev = np.mean(prices[-ContextInfo.short_period-1:-1])
ma_short_curr = np.mean(prices[-ContextInfo.short_period:])
ma_long_prev = np.mean(prices[-ContextInfo.long_period-1:-1])
ma_long_curr = np.mean(prices[-ContextInfo.long_period:])
# 金叉条件(买入信号)
gold_cross = (ma_short_prev <= ma_long_prev) and (ma_short_curr > ma_long_curr)
# 死叉条件(卖出信号)
death_cross = (ma_short_prev >= ma_long_prev) and (ma_short_curr < ma_long_curr)
# 获取当前Bar的高低价供绘图定位
high_prices = ContextInfo.get_history_data(1, '1d', 'high')[stock_code]
low_prices = ContextInfo.get_history_data(1, '1d', 'low')[stock_code]
curr_high = high_prices[-1]
curr_low = low_prices[-1]
# 1. 绘制金叉信号:天蓝色贯穿垂直线 + 低位矩形图标
if gold_cross:
ContextInfo.draw_vertline(True, curr_low * 0.95, curr_high * 1.05, 'cyan', 'noaxis')
ContextInfo.draw_icon(True, curr_low * 0.98, 0) # 0: 矩形图标
# 2. 绘制死叉信号:红色贯穿垂直线 + 高位椭圆图标
if death_cross:
ContextInfo.draw_vertline(True, curr_low * 0.95, curr_high * 1.05, 'red', 'noaxis')
ContextInfo.draw_icon(True, curr_high * 1.02, 1) # 1: 椭圆图标
height 参数上叠加微小比例偏移(例如买入点设为 low * 0.98,卖出点设为 high * 1.02)。draw_vertline 的 limit 参数建议传入 'noaxis',防止垂直线的上下限压扁主图 K 线的显示比例。