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

Analyzers.Returns - ValueError: math domain error

  • I often face an error using this analyzer during optimization.

    cerebro.addanalyzer(bt.analyzers.Returns, _name='return')

    Full traceback:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\multiprocessing\", line 119, in worker
        result = (True, func(*args, **kwds))
      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\", line 1007, in __call__
        return self.runstrategies(iterstrat, predata=predata)
      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\", line 1301, in runstrategies
      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\", line 464, in _stop
      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\", line 200, in _stop
      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\analyzers\", line 128, in stop
        math.log(self._value_end / self._value_start))
    ValueError: math domain error
    The above exception was the direct cause of the following exception:
    Traceback (most recent call last):
      File "Optimize", line 156, in <module>
        bt_tools.optimization(strategy, params)
      File "..\", line 327, in optimization
        def optimization_results_handler(self, results_raw):
      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\", line 1143, in run
        for r in pool.imap(self, iterstrats):
      File "C:\ProgramData\Anaconda3\lib\multiprocessing\", line 735, in next
        raise value
    ValueError: math domain error

  • Just as a guess - looks like it comes frommath.log which means that self._value_end / self._value_start is less than or equal to zero. So check the equity numbers, maybe it goes to zero some how.

  • to fix this added two lines:

            # Compound return
            if self._value_end <= 0:
                self._value_end = 0.00001
            self.rets['rtot'] = rtot = (
                math.log(self._value_end / self._value_start))

    it may be not the best solution, but it works

  • administrators

    The proper value should/would be float('-inf'), which is what the logarithmic function tends to when it approaches zero.

    There is a fix in the development branch at:

  • @backtrader

    I get the same error with bt.analyzers.LogReturnsRolling and as far as I understood the problem the issue was also a 0 in the calculation. I assume that a similar fix could be the solution?

    Once I also stumbled uppon a zero division error in the vwr analyzer in line 154 of (dt = pn / (pi * math.exp(ravg * n)) - 1.0)

    Best, J