"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(shadow-account): honour every documented entry condition in the engine
cgycoreyc1bfa3f94962
diff --git a/agent/src/shadow_account/codegen.py b/agent/src/shadow_account/codegen.pyindex 30700b9a0..92b1de1f6 100644--- a/agent/src/shadow_account/codegen.py+++ b/agent/src/shadow_account/codegen.py@@ -19,7 +19,12 @@ from typing import Anyfrom jinja2 import Environment, FileSystemLoader, select_autoescape-from src.shadow_account.models import PRICE_FEATURES, ShadowProfile, ShadowRule+from src.shadow_account.models import (+ PRICE_FEATURES,+ ShadowProfile,+ ShadowRule,+ canonical_comparison,+)_TEMPLATES_DIR = Path(__file__).parent / "templates"_SIGNAL_ENGINE_TEMPLATE = "signal_engine.py.j2"@@ -69,9 +74,80 @@ def _env() -> Environment:return env+def _finite_number(value: Any) -> float | None:+ """Return *value* as a finite float, or ``None`` when it is not one."""+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return None+ number = float(value)+ return number if math.isfinite(number) else None+++def _unsupported_bound(feature: str, bounds: Any) -> ValueError:+ """Build the refusal for a condition the template cannot express exactly."""+ return ValueError(+ f"entry_condition[{feature!r}] = {bounds!r} cannot be expressed by the "+ "signal-engine template, which supports inclusive bounds only "+ "('>=' / '<=' or {\"min\", \"max\"})"+ )+++def _inclusive_slot(op: Any) -> str | None:+ """Map an inclusive comparison operator to a template bound slot."""+ return {">=": "min", "<=": "max"}.get(canonical_comparison(op) or "")+++def _pair_or_scalar_bound(feature: str, bounds: Any) -> tuple[str, float]:+ """Map one ``(op, value)`` pair or bare scalar to a single bound slot.++ A bare scalar means ``>=``, which is how the scanner reads one.++ Args:+ feature: The ``PRICE_FEATURES`` name the condition belongs to.+ bounds: The condition as the profile states it.++ Returns:+ ``("min" | "max", threshold)``.++ Raises:+ ValueError: If the pair is malformed or its operator has no exact+ inclusive representation.+ """+ if isinstance(bounds, (list, tuple)):+ if len(bounds) < 2:+ raise _unsupported_bound(feature, bounds)+ slot = _inclusive_slot(bounds[0])+ threshold = _finite_number(bounds[1])+ else:+ slot, threshold = "min", _finite_number(bounds)+ if slot is None or threshold is None:+ raise _unsupported_bound(feature, bounds)+ return slot, threshold++def _rule_to_context(rule: ShadowRule) -> dict[str, Any]:- """Flatten a ShadowRule into the scalar fields the template consumes."""- market = str(rule.entry_condition.get("market", "other"))+ """Flatten a ShadowRule into the scalar fields the template consumes.++ A condition that names a price feature must either become a bound the+ template can express or be refused: a bound the template silently ignores+ would backtest the rule wider than the profile states it. ``None`` means+ "no bound" and is not an error.++ Args:+ rule: The rule to flatten.++ Returns:+ Scalar context for the signal-engine template.++ Raises:+ ValueError: If ``market`` is not a string, or a price-feature+ condition cannot be expressed as an inclusive bound.+ """+ market = rule.entry_condition.get("market", "other")+ if not isinstance(market, str):+ raise ValueError(+ f"entry_condition['market'] = {market!r} must be a string; a "+ "comparison cannot name a market bucket"+ )hour = rule.entry_condition.get("entry_hour") or {}hold_lo, hold_hi = rule.holding_days_rangehold_days = max(1, int(round((hold_lo + hold_hi) / 2)))@@ -85,12 +161,19 @@ def _rule_to_context(rule: ShadowRule) -> dict[str, Any]:}for feature in PRICE_FEATURES:bounds = rule.entry_condition.get(feature)+ if bounds is None:+ continueif isinstance(bounds, dict):- lo = bounds.get("min")- hi = bounds.get("max")- if isinstance(lo, (int, float)) and isinstance(hi, (int, float)):- ctx[feature + "_min"] = float(lo)- ctx[feature + "_max"] = float(hi)+ for slot in ("min", "max"):+ if slot not in bounds or bounds[slot] is None:+ continue+ threshold = _finite_number(bounds[slot])+ if threshold is None:+ raise _unsupported_bound(feature, bounds)+ ctx[f"{feature}_{slot}"] = threshold+ continue+ slot, threshold = _pair_or_scalar_bound(feature, bounds)+ ctx[f"{feature}_{slot}"] = thresholdreturn ctx@@ -103,6 +186,10 @@ def render_signal_engine(profile: ShadowProfile) -> str:Returns:Python source string. The caller is expected to ``validate_generated``before writing to disk.++ Raises:+ ValueError: If a rule carries a condition the template cannot express+ exactly as an inclusive bound (see ``_rule_to_context``)."""template = _env().get_template(_SIGNAL_ENGINE_TEMPLATE)return template.render(@@ -203,7 +290,10 @@ def write_run_dir("""Materialize a full run_dir with ``code/signal_engine.py`` + ``config.json``.Raises:- ValueError: Generated signal_engine fails static validation.+ ValueError: Generated signal_engine fails static validation, or+ ``render_signal_engine`` refuses a condition the template cannot+ express (the refusal propagates from here; callers are+ ``backtester.py`` and the ``shadow_account_tool`` backtest tool)."""run_dir = Path(run_dir)(run_dir / "code").mkdir(parents=True, exist_ok=True)diff --git a/agent/src/shadow_account/models.py b/agent/src/shadow_account/models.pyindex 5c26f40cd..ac33e040e 100644--- a/agent/src/shadow_account/models.py+++ b/agent/src/shadow_account/models.py@@ -16,6 +16,45 @@ from typing import Any#: keeps the three modules from drifting apart.PRICE_FEATURES: tuple[str, ...] = ("entry_rsi14", "prior_5d_return")+#: Canonical comparison spellings accepted inside an ``entry_condition`` value.+#: This is the shared *spelling* vocabulary: the live scanner and the generated+#: signal engine both parse operators through this table, so neither side+#: invents its own names. Honouring an operator is a separate matter —+#: ``scanner._compare`` evaluates every canonical operator, whereas the+#: generated engine expresses the inclusive subset (``>=`` / ``<=``) only and+#: raises for anything else.+COMPARISON_ALIASES: dict[str, str] = {+ ">": ">",+ "gt": ">",+ ">=": ">=",+ "gte": ">=",+ "ge": ">=",+ "<": "<",+ "lt": "<",+ "<=": "<=",+ "lte": "<=",+ "le": "<=",+ "==": "==",+ "=": "==",+ "eq": "==",+ "!=": "!=",+ "<>": "!=",+ "ne": "!=",+}+++def canonical_comparison(op: Any) -> str | None:+ """Return the canonical operator spelling for *op*, or ``None``.++ Args:+ op: An operator as written in a rule condition.++ Returns:+ One of ``>``, ``>=``, ``<``, ``<=``, ``==``, ``!=``; ``None`` when the+ spelling is not part of the shared grammar.+ """+ return COMPARISON_ALIASES.get(str(op).strip().lower())+@dataclass(frozen=True)class ShadowRule:@@ -25,8 +64,12 @@ class ShadowRule:rule_id: Stable ID like "R1", "R2".human_text: Chinese natural-language description (<=30 chars).entry_condition: Structured condition dict for codegen. Keys are- feature names (e.g. "prior_5d_return", "market"); values are- either scalars or (op, value) tuples (e.g. ("<=", -0.08)).+ feature names (e.g. "prior_5d_return", "market"). For a+ ``PRICE_FEATURES`` key the value may be a bare scalar (read as+ ``>=``), an ``(op, value)`` pair, or a ``{"min", "max"}``+ mapping; the generated engine (``codegen.render_signal_engine``)+ expresses inclusive bounds only and raises ``ValueError`` for+ ``>``, ``<``, ``==``, ``!=``. ``market`` must be a string.exit_condition: Structured exit condition dict.holding_days_range: (min, max) integer days.support_count: Number of profitable roundtrips supporting this rule.diff --git a/agent/src/shadow_account/scanner.py b/agent/src/shadow_account/scanner.pyindex 024cc948e..65889e543 100644--- a/agent/src/shadow_account/scanner.py+++ b/agent/src/shadow_account/scanner.py@@ -13,7 +13,11 @@ import pandas as pdfrom src.shadow_account.backtester import _LIQUID_BASKETS, SUPPORTED_MARKETSfrom src.shadow_account.indicators import RSI_PERIOD as _RSI_PERIOD, compute_rsi as _compute_rsi-from src.shadow_account.models import ShadowProfile, ShadowRule+from src.shadow_account.models import (+ ShadowProfile,+ ShadowRule,+ canonical_comparison,+)PriceFetcher = Callable[..., pd.DataFrame | None]@@ -253,19 +257,20 @@ def _compare(value: float | bool, condition: Any) -> bool:if threshold is None:return True- if op in {">", "gt"}:+ canonical = canonical_comparison(op)+ if canonical is None:+ return True+ if canonical == ">":return value > threshold- if op in {">=", "gte", "ge"}:+ if canonical == ">=":return value >= threshold- if op in {"<", "lt"}:+ if canonical == "<":return value < threshold- if op in {"<=", "lte", "le"}:+ if canonical == "<=":return value <= threshold- if op in {"==", "=", "eq"}:+ if canonical == "==":return value == threshold- if op in {"!=", "<>", "ne"}:- return value != threshold- return True+ return value != thresholddef _int_condition_value(condition: Any, default: int) -> int:diff --git a/agent/src/shadow_account/templates/signal_engine.py.j2 b/agent/src/shadow_account/templates/signal_engine.py.j2index 62b371422..cde65e755 100644--- a/agent/src/shadow_account/templates/signal_engine.py.j2+++ b/agent/src/shadow_account/templates/signal_engine.py.j2@@ -35,7 +35,8 @@ class SignalEngine:For each code we pick the first rule whose market matches, then checkper-bar entry conditions: hour window, plus optionally RSI range andprior-return range (read from the rule dict — absent keys skip the- check). When all conditions pass we enter a position and hold for the+ check). Entry bounds are inclusive and each side (``min``, ``max``) is+ optional. When all conditions pass we enter a position and hold for therule's holding days. Non-matching codes yield a zero series."""@@ -118,14 +119,22 @@ class SignalEngine:if bar_hour < hour_min or bar_hour > hour_max:continue- if rsi_min is not None and rsi_max is not None:+ if rsi_min is not None or rsi_max is not None:rsi_val = rsi.iloc[i]- if pd.isna(rsi_val) or rsi_val < rsi_min or rsi_val > rsi_max:+ if pd.isna(rsi_val):+ continue+ if rsi_min is not None and rsi_val < rsi_min:+ continue+ if rsi_max is not None and rsi_val > rsi_max:continue- if ret_min is not None and ret_max is not None:+ if ret_min is not None or ret_max is not None:ret_val = prior_ret.iloc[i]- if pd.isna(ret_val) or ret_val < ret_min or ret_val > ret_max:+ if pd.isna(ret_val):+ continue+ if ret_min is not None and ret_val < ret_min:+ continue+ if ret_max is not None and ret_val > ret_max:continuevalues[i] = weightdiff --git a/agent/tests/test_shadow_codegen_condition_bounds.py b/agent/tests/test_shadow_codegen_condition_bounds.pynew file mode 100644index 000000000..7fad54825--- /dev/null+++ b/agent/tests/test_shadow_codegen_condition_bounds.py@@ -0,0 +1,218 @@+"""A rule's entry bounds must survive into the engine that actually executes.++Seam under test: ``save_profile`` -> ``load_profile`` -> ``render_signal_engine``,+observed two ways — the ``RULES`` literal of the generated ``code/signal_engine.py``+and the signals that generated engine produces when it is executed. Nothing here+reaches into ``codegen._rule_to_context``.++Why the round-trip matters: ``models.ShadowRule`` documents a price-feature+value as a bare scalar (read as ``>=``), an ``(op, value)`` pair or a+``{"min", "max"}`` mapping. ``save_profile`` writes JSON, so that pair is read+back as a list, and ``scanner._compare`` already accepts all of those spellings.+The generated engine runs the shadow's own backtest, so a bound it drops+backtests a looser rule than the profile states.+"""++from __future__ import annotations++from collections.abc import Callable+from typing import Any++import pandas as pd+import pytest++from src.shadow_account.codegen import render_signal_engine+from src.shadow_account.models import ShadowProfile, ShadowRule+from src.shadow_account.storage import load_profile, save_profile++SHADOW_ID = "shadow_0000b0und"++#: Daily bar timestamps start here; one bar per close handed to ``_signals``.+_START = pd.Timestamp("2024-03-01")++#: Twenty monotonically rising closes: RSI(14) reads 100 from bar 14 onwards.+_RISING_CLOSES = [100.0 + i for i in range(20)]++#: First bar of ``_RISING_CLOSES`` with a warm (non-NaN) RSI(14).+_RISING_FIRST_RSI_BAR = 14+++def _profile(entry_condition: dict[str, Any]) -> ShadowProfile:+ rule = ShadowRule(+ rule_id="R1",+ human_text="5-day pullback then bounce",+ entry_condition=entry_condition,+ exit_condition={"holding_days": {"min": 2, "max": 5}},+ holding_days_range=(2, 5),+ support_count=3,+ coverage_rate=0.5,+ sample_trades=("AAA@2025-01-02",),+ )+ return ShadowProfile(+ shadow_id=SHADOW_ID,+ created_at="2025-01-01T00:00:00+00:00",+ journal_hash="0123456789abcdef",+ source_market="us",+ profitable_roundtrips=3,+ total_roundtrips=5,+ date_range=("2024-01-01", "2024-12-31"),+ profile_text="test portrait",+ rules=(rule,),+ preferred_markets=("us",),+ typical_holding_days=(3.0, 6.0),+ )+++def saved_profile(tmp_path, monkeypatch) -> Callable[[dict[str, Any]], ShadowProfile]:+ """Persist a rule with the given ``entry_condition`` and load it back."""++ def _save(entry_condition: dict[str, Any]) -> ShadowProfile:+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path / "state"))+ save_profile(_profile(entry_condition))+ return load_profile(SHADOW_ID)++ return _save+++def _generated(source: str) -> dict[str, Any]:+ """Execute the generated module and return its namespace."""+ namespace: dict[str, Any] = {}+ exec(+ compile(source, "<generated signal_engine>", "exec"), namespace+ ) # noqa: S102 - code under test+ return namespace+++def _signals(source: str, closes: list[float]) -> list[float]:+ """Run the generated engine over one symbol and return its signal series."""+ module = _generated(source)+ index = pd.date_range(_START, periods=len(closes), freq="D")+ frame = pd.DataFrame({"close": closes}, index=index)+ return module["SignalEngine"]().generate({"AAA": frame})["AAA"].tolist()+++def _first_entry(signals: list[float]) -> int | None:+ """Index of the first non-zero signal, or ``None`` if the engine never enters."""+ return next((i for i, value in enumerate(signals) if value), None)+++ ("op", "bound_key"),+ [+ (">=", "prior_5d_return_min"),+ ("gte", "prior_5d_return_min"),+ ("ge", "prior_5d_return_min"),+ ("<=", "prior_5d_return_max"),+ ("lte", "prior_5d_return_max"),+ ("le", "prior_5d_return_max"),+ ],+)+def test_a_json_list_bound_reaches_the_generated_engine(+ saved_profile,+ op,+ bound_key,+) -> None:+ loaded = saved_profile({"market": "us", "prior_5d_return": (op, -0.08)})+ # JSON has no tuple: the documented (op, value) pair comes back as a list.+ assert loaded.rules[0].entry_condition["prior_5d_return"] == [op, -0.08]++ rule = _generated(render_signal_engine(loaded))["RULES"][0]+ assert rule[bound_key] == -0.08+++def test_a_one_sided_dict_bound_reaches_the_generated_engine(saved_profile) -> None:+ """The scanner enforces `{"max": x}` alone; the engine must too."""+ loaded = saved_profile({"market": "us", "prior_5d_return": {"max": -0.08}})++ rule = _generated(render_signal_engine(loaded))["RULES"][0]+ assert rule["prior_5d_return_max"] == -0.08+++def test_a_both_sided_dict_bound_still_reaches_the_generated_engine(+ saved_profile,+) -> None:+ loaded = saved_profile(+ {"market": "us", "prior_5d_return": {"min": -0.20, "max": -0.08}}+ )++ rule = _generated(render_signal_engine(loaded))["RULES"][0]+ assert (rule["prior_5d_return_min"], rule["prior_5d_return_max"]) == (-0.20, -0.08)+++ ("entry_condition", "closes", "first_entry"),+ [+ # +10% over 5 bars: above the -8% ceiling, so no bar enters.+ ({"prior_5d_return": {"max": -0.08}}, [100.0] * 5 + [110.0], None),+ # -9% over 5 bars: inside the ceiling, so the last bar enters.+ ({"prior_5d_return": {"max": -0.08}}, [100.0] * 5 + [91.0], 5),+ # RSI(14) reads 100 on rising closes: above a 50 ceiling, never enters.+ ({"entry_rsi14": {"max": 50.0}}, _RISING_CLOSES, None),+ # Same closes under a 50 floor: the first warm RSI bar enters.+ ({"entry_rsi14": {"min": 50.0}}, _RISING_CLOSES, _RISING_FIRST_RSI_BAR),+ ],+)+def test_the_generated_engine_applies_a_one_sided_bound(+ saved_profile,+ entry_condition,+ closes,+ first_entry,+) -> None:+ """The executed engine must filter on a one-sided bound, not just print it.++ Each side of a bound carries its own entry, for RSI as well as for the+ prior return. If the template's RSI guard reverted to requiring both sides+ (``rsi_min is not None and rsi_max is not None``), a ``min``-only RSI rule+ would skip the check and enter on bar 0 rather than ``_RISING_FIRST_RSI_BAR``,+ and a ``max``-only RSI rule would enter on every warm bar rather than none.+ """+ loaded = saved_profile({**entry_condition, "market": "us"})++ signals = _signals(render_signal_engine(loaded), closes)+ assert _first_entry(signals) == first_entry+++def test_a_documented_scalar_condition_bounds_the_generated_engine(+ saved_profile,+) -> None:+ """`models.ShadowRule` documents scalars; the scanner reads one as `>=`."""+ loaded = saved_profile({"market": "us", "prior_5d_return": -0.08})+ source = render_signal_engine(loaded)++ assert _signals(source, [100.0] * 5 + [91.0]) == [0.0] * 6 # -9%, below+ assert _signals(source, [100.0] * 5 + [95.0])[-1] == 1.0 # -5%, above++[email protected]("op", [">", "<"])+def test_a_strict_comparison_is_refused_instead_of_dropped(saved_profile, op) -> None:+ """A strict operator has no exact inclusive render, so it errors instead."""+ loaded = saved_profile({"market": "us", "prior_5d_return": (op, 0.05)})++ with pytest.raises(ValueError, match="prior_5d_return"):+ render_signal_engine(loaded)+++def test_a_null_bound_is_no_bound_in_the_generated_engine(saved_profile) -> None:+ """``None`` means "no bound" here too, matching the scanner's ``_to_float``."""+ loaded = saved_profile({"market": "us", "prior_5d_return": {"max": None}})++ rule = _generated(render_signal_engine(loaded))["RULES"][0]+ assert "prior_5d_return_max" not in rule+ assert "prior_5d_return_min" not in rule+++def test_a_non_finite_bound_is_refused_instead_of_dropped(saved_profile) -> None:+ """A NaN threshold is not a bound the template can render, so it errors."""+ loaded = saved_profile({"market": "us", "prior_5d_return": {"min": float("nan")}})++ with pytest.raises(ValueError, match="prior_5d_return"):+ render_signal_engine(loaded)+++def test_a_condition_tuple_cannot_become_a_market_name(saved_profile) -> None:+ """`market` is a documented key; a tuple there must not stringify silently."""+ loaded = saved_profile({"market": ("==", "us")})++ with pytest.raises(ValueError, match="market"):+ render_signal_engine(loaded)