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/

    How to loop throug cerebro?

    Indicators/Strategies/Analyzers
    2
    5
    32
    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.
    • C
      chhrissi2909 last edited by

      Hello,

      I am trying to backtest some stocks at ones. To solve this I want to loop through the cerebro for every stock in the code.

      When I do that, than the code perfectly runs and calculates my resuluts, but when the code goes into the second loop, than I get an error message like this:

      Traceback (most recent call last):
        File "d:\Desktop\DonchianMT5Data_alle_Stocks.py", line 309, in <module>
          results = cerebro.run(tradehistory=True)
        File "C:\Python\lib\site-packages\backtrader\cerebro.py", line 1127, in run
          runstrat = self.runstrategies(iterstrat)
        File "C:\Python\lib\site-packages\backtrader\cerebro.py", line 1257, in runstrategies
          strat._addanalyzer(ancls, *anargs, **ankwargs)
        File "C:\Python\lib\site-packages\backtrader\strategy.py", line 247, in _addanalyzer
          analyzer = ancls(*anargs, **ankwargs)
      TypeError: 'list' object is not callable
      PS D:\Desktop> 
      

      the code in the cerebro part looks like this:

      
      symbolpfad = "D:\Desktop\ZigZag Freelancer\MT5_Daten\SPX_Symbole komplett1.csv"
      symbolliste = pd.read_csv(symbolpfad)
      if __name__ == '__main__':
          ## ----------------------------------------------- Prepare Backtestfeed -----------------------------------------------
          # Find Data.
          for i in range(len(symbolliste)):
              cerebro = bt.Cerebro()
              datapath = "D:/Desktop/ZigZag/strategy/data_Tiingo/SPX/"+symbolliste.Symbol[i]+".csv"
              data_df = pd.read_csv(datapath,
                                      index_col=0, 
                                      usecols=["time", "open","high", "low", "close"])
              data_df.index = pd.to_datetime(data_df.index)
              feed = bt.feeds.PandasData(dataname=data_df) 
              cerebro.adddata(feed)
              cerebro.broker.setcash(STARTING_CAP)
              cerebro.broker.setcommission(commission=COMMISSION, leverage=2)
      
              # Add Analyzers
              cerebro.addanalyzer(MaxDD, _name='max_dd')
              cerebro.addanalyzer(HitRate, _name='hit_rate')
              cerebro.addanalyzer(TotalTrades, _name='total_trades')
              cerebro.addanalyzer(trade_list, _name='trade_list')
              cerebro.addanalyzer(btanalyzers.SharpeRatio, _name='sharpe', riskfreerate=0.0)
              cerebro.addstrategy(NoStrategy, period_high=DONCHIAN_HIGH,
                                              period_low=DONCHIAN_LOW,
                                              lookback=0,
                                              risk=RISK,
                                              Einstiegs_Puffer=EINSTIEGS_PUFFER,
                                              Ausstiegs_Puffer=AUSSTIEGS_PUFFER,
                                              Use_TSL_close=USE_TSL_CLOSE)
      
              ## Run Backtest ---------------------------------------------------
              # Print out the starting conditions
              print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
              # Run over everything
              results = cerebro.run(tradehistory=True)
              # Print out the final result
              print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
              rendite = round(( (cerebro.broker.getvalue()/STARTING_CAP) - 1)*100,2)
              # Print Analyzers
      
              # Plot
              trade_list = results[0].analyzers.trade_list.get_analysis()
              tabulate(trade_list, headers="keys")
              #print (tabulate(trade_list, headers="keys"))
              
              trade_list_df = pd.DataFrame(trade_list) 
              print(trade_list_df)
      
      1. Is it even possible to loop through cerebro for more than 20 Stocks an save the resuluts f.e. in a excel?
      2. If yes, what is wrong with my code?

      best regards
      Chrsitian

      C run-out 2 Replies Last reply Reply Quote 0
      • C
        chhrissi2909 @chhrissi2909 last edited by

        @chhrissi2909 line 309 is this line:

        results = cerebro.run(tradehistory=True)
        
        1 Reply Last reply Reply Quote 0
        • run-out
          run-out @chhrissi2909 last edited by

          @chhrissi2909 said in How to loop throug cerebro?:

          File "C:\Python\lib\site-packages\backtrader\strategy.py", line 247, in _addanalyzer
          analyzer = ancls(*anargs, **ankwargs)
          TypeError: 'list' object is not callable

          This error has shown up for me from time to time, usually when my backtest has no trades. This will be in your anlyzers. Turn off all your analyzers and see if the backtest runs. If so, turn on the analyzers one by one to find the culprit.

          C 2 Replies Last reply Reply Quote 0
          • C
            chhrissi2909 @run-out last edited by

            @run-out Yes you are right. This is because of the trade_list.

            If I comment the trade_list results out like this...

                    #trade_list = results[0].analyzers.trade_list.get_analysis()
                    #tabulate(trade_list, headers="keys")
            

            ... than the code works fine. But I need the results of the trade list. (this is why I make the backtest ^^)

            1 Reply Last reply Reply Quote 1
            • C
              chhrissi2909 @run-out last edited by

              @run-out Hey I found the error!!!

              here I found the solution: https://community.backtrader.com/topic/2582/run-multiple-data-in-for-loop

              I gave my trade_list class an other name. In my example I gave it the name "Trade_The_List" and than I replaced it in the analyzer like this:

              cerebro.addanalyzer(Trade_The_List, _name='trade_list')
              

              now it works :)

              thank you for your help!

              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(); }); }