如何在 QMT 平台实现 MACD 交易策略?
学习如何在 QMT 平台上使用 Python 编写经典的 MACD 指标金叉死叉交易策略。本教程提供详细的代码示例和策略逻辑解释,帮助您快速上手量化交易。
Q: 请帮我用 Python 编写一个 MACD 指标金叉买入,死叉卖出的交易策略。
这是一个基于 QMT 平台的 Python 策略,实现了 MACD 指标金叉买入、死叉卖出 的逻辑。
策略逻辑说明
- 指标计算:使用
talib库计算 MACD 指标(快线 DIF、慢线 DEA、柱状图 MACD)。参数默认为 12, 26, 9。 - 金叉(买入信号):当 DIF 线 上穿 DEA 线时。
- 死叉(卖出信号):当 DIF 线 下穿 DEA 线时。
- 交易执行:
- 产生金叉且当前无持仓 -> 全仓买入。
- 产生死叉且当前有持仓 -> 清仓卖出。
策略代码
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import talib
def init(ContextInfo):
""" 初始化函数,策略启动时调用一次 """
# 设置资金账号 (请修改为您自己的资金账号)
ContextInfo.accid = '6000000000'
# 设置账号类型:'STOCK'股票,'FUTURE'期货
ContextInfo.accountType = 'STOCK'
# 绑定账号,用于接收回报
ContextInfo.set_account(ContextInfo.accid)
# 设置 MACD 参数
ContextInfo.fast_period = 12
ContextInfo.slow_period = 26
ContextInfo.signal_period = 9
print("策略初始化完成,MACD 参数:{}, {}, {}".format(
ContextInfo.fast_period,
ContextInfo.slow_period,
ContextInfo.signal_period))
def handlebar(ContextInfo):
""" K 线处理函数,每根 K 线执行一次 """
# 获取当前主图的股票代码
stock_code = ContextInfo.stockcode
period = ContextInfo.period
data_len =
market_data = ContextInfo.get_market_data_ex([],
[stock_code],
period=period,
count=data_len,
dividend_type=)
stock_code market_data (market_data[stock_code]) < :
close_price = market_data[stock_code][]
close_np = np.array(close_price)
diff, dea, macd = talib.MACD(
close_np,
fastperiod=ContextInfo.fast_period,
slowperiod=ContextInfo.slow_period,
signalperiod=ContextInfo.signal_period)
current_diff = diff[-]
current_dea = dea[-]
last_diff = diff[-]
last_dea = dea[-]
np.isnan(current_diff) np.isnan(last_diff):
golden_cross = (last_diff < last_dea) (current_diff > current_dea)
death_cross = (last_diff > last_dea) (current_diff < current_dea)
positions = ContextInfo.get_trade_detail_data(ContextInfo.accid, ContextInfo.accountType, )
current_vol =
pos positions:
pos.m_strInstrumentID == stock_code:
current_vol = pos.m_nVolume
last_price = close_price.iloc[-]
golden_cross:
current_vol == :
()
ContextInfo.draw_text(, last_price, )
passorder(, , ContextInfo.accid, stock_code, , -, , ContextInfo)
death_cross:
current_vol > :
()
ContextInfo.draw_text(, last_price, )
passorder(, , ContextInfo.accid, stock_code, , -, current_vol, ContextInfo)
ContextInfo.paint(, current_diff, -, , )
ContextInfo.paint(, current_dea, -, , )
macd_color = macd[-] >
ContextInfo.paint(, macd[-] * , -, , macd_color)

