【新手攻略】QMT量化编程手把手教你写策略!
发布时间:3小时前阅读:15
QMT 量化交易系统支持使用 Python 编写策略,新手可参考以下内容来写策略:
了解策略基本结构
在 QMT 中,任何一个 Python 策略都必须包含init和handlebar两个函数。
init初始化函数:在整个策略生命周期中只会被执行一次,通常用于设置股票池、资金账号、初始化全局变量、设置回测参数等初始化工作。handlebar行情处理函数:是策略的核心,会在每一根 K 线上被执行一次。可在这里编写交易逻辑,如读取行情数据、计算指标、判断买卖条件、下单等。ContextInfo上下文对象:包含了大量有用的属性和方法,如ContextInfo.barpos可获取当前正在处理的 K 线的索引号,ContextInfo.get_market_data()可获取行情数据等。还可在其上自定义属性,在init和handlebar之间共享数据。
编写简单策略示例
以下是一个简单策略,它在初始化时打印 “hello init”,并在每一根 K 线上打印 “hello handlebar”。
python
# coding:gbk
def init(ContextInfo):
print('hello init')
# 可以在这里设置股票池,例如取“上证50”成分股
stock_list = ContextInfo.get_stock_list_in_sector("上证50", "")
ContextInfo.set_universe(stock_list)
def handlebar(ContextInfo):
print('hello handlebar')
# 获取当前K线的索引和时间
index = ContextInfo.barpos
timetag = ContextInfo.get_bar_timetag(index)
print('当前K线索引:', index, '时间戳:', timetag)
实现简单交易策略
若要实现一个根据价格判断买卖的策略,如当今日收盘价超过过去 5 日均线时买入,低于时卖出,可参考以下代码:
python
# coding:gbk
import pandas as pd
def init(ContextInfo):
# 设置要交易的股票代码
ContextInfo.stock_code = "600570.SS"
# 设置股票池
ContextInfo.set_universe([ContextInfo.stock_code])
def handlebar(ContextInfo):
stock_code = ContextInfo.stock_code
# 获取历史行情数据
history_data = ContextInfo.get_market_data(stock_code, frequency='1d', count=5)
df = pd.DataFrame(history_data)
# 计算5日均线
df['ma5'] = df['close'].rolling(window=5).mean()
current_ma5 = df['ma5'].iloc[-1]
current_price = df['close'].iloc[-1]
# 获取当前现金
cash = ContextInfo.get_portfolio_value()['cash']
if current_price > current_ma5:
# 全仓买入
ContextInfo.order(stock_code, cash=cash)
elif current_price < current_ma5 and ContextInfo.get_position(stock_code)['amount'] > 0:
# 卖出所有股票
ContextInfo.order(stock_code, amount=ContextInfo.get_position(stock_code)['amount'], side='sell')
编写好策略后,可在 QMT 的回测模块中设置回测时间范围、初始资金等参数,对策略进行回测,查看收益曲线等指标,以评估策略效果。
股票开户找我!无门槛国债逆回购一折 (百万分之一)!ETF佣金万0.5!融资利率5%以下!优惠多多!免费量化!ptrade&QMT!

温馨提示:投资有风险,选择需谨慎。
-
养虾理财用的金融Skill是什么?国泰海通灵犀Skills实测,新手也能装
2026-05-09 13:41
-
豆包开启付费!AI行业迎来拐点,普通投资者该怎么布局?
2026-05-09 13:41
-
2026国金证券新人开户能够享受哪些福利?(含6888元品质礼包)
2026-05-09 13:41


问一问

+微信
分享该文章
