Skip to content

Commit

Permalink
ENH: Add the possibility to let unclose trades at end of bt.run (#273)
Browse files Browse the repository at this point in the history
  • Loading branch information
Benouare committed Mar 10, 2021
1 parent 73e1534 commit 9eba337
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
22 changes: 12 additions & 10 deletions backtesting/backtesting.py
Original file line number Diff line number Diff line change
Expand Up @@ -984,7 +984,8 @@ def __init__(self,
margin: float = 1.,
trade_on_close=False,
hedging=False,
exclusive_orders=False
exclusive_orders=False,
close_all_at_end=True
):
"""
Initialize a backtest. Requires data and a strategy to test.
Expand Down Expand Up @@ -1078,7 +1079,7 @@ def __init__(self,
warnings.warn('Data index is not datetime. Assuming simple periods, '
'but `pd.DateTimeIndex` is advised.',
stacklevel=2)

self._close_all_at_end = close_all_at_end
self._data: pd.DataFrame = data
self._broker = partial(
_Broker, cash=cash, commission=commission, margin=margin,
Expand Down Expand Up @@ -1164,14 +1165,15 @@ def run(self, **kwargs) -> pd.Series:
# Next tick, a moment before bar close
strategy.next()
else:
# Close any remaining open trades so they produce some stats
for trade in broker.trades:
trade.close()

# Re-run broker one last time to handle orders placed in the last strategy
# iteration. Use the same OHLC values as in the last broker iteration.
if start < len(self._data):
try_(broker.next, exception=_OutOfMoneyError)
if self._close_all_at_end is True:
# Close any remaining open trades so they produce some stats
for trade in broker.trades:
trade.close()

# Re-run broker one last time to handle orders placed in the last strategy
# iteration. Use the same OHLC values as in the last broker iteration.
if start < len(self._data):
try_(broker.next, exception=_OutOfMoneyError)

# Set data back to full length
# for future `indicator._opts['data'].index` calls to work
Expand Down
25 changes: 25 additions & 0 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,31 @@ def next(self):

self.assertFalse(Backtest(SHORT_DATA, S).run()._trades.empty)

def test_dont_close_orders_from_last_strategy_iteration(self):
class S(Strategy):
def init(self): pass

def next(self):
if not self.position:
self.buy()
elif len(self.data) == len(SHORT_DATA):
self.position.close()
self.assertEqual(len(
Backtest(SHORT_DATA, S, close_all_at_end=False).run()._strategy.closed_trades), 0)
self.assertEqual(len(
Backtest(SHORT_DATA, S, close_all_at_end=False).run()._strategy.trades), 1)

def test_dont_close_orders_trades_from_last_strategy_iteration(self):
class S(Strategy):
def init(self): pass

def next(self):
if not self.position:
self.buy()

self.assertGreater(len(
Backtest(SHORT_DATA, S, close_all_at_end=False).run()._strategy.trades), 0)

def test_check_adjusted_price_when_placing_order(self):
class S(Strategy):
def init(self): pass
Expand Down

0 comments on commit 9eba337

Please sign in to comment.