Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    No trades executed. Only 1 buy.

    General Code/Help
    2
    3
    59
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • B
      bt88 last edited by

      Hi all.

      I am trying to backtest my strategy using a simple machine learning model on the E-Mini S&P500 futures. I got my prediction in a pandas dataframe (column: datetime, OHLCV, prediction) and exported to a .csv file, which i then fed into backtrader as datafeed. I am using a 1 minute intraday interval.

      import backtrader as bt
      
      futures_like = True
      if futures_like:
          commission, margin, mult = 0.52, 2000.0, 1.0
      else:
          commission, margin, mult = 0.005, None, 1
          
      class TestStrategyRF(bt.Strategy):
      
          def log(self, txt, dt=None):
              dt = dt or self.datas[0].datetime.date(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              self.data_close = self.datas[0].close
              self.data_prediction = self.datas[0].prediction
      
              self.order = None
              self.buyprice = None
              self.buycomm = None
      
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  return
      
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          'BUY EXECUTED, Size: %d, Price: %.2f, Cost: %.2f, Comm %.2f' %
                          (order.executed.size,
                           order.executed.price,
                           order.executed.value,
                           order.executed.comm))
      
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else: 
                      self.log('SELL EXECUTED, Size: %d, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.size,
                                order.executed.price,
                                order.executed.value,
                                order.executed.comm))
                                
                      gross_pnl = (order.executed.price - self.buyprice) * order.executed.size
                      if margin:
                          gross_pnl *= mult
      
                      net_pnl = gross_pnl - self.buycomm - order.executed.comm
      
                      self.log('OPERATION PROFIT, GROSS_TEST %.2f, NET_TEST %.2f' %
                              (gross_pnl, net_pnl)) 
      
              elif order.status in [order.Canceled]:
                  self.log('Order Canceled')
              elif order.status in [order.Margin]:
                  self.log('Order Margin')
              elif order.status in [order.Rejected]:
                  self.log('Order Rejected')
      
          def next(self):
              self.log('Close, %.2f' % self.data_close[0])
      
              if self.order:
                  return
      
              if not self.position:
                  if self.data_prediction[0] > 0:
                      self.log('BUY CREATE, %.2f' % self.data_close[0])
                      self.order = self.buy()
      
              else:
                  if self.data_prediction[0] < 0:
                      self.log('SELL CREATE, %.2f' % self.data_close[0])
                      self.order = self.sell()
      

      Everything ran smoothly but it only executed the first BUY and then nothing.
      Screenshot 2021-07-27 at 5.09.52 PM.png

      If i commented the following lines, however, it will generate the trades. (but somehow i think they're not quite right)

              # if self.order:
              #     return
      

      Screenshot 2021-07-27 at 5.09.03 PM.png

      I can't seem to figure out what's wrong. Perhaps my logic is incorrect. Can somebody advise? Also, this is my first time trying to implement and backtest a ML model using backtrader, is my approach correct?

      Thank you in advance.

      vladisld 1 Reply Last reply Reply Quote 0
      • vladisld
        vladisld @bt88 last edited by

        @bt88 It seems the self.order is not set to None anywhere - probably need to reset it to None in notify_order once the order is completed.

        B 1 Reply Last reply Reply Quote 2
        • B
          bt88 @vladisld last edited by

          Thanks @vladisld ! That solves it.

          1 Reply Last reply Reply Quote 1
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors