0

My code is attached below, with example output. I am trying to plot the trades of my strategy, but they are displaying weird in the output. The buy/sell markers are sometimes not on the curve, just floating in space. This makes me think that my data has errors. Do you know why this is happening? enter image description here

import backtrader as bt
import backtrader.analyzers as btanalyzers
import matplotlib
from datetime import datetime
 
class MaCrossStrategy(bt.Strategy):
 
    params = (
        ('fast_length', 5),
        ('slow_length', 25)
    )
     
    def __init__(self):
        self.crossovers = []
         
        for d in self.datas: 
            ma_fast = bt.ind.SMA(d, period = self.params.fast_length)
            ma_slow = bt.ind.SMA(d, period = self.params.slow_length)
 
            self.crossovers.append(bt.ind.CrossOver(ma_fast, ma_slow))
 
    def next(self):
        for i, d in enumerate(self.datas):
            if not self.getposition(d).size:
                if self.crossovers[i] > 0: 
                    self.buy(data = d)
            elif self.crossovers[i] < 0: 
                self.close(data = d)
 
cerebro = bt.Cerebro()
 
stocks = ['SPY', 'QQQ', 'VOO']
for s in stocks: 
    data = bt.feeds.YahooFinanceData(dataname = s, fromdate = datetime(2010, 1, 1), todate = datetime(2020, 1, 1))
    cerebro.adddata(data, name = s)
 
 
cerebro.addstrategy(MaCrossStrategy)
 
cerebro.broker.setcash(1000000.0)
 
cerebro.addsizer(bt.sizers.PercentSizer, percents = 10)
 
cerebro.addanalyzer(btanalyzers.SharpeRatio, _name = "sharpe")
cerebro.addanalyzer(btanalyzers.Returns,     _name = "returns")
cerebro.addanalyzer(btanalyzers.Transactions, _name = "trans")
 
back = cerebro.run()
 
cerebro.broker.getvalue()
back[0].analyzers.returns.get_analysis()['rnorm100']
back[0].analyzers.sharpe.get_analysis()
back[0].analyzers.trans.get_analysis()

cerebro.plot(style='candlestick')
Deemo
  • 131
  • 1
  • 1
  • 10

1 Answers1

0

I have determined that the error is in the data, or how backtraders Yahoo.py processes it when doing an online pull. When manually downloading the data and opening it using YahooFinanceCSVData(), the error does not occur. There is already a known issue with the online data collection version, YahooFinanceData(), and this may be related.

Deemo
  • 131
  • 1
  • 1
  • 10