"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
refactor(shadow-account): centralize price feature contract
卫斯李f5900c5f33d3
diff --git a/agent/src/shadow_account/codegen.py b/agent/src/shadow_account/codegen.pyindex 3c1cc17be..30700b9a0 100644--- a/agent/src/shadow_account/codegen.py+++ b/agent/src/shadow_account/codegen.py@@ -19,7 +19,7 @@ from typing import Anyfrom jinja2 import Environment, FileSystemLoader, select_autoescape-from src.shadow_account.models import ShadowProfile, ShadowRule+from src.shadow_account.models import PRICE_FEATURES, ShadowProfile, ShadowRule_TEMPLATES_DIR = Path(__file__).parent / "templates"_SIGNAL_ENGINE_TEMPLATE = "signal_engine.py.j2"@@ -83,7 +83,7 @@ def _rule_to_context(rule: ShadowRule) -> dict[str, Any]:"hold_days": hold_days,"weight": float(rule.weight),}- for feature in ("entry_rsi14", "prior_5d_return"):+ for feature in PRICE_FEATURES:bounds = rule.entry_condition.get(feature)if isinstance(bounds, dict):lo = bounds.get("min")diff --git a/agent/src/shadow_account/extractor.py b/agent/src/shadow_account/extractor.pyindex 576187114..ab7bd1039 100644--- a/agent/src/shadow_account/extractor.py+++ b/agent/src/shadow_account/extractor.py@@ -26,7 +26,7 @@ from typing import Anyimport numpy as npimport pandas as pd-from src.shadow_account.models import ShadowProfile, ShadowRule+from src.shadow_account.models import PRICE_FEATURES, ShadowProfile, ShadowRulefrom src.shadow_account.storage import hash_journal, new_shadow_id, now_isofrom src.tools.trade_journal_parsers import parse_file, records_to_dataframefrom src.tools.trade_journal_tool import pair_trades_fifo@@ -40,7 +40,9 @@ _NUMERIC_FEATURES = ("holding_days", "pnl_pct", "entry_hour", "entry_weekday")_CATEGORICAL_FEATURES = ("market",)# Price-context features attached as-of buy_dt (NaN when price data unavailable).-_PRICE_FEATURES = ("entry_rsi14", "prior_5d_return")+# Names live on the data-contract boundary (models.PRICE_FEATURES) so the+# extractor, codegen, and scanner cannot drift; aliased here for local use.+_PRICE_FEATURES = PRICE_FEATURES_RSI_PERIOD = 14_PRIOR_RETURN_WINDOW = 5# Calendar buffer added before the earliest buy_dt so the RSI warmup has enough@@ -484,8 +486,10 @@ def _cluster_to_rule(if feature in cluster_df.columns:series = cluster_df[feature].dropna()if len(series) >= 2:- lo = float(round(series.quantile(0.10), 2))- hi = float(round(series.quantile(0.90), 2))+ # 4 decimals: RSI bounds tolerate it and return-type features+ # (prior_5d_return ~ ±0.0x) would lose meaningful precision at 2.+ lo = float(round(series.quantile(0.10), 4))+ hi = float(round(series.quantile(0.90), 4))entry_condition[feature] = {"min": lo, "max": hi}exit_condition: dict[str, Any] = {"holding_days": {"min": hold_lo, "max": hold_hi},diff --git a/agent/src/shadow_account/models.py b/agent/src/shadow_account/models.pyindex 92a0224fc..8c9dcd5d4 100644--- a/agent/src/shadow_account/models.py+++ b/agent/src/shadow_account/models.py@@ -9,6 +9,13 @@ from __future__ import annotationsfrom dataclasses import asdict, dataclass, fieldfrom typing import Any+#: Deterministic price-context feature names shared across the pipeline.+#: The extractor computes these as-of ``buy_dt``, codegen flattens their+#: ``{min,max}`` bounds into the template, and the scanner evaluates them in+#: real time. Defining the names here — on the stable data-contract boundary —+#: keeps the three modules from drifting apart.+PRICE_FEATURES: tuple[str, ...] = ("entry_rsi14", "prior_5d_return")+@dataclass(frozen=True)class ShadowRule:diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.pyindex 33af5163b..b4ca12d78 100644--- a/agent/tests/test_shadow_account.py+++ b/agent/tests/test_shadow_account.py@@ -861,6 +861,66 @@ def test_single_cluster_fallback_carries_price_bounds() -> None:assert entry["entry_rsi14"]["min"] <= entry["entry_rsi14"]["max"]+def test_codegen_and_extractor_share_price_feature_names() -> None:+ """codegen must read the same price-feature names the extractor writes.++ Both now source ``PRICE_FEATURES`` from ``models`` instead of repeating a+ literal tuple, so a single edit cannot leave one side stale.+ """+ from src.shadow_account import codegen, extractor+ from src.shadow_account.models import PRICE_FEATURES++ assert extractor._PRICE_FEATURES is PRICE_FEATURES+ # codegen flattens exactly these features' bounds — guard against drift.+ rule = ShadowRule(+ rule_id="R1",+ human_text="x",+ entry_condition={+ "market": "us",+ "entry_hour": {"min": 9, "max": 11},+ **{f: {"min": 1.0, "max": 2.0} for f in PRICE_FEATURES},+ },+ exit_condition={"holding_days": {"min": 2, "max": 5}},+ holding_days_range=(2, 5),+ support_count=5,+ coverage_rate=0.5,+ sample_trades=("AAPL@2026-01-01",),+ )+ ctx = codegen._rule_to_context(rule)+ for feature in PRICE_FEATURES:+ assert f"{feature}_min" in ctx and f"{feature}_max" in ctx+++def test_price_bounds_keep_four_decimal_precision() -> None:+ """Small ``prior_5d_return`` bounds must survive rounding.++ Regression for PR #314 review nit: ``round(.,2)`` collapsed return-type+ bounds (e.g. 0.0123 → 0.01); the extractor now rounds price-feature bounds+ to 4 decimals.+ """+ from src.shadow_account.extractor import _extract_rules++ df = pd.DataFrame({+ "market": ["us"] * 4,+ "holding_days": [3.0, 4.0, 5.0, 6.0],+ "entry_hour": [10, 11, 10, 11],+ "symbol": ["AAPL", "MSFT", "NVDA", "AMZN"],+ "buy_dt": pd.to_datetime(+ ["2026-01-01", "2026-01-02", "2026-01-03", "2026-01-04"]+ ),+ "prior_5d_return": [0.0123, 0.0156, 0.0188, 0.0211],+ })++ rules = _extract_rules(df, min_support=10, max_rules=1, llm_translator=None)+ bounds = rules[0].entry_condition["prior_5d_return"]+ # At 2 decimals both would round to 0.01/0.02; 4-decimal keeps them distinct.+ assert bounds["min"] != round(bounds["min"], 2) or bounds["max"] != round(bounds["max"], 2)+ assert bounds["min"] == round(bounds["min"], 4)+ assert bounds["max"] == round(bounds["max"], 4)++# ---- Degradation branches in the price-fetch / attach path ----from src.shadow_account.extractor import ( # noqa: E402