3

I am using BackTrader for backtesting (using python3 in Jupiter Notebook on a Mac), and have used the following example from their documentation found at https://www.backtrader.com/docu/plotting/plotting.html:

import backtrader as bt

class Ind(bt.Strategy):

    def __init__(self):

        self.sma = bt.indicators.SimpleMovingAverage(self.data)

datapath = 'CSV file on my computer.txt'  

data = bt.feeds.BacktraderCSVData(dataname = datapath)

cerebro = bt.Cerebro()
cerebro.adddata(data)
cerebro.addstrategy(Ind)
cerebro.run()
cerebro.plot()

When I plot a graph using BackTrader's cerebro.plot() function, it works fine the first time (see picture 1). First time plot

However, when I re-run the cell again (to tweak inputs), it disappears and is just left with the figure size output at the bottom (see picture 2). Output after re-running cell

It still doesn't work if I copy and paste the code in a new cell below and run it. I am still just left with the figure size output at the bottom.

This is very frustrating as every time I want to reproduce one of their plots, I am having to restart Jupiter notebook to do it.

Thanks in advance!

mike_papa
  • 63
  • 2
  • 4
  • 1
    Additional info: I have also had the same problem when using the standard python debugger in Jupiter notebook – mike_papa Jun 29 '18 at 09:07

1 Answers1

2

I've encountered the same problem, I believe it it related to backtrader's interactions with matplotlib. I was able to fix it by including the line

%matplotlib inline

at the very top of my notebook (being right at the very top seems to be important, as noted here). I did NOT need to include statements like import matplotlib.

This generates a system warning message each time a plot is generated, these can be suppressed using

import warnings
warnings.filterwarnings('ignore')

as noted in this question.

Minimal failing repro of the op's issue:

In [1]:

import backtrader as bt
import datetime

if __name__ == '__main__':
    cerebro = bt.Cerebro()

    data = bt.feeds.YahooFinanceData(
        dataname='AAPL',
        fromdate=datetime.datetime(2000, 1, 1),
        todate=datetime.datetime(2000, 12, 31),
        reverse=False)

    cerebro.adddata(data)
    cerebro.run()
    cerebro.plot(style='bar')

In [2]:

cerebro.plot(style='bar')

Fixed version of minimal failing repro:

In [1]:

%matplotlib inline

import warnings
warnings.filterwarnings('ignore')

import backtrader as bt
import datetime

if __name__ == '__main__':
    cerebro = bt.Cerebro()

    data = bt.feeds.YahooFinanceData(
        dataname='AAPL',
        fromdate=datetime.datetime(2000, 1, 1),
        todate=datetime.datetime(2000, 12, 31),
        reverse=False)

    cerebro.adddata(data)
    cerebro.run()
    cerebro.plot(style='bar')

In [2]:

cerebro.plot(style='bar')
StackG
  • 2,320
  • 5
  • 24
  • 43