For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

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[0]
            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()

    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 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?

  • Typically if bt doesn't execute the orders, it means that there are not enough money. bt calculates size for target orders based on the close price, but executes orders at the next open. Try to set target=0.9 and check out the results.

Log in to reply