Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(strategy-discovery): resolve position size per regime, not once for the whole run

Lanre Shittu189f4d05512c
diff --git a/agent/src/strategy_discovery/evidence_harness.py b/agent/src/strategy_discovery/evidence_harness.py
index 92f82219e..add6de265 100644
--- a/agent/src/strategy_discovery/evidence_harness.py
+++ b/agent/src/strategy_discovery/evidence_harness.py
@@ -484,7 +484,6 @@ def compute_evidence_for_run(
unlabeled_trades,
)
- resolved_size = _resolve_position_size(position_size, exposures)
breakeven_caveat = _breakeven_caveat(max_concurrent)
last_verified = (
today if isinstance(today, str) and today else date.today().isoformat()
@@ -500,12 +499,16 @@ def compute_evidence_for_run(
if trades_in_regime < 1:
continue
bar_indices = [i for i, label in enumerate(regime_per_bar) if label == regime]
+ regime_exposures = [
+ value for i in bar_indices if (value := exposures[i]) is not None
+ ]
+ resolved_size = _resolve_position_size(position_size, regime_exposures)
strategy_returns = _bar_returns(bar_indices, equities)
compounded_return = _compounded(strategy_returns)
benchmark_compounded: float | None = None
- if all(value is not None for value in benchmarks):
+ if all(benchmarks[i] is not None for i in bar_indices):
benchmark_returns = _bar_returns(bar_indices, benchmarks) # type: ignore[arg-type]
benchmark_compounded = _compounded(benchmark_returns)
excess = (
diff --git a/agent/src/strategy_discovery/run_artifacts.py b/agent/src/strategy_discovery/run_artifacts.py
index aacc28848..f5076ed97 100644
--- a/agent/src/strategy_discovery/run_artifacts.py
+++ b/agent/src/strategy_discovery/run_artifacts.py
@@ -235,8 +235,9 @@ def read_trade_dates(path: Path) -> list[date] | None:
def read_equity_series(
path: Path,
-) -> tuple[list[date], list[float], list[float | None], list[float]] | None:
- """(dates, equity, benchmark-or-None-per-bar, exposures) from ``equity.csv``.
+) -> tuple[list[date], list[float], list[float | None], list[float | None]] | None:
+ """(dates, equity, benchmark-or-None-per-bar, exposure-or-None-per-bar) from
+ ``equity.csv``.
Column aliases: the date column is ``timestamp`` in engine artifacts
(legacy ``date`` still parses); the benchmark column is
@@ -245,6 +246,11 @@ def read_equity_series(
value are skipped. Returns ``None`` when the file lacks a usable
date/equity column pair, contains no usable rows, or is unreadable
(decode / OS / CSV errors degrade instead of raising).
+
+ Exposure is aligned to bar position like benchmark, ``None`` where the
+ column is absent or the value isn't a finite positive number, so a
+ caller can slice it by the same ``bar_indices`` used for every other
+ per-bar series instead of a compacted, position-losing subsequence.
"""
try:
with path.open(newline="", encoding="utf-8-sig") as handle:
@@ -296,7 +302,8 @@ def read_equity_series(
equities = [values[0] for _, values in ordered]
benchmarks = [values[1] for _, values in ordered]
exposures = [
- values[2] for _, values in ordered if values[2] is not None and values[2] > 0
+ values[2] if values[2] is not None and values[2] > 0 else None
+ for _, values in ordered
]
return dates, equities, benchmarks, exposures
diff --git a/agent/tests/test_strategy_discovery_harness.py b/agent/tests/test_strategy_discovery_harness.py
index 879433287..fa58b1257 100644
--- a/agent/tests/test_strategy_discovery_harness.py
+++ b/agent/tests/test_strategy_discovery_harness.py
@@ -124,6 +124,30 @@ def _engine_equity_frame() -> pd.DataFrame:
return eq_df
+def _engine_equity_frame_with_regime_exposure(
+ bear_exposure: float, bull_exposure: float, other_exposure: float = 1.0
+) -> pd.DataFrame:
+ """Same frame as _engine_equity_frame, plus an exposure column that
+ differs between the bear-labeled bars (index 8..17) and the
+ bull-labeled bars (index 18..27).
+
+ These are the harness's own trailing-window regime labels for
+ benchmark_window=5/bear_threshold=-0.05/bull_threshold=0.05 (the
+ fixed windows _compute_with_fixture_windows always uses), not the
+ raw curve's decline/rally span from _benchmark_series — the 5-bar
+ trailing anchor keeps the bear label through two bars of the actual
+ rally before the rolling return clears the threshold, confirmed via
+ the harness's own regime labeler."""
+ eq_df = _engine_equity_frame()
+ exposure = [other_exposure] * DAYS
+ for i in range(8, 18):
+ exposure[i] = bear_exposure
+ for i in range(18, 28):
+ exposure[i] = bull_exposure
+ eq_df["exposure"] = exposure
+ return eq_df
+
+
def _entry_row(trade_date: date, code: str) -> dict:
return {
"timestamp": trade_date.strftime("%Y-%m-%d"),
@@ -242,6 +266,33 @@ def _write_run_fixture(
return run_dir
+def _write_run_fixture_with_regime_exposure(
+ base_dir: Path, *, bear_exposure: float, bull_exposure: float
+) -> Path:
+ """Same as _write_run_fixture but equity.csv carries a per-regime
+ exposure column instead of none at all."""
+ run_dir = base_dir / "run_fixture"
+ artifacts = run_dir / "artifacts"
+ artifacts.mkdir(parents=True, exist_ok=True)
+
+ _engine_equity_frame_with_regime_exposure(bear_exposure, bull_exposure).to_csv(
+ artifacts / "equity.csv"
+ )
+
+ round_trips = [
+ (
+ trade_date,
+ "TEST.SH",
+ 50.0,
+ "signal" if i < 8 else "end",
+ )
+ for i, trade_date in enumerate(ALL_TRADE_DAYS)
+ ]
+ _write_trades_csv(artifacts, _engine_trade_rows(round_trips))
+ _write_run_state(run_dir, trade_count=len(ALL_TRADE_DAYS))
+ return run_dir
+
+
def _write_multi_position_fixture(base_dir: Path) -> Path:
"""Two overlapping holdings: AAA Jan 14-16 and BBB Jan 15-21 → peak 2."""
run_dir = base_dir / "multi_position_run"
@@ -480,6 +531,20 @@ class TestComputeEvidence:
f"(full={full}, half={half})"
)
+ def test_position_size_is_resolved_per_regime_not_blended_across_run(
+ self, tmp_path
+ ) -> None:
+ # Exposure-derived sizing (no explicit position_size) must use each
+ # regime's own bars, not a single whole-run average that leaks the
+ # bear window's exposure into the bull window's breakeven math.
+ run_dir = _write_run_fixture_with_regime_exposure(
+ tmp_path, bear_exposure=0.25, bull_exposure=0.75
+ )
+ rows = _compute_with_fixture_windows(run_dir)
+ by_regime = {row.regime: row for row in rows}
+ assert by_regime["bear_market"].position_size == pytest.approx(0.25)
+ assert by_regime["bull_market"].position_size == pytest.approx(0.75)
+
def test_single_position_run_carries_no_concurrency_caveat(self, tmp_path) -> None:
run_dir = _write_run_fixture(tmp_path)
rows = _compute_with_fixture_windows(run_dir)