量化交易研究

量化交易回测框架Backtrader使用框架的技术指标(indi

2020-04-13  本文已影响0人  一块自由的砖

简介

股市里面有很多指标,常见的股票均线、MACD、KDJ、布林线等指标,还有很多,反正手指头+脚指头全加到一起也是数不过来的。backtrader框架封装一部分比较常用的技术指标函数,实际项目用,我们会使用技术分析库ta-lib,以后在使用框架做分析是会针对ta-lib做详细的介绍。本次的代码具体可以参看Backtrader官方文档Quickstart

目标:

  1. 使用SMA指标(n日的收盘价平均线)和收盘价来确定股票买卖的触发条件

原理

通过判定收盘价和n日期内的均线,是否有交叉来判定买卖,比如收盘价上穿过均线,就购买,当收盘价下穿均线就是卖出。

实践

#############################################################
#class
#############################################################
# Create a Stratey
class TestStrategy(bt.Strategy):
    # 自定义均线的实践间隔,默认是5天
    params = (
        ('maperiod', 5),
    )
    def log(self, txt, dt=None):
        ''' Logging function for this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close
        # To keep track of pending orders
        self.order = None
        # buy price
        self.buyprice = None
        # buy commission
        self.buycomm = None
        # 增加均线,简单移动平均线(SMA)又称“算术移动平均线”,是指对特定期间的收盘价进行简单平均化
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod)
    #订单状态改变回调方法 be notified through notify_order(order) of any status change in an order
    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return
        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            elif order.issell():
               self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))
            self.bar_executed = len(self)
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
        # Write down: no pending order
        self.order = None

    #交易状态改变回调方法 be notified through notify_trade(trade) of any opening/updating/closing trade
    def notify_trade(self, trade):
        if not trade.isclosed:
            return
        # 每笔交易收益 毛利和净利
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))

    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose[0])
        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return
        # Check if we are in the market(当前账户持股情况,size,price等等)
        if not self.position:
            # Not yet ... we MIGHT BUY if ...
            if self.dataclose[0] >= self.sma[0]:
                #当收盘价,大于等于均线的价格
                # BUY, BUY, BUY!!! (with all possible default parameters)
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                # Keep track of the created order to avoid a 2nd order
                self.order = self.buy()
        else:
            # Already in the market ... we might sell
            if self.dataclose[0] < self.sma[0]:
                #当收盘价,小于均线价格
                # SELL, SELL, SELL!!! (with all possible default parameters)
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()

分析说明

重点是修改自定义策略中的next方法,判断5日均线和每日收盘价的大小,来判断是否买卖。目前默认参数设置为3,为三日。通过传入参数5,实现5日。比较简单无特别说明。你可以自己改改日期,看看那个时间的均线能盈利。

源码

全代码请到github上clone了。github地址:[qtbt](https://github.com/horacepei/qtbt.git

上一篇下一篇

猜你喜欢

热点阅读