Home >  > backtrader python试用小记

backtrader python试用小记

1

今天花半小时试用了一下Backtrader,发现还真的挺简单的,而且发现它的回测结果展示挺炫酷的。

一、安装,直接用pip install backtrader

二、回测
1.成果展示(双均线)

打印的内容:

2.代码
test.py

# from __future__ import (absolute_import, division, print_function,
#                         unicode_literals)

import backtrader as bt
import datetime
from strategy import SmaCross


cerebro = bt.Cerebro()


# Create a Data Feed
data = bt.feeds.YahooFinanceCSVData(
    dataname="oracal.csv",
    # Do not pass values before this date
    fromdate=datetime.datetime(2000, 1, 1),
    # Do not pass values after this date
    todate=datetime.datetime(2000, 12, 31),
    reverse=False)



# Add the Data Feed to Cerebro
cerebro.adddata(data)

cerebro.addstrategy(SmaCross)
  
# Set our desired cash start    
cerebro.broker.setcash(100000.0)

print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

cerebro.run()

print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

2.strategy.py

import backtrader as bt
from datetime import datetime

# Create a subclass of Strategy to define the indicators and logic

class SmaCross(bt.Strategy):
    # list of parameters which are configurable for the strategy
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30   # period for the slow moving average
    )


    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):
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
        self.dataclose = self.datas[0].close
        self.order = None

    def next(self):
        self.log('Close,%.2f' % self.dataclose[0])

        print(len(self))
        print(self.order)
        print(self.position)


        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.order = self.buy()  # enter long
                self.log('-----buy, close price is: %.2f' % self.dataclose[0])

        elif self.crossover < 0:  # in the market & cross to the downside
            self.order = self.close()  # close long position
            self.log('-----sell, close price is:%.2f' % self.dataclose[0])


cerebro = bt.Cerebro()  # create a "Cerebro" engine instance

# Create a data feed
data = bt.feeds.YahooFinanceData(dataname='MSFT',
                                 fromdate=datetime(2011, 1, 1),
                                 todate=datetime(2012, 12, 31))

cerebro.adddata(data)  # Add the data feed

cerebro.addstrategy(SmaCross)  # Add the trading strategy
cerebro.run()  # run it all
cerebro.plot()  # and plot it with a single command

3.oracal.csv

Date,Open,High,Low,Close,Adj Close,Volume
1995-01-03,2.179012,2.191358,2.117284,2.117284,1.883304,36301200
1995-01-04,2.123457,2.148148,2.092592,2.135803,1.899776,46051600
1995-01-05,2.141975,2.148148,2.086420,2.092592,1.861340,37762800
1995-01-06,2.092592,2.154321,2.061728,2.117284,1.883304,41864400
1995-01-09,2.135803,2.179012,2.129630,2.179012,1.938211,34639200
1995-01-10,2.191358,2.216049,2.185185,2.185185,1.943701,42088000
1995-01-11,2.203704,2.216049,2.098765,2.120370,1.886049,46762000
1995-01-12,2.123457,2.129630,2.086420,2.104938,1.872322,41294400

参考:
oracal

https://www.youtube.com/watch?v=K8buXUxEfMc

https://www.backtrader.com/home/helloalgotrading/

暧昧帖

本文暂无标签
Comment (1)
Trackback (0)
  1. 007 Google Chrome 78.0.3904.108unknow 沙发 2020/12/06 17:24

    运行代码出错的了??

  • 还没有Trackback

发表评论

*

*