Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. Giacomo
    3. Posts
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    G
    • Profile
    • Following 0
    • Followers 0
    • Topics 3
    • Posts 6
    • Best 1
    • Groups 0

    Posts made by Giacomo

    • Turtle strategy - boolean error

      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

      posted in General Code/Help
      G
      Giacomo
    • Cerebro.plot() causing Process finished with exit code 139 ?

      Hi,

      I'm learning how to use the backtest, I have the most simple strategy in order to keep the script short

      import backtrader as bt
      import datetime
      
      class RSIStrategy(bt.Strategy):
      
          def __init__(self):
              self.rsi = bt.talib.RSI(self.data, period=14)
      
          def next(self):
              if self.rsi < 30 and not self.position:
                  self.buy(size=1)
              if self.rsi > 70 and self.position:
                  self.close(size=1)
      
      
      Cerebro = bt.Cerebro()
      
      fromdate = datetime.datetime.strptime('2020-01-01', '%Y-%m-%d')
      todate = datetime.datetime.strptime('2020-01-05', '%Y-%m-%d')
      
      data = bt.feeds.GenericCSVData(dataname='/path/2020_1minute.csv',
                                     dtformat=('%Y-%m-%d'),
                                     tmformat=('%H:%M:%S'),
                                     datetime=0,
                                     open=1,
                                     high=2,
                                     low=3,
                                     close=4,
                                     volume=5,
                                     time=6,
                                     openinterest=-1,
                                     compression=1,
                                     timeframe=bt.TimeFrame.Minutes,
                                     fromdate=fromdate,
                                     todate=todate
                                     )
      
      Cerebro.adddata(data)
      
      Cerebro.addstrategy(RSIStrategy)
      
      Cerebro.run()
      
      Cerebro.plot()
      

      When I run it I get the following error

      Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
      

      The data csv file looks like this

      2020-01-01,7195.24000000,7196.25000000,7183.14000000,7186.68000000,51.64281200,00:00:00
      2020-01-01,7187.67000000,7188.06000000,7182.20000000,7184.03000000,7.24814800,00:01:00
      2020-01-01,7184.41000000,7184.71000000,7180.26000000,7182.43000000,11.68167700,00:02:00
      2020-01-01,7183.83000000,7188.94000000,7182.49000000,7185.94000000,10.02539100,00:03:00
      2020-01-01,7185.54000000,7185.54000000,7178.64000000,7179.78000000,14.91110500,00:04:00
      2020-01-01,7179.76000000,7182.51000000,7178.20000000,7179.99000000,12.46324300,00:05:00
      

      If I comment out Cerebro.plot() everything runs smoothly but I get no useful output. Any idea of what might be causing this error?

      Thank you very much

      posted in General Code/Help
      G
      Giacomo
    • RE: GenericCSVData - 'Cerebro' object has no attribute '_exactbars'

      Solved

      self.rsi = bt.indicators.RSI_SMA(self.data.close, period=self.params.period, safediv=True)
      
      posted in General Code/Help
      G
      Giacomo
    • RE: GenericCSVData - 'Cerebro' object has no attribute '_exactbars'

      @vladisld thank you! That did made a difference.

      Now I'm dividing by zero somewhere apparently

      ZeroDivisionError: float division by zero
      

      I know that the problem is with the bt.feeds.GenericCSVData part, because if I replace that bit with a feed from yahoo it works

      posted in General Code/Help
      G
      Giacomo
    • RE: GenericCSVData - 'Cerebro' object has no attribute '_exactbars'

      @rajanprabu thank you very much for pointing out the index mix up.
      I changed the csv file to have it looking as follow

      date,open,high,low,close,volume,time
      2020-01-01,7195.24000000,7196.25000000,7183.14000000,7186.68000000,51.64281200,00:00:00
      2020-01-01,7187.67000000,7188.06000000,7182.20000000,7184.03000000,7.24814800,00:01:00
      

      I also added cerebtro.run()

      However the same error persists.

      Here my current code

      import backtrader as bt
      
      class firstStrategy(bt.Strategy):
          params = (
              ('period', 21),
              )
      
          def __init__(self):
              self.startcash = self.broker.getvalue()
              self.rsi = bt.indicators.RSI_SMA(self.data.close, period=self.params.period)
      
          def next(self):
              if not self.position:
                  if self.rsi < 30:
                      self.buy(size=100)
              else:
                  if self.rsi > 70:
                      self.sell(size=100)
      
          def stop(self):
              pnl = round(self.broker.getvalue() - self.startcash,2)
              print('RSI Period: {} Final PnL: {}'.format(
                  self.params.period, pnl))
      
      if __name__ == '__main__':
          startcash = 10000
      
      cerebro = bt.Cerebro()
      
      cerebro.optstrategy(firstStrategy, period=range(14, 21))
      
      data = bt.feeds.GenericCSVData(dataname='/Users/giacomofederle/TRADINGBOT/crypto_bot_course/2020_1minute.csv',
                                     dtformat=('%Y-%m-%d'),
                                     tmformat=('%H:%M:%S'),
                                     datetime=0,
                                     open=1,
                                     high=2,
                                     low=3,
                                     close=4,
                                     volume=5,
                                     time=6,
                                     openinterest=-1)
      
      cerebro.adddata(data)
      
      cerebro.plot()
      
      cerebro.run()
      

      thank you again

      posted in General Code/Help
      G
      Giacomo
    • GenericCSVData - 'Cerebro' object has no attribute '_exactbars'

      Hi there,

      newbie here.
      I'm trying to feed to cerebro a csv file, this is my code:

      import backtrader as bt
      from binance.client import Client
      import pandas as pd
      
      class firstStrategy(bt.Strategy):
          params = (
              ('period', 21),
              )
      
          def __init__(self):
              self.startcash = self.broker.getvalue()
              self.rsi = bt.indicators.RSI_SMA(self.data.close, period=self.params.period)
      
          def next(self):
              if not self.position:
                  if self.rsi < 30:
                      self.buy(size=100)
              else:
                  if self.rsi > 70:
                      self.sell(size=100)
      
          def stop(self):
              pnl = round(self.broker.getvalue() - self.startcash,2)
              print('RSI Period: {} Final PnL: {}'.format(
                  self.params.period, pnl))
      
      if __name__ == '__main__':
          startcash = 10000
      
      cerebro = bt.Cerebro()
      
      cerebro.optstrategy(firstStrategy, period=range(14, 21))
      
      data = bt.feeds.GenericCSVData(dataname='..../2020_1minute.csv',
                                     dtformat=('%Y-%m-%d'),
                                     tmformat=('%H.%M.%S'),
                                     datetime=11,
                                     open=0,
                                     high=1,
                                     low=2,
                                     close=3,
                                     volume=4,
                                     time=12,
                                     openinterest=-1)
      
      
      cerebro.adddata(data)
      
      cerebro.plot()
      

      this is what the csv looks like

      ,open,high,low,close,volume,close_time,quote_asset_volume,number_of_trades,taker_buy_base_asset_volume,taker_buy_quite_asset_volume,ignore,date,time
      0,7195.24000000,7196.25000000,7183.14000000,7186.68000000,51.64281200,2020-01-01 00:00:59.999000072,371233.51835535,493,19.59823000,140888.41428273,0,2020-01-01,00:00:00
      1,7187.67000000,7188.06000000,7182.20000000,7184.03000000,7.24814800,2020-01-01 00:01:59.999000072,52080.12778780,135,2.03177200,14599.21192429,0,2020-01-01,00:01:00
      2,7184.41000000,7184.71000000,7180.26000000,7182.43000000,11.68167700,2020-01-01 00:02:59.999000072,83903.74163545,202,5.47924400,39357.08177646,0,2020-01-01,00:02:00
      

      ultimately the error I get is the following:

      AttributeError: 'Cerebro' object has no attribute '_exactbars'
      

      If anyone has any idea of what might be happening I would be very grateful for any hint!

      posted in General Code/Help
      G
      Giacomo
    • 1 / 1