For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Unable to get the correct key to generate Sharpe Ratio

  • Hello,

    I define these functions to print out SQN, SharpeRatio and drawdown info. Both SQN and Drawdown info are generated, but I'm running into this error for SharpeRatio. Seems like I'm using the wrong key 'sharperatio' that is holding the ratio value?

    AttributeError Traceback (most recent call last)
    <ipython-input-22-de114c2a5d1c> in <module>()
    232 printSQN(thestrat.analyzers.sqn.get_analysis())
    233 print('Sharpe Ratio:',thestrat.analyzers.mysharpe.get_analysis())
    --> 234 printSharpeRatio(thestrat.analyzers.mysharpe.get_analysis())
    235 printDrawDown(thestrat.analyzers.DrawDown.get_analysis())

    <ipython-input-22-de114c2a5d1c> in printSharpeRatio(analyzer)
    163 print('SQN: {}'.format(sqn))
    164 def printSharpeRatio(analyzer):
    --> 165 SharpeRatio = round(analyzer.sharperatio,3)
    166 print('Sharpe Ratio: {}'.format(SharpeRatio))
    167 def printDrawDown(analyzer):

    AttributeError: 'collections.OrderedDict' object has no attribute 'sharperatio'

    My code:

    # print functions
    def printSQN(analyzer):
    sqn = round(analyzer.sqn,2)
    print('SQN: {}'.format(sqn))
    def printSharpeRatio(analyzer):
    SharpeRatio = round(analyzer.sharperatio,3)
    print('Sharpe Ratio: {}'.format(SharpeRatio))
    def printDrawDown(analyzer):
    drawdown = round(analyzer.drawdown,2)
    moneydown = round(analyzer.moneydown,2)
    duration = analyzer.len
    maxdrawdown = round(analyzer.max.drawdown,2)
    maxmoneydown = round(analyzer.max.moneydown,2)
    maxduration = analyzer.max.len
    print('Drawdown %    : {}, Drawdown $    : {}, Duration    : {}'.format(drawdown,moneydown,duration))
    print('Max Drawdown %: {}, Max Drawdown $: {}, Max Duration: {}'.format(maxdrawdown,maxmoneydown,maxduration))
    # Analyzer
    cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='mysharpe')
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name='DrawDown')
    # print the analyzers

  • Did some workaround. not sure if this is the best way. Tks all for reading. Cheers.

    def printSharpeRatio(analyzer):
      od = thestrat.analyzers.mysharpe.get_analysis()
      for key, value in od.items(): 
          print('Sharpe Ratio:', round(value,3))


    Sharpe Ratio: 1.385

  • The analyzer SharpeRatio returns a ditionary with key/value combination.

    {'sharperatio': 11.647332609673256}

    You can work with this as you see fit so your answer is indeed a correct way to work with this analyzer.

  • @run-out Tks for your reply. :)

Log in to reply