refactor: Simplify backtest code slightly

This should also slighly improve performance for detail backtests
as it removes one comparison
This commit is contained in:
Matthias 2024-10-12 11:34:13 +02:00
parent bd7f0383d1
commit 883122a98b

View File

@ -1332,9 +1332,8 @@ class Backtesting:
row: tuple,
pair: str,
current_time: datetime,
end_date: datetime,
trade_dir: Optional[LongShort],
is_first: bool = True,
can_enter: bool,
) -> None:
"""
NOTE: This method is used by Hyperopt at each iteration. Please keep it optimized.
@ -1355,8 +1354,7 @@ class Backtesting:
# We only open trades on the main candle, not on detail candles
if (
(self._position_stacking or len(LocalTrade.bt_trades_open_pp[pair]) == 0)
and is_first
and current_time != end_date
and can_enter
and trade_dir is not None
and not PairLocks.is_pair_locked(pair, row[DATE_IDX], trade_dir)
):
@ -1444,6 +1442,7 @@ class Backtesting:
row_index += 1
indexes[pair] = row_index
is_last_row = current_time == end_date
self.dataprovider._set_dataframe_max_index(self.required_startup + row_index)
self.dataprovider._set_dataframe_max_date(current_time)
current_detail_time: datetime = row[DATE_IDX].to_pydatetime()
@ -1467,7 +1466,7 @@ class Backtesting:
if len(detail_data) == 0:
# Fall back to "regular" data if no detail data was found for this candle
self.dataprovider._set_dataframe_max_date(current_time)
self.backtest_loop(row, pair, current_time, end_date, trade_dir)
self.backtest_loop(row, pair, current_time, trade_dir, not is_last_row)
continue
detail_data.loc[:, "enter_long"] = row[LONG_IDX]
detail_data.loc[:, "exit_long"] = row[ELONG_IDX]
@ -1483,15 +1482,14 @@ class Backtesting:
det_row,
pair,
current_time_det,
end_date,
trade_dir,
is_first,
is_first and not is_last_row,
)
current_time_det += self.timeframe_detail_td
is_first = False
else:
self.dataprovider._set_dataframe_max_date(current_time)
self.backtest_loop(row, pair, current_time, end_date, trade_dir)
self.backtest_loop(row, pair, current_time, trade_dir, not is_last_row)
self.handle_left_open(LocalTrade.bt_trades_open_pp, data=data)
self.wallets.update()