#encoding:gbk
import numpy as np
import pandas as pd
import datetime
import talib
"""
示例说明:双均线回测,通过计算快慢双均线,在金叉时买入,死叉时做卖出
"""
class _c():
pass
C = _c() #创建空的类的实例 用来保存全局变量
def init(C):
C.stock= C.stockcode + '.' + C.market #品种为模型交易界面选择品种,本例默认为沪深300指数
C.stock="601857.SH"
C.line10=10 #快线周期
C.line20=20 #慢线周期
#设置股票池 订阅品种行情
C.set_universe([C.stock])
C.accountid="test"
def handlebar(C):
#K线的日期
bar_date = timetag_to_datetime(C.get_bar_timetag(C.barpos), '%Y%m%d%H%M%S')
#获取行情数据
local_data = C.get_market_data_ex(['close'], [C.stock], end_time = bar_date, period = C.period, count = max(C.line10, C.line20), subscribe = False)
close_list = list(local_data[C.stock].iloc[:, 0])
#print(close_list)
if len(close_list)<1:
print(bar_date," 获取行情数据失败")
#获取两条均线前一天的值
pre_line1 = round(np.mean(close_list[-C.line10-1:-1]),2)
pre_line2 = round(np.mean(close_list[-C.line20-1:-1]),2)
#print(f"前一天,短均线{pre_line1},短均线{pre_line2}")
#获取两条均线当天的数值
current_line1 = round(np.mean(close_list[-C.line10:]),2)
current_line2 = round(np.mean(close_list[-C.line20:]),2)
#print(f"{bar_date},短均线{current_line1},短均线{current_line2}")
#获取股票账户资金余额
available_cash=get_stock_cash(C.accountid)
print(f"资金余额,{available_cash}")
# 获取股票账户持仓总数
holding_vol = get_stock_holdings(C.accountid,C.stock)
print(f"持仓总数,{C.stock},{holding_vol}")
#如果快线穿过慢线,则买入
if holding_vol==0 and pre_line1<pre_line2 and current_line1 > current_line2:
#msg = f"{bar_date} 双均线实盘 {C.stock} 上穿均线 买入"
#print(msg)
vol = int(available_cash / close_list[-1] / 100) * 100
# 下单开仓
passorder(23, 1101, C.accountid, C.stock, 5, -1, vol, C)
print(f"{bar_date} 开仓")
C.draw_text(1, 1, '开')
#如果快线下穿慢线,则卖出
elif holding_vol > 0 and pre_line1>pre_line2 and current_line1 < current_line2:
#msg = f"{bar_date}双均线实盘 {C.stock} 下穿均线 卖出 "
#print(msg)
# 状态变更为未持仓
C.holding = False
# 下单平仓
passorder(24, 1101, C.accountid, C.stock, 5, -1, holding_vol, C)
print(f"{bar_date} 平仓")
C.draw_text(1, 1, '平')
def get_stock_cash(accountid):
account = get_trade_detail_data(accountid, 'stock', 'account')
account = account[0]
available_cash = int(account.m_dAvailable)
return available_cash
def get_stock_holdings(accountid,stock):
holdings = get_trade_detail_data(accountid, 'stock', 'position')
holdings = {i.m_strInstrumentID + '.' + i.m_strExchangeID: i.m_nVolume for i in holdings}
holding_vol = holdings[stock] if stock in holdings else 0
return holding_vol
QMT实战:双均线回测(1)
于 2024-07-12 14:20:56 首次发布