backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

MultiBacktest.run errors out when tested strategy sometimes never enters a position

Open NutchapolSal opened this issue 10 months ago • 2 comments

Expected behavior

MultiBacktest.run should correctly handle when strategy chooses not to enter any positions and return a sensible dataframe

Code sample

import random
from backtesting.test import GOOG

# will_buys = [True, True, True, True, True] # works, returns series
# will_buys = [False, False, False, False, False] # works, returns series of None
will_buys = [True, False, False, False, False] # errors
# will_buys = [False, True, False, False, False] # works but returns a weird nested series thing
# note the effect of (not) buying in the first tested instrument
class TestStrat(Strategy):
    def init(self):
        self.will_buy = will_buys[len(self.data.index) - 2144]
        self.has_bought = False

    def next(self):
        if not self.will_buy:
            return
        
        if self.position:
            self.position.close()
        
        if not self.has_bought:
            self.buy()
            self.has_bought = True
        

print(will_buys)

bt = MultiBacktest([GOOG[:-4],GOOG[:-3],GOOG[:-2],GOOG[:-1],GOOG], TestStrat,
               cash=10000, commission=.002,
               exclusive_orders=True)
bt.run()

Actual behavior

MultiBacktest.run errors out with TypeError: object of type 'NoneType' has no len() or returns an undocumented nested dataframe(?) object

Additional info, steps to reproduce, full crash traceback, screenshots

No response

Software versions

  • backtesting.__version__: 0.6.5
  • pandas.__version__: 3.0.0
  • numpy.__version__: 2.4.1
  • bokeh.__version__: 3.8.2
  • OS: Windows 11

NutchapolSal avatar Jan 25 '26 13:01 NutchapolSal

I've found the cause: L611 of backtesting/lib.py - stats.filter(regex='^[^_]') if stats['# Trades'] else None

removing if stats['# Trades'] else None fixes both cases. the "statistics" you get (instead of None) is one that Backtest.run already computes for strategies that do nothing.

NutchapolSal avatar Jan 25 '26 14:01 NutchapolSal

Can confirm the root cause @NutchapolSal found. The conditional if stats['# Trades'] else None short-circuits to None when the strategy has zero trades, but MultiBacktest.run doesn't handle None in the resulting series correctly. Dropping the conditional and always returning the stats object (with 0 trades) is the right fix since Backtest.run already populates valid stats for no-trade strategies.

atharvajoshi01 avatar Apr 08 '26 01:04 atharvajoshi01