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/

    Using Timer to Buy and different indicator to Sell Strategy Help

    General Code/Help
    2
    2
    160
    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.
    • Liz
      Liz last edited by

      Hi, I'm new to backtrader so thank you in advance for answering a probably obvious question.

      My example strategy is to execute a buy on a given day (weekday 4), and sell according to an indicator (when RSI >70) .

      I am having trouble getting these 2 actions to tie together correctly. I can run the code successfully, but it seems as though it isn't taking into account the buy day.

      Any help / further guidance is appreciated.

      import backtrader as bt
      import datetime
      matplotlib.use('QT5Agg')
      
      class firstStrategy(bt.Strategy):
      
          def __init__(self):
              self.rsi = bt.indicators.RSI_SMA(self.data.close, period=21)
              self.add_timer(
              when=bt.timer.SESSION_END,
              weekday=[4],
              weekcarry=True,
              timername='buytimer', # in case the day is a non-trading day the timer should kick in on the next trading day
              )
          def notify_timer(self, timer, when, *args, **kwargs):
              if not self.position:
                      self.buy(size=1)
          
          def next(self):
      #        if not self.position:
      #            self.notify_timer(timer,when)
      #
      #        else:
              if self.rsi > 70:
                      self.sell(size=1)
      
      
      #Variable for our starting cash
      startcash = 100000
      
      #Create an instance of cerebro
      cerebro = bt.Cerebro()
      
      #Add our strategy
      cerebro.addstrategy(firstStrategy)
      
      data = bt.feeds.YahooFinanceCSVData(
          dataname='BTC-USD.csv',
          fromdate=datetime.datetime(2019, 5, 1),   #2014, 9, 21
          todate=datetime.datetime(2020, 7, 8)
          )
      
      #Add the data to Cerebro
      cerebro.adddata(data)
      
      # Set our desired cash start
      cerebro.broker.setcash(startcash)
      
      # Run over everything
      cerebro.run()
      
      #Get final portfolio Value
      portvalue = cerebro.broker.getvalue()
      pnl = portvalue - startcash
      
      #Print out the final result
      print('Final Portfolio Value: ${}'.format(portvalue))
      print('P/L: ${}'.format(pnl))
      
      #Finally plot the end results
      cerebro.plot(style='candlestick',iplot=False)
      
      run-out 1 Reply Last reply Reply Quote 0
      • run-out
        run-out @Liz last edited by

        Just a few things to tidy up your code.

        @Liz said in Using Timer to Buy and different indicator to Sell Strategy Help:

        weekday=[4],

        Weekdays is plural.

        Check if there's an open order in:

         def notify_timer(self, timer, when, *args, **kwargs):
                if not self.position or not self.order:
                    self.buy(size=1)
        

        Use close instead of sell in next:

         if self.position and self.rsi > 70:
             self.close()
        
        1 Reply Last reply Reply Quote 1
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
        $(document).ready(function () { app.coldLoad(); }); }