Backtrader doesn`t execute trades / buy and sell don´t work
I have written a simple Python script using backtrader that is supposed to sell an ETF (SPY in my case) when the price of the ETF is over its 200-day simple moving average (SMA200). The code is as follows:
import backtrader as bt import yfinance stock = yfinance.Ticker("SPY") stock_data = stock.history(period="4y") # print(stock_data.head()) class SMA200Strategy(bt.Strategy): def __init__(self): self.etf = self.datas self.etf_sma = bt.ind.SMA(self.etf.lines.close, period=200) self.crossover = bt.ind.CrossOver(self.etf, self.etf_sma) def next(self): if self.crossover > 0: self.order_target_percent(self.etf, target=1) elif self.crossover < 0: self.order_target_percent(self.etf, target=0) cerebro = bt.Cerebro() cerebro.broker.setcash(100000) cerebro.adddata( bt.feeds.PandasData(dataname=stock_data)) cerebro.addstrategy(SMA200Strategy) cerebro.run() cerebro.plot()
The crossover occurs at the correct points, however, backtrader doesnt execute my sell/buy command (self.order_target_percent(self.etf, target=1)/self.order_target_percent(self.etf, target=0))
You can see in this image outputted by backtrader that the crossover signals are generated, but then no buy/sell orders are executed in many cases: Imgur
I have tried using other data but I checked and the data loaded by yfinance is correct and in the fitting format (a pandas dataframe).
I have also tried self.buy and self.close, but even those commands don´t work reliably.
How can I make backtrader actually execute my buy/sell commands in all cases?
btdoesn't execute the orders, it means that there are not enough money.
btcalculates size for target orders based on the
closeprice, but executes orders at the next
open. Try to set
target=0.9and check out the results.