Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow open trades at end of backtest. #1102

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ doc/build/*
*~*

.venv/
build/*
18 changes: 13 additions & 5 deletions backtesting/backtesting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,8 @@ def __init__(self,
margin: float = 1.,
trade_on_close=False,
hedging=False,
exclusive_orders=False
exclusive_orders=False,
leave_orders_open=False
):
"""
Initialize a backtest. Requires data and a strategy to test.
Expand Down Expand Up @@ -1073,7 +1074,11 @@ def __init__(self,

If `exclusive_orders` is `True`, each new order auto-closes the previous
trade/position, making at most a single trade (long or short) in effect
at each time.
at each time.

If `leave_orders_open` is `True`, trades are not automatically closed at
completion of the backtest. This allows strategies to be run in a "forward"
manner, where a user can see open trades with updated data.

[FIFO]: https://www.investopedia.com/terms/n/nfa-compliance-rule-2-43b.asp
"""
Expand Down Expand Up @@ -1133,6 +1138,7 @@ def __init__(self,
)
self._strategy = strategy
self._results: Optional[pd.Series] = None
self.leave_orders_open = leave_orders_open

def run(self, **kwargs) -> pd.Series:
"""
Expand Down Expand Up @@ -1218,9 +1224,11 @@ 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()
# Close any remaining open trades so they produce some stats
# if self.leave_orders_open is False
if self.leave_orders_open is False:
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.
Expand Down