Do your own quantitative trading software (26) Xiaobai Quantitative event backtesting of MetaTrader5 automatic backtesting

Make your own quantitative trading software (26) Xiaobai Quantitative Event Backtesting of MetaTrader5 Automatic Backtesting
Our previous article introduced Xiaobai’s quantitative MetaTrader5 market analysis and trading knowledge. In this article, we use Xiaobai’s quantitative event backtest module Let's make a demonstration of MetaTrader5 automatic backtest.
We used the following Xiaobai modules.
Xiaobai quantized event backtest module HP_quant
Xiaobai quantified MetaTrader5 module HP_mt5
Xiaobai quantized formula function library module HP_formula
Of course we can also use the talib library, for example, the following code:

mydf['opentunmo']=talib.CDLENGULFING(OPEN, HIGH, LOW, CLOSE)  #-100 为向下吞没, 100为向上吞没
upperband, middleband, lowerband=talib.BBANDS(CLOSE, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
mydf['upperband']=upperband
mydf['middleband']=middleband
mydf['lowerband']=lowerband

The backtest program we give below still uses Xiaobai's quantified formula function library module HP_formula, which is convenient for users to use custom formula indicators. The source code is directly given below, including the comments.

# encoding:utf-8
'''
独狼荷蒲qq:2886002
通通小白python量化群:524949939
tkinter,pyqt,gui,Python交流2:517029284
微信公众号:独狼股票分析
'''
import datetime
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import MetaTrader5 as mt5
import talib
import HP_mt5 as hmt5    #小白MT5模块
import HP_quant as hqu   #小白量化回测
from HP_formula import *   #小白公式函数模块


#买
def buy(context, data,volume=0.1):
    data.price=data.close+context.dc
    context.volume=volume
    context.mode=1
    context.price=data.price
    context.s1=context.s1+1
    print('买多')

#卖    
def sell(context, data,volume=0.1):
    data.price=data.close-context.dc
    context.mode=2
    context.volume=volume
    context.price=data.price
    context.s2=context.s2+1
    print('买空')

#平仓
def pingcang(context, data):
    if context.mode==1:
        context.cash=context.cash+context.yingli
    else:
        context.cash=context.cash+context.yingli
    context.mode=0
    context.s3=context.s3+1
    print('平仓')
    
#止损
def zhisun(context, data):
    context.cash=context.cash+context.kuisun
    context.mode=0
    context.s4=context.s4+1
    print('止损')

# BOLL 布林带指标
def BOLL(N=20, P=2):
    """
    BOLL 布林带
    """
    MID = MA(CLOSE, N)
    UPPER = MID + STD(CLOSE, N) * P
    LOWER = MID - STD(CLOSE, N) * P
    return UPPER, MID, LOWER

G=hqu.GlobalVars()   #用户全局变量
context = hqu.Context()  #创建回测句柄
data = hqu.Data()  #创建交易数据

data.symbol='GOLD'   #回测品种
data.price=0.0  #成本价

def initialize(context,df):
    print('回测初始化')
    # 定义一个全局变量, 保存要操作的证券                                                                                           
    context.stocks = ['GOLD']   #股票池
    context.cash=2000.00    #现金
    context.i=0        #i是起始位置
    context.start=0        #i是起始位置
    context.end=1500        #i是结束位置
    df['day']=[ x[0:10] for x in df.date.astype(str)]
    df['hour']=[ x[0:2] for x in df.time.astype(str)]
    df['minute']=[ x[3:5] for x in df.time.astype(str)]
    df['mode']=0  #买卖状态
    df['yl']=0   #盈利
    df['jz']=2000  #净值
    
    df2=df[df.minute=='00']
    df3=df2[df2.hour>='01']
    df3=df3.reset_index(level=None, drop=True ,col_level=0, col_fill='') 
    day=df3.at[len(df3)-1,'day']
    context.mydf=df    #df数据
    context.day= day   #当前日期
    context.yingli=5.0   #基准盈利
    context.kuisun=-10.0  #基准亏损
    context.volume=0.1   #持仓量
    context.mode=0   #买单状态0:空仓,1:多单,2:空单
    context.end=len(context.mydf)  #结束位置
    context.start=0        #i是起始位置
    context.dc=0.5   #点差
    context.price=0.0   #成本价
    context.s1=0   #买多次数
    context.s2=0   #买空次数
    context.s3=0   #平仓次数
    context.s4=0   #止损次数


#------------------------------------------------------
pd.set_option('display.max_columns', 50) # number of columns to be displayed
pd.set_option('display.width', 1500)      # max table width to display
startTime=datetime.datetime.now()

# 连接到MetaTrader 5
if not mt5.initialize(login=26,server="XMGlobal-MT5",password="26"):
    print("initialize() failed")
    mt5.shutdown()

# 建立与MetaTrader 5程序端的连接
if not mt5.initialize():
    print("initialize() failed, error code =", mt5.last_error())
    quit()


rates= mt5.copy_rates_from_pos("GOLD", mt5.TIMEFRAME_H1, 0, 10000)
data2=hmt5.tohpdata(rates)
data2['time']=[x[11:19] for x in data2.time.astype(str)]
print(data2)

mydf=data2.copy()
mydf=mydf.reset_index(level=None, drop=True ,col_level=0, col_fill='')
CLOSE= mydf['close']
HIGH=mydf['high']
LOW=mydf.low
OPEN=mydf.open


u,m,l=BOLL()
mydf['u']=u
mydf['m']=m
mydf['l']=l


mydf['ma3']=EMA(CLOSE,3)*0.995
mydf['ma3b']=EMA(CLOSE,3)*1.005
#买点策略,3日均线上穿布林指标下规
mydf['B']=CROSS(mydf['ma3'],mydf['l'])

#mydf['S']=CROSS(mydf['u'],mydf['ma3b'])
mydf['S']=0   #关闭卖出信号


#绘图
i=1
mydf2=mydf.tail(i*100).head(100)

mydf2.u.plot.line(legend=True)
mydf2.m.plot.line(legend=True)
mydf2.l.plot.line(legend=True)
mydf2.ma3.plot.line(legend=True)
mydf2.ma3b.plot.line(legend=True)

#策略初始化
initialize(context,mydf)
context.end=len(mydf)
print(mydf)

#用户策略
def handle_data(context,data):
    i=context.i

    #获取每个数据的值
    df3=context.mydf
    day=df3.at[i,'day']
    data.day=df3.at[i,'day']
    data.high=df3.at[i,'high']
    data.low=df3.at[i,'low']
    data.open=df3.at[i,'open']
    data.time=df3.at[i,'time']
    data.close=df3.at[i,'close']
    B=df3.at[i,'B']
    S=df3.at[i,'S']
    
    if context.mode==0 and B==1:  #买多
        buy(context, data)
    elif context.mode==0 and S==1:  #买空
        sell(context, data)
    elif context.mode==1:  #买多状态
        if data.high-context.dc-data.price > context.yingli: #买多止盈
            pingcang(context, data)
        elif data.price-data.low-context.dc < context.kuisun:  #买多止损
            zhisun(context, data)
    elif context.mode==2:   #买空状态
        if data.price-data.low+context.dc > context.yingli:  #买空止盈
            pingcang(context, data)
        elif data.high-data.price+context.dc < context.kuisun: #买空止损
            zhisun(context, data)

    context.i=i+1   #继续下一个周期


#开始回测
m=context.end-context.start

for i in range(context.start,context.end):
    context.i=i
    handle_data(context,data)
    print('当前进度:',(i*100/m),data.day,data.time,'资金: ',context.cash)

print('买多:',context.s1,'买空:',context.s2,'止损:',context.s4,'资金:',context.cash)    
    
#关闭MT5连接
mt5.shutdown()

Let's take a look at the running results:

当前进度: 99.87 2020-07-10 11:00:00 资金:  2420.0
当前进度: 99.88 2020-07-10 12:00:00 资金:  2420.0
买多
当前进度: 99.89 2020-07-10 13:00:00 资金:  2420.0
当前进度: 99.9 2020-07-10 14:00:00 资金:  2420.0
当前进度: 99.91 2020-07-10 15:00:00 资金:  2420.0
当前进度: 99.92 2020-07-10 16:00:00 资金:  2420.0
当前进度: 99.93 2020-07-10 17:00:00 资金:  2420.0
当前进度: 99.94 2020-07-10 18:00:00 资金:  2420.0
当前进度: 99.95 2020-07-10 19:00:00 资金:  2420.0
当前进度: 99.96 2020-07-10 20:00:00 资金:  2420.0
当前进度: 99.97 2020-07-10 21:00:00 资金:  2420.0
当前进度: 99.98 2020-07-10 22:00:00 资金:  2420.0
当前进度: 99.99 2020-07-10 23:00:00 资金:  2420.0
买多: 85 买空: 0 止损: 0 资金: 2420.0

The displayed section of the graph is as follows: The
Insert picture description here
above article introduces the development of the Python aspect of MetaTrader5. MetaTrader5 provides market data such as foreign exchange, futures, and digital currencies. It is not difficult for readers to combine the previous articles and write a fully automatic trading program according to their own strategies.
Dulang Hepu qq: 2886002
Tongtong Xiaobai python quantitative group: 524949939
WeChat public account: Dulang stock analysis

Xiaobai quantitative backtesting framework is a source code module library provided by us for readers of "Building a Quantitative Investment System with Python as a Tool". Users can improve and modify at will. Some readers use Xiaobai’s quantitative module to build a special backtest program for themselves, and some readers use this set of Xiaobai’s quantitative module to build a web stock data website for themselves, through Xiaobai’s quantitative module imitating Tongda letter and imitating big wisdom, The self-editing indicator function of imitating the flying fox trader displays the result data of the indicator calculation to the user in the form of a website, while hiding its own logic algorithm. Welcome everyone to buy our genuine book <Building a Quantitative Investment System with Python as a Tool> on JD.com, Taobao and other websites, join the readers, and work together to improve Xiaobai's quantitative platform, research quantitative technology, and improve and develop together.

Guess you like

Origin blog.csdn.net/hepu8/article/details/107308007