钱多多小栈
专注量化回测的站点

Backtrader-快速开始(加入股票指标)

股票有很多指标,后面的实例中会增加其中的一个指标。指标的效果肯定要优于咱们原来实例中的收盘价三连跌。

指标灵感来源于PyAlgoTrade的一个使用简单移动平均线指标(SMA)的策略。

  • 在空仓情况下,如果收盘价大于SMA指标则买入
  • 在持仓情况下,如果收盘价小于SMA指标则卖出
  • 持仓情况下,只操作一次

以前的实例代码大部分保留,只要少量改动即可,首先,在init的方法中引入SMA指标:

self.sma = bt.indicators.MovingAverageSimple(self.datas[0], period=self.params.maperiod)

其次,修改买入卖出判定逻辑即可,代码如下:

# -*- coding: utf-8 -*-
"""
backtrader手册样例代码
@author: 一块自由的砖
"""
#############################################################
#import
#############################################################
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import os,sys
import pandas as pd
import backtrader as bt
#############################################################
#global const values
#############################################################
#############################################################
#static function
#############################################################
#############################################################
#class
#############################################################
# Create a Stratey
class TestStrategy(bt.Strategy):
    params = (
        ('maperiod', 15),
    )

    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 and buy price/commission(价格、佣金)
        self.order = None
        self.buyprice = None
        self.buycomm = None
        # Add a MovingAverageSimple indicator
        self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)
    
    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

    def notify_trade(self, trade):
        if not trade.isclosed:
            return
        # 一次卖出后交易完成后的收益情况: gross 毛利  net 净/纯利
        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(检查是否持股)
        if not self.position:
            # 判定当前交易日的收盘价是否小于的15日的均值
            if self.dataclose[0] > self.sma[0]:
                # previous close less than the previous close
                # BUY, BUY, BUY!!! 购买动作,创建买单,给买入价
                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,持股情况下,收盘价是否小于15日的均值
            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()
#############################################################
#global values
#############################################################
#############################################################
#global function
#############################################################
# 通过读取cvs文件,获取想要的数据
def get_dataframe():
    # Get a pandas dataframe(这里是股票数据文件放的目录路径)
    datapath = 'qtbt\data\stockinfo.csv'
    # 数据转换用临时文件路径和名称,用完后删除
    tmpdatapath = datapath + '.tmp'
    print('-----------------------read csv---------------------------')
    dataframe = pd.read_csv(datapath,
                                skiprows=0,
                                header=0,
                                parse_dates=True,
                                index_col=0)
    # 定义交易日期格式
    dataframe.trade_date =  pd.to_datetime(dataframe.trade_date, format="%Y%m%d")
    # 原始cvs数据有很多列,这里组织需要使用的数据列,生成目标数据的tmp数据文件后,读取需要的数据
    dataframe['openinterest'] = '0'
    feedsdf = dataframe[['trade_date', 'open', 'high', 'low', 'close', 'vol', 'openinterest']]
    feedsdf.columns =['datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']
    # 按照交易日期升序排列
    feedsdf.set_index(keys='datetime', inplace =True)
    # 生成临时文件
    feedsdf.iloc[::-1].to_csv(tmpdatapath)
    # 获取需要使用的数据
    feedsdf = pd.read_csv(tmpdatapath, skiprows=0, header=0, parse_dates=True, index_col=0)
    # 删除tmp临时文件
    if os.path.isfile(tmpdatapath):
        os.remove(tmpdatapath)
        print(tmpdatapath+" removed!")
    # 返回需要的数据
    return feedsdf
########################################################################
#main
########################################################################
if __name__ == '__main__':
    # Create a cerebro entity(创建cerebro)
    cerebro = bt.Cerebro()
    # Add a strategy(加入自定义策略,可以设置自定义参数,方便调节)
    cerebro.addstrategy(TestStrategy)
    # Get a pandas dataframe(获取dataframe格式股票数据)
    feedsdf = get_dataframe()
    # Pass it to the backtrader datafeed and add it to the cerebro(加入数据)
    data = bt.feeds.PandasData(dataname=feedsdf)
    # 加入数据到Cerebro
    cerebro.adddata(data)
    # Add a FixedSize sizer according to the stake(国内1手是100股,最小的交易单位)
    cerebro.addsizer(bt.sizers.FixedSize, stake=100)
    # Set our desired cash start(给经纪人,可以理解为交易所股票账户充钱)
    cerebro.broker.setcash(100000.0)
    # Set the commission - 0.1% ... divide by 100 to remove the %
    cerebro.broker.setcommission(commission=0.001)
    # Print out the starting conditions(输出账户金额)
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    # Run over everything(执行回测)
    cerebro.run()
    # Print out the final result(输出账户金额)
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

程序输出,和以前没啥变化,主要是买入和卖出的时机不同了。

未经允许不得转载:钱多多量化小栈 » Backtrader-快速开始(加入股票指标)