"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(shadow-account): make generated signal engines pass the backtest sandbox validator (#992)
shadowinlife972a8983e508
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 79c1beb9a..371d01da0 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -183,6 +183,17 @@ def _is_literal_node(node: ast.AST) -> bool:"""Return whether an AST node is made only from literal values."""if isinstance(node, ast.Constant):return True+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):+ # Signed numbers (e.g. a mined ``-0.08`` return threshold) parse as a+ # UnaryOp over a Constant rather than a bare Constant. They are+ # compile-time constants: no name lookup, call, or attribute access+ # runs when the definition is imported, so they stay import-time safe.+ operand = node.operand+ return (+ isinstance(operand, ast.Constant)+ and isinstance(operand.value, (int, float, complex))+ and not isinstance(operand.value, bool)+ )if isinstance(node, (ast.Tuple, ast.List, ast.Set)):return all(_is_literal_node(item) for item in node.elts)if isinstance(node, ast.Dict):diff --git a/agent/src/shadow_account/templates/signal_engine.py.j2 b/agent/src/shadow_account/templates/signal_engine.py.j2index 79e1d28f2..f0a832490 100644--- a/agent/src/shadow_account/templates/signal_engine.py.j2+++ b/agent/src/shadow_account/templates/signal_engine.py.j2@@ -39,8 +39,7 @@ class SignalEngine:rule's holding days. Non-matching codes yield a zero series."""- @staticmethod- def _compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:+ def _compute_rsi(self, close: pd.Series, period: int = 14) -> pd.Series:"""Causal Wilder-EWM RSI (mirrors ``compute_rsi`` in example_signal_engine.py:13)."""delta = close.diff()gain = delta.clip(lower=0)@@ -50,8 +49,7 @@ class SignalEngine:rs = avg_gain / avg_lossreturn 100 - 100 / (1 + rs)- @staticmethod- def _compute_prior_return(close: pd.Series, window: int = 5) -> pd.Series:+ def _compute_prior_return(self, close: pd.Series, window: int = 5) -> pd.Series:"""Trailing close-to-close return over *window* bars."""return close.pct_change(window)@@ -77,8 +75,8 @@ class SignalEngine:return rulereturn None- @staticmethoddef _conditional_entry(+ self,index: pd.Index,rsi: pd.Series,prior_ret: pd.Series,diff --git a/agent/tests/test_backtest_runner_security.py b/agent/tests/test_backtest_runner_security.pyindex e047fd173..2ecd96691 100644--- a/agent/tests/test_backtest_runner_security.py+++ b/agent/tests/test_backtest_runner_security.py@@ -450,3 +450,57 @@ def test_signal_engine_allows_unreachable_network_helper(tmp_path) -> None:module = _load_module_from_file(signal_file, _module_name())assert hasattr(module, "SignalEngine")+++def test_signal_engine_allows_signed_numeric_literal_assignment(tmp_path) -> None:+ # A negative threshold (e.g. a mined ``prior_5d_return`` bound) parses as+ # ``UnaryOp(USub, Constant)`` rather than a bare ``Constant``. It is still a+ # compile-time constant that executes nothing at import, so it must be treated+ # as a safe literal assignment (issue #985 second rejection path).+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Strategy with signed numeric thresholds."""',+ "THRESHOLD = -0.08",+ "BOUNDS = [{'min': -0.08, 'max': 0.02}]",+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ " return []",+ ]+ ),+ encoding="utf-8",+ )++ module = _load_module_from_file(signal_file, _module_name())++ assert module.THRESHOLD == -0.08+ assert module.BOUNDS == [{"min": -0.08, "max": 0.02}]+++ "decorator_line",+ [" @staticmethod", " @classmethod", " @some_decorator"],+ ids=["staticmethod", "classmethod", "custom"],+)+def test_signal_engine_still_rejects_decorators(tmp_path, decorator_line) -> None:+ # The issue #985 fix removes decorators from the generated template instead of+ # loosening this validator, so every decorator must stay rejected.+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Strategy with a decorated method."""',+ "class SignalEngine:",+ decorator_line,+ " def helper(cls):",+ " return []",+ " def generate(self, *args, **kwargs):",+ " return []",+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="Decorators are not allowed"):+ _load_module_from_file(signal_file, _module_name())diff --git a/agent/tests/test_shadow_codegen_security.py b/agent/tests/test_shadow_codegen_security.pyindex 279afa1a7..9069f9bf1 100644--- a/agent/tests/test_shadow_codegen_security.py+++ b/agent/tests/test_shadow_codegen_security.py@@ -3,9 +3,13 @@from __future__ import annotationsimport ast+import uuid+import numpy as np+import pandas as pdimport pytest+from backtest.runner import _load_module_from_filefrom src.shadow_account.codegen import render_signal_engine, validate_generatedfrom src.shadow_account.models import ShadowProfile, ShadowRule@@ -78,3 +82,82 @@ def test_render_signal_engine_escapes_python_literals_for_dynamic_values() -> Noassert isinstance(rules, list)assert rules[0]["rule_id"] == profile.rules[0].rule_idassert rules[0]["market"] == profile.rules[0].entry_condition["market"]+++def _conditional_entry_profile() -> ShadowProfile:+ """Profile with RSI + negative prior-return bounds (issue #985 shape)."""+ return ShadowProfile(+ shadow_id="shadow_entry985",+ created_at="2026-08-06T00:00:00Z",+ journal_hash="deadbeef",+ source_market="china_a",+ profitable_roundtrips=5,+ total_roundtrips=8,+ date_range=("2026-01-01", "2026-06-30"),+ profile_text="conditional entry regression profile",+ rules=(+ ShadowRule(+ rule_id="R1",+ human_text="buy low RSI after a pullback, hold 3 days",+ entry_condition={+ "market": "china_a",+ "entry_hour": {"min": 9, "max": 15},+ "entry_rsi14": {"min": 20.0, "max": 45.0},+ "prior_5d_return": {"min": -0.08, "max": 0.02},+ },+ exit_condition={},+ holding_days_range=(3, 3),+ support_count=4,+ coverage_rate=0.5,+ sample_trades=("600519.SH@2026-02-03",),+ weight=1.0,+ ),+ ),+ preferred_markets=("china_a",),+ typical_holding_days=(3.0, 3.0),+ )+++def test_rendered_signal_engine_passes_runner_validation(tmp_path) -> None:+ """Issue #985: the generated engine must clear the backtest runner's+ strict AST validator, not just codegen's own looser shape check.++ Two historical rejection paths are covered together:+ * ``@staticmethod`` decorators on the helper methods (the runner rejects+ every decorator), and+ * negative mined thresholds (``prior_5d_return_min = -0.08``) in the+ top-level ``RULES`` literal, which parse as ``UnaryOp(USub)``.+ """+ source = render_signal_engine(_conditional_entry_profile())+ ok, err = validate_generated(source)+ assert ok, f"generated source failed codegen validation: {err}"++ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(source, encoding="utf-8")++ module = _load_module_from_file(signal_file, f"signal_engine_{uuid.uuid4().hex}")++ engine = module.SignalEngine()+ rng = np.random.default_rng(7)+ idx = pd.date_range("2026-01-05", periods=120, freq="B")+ close = pd.Series(+ 100.0 * np.exp(np.cumsum(rng.normal(-0.002, 0.012, len(idx)))), index=idx+ )+ df = pd.DataFrame(+ {+ "open": close,+ "high": close + 1.0,+ "low": close - 1.0,+ "close": close,+ "volume": 1_000_000.0,+ },+ index=idx,+ )++ signals = engine.generate({"600519.SH": df})++ assert set(signals) == {"600519.SH"}+ series = signals["600519.SH"]+ assert len(series) == len(idx)+ assert (series > 0).any(), "conditional entry should fire on the pullback"