Skip to content

Commit b4d04dc

Browse files
committed
BUG: Handle orders placed in the last strategy iteration
Fixes #158
1 parent 9137b71 commit b4d04dc

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

β€Žbacktesting/backtesting.pyβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,6 +1148,11 @@ def run(self, **kwargs) -> pd.Series:
11481148

11491149
# Next tick, a moment before bar close
11501150
strategy.next()
1151+
else:
1152+
# Re-run broker one last time to handle orders placed in the last strategy
1153+
# iteration. Use the same OHLC values as in the last broker iteration.
1154+
if start < len(self._data):
1155+
try_(broker.next, exception=_OutOfMoneyError)
11511156

11521157
# Set data back to full length
11531158
# for future `indicator._opts['data'].index` calls to work

β€Žbacktesting/test/_test.pyβ€Ž

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,18 @@ def next(self):
380380
bt = Backtest(GOOG, SmaCross, commission=.002)
381381
bt.run()
382382

383+
def test_close_orders_from_last_strategy_iteration(self):
384+
class S(Strategy):
385+
def init(self): pass
386+
387+
def next(self):
388+
if not self.position:
389+
self.buy()
390+
elif len(self.data) == len(SHORT_DATA):
391+
self.position.close()
392+
393+
self.assertFalse(Backtest(SHORT_DATA, S).run()._trades.empty)
394+
383395

384396
class TestStrategy(TestCase):
385397
def _Backtest(self, strategy_coroutine, **kwargs):

0 commit comments

Comments
Β (0)