@@ -1089,7 +1089,7 @@ def __init__(self,
1089
1089
trade_on_close = False ,
1090
1090
hedging = False ,
1091
1091
exclusive_orders = False ,
1092
- close_all_at_end = False
1092
+ finalize_trades = False ,
1093
1093
):
1094
1094
"""
1095
1095
Initialize a backtest. Requires data and a strategy to test.
@@ -1156,11 +1156,13 @@ def __init__(self,
1156
1156
trade/position, making at most a single trade (long or short) in effect
1157
1157
at each time.
1158
1158
1159
- If `close_all_at_end` is `False`, the trade will not be close at end,
1160
- and will not apear in _Stats.
1159
+ If `finalize_trades` is `True`, the trades that are still
1160
+ [active and ongoing] at the end of the backtest will be closed on
1161
+ the last bar and will contribute to the computed backtest statistics.
1161
1162
1162
1163
[FIFO]: https://www.investopedia.com/terms/n/nfa-compliance-rule-2-43b.asp
1163
- """
1164
+ [active and ongoing]: https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Strategy.trades
1165
+ """ # noqa: E501
1164
1166
1165
1167
if not (isinstance (strategy , type ) and issubclass (strategy , Strategy )):
1166
1168
raise TypeError ('`strategy` must be a Strategy sub-type' )
@@ -1213,7 +1215,7 @@ def __init__(self,
1213
1215
warnings .warn ('Data index is not datetime. Assuming simple periods, '
1214
1216
'but `pd.DateTimeIndex` is advised.' ,
1215
1217
stacklevel = 2 )
1216
- self . _close_all_at_end = bool ( close_all_at_end )
1218
+
1217
1219
self ._data : pd .DataFrame = data
1218
1220
self ._broker = partial (
1219
1221
_Broker , cash = cash , spread = spread , commission = commission , margin = margin ,
@@ -1222,6 +1224,7 @@ def __init__(self,
1222
1224
)
1223
1225
self ._strategy = strategy
1224
1226
self ._results : Optional [pd .Series ] = None
1227
+ self ._finalize_trades = bool (finalize_trades )
1225
1228
1226
1229
def run (self , ** kwargs ) -> pd .Series :
1227
1230
"""
@@ -1308,13 +1311,13 @@ def run(self, **kwargs) -> pd.Series:
1308
1311
# Next tick, a moment before bar close
1309
1312
strategy .next ()
1310
1313
else :
1311
- if self ._close_all_at_end is True :
1314
+ if self ._finalize_trades is True :
1312
1315
# Close any remaining open trades so they produce some stats
1313
1316
for trade in broker .trades :
1314
1317
trade .close ()
1315
1318
1316
- # Re-run broker one last time to handle orders placed in the last strategy
1317
- # iteration. Use the same OHLC values as in the last broker iteration.
1319
+ # HACK: Re-run broker one last time to handle close orders placed in the last
1320
+ # strategy iteration. Use the same OHLC values as in the last broker iteration.
1318
1321
if start < len (self ._data ):
1319
1322
try_ (broker .next , exception = _OutOfMoneyError )
1320
1323
0 commit comments