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/

    Turtle strategy - boolean error

    General Code/Help
    3
    3
    81
    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.
    • G
      Giacomo last edited by

      Hi there,

      the aim of this simple script is to find the optimal interval to use in the turtle strategy,
      however I am getting an error that I cannot untangle. Here the code:

      import backtrader as bt
      import datetime
      
      # might want to try changing the position of this
      closes = []
      in_position = False
      
      class Turtle_Strategy(bt.Strategy):
          params = (
              ('interval', 20),
              )
      
          def __init__(self):
              self.start_cash = self.broker.getvalue()
              self.interval = self.params.interval
      
          def next(self):
              closes.append(self.data.close)
      
              if len(closes) >= self.params.interval:
                  local_min = min(closes[-self.params.interval - 1:-1])
                  local_max = max(closes[-self.params.interval - 1:-1])
      
                  if closes[-1] <= local_min:
                      in_position = True
                      self.buy(size=100)
      
                  if closes[-1] >= local_max: # and in_position:
                      self.sell(size=100)
                      in_position = False
      
          def stop(self):
              pnl = round(self.broker.getvalue() - self.start_cash, 2)
              print('Interval: {} Final PnL: {}'.format(self.params.interval, pnl))
      
      
      if __name__ == '__main__':
      
          # Variable for our starting cash
          start_cash = 10000
      
          # Create an instance of cerebro
          cerebro = bt.Cerebro()
      
          # Add our strategy
          cerebro.optstrategy(Turtle_Strategy, interval=range(14, 20))
      
          # data
          data = bt.feeds.GenericCSVData(dataname='/path/data.csv',
      
                                         # fromdate=datetime.datetime(2020, 1, 1),
                                         # todate=datetime.datetime(2020, 1, 12),
      
                                         dtformat='%Y-%m-%d',
                                         tmformat='%H:%M:%S',
                                         datetime=0,
                                         open=1,
                                         high=2,
                                         low=3,
                                         close=4,
                                         volume=5,
                                         time=6,
                                         openinterest=-1)
          # Add the data to Cerebro
          cerebro.adddata(data)
      
          # Set our desired cash start
          cerebro.broker.setcash(start_cash)
      
          # Run over everything
          starts = cerebro.run()
      
      

      Here the error

      /Users/trading_bot/env/bin/python /Users/trading_bot/turtule/turtle_optimizer.py
      Interval: 16 Final PnL: 0.0
      Interval: 15 Final PnL: 0.0
      Interval: 17 Final PnL: 0.0
      Interval: 14 Final PnL: 0.0
      multiprocessing.pool.RemoteTraceback: 
      """
      Traceback (most recent call last):
        File "/Users/anaconda3/lib/python3.7/multiprocessing/pool.py", line 121, in worker
          result = (True, func(*args, **kwds))
        File "/Users/giacomofederle/trading_bot/env/lib/python3.7/site-packages/backtrader/cerebro.py", line 1007, in __call__
          return self.runstrategies(iterstrat, predata=predata)
        File "/Users/trading_bot/env/lib/python3.7/site-packages/backtrader/cerebro.py", line 1293, in runstrategies
          self._runonce(runstrats)
        File "/Users/trading_bot/env/lib/python3.7/site-packages/backtrader/cerebro.py", line 1695, in _runonce
          strat._oncepost(dt0)
        File "/Users/trading_bot/env/lib/python3.7/site-packages/backtrader/strategy.py", line 311, in _oncepost
          self.nextstart()  # only called for the 1st value
        File "/Users/trading_bot/env/lib/python3.7/site-packages/backtrader/lineiterator.py", line 347, in nextstart
          self.next()
        File "/Users/trading_bot/turtule/turtle_optimizer.py", line 21, in next
          local_min = min(closes[-self.params.interval - 1:-1])
      TypeError: __bool__ should return bool, returned LineOwnOperation
      """
      
      The above exception was the direct cause of the following exception:
      
      Traceback (most recent call last):
        File "/Userstrading_bot/turtule/turtle_optimizer.py", line 71, in <module>
          starts = cerebro.run()
        File "/Users/trading_bot/env/lib/python3.7/site-packages/backtrader/cerebro.py", line 1143, in run
          for r in pool.imap(self, iterstrats):
        File "/Users/anaconda3/lib/python3.7/multiprocessing/pool.py", line 774, in next
          raise value
      TypeError: __bool__ should return bool, returned LineOwnOperation
      
      Process finished with exit code 1
      
      

      Thank you very much in advance, I am looking forward to some suggestions

      run-out 1 Reply Last reply Reply Quote 0
      • hghhgghdf dfdf
        hghhgghdf dfdf last edited by

        @Giacomo said in Turtle strategy - boolean error:

        closes.append(self.data.close)

        self.data.close is the line object. use list notation to get line values out of it.
        So it's fixed by writing it like this:

        closes.append(self.data.close[0])
        

        But it's an ugly as hell solution. How I would write it:

            closes = self.data.close.get(size=20)
        ....
            local_min = min(closes)
        ....
            if self.data.close[0] <= local_min:
            
            
        
        1 Reply Last reply Reply Quote 1
        • run-out
          run-out @Giacomo last edited by

          @Giacomo said in Turtle strategy - boolean error:

          closes = []

          You are using closes = [] as a global variable. You need to move this into the init as:

          self.closes = list()
          

          This will make it a local variable to the Strategy class. Then change all the closes in next to self.closes.

          I made this change and it works fine.

          You may wish to consider using self.datas[0].close.get(ago=1, size=??) instead of min(self.closes[-self.params.interval - 1:-1])

          Or even better setting up local_min/local_max as indicators in init using bt.ind.MaxN and bt.ind.MinN

          1 Reply Last reply Reply Quote 2
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
          $(document).ready(function () { app.coldLoad(); }); }