Skip to content

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

@NutchapolSal

Description

@NutchapolSal

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions