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/

    Problem with analyzers of optstrategy

    General Code/Help
    4
    5
    1377
    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.
    • K
      kawaseiryuu last edited by kawaseiryuu

      Hi!
      I meet some errors when I try to add analyzers to optstrategy. I test several analyzers such as SharpeRatio, Returns, and Pyfolio, only Returns can get a correct output while SharpeRatio and Pyfolio show errors as below. If I change to addstrategy, they all go well.

      Exception in thread Thread-3:
      Traceback (most recent call last):
        File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
          self.run()
        File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
          self._target(*self._args, **self._kwargs)
        File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 463, in _handle_results
          task = get()
        File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 251, in recv
          return _ForkingPickler.loads(buf.getbuffer())
      AttributeError: Can't get attribute 'Lines_LineSeries_LineIterator_DataAccessor_ObserverBase_Observer_DataTrades_fa4c53589de546008b442399c00e4727' on <module 'backtrader.lineseries' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/backtrader/lineseries.py'>
      

      The code:

      def runstrat():
          args = parse_args()
      
          # Create a cerebro entity
          cerebro = bt.Cerebro()
      
          # Handy dictionary for the argument timeframe conversion
          tframes = dict(
              ticks=bt.TimeFrame.Ticks,
              microseconds=bt.TimeFrame.MicroSeconds,
              seconds=bt.TimeFrame.Seconds,
              minutes=bt.TimeFrame.Minutes,
              daily=bt.TimeFrame.Days,
              weekly=bt.TimeFrame.Weeks,
              monthly=bt.TimeFrame.Months
          )
      
          # Load the Data
          data0 = btfeeds.GenericCSVData(
              dataname=args.datapath,
              fromdate=args.startdate,
              todate=args.enddate,
              dtformat=args.dtformat,
              timeframe=tframes[args.rawtframe],
          )
      
          data1 = btfeeds.GenericCSVData(
              dataname=args.datapath,
              fromdate=args.startdate,
              todate=args.enddate,
              dtformat=args.dtformat,
              timeframe=tframes[args.rawtframe],
          )
      
          # First add the original data - smaller timeframe
          cerebro.resampledata(
              data0,
              timeframe=tframes[args.tframe],
              compression=args.compression,
          )
      
          cerebro.resampledata(
              data1,
              timeframe=tframes[args.tframe],
              compression=args.compression,
          )
      
          cerebro.addanalyzer(bt.analyzers.SharpeRatio, timeframe=bt.TimeFrame.Days, riskfreerate=0.03)
          cerebro.addanalyzer(bt.analyzers.Returns, timeframe=bt.TimeFrame.Days)
      
          cerebro.optstrategy(
              MyStrategy,
              maperiod=args.period,
              matype=args.matype,
              stoplose=args.stoplose
          )
      
          cerebro.broker.setcash(args.capital)
          cerebro.addsizer(bt.sizers.FixedSize, stake=args.stakesize)
      
          comminfo = CommInfo_Bonds_Perc(commission=args.commperc)
          cerebro.broker.addcommissioninfo(comminfo)
      
          # Run over everything
          results = cerebro.run()
      
          strats = [x[0] for x in results]
      
          for strat in enumerate(strats):
              print('Returns:', strat.analyzers.returns.get_analysis())
              print('Sharpe Ratio:', strat.analyzers.sharperatio.get_analysis())
      

      Appreciation for any help.

      1 Reply Last reply Reply Quote 0
      • B
        backtrader administrators last edited by

        That's for a non-analyzer related error. Use in any case stdstats=False when creating a Cerebro or when doing cerebro.run, to disable the automatically added Observers

        K 1 Reply Last reply Reply Quote 0
        • K
          kawaseiryuu @backtrader last edited by

          @backtrader Thanks! It better solves my problem.

          1 Reply Last reply Reply Quote 0
          • Shivanshu Bohara
            Shivanshu Bohara last edited by

            How do you get that which Return and Sharpe Ratio corresponds to which map period and stop loss?

            B 1 Reply Last reply Reply Quote 0
            • B
              benmercerdev @Shivanshu Bohara last edited by

              @Shivanshu-Bohara given the code example from above you could print out the params for each, like this:

              
                  strats = [x[0] for x in results]
              
                  for strat in enumerate(strats):
                      print('Params: ', s.p._kwargs())
                      print('Returns:', strat.analyzers.returns.get_analysis())
                      print('Sharpe Ratio:', strat.analyzers.sharperatio.get_analysis())
              
              1 Reply Last reply Reply Quote 0
              • 1 / 1
              • First post
                Last post
              Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors