"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): harden scheduled rebalancing
thisisjun78649b6c0559d44
diff --git a/README.md b/README.mdindex 9eaa483f3..c1a42fc5e 100644--- a/README.md+++ b/README.md@@ -1126,9 +1126,12 @@ select execution bars in `config.json`:`MS` executes the aligned target on the first observed trading bar of eachmonth. Weekly/quarterly pandas offset aliases (for example `W-FRI` and `QS`) and-explicit ISO date lists are also accepted. Omit `rebalance_mask` to preserve-the existing every-bar rebalance behavior. A mask is deliberately incompatible-with `position_adjustment="hold"`.+explicit ISO date lists are also accepted. An alias must not be finer than the+aligned bar interval. Period aliases select the first observed bar in each+period; `W-FRI` starts a Friday-anchored week and therefore normally executes+on the following Monday, not on Friday itself. Omit `rebalance_mask` to+preserve the existing every-bar rebalance behavior. A mask is deliberately+incompatible with `position_adjustment="hold"`.**Bench a pre-built alpha zoo** (one line):```bashdiff --git a/agent/backtest/rebalance_mask.py b/agent/backtest/rebalance_mask.pyindex 67db191df..7948758e1 100644--- a/agent/backtest/rebalance_mask.py+++ b/agent/backtest/rebalance_mask.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom bisect import bisect_leftfrom datetime import date-from typing import TypeAlias+from typing import TypeAlias, castimport pandas as pdfrom pandas.tseries.frequencies import to_offset@@ -56,23 +56,39 @@ def resolve_rebalance_dates(raise ValueError("rebalance_mask does not intersect the aligned trading dates")if isinstance(validated, str):+ offset = to_offset(validated)+ bounds = dates.asi8.tolist()+ if len(bounds) > 1:+ minimum_spacing = min(+ current - previous+ for previous, current in zip(bounds, bounds[1:])+ if current > previous+ )+ try:+ offset_nanos = offset.nanos+ except ValueError:+ pass+ else:+ if offset_nanos < minimum_spacing:+ raise ValueError(+ "rebalance_mask offset alias must not be finer than "+ "the aligned bar spacing"+ )observed = pd.Series(dates, index=dates)selected = []for item in observed.resample(validated).first().dropna().tolist():- timestamp = pd.Timestamp(item)- assert isinstance(timestamp, pd.Timestamp)+ timestamp = cast(pd.Timestamp, pd.Timestamp(item))selected.append(timestamp)else:selected = []+ bounds = dates.asi8.tolist()for item in validated:- requested = pd.Timestamp(item)- assert isinstance(requested, pd.Timestamp)+ requested = cast(pd.Timestamp, pd.Timestamp(item))if dates.tz is not None:requested = requested.tz_localize(dates.tz)- index = bisect_left(dates.asi8.tolist(), requested.value)+ index = bisect_left(bounds, requested.value)if index < len(dates):- timestamp = dates[index]- assert isinstance(timestamp, pd.Timestamp)+ timestamp = cast(pd.Timestamp, dates[index])selected.append(timestamp)execution_dates = frozenset(selected)diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.mdindex 7dfb57ed1..8d9876675 100644--- a/agent/src/skills/strategy-generate/SKILL.md+++ b/agent/src/skills/strategy-generate/SKILL.md@@ -129,6 +129,7 @@ Self-check after writing `signal_engine.py`:"optimizer_params": {},"engine": "daily","position_adjustment": "rebalance",+ "rebalance_mask": "MS","rebalance_tolerance": 0.05,"validation": null}@@ -150,10 +151,11 @@ Self-check after writing `signal_engine.py`:- `optimizer_params`: optimizer parameters, such as `{"lookback": 60}`. `mean_variance` additionally supports `{"risk_free": 0.0}`; `turnover_aware` supports `{"risk_aversion": 1.0, "turnover_penalty": 0.5}` (L1 penalty on weight changes; tune to data frequency)- `engine`: backtest engine, default `"daily"`. For options strategies, set `"options"` (requires `OptionsSignalEngine`)- `position_adjustment`: **always state this explicitly** — the two modes produce different books from the same signals, and neither is right for every strategy.- - `"rebalance"` executes every target change with market fills and weighted-average entry accounting. It also re-sizes whenever the held weight has drifted from the target, and a strategy restates its target on every bar, so a constant target means a fill on every bar: measured on a 40-bar rising series, a constant 20% target produced **40 fills instead of 1**, with the fees, slippage and transaction taxes that follow. A strategy that rebalances on its own schedule (e.g. `rebalance_freq=20`) will still trade daily here.+ - `"rebalance"` executes every target change with market fills and weighted-average entry accounting. It also re-sizes whenever the held weight has drifted from the target, and a strategy restates its target on every bar, so a constant target means a fill on every bar: measured on a 40-bar rising series, a constant 20% target produced **40 fills instead of 1**, with the fees, slippage and transaction taxes that follow. Use `rebalance_mask` when the strategy has its own execution cadence.- `"hold"` keeps a same-direction position until it exits or reverses, so the weight drifts with price and a requested resize is **not executed**. Dropped requests are counted in the report as `dropped_target_adjustment_count`, with the first twenty listed, so a rebalance count that does not match the trade log is explained rather than silent.- Rule of thumb: `"rebalance"` when the target weight itself carries the strategy (optimizers, risk budgets, continuous scaling); `"hold"` when entries and exits carry it and the weight in between is incidental.-- `rebalance_tolerance`: drift band around the target, as a fraction of it, used only under `"rebalance"`. A resize executes once the held weight has moved further than this from its target; a **changed** target breaches any sane band on its own, so target changes always execute. Default `0.0` means no band, and then the resize test is decided by the slippage width alone — measured on a constant 20% target over 60 bars, `0.0` produced 60 fills, `0.02` produced 12, and `0.05` produced 5 while the weight never left 0.21. **State it for any strategy with its own rebalance cadence**, otherwise a `rebalance_freq=20` strategy still trades every bar. `0.05` is a reasonable starting point, not a recommendation with evidence behind it — it is your modelling choice and the report records the value the run used.+- `rebalance_mask`: optional execution schedule used only under `"rebalance"`. Use a pandas offset alias such as `"MS"`, `"W-FRI"`, or `"QS"`, or an explicit ISO-date list such as `["2026-01-02", "2026-02-02"]`. Each period/date selects the first aligned trading bar on or after it; ordinary bars HOLD even when the dense target is zero. An alias must not be finer than the aligned bar interval; `W-FRI` starts a Friday-anchored period and normally executes on the following Monday. Omit it to preserve every-bar execution. Do not combine it with `"hold"`.+- `rebalance_tolerance`: drift band around the target, as a fraction of it, used only under `"rebalance"`. A resize executes once the held weight has moved further than this from its target; a **changed** target breaches any sane band on its own, so target changes always execute. Default `0.0` means no band, and then the resize test is decided by the slippage width alone — measured on a constant 20% target over 60 bars, `0.0` produced 60 fills, `0.02` produced 12, and `0.05` produced 5 while the weight never left 0.21. Use `rebalance_mask`, not tolerance, to express a strategy's execution cadence. `0.05` is a reasonable starting point, not a recommendation with evidence behind it — it is your modelling choice and the report records the value the run used.- `initial_cash`: default 1,000,000- `commission`: default 0.1%- `validation`: optional statistical validation after backtest completes. Omit to skip. Example:diff --git a/agent/tests/test_rebalance_mask.py b/agent/tests/test_rebalance_mask.pyindex d01bfda34..0a487639c 100644--- a/agent/tests/test_rebalance_mask.py+++ b/agent/tests/test_rebalance_mask.py@@ -6,6 +6,7 @@ import pandas as pdimport pytestfrom backtest.engines.base import BaseEngine+from backtest.runner import BacktestConfigSchemaclass _MaskEngine(BaseEngine):@@ -88,6 +89,15 @@ def test_mask_true_zero_target_explicitly_exits_position() -> None:assert [fill.action for fill in engine.fill_records] == ["open", "close"]+def test_off_mask_zero_target_keeps_position_open() -> None:+ engine = _MaskEngine(rebalance_mask=["2026-01-02"])++ _run_masked(engine, [0.5, 0.0, 0.0])++ assert engine.bar_sizes == pytest.approx([5.0, 5.0, 5.0])+ assert [fill.action for fill in engine.fill_records[:-1]] == ["open"]++def test_missing_mask_preserves_every_bar_legacy_rebalance() -> None:engine = _MaskEngine()@@ -134,3 +144,57 @@ def test_mask_without_trading_date_intersection_is_rejected() -> None:def test_invalid_mask_alias_is_rejected() -> None:with pytest.raises(ValueError, match="rebalance_mask"):_MaskEngine(rebalance_mask="monthly")+++def test_alias_finer_than_aligned_bar_spacing_is_rejected() -> None:+ dates = pd.bdate_range("2026-01-02", periods=3)+ engine = _MaskEngine(rebalance_mask="h")++ with pytest.raises(ValueError, match="rebalance_mask.*finer"):+ _run_masked(engine, [0.2, 0.8, 0.2], dates=dates)+++ ("mask", "position_adjustment"),+ [+ ("MS", "rebalance"),+ (["2026-01-02"], "rebalance"),+ (None, "hold"),+ ],+)+def test_schema_accepts_supported_mask_combinations(+ mask: str | list[str] | None,+ position_adjustment: str,+) -> None:+ config = BacktestConfigSchema.model_validate(+ {+ "codes": ["AAPL.US"],+ "start_date": "2026-01-01",+ "end_date": "2026-01-31",+ "source": "yfinance",+ "position_adjustment": position_adjustment,+ "rebalance_mask": mask,+ }+ )++ assert config.rebalance_mask == mask+++ "overrides",+ [+ {"position_adjustment": "hold", "rebalance_mask": "MS"},+ {"position_adjustment": "rebalance", "rebalance_mask": "monthly"},+ ],+)+def test_schema_rejects_ambiguous_or_invalid_mask(overrides: dict[str, object]) -> None:+ with pytest.raises(ValueError, match="rebalance_mask"):+ BacktestConfigSchema.model_validate(+ {+ "codes": ["AAPL.US"],+ "start_date": "2026-01-01",+ "end_date": "2026-01-31",+ "source": "yfinance",+ **overrides,+ }+ )