ZeroDivisionError: float division by zero (SharpeRatio)



  • I made too wary strategy, which had no one trades, even positions.
    Yet if it uses SharpeRatio, ZeroDivisionError apper in this code:

    class SharpeRatio(Analyzer):
    ...
        ratio = ret_free_avg / retdev
    ...
    

    due to retdev is zero.

    It was patched dirty by:

    if retdev != 0:
        ratio = ret_free_avg / retdev
    else:
        ratio = 0
    

    Is it correct? Happy NY!



  • bt's Sharpe Ratio can give you zero division mistake if you use less than 1 year of data.



  • Hm. I changer data range to 2 years - same result.


  • administrators

    That must be an old version of backtrader. This behavior is wrapped in an try/except block which will assign None to the ratio if the operation cannot be performed.

    Actual code:

    
                try:
                    ratio = ret_free_avg / retdev
    
                    if factor is not None and \
                       self.p.convertrate and self.p.annualize:
    
                        ratio = math.sqrt(factor) * ratio
                except (ValueError, TypeError):
                    ratio = None
    


  • Yes. Same code I saw in my copy of backtrader - 1.9.20.105.

    The problem is that traceback fills the console:

    Starting Portfolio Value: 1000.00
    Buys total 0, profit percents 0.00
    Sells total 0, profit percents 0.00
    ---
    2015-12-30, Ending value 1000.00
    Traceback (most recent call last):
      File "D:/Projects/trading-bot/main/lab/backtrader/netflix.py", line 74, in <module>
    	strategies = back_trader.run()
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\cerebro.py", line 809, in run
    	runstrat = self.runstrategies(iterstrat)
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\cerebro.py", line 934, in runstrategies
    	strat._stop()
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\strategy.py", line 417, in _stop
    	analyzer._stop()
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\analyzer.py", line 194, in _stop
    	self.stop()
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\analyzers\sharpe.py", line 178, in stop
    	ratio = ret_free_avg / retdev
    ZeroDivisionError: float division by zero

  • administrators

    In this case and even if ZeroDivisionError is defined in Python 2.7, the original tests showed the existing exceptions enough to catch the problem. Will be added.



  • Great, thank you!


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.