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

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
        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:

                    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 -

    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/", line 74, in <module>
    	strategies =
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\", line 809, in run
    	runstrat = self.runstrategies(iterstrat)
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\", line 934, in runstrategies
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\", line 417, in _stop
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\", line 194, in _stop
      File "C:\Users\Home\AppData\Local\Programs\Python\Python35-32\lib\site-packages\backtrader\analyzers\", 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