Skip to content

Commit 0d36e37

Browse files
elpoliniElpolinikernc
authored
BUG: Fix MultiBacktest with some no-trade results (#1366)
* fix: handle mixed no-trade MultiBacktest results * Make class non-local and simplify assertions Fixes CI error: > AttributeError: Can't get local object 'TestLib.test_MultiBacktest_handles_mixed_no_trade_results.<locals>.SometimesNoTrade' --------- Co-authored-by: Elpolini <contacto@elpolini.com> Co-authored-by: kernc <kerncece@gmail.com>
1 parent e6e0299 commit 0d36e37

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

β€Žbacktesting/lib.pyβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,7 @@ def _mp_task_run(args):
608608
data_shm, strategy, bt_kwargs, run_kwargs = args
609609
dfs, shms = zip(*(SharedMemoryManager.shm2df(i) for i in data_shm))
610610
try:
611-
return [stats.filter(regex='^[^_]') if stats['# Trades'] else None
611+
return [stats.filter(regex='^[^_]')
612612
for stats in (Backtest(df, strategy, **bt_kwargs).run(**run_kwargs)
613613
for df in dfs)]
614614
finally:

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1067,6 +1067,25 @@ def test_MultiBacktest(self):
10671067
print(start_method, time.monotonic() - start_time)
10681068
plot_heatmaps(heatmap.mean(axis=1), open_browser=False)
10691069

1070+
class SometimesNoTrade(Strategy):
1071+
def init(self):
1072+
self._will_trade = len(self.data) == 20
1073+
1074+
def next(self):
1075+
if not self._will_trade:
1076+
return
1077+
if self.position:
1078+
self.position.close()
1079+
elif not self.closed_trades:
1080+
self.buy()
1081+
1082+
def test_MultiBacktest_handles_mixed_no_trade_results(self):
1083+
btm = MultiBacktest([GOOG.iloc[:20], GOOG.iloc[:21], GOOG.iloc[:22]],
1084+
self.SometimesNoTrade, cash=100_000)
1085+
res = btm.run()
1086+
self.assertEqual(res.loc['# Trades'].tolist(), [1, 0, 0])
1087+
self.assertNotIsInstance(res.iloc[0, 0], pd.Series)
1088+
10701089

10711090
class TestUtil(TestCase):
10721091
def test_as_str(self):

0 commit comments

Comments
Β (0)