"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(engines): stop the silent-wrong-answer paths in composite, options, metrics
Haozhe Wu9a806223bde0
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex 7636ed58c..377862027 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -49,6 +49,58 @@ _MARKET_PATTERNS = [_CHINA_EXCHANGES = {"CFFEX", "SHFE", "DCE", "ZCE", "INE", "GFEX"}+# Settlement currency per market. A composite backtest holds one shared capital+# pool, so a code set spanning two of these would add CNY to USD to KRW as if+# they were the same unit.+_MARKET_CURRENCY = {+ "a_share": "CNY",+ "us_equity": "USD",+ "hk_equity": "HKD",+ "india_equity": "INR",+ "kr_equity": "KRW",+ # Every crypto pattern in _MARKET_PATTERNS is USDT-quoted, and USDT is+ # carried at its USD peg. This is the one approximation in the table: a+ # depeg would make a crypto+US book wrong by the depeg amount, which is+ # orders of magnitude below the CNY/USD-style unit error this guard exists+ # to catch.+ "crypto": "USD",+}++# Non-US futures venues. The GlobalFuturesEngine is USD-denominated end to end+# — margin, commission and contract multipliers are all in USD and it carries+# no EUR or JPY product — so anything it handles settles in USD unless the+# symbol names a venue that does not.+_FUTURES_EXCHANGE_CURRENCY = {"EUREX": "EUR"}+++def code_currency(code: str) -> str:+ """Return the currency a symbol settles in.++ Args:+ code: Ticker / symbol string.++ Returns:+ A currency code such as ``"CNY"``. A forex pair resolves to its quote+ currency and Chinese futures to ``"CNY"``. A symbol whose currency+ cannot be established returns a ``"UNKNOWN:<market>"`` marker rather+ than a guess, so a homogeneous set still compares equal while a mixed+ one cannot pass a same-currency check by accident.+ """+ market = _detect_market(code)+ if market in _MARKET_CURRENCY:+ return _MARKET_CURRENCY[market]+ if market == "forex":+ pair = code.upper().replace("/", "")+ if pair.endswith(".FX"):+ pair = pair[:-3]+ return pair[3:6] if len(pair) == 6 else "UNKNOWN:forex"+ if market == "futures":+ if _is_china_futures(code):+ return "CNY"+ exchange = code.upper().rpartition(".")[2]+ return _FUTURES_EXCHANGE_CURRENCY.get(exchange, "USD")+ return f"UNKNOWN:{market}"+# Known Chinese-futures product codes — used as a heuristic when a symbol# lacks an exchange suffix (e.g. bare ``RB2410``, ``IF2406``). Without this# table composite.py was misrouting such bare codes to GlobalFutures.diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.pyindex 87ccbcdda..c4b37b87b 100644--- a/agent/backtest/engines/composite.py+++ b/agent/backtest/engines/composite.py@@ -16,6 +16,7 @@ from backtest.engines.base import BaseEnginefrom backtest.engines._market_hooks import (_detect_market,_is_china_futures,+ code_currency,calc_crypto_funding_fee,check_crypto_liquidation,calc_forex_swap,@@ -61,6 +62,40 @@ def _build_rule_engines(config: dict, codes: List[str]) -> Dict[str, BaseEngine]return engines+def _reject_mixed_currency(codes: List[str]) -> None:+ """Refuse a code set whose members do not settle in one currency.++ The shared capital pool holds a single scalar of cash and sums position+ values into a single equity curve. With codes from two currency zones that+ curve adds CNY to USD to KRW as if the units matched, and every metric+ derived from it — return, Sharpe, drawdown — is meaningless. There is no FX+ translation layer yet, so this fails closed rather than reporting a number+ that looks fine.++ Args:+ codes: Instrument codes for the backtest.++ Raises:+ ValueError: If the codes span more than one settlement currency.+ """+ by_currency: Dict[str, List[str]] = {}+ for code in codes:+ by_currency.setdefault(code_currency(code), []).append(code)+ if len(by_currency) <= 1:+ return+ breakdown = "; ".join(+ f"{currency}: {', '.join(sorted(members))}"+ for currency, members in sorted(by_currency.items())+ )+ raise ValueError(+ "composite backtest requires one settlement currency across all codes, "+ f"but got {len(by_currency)} — {breakdown}. The shared capital pool has "+ "no FX translation, so a mixed-currency equity curve would sum "+ "different units. Split the run by currency, or convert the inputs "+ "to one currency before loading."+ )++class CompositeEngine(BaseEngine):"""Cross-market engine with shared capital pool.@@ -88,6 +123,26 @@ class CompositeEngine(BaseEngine):# Forex dedup stateself._last_swap_dates: dict = {}+ def run_backtest(self, config: dict, *args, **kwargs):+ """Run the pipeline, refusing a code set that spans currencies.++ The check lives here rather than in ``__init__`` because the damage is+ in the shared equity curve, not in constructing the rule-book engines.++ Args:+ config: Backtest configuration dict.+ *args: Forwarded to :meth:`BaseEngine.run_backtest`.+ **kwargs: Forwarded to :meth:`BaseEngine.run_backtest`.++ Returns:+ The metrics dictionary from :meth:`BaseEngine.run_backtest`.++ Raises:+ ValueError: If the codes span more than one settlement currency.+ """+ _reject_mixed_currency(config.get("codes") or list(self._symbol_market))+ return super().run_backtest(config, *args, **kwargs)+def _rule_for(self, symbol: str) -> BaseEngine:"""Get the sub-engine that provides rules for this symbol."""market = self._symbol_market.get(symbol, "a_share")diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.pyindex 27ca6294a..6ed13c25d 100644--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@ -156,6 +156,31 @@ def iv_smile_adjustment(S: float, K: float, base_iv: float,return max(adj, 0.01)+def leg_iv(S: float, K: float, base_iv: float, skew: float, curvature: float) -> float:+ """Return the implied vol a single leg is priced at.++ Every site that prices a leg must go through this — opening, marking to+ market, Greeks, and the American continuation value. Opening a leg on the+ smile and marking it at flat at-the-money vol books a fictitious profit the+ instant the position exists: on a 30-day 10%-OTM call at ``skew=-0.15`` the+ gap is +16.7% of premium, and +93.0% at 20% OTM, which then contaminates+ Sharpe, Calmar and drawdown.++ Args:+ S: Spot price.+ K: Strike price.+ base_iv: At-the-money implied volatility.+ skew: Slope of the smile; ``0`` with ``curvature`` disables the smile.+ curvature: Curvature of the smile.++ Returns:+ The leg's implied volatility.+ """+ if skew == 0 and curvature == 0:+ return base_iv+ return iv_smile_adjustment(S, K, base_iv, skew, curvature)++# --- Option positions ---@@ -328,7 +353,10 @@ def run_options_backtest(if T_ex <= 0:continueintrinsic = pos.intrinsic_value(spot)- continuation = bs_price(spot, pos.strike, T_ex, risk_free_rate, iv_val_ex, pos.option_type)+ # The continuation value must use the same vol the leg is+ # marked at, or early exercise triggers off a mispriced hold.+ iv_ex = leg_iv(spot, pos.strike, iv_val_ex, iv_skew, iv_curvature)+ continuation = bs_price(spot, pos.strike, T_ex, risk_free_rate, iv_ex, pos.option_type)if intrinsic > 0 and intrinsic > continuation * 1.02:# Early exercise is optimalsettlement = intrinsic * pos.qty * contract_multiplier@@ -393,12 +421,7 @@ def run_options_backtest(expiry_ts = pd.Timestamp(expiry)T = max((expiry_ts - ts).days / 365.0, 0.001)- # Apply IV smile adjustment (v2) if configured- adj_iv = iv_val- if iv_skew != 0 or iv_curvature != 0:- adj_iv = iv_smile_adjustment(spot, strike, iv_val, iv_skew, iv_curvature)-- # Black-Scholes price (with smile-adjusted IV if enabled)+ adj_iv = leg_iv(spot, strike, iv_val, iv_skew, iv_curvature)opt_price = bs_price(spot, strike, T, risk_free_rate, adj_iv, leg_type)if action == "open":@@ -499,10 +522,12 @@ def run_options_backtest(iv_val = ivs.get(pos.underlying_code, 0.3)T = pos.time_to_expiry(ts)- mark_price = bs_price(spot, pos.strike, T, risk_free_rate, iv_val, pos.option_type)+ mark_iv = leg_iv(spot, pos.strike, iv_val, iv_skew, iv_curvature)++ mark_price = bs_price(spot, pos.strike, T, risk_free_rate, mark_iv, pos.option_type)portfolio_value += mark_price * pos.qty * contract_multiplier- greeks = bs_greeks(spot, pos.strike, T, risk_free_rate, iv_val, pos.option_type)+ greeks = bs_greeks(spot, pos.strike, T, risk_free_rate, mark_iv, pos.option_type)total_delta += greeks["delta"] * pos.qty * contract_multipliertotal_gamma += greeks["gamma"] * pos.qty * contract_multipliertotal_theta += greeks["theta"] * pos.qty * contract_multiplierdiff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex 336359aaf..0f261e30a 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -540,10 +540,13 @@ def calc_metrics(bench_return = 0.0excess = 0.0ir = 0.0+ tracking_error = 0.0+ bench_beta = 0.0if bench_ret is not None and len(bench_ret) > 0:bench_return = float((1 + bench_ret).prod() - 1)excess = total_ret - bench_return- active_ret = port_ret - bench_ret.reindex(port_ret.index).fillna(0.0)+ aligned_bench = bench_ret.reindex(port_ret.index).fillna(0.0)+ active_ret = port_ret - aligned_bench# Same ddof=1 small-sample guard as ``vol`` / ``downside_std`` so the# information ratio stays finite for a single-observation series.active_std = float(active_ret.std()) if len(active_ret) > 1 and returns_finite else 0.0@@ -554,6 +557,18 @@ def calc_metrics()if not np.isfinite(ir):ir = 0.0+ # The information ratio's own denominator, annualised. A+ # benchmark-relative mandate is written around this number, and it was+ # being computed and thrown away.+ tracking_error = active_std * np.sqrt(bpy) if returns_finite else 0.0+ if not np.isfinite(tracking_error):+ tracking_error = 0.0+ bench_var = float(aligned_bench.var()) if len(aligned_bench) > 1 else 0.0+ if returns_finite and bench_var > 0:+ covariance = float(port_ret.cov(aligned_bench))+ bench_beta = covariance / bench_var+ if not np.isfinite(bench_beta):+ bench_beta = 0.0return {"final_value": float(equity_curve.iloc[-1]),@@ -572,6 +587,8 @@ def calc_metrics("benchmark_return": round(bench_return, 6),"excess_return": round(excess, 6),"information_ratio": round(ir, 4),+ "tracking_error": round(float(tracking_error), 6),+ "benchmark_beta": round(float(bench_beta), 4),"avg_turnover": round(avg_turnover, 6),"total_turnover": round(total_turnover, 6),}@@ -586,5 +603,6 @@ def _empty_metrics(initial_cash: float) -> Dict[str, Any]:"win_rate": 0, "profit_loss_ratio": 0, "profit_factor": 0,"max_consecutive_loss": 0, "avg_holding_days": 0, "trade_count": 0,"benchmark_return": 0, "excess_return": 0, "information_ratio": 0,+ "tracking_error": 0.0, "benchmark_beta": 0.0,"avg_turnover": 0.0, "total_turnover": 0.0,}diff --git a/agent/src/swarm/presets/derivatives_strategy_desk.yaml b/agent/src/swarm/presets/derivatives_strategy_desk.yamlindex 93b3e638e..ef4b88f3f 100644--- a/agent/src/swarm/presets/derivatives_strategy_desk.yaml+++ b/agent/src/swarm/presets/derivatives_strategy_desk.yaml@@ -52,7 +52,7 @@ agents:4. **Term Structure Shape** — Front-month / second-month / quarterly IV comparison; term structure slope and trading implications5. **Skew Characteristics Analysis** — Put skew and risk reversal current levels; compare vs. historical median; assess market sentiment bias6. **Volatility Strategy Direction Recommendation** — Based on the above, explicitly recommend "long volatility / short volatility / directional bias / calendar spread"; include confidence level- tools: [bash, read_file, write_file, load_skill, options_pricing]+ tools: [bash, read_file, write_file, load_skill, options_pricing, get_options_chain]skills: [volatility, options-advanced]max_iterations: 50timeout_seconds: 1800@@ -117,7 +117,7 @@ agents:4. **Initial Greeks Overview** — Current values of Delta / Gamma / Theta / Vega and their interpretation (risk exposure direction at initiation)5. **Entry and Exit Rules** — Entry trigger conditions, profit-taking rules, stop-loss rules, time stop rules; specific and actionable6. **Strategy Applicability and Failure Scenarios** — Under what conditions the strategy is effective; under what conditions it fails (requiring prompt adjustment)- tools: [bash, read_file, write_file, load_skill, options_pricing]+ tools: [bash, read_file, write_file, load_skill, options_pricing, get_options_chain]skills: [options-strategy, options-advanced, hedging-strategy, options-payoff]max_iterations: 50timeout_seconds: 1800@@ -178,7 +178,7 @@ agents:4. **Gamma / Theta Trade-off Analysis** — Current intraday battle between Gamma and Theta; analyze whether it is "trading time for space" or "trading space for time"5. **Stress Test Results** — Historical extreme scenario and single-day shock test results; provide maximum expected shortfall (ES / CVaR)6. **Dynamic Adjustment Recommendations** — At what price / time / IV level should the strategy be adjusted (Delta rebalancing trigger, roll timing, stop-loss exit conditions)- tools: [bash, read_file, write_file, load_skill, options_pricing]+ tools: [bash, read_file, write_file, load_skill, options_pricing, get_options_chain]skills: [options-advanced, risk-analysis, volatility, options-payoff]max_iterations: 50timeout_seconds: 1800diff --git a/agent/src/swarm/presets/value_investing_committee.yaml b/agent/src/swarm/presets/value_investing_committee.yamlindex 0b2cca368..5962c94ee 100644--- a/agent/src/swarm/presets/value_investing_committee.yaml+++ b/agent/src/swarm/presets/value_investing_committee.yaml@@ -28,7 +28,7 @@ agents:Use load_skill / get_financial_statements / get_market_data / financial_rigor to source and verify numbers precisely (no "TBD" skips).tools: [bash, read_file, write_file, load_skill, get_market_data, get_financial_statements, web_search, financial_rigor]- skills: [fundamental-filter, valuation-model, quality-screen, management-deep-dive]+ skills: [fundamental-filter, valuation-model, management-deep-dive]max_iterations: 50timeout_seconds: 1800max_retries: 1@@ -88,7 +88,7 @@ agents:load_skill("thesis-tracker") to build a thesis and red lines.tools: [bash, read_file, write_file, load_skill, get_market_data, get_financial_statements, web_search, financial_rigor]- skills: [management-deep-dive, fundamental-filter, thesis-tracker, quality-screen]+ skills: [management-deep-dive, fundamental-filter, thesis-tracker]max_iterations: 50timeout_seconds: 1800max_retries: 1@@ -149,7 +149,7 @@ agents:Output the full Markdown report and save it with write_file.tools: [bash, read_file, write_file, report_audit]- skills: [report-generate, investment-checklist]+ skills: [report-generate]max_iterations: 50timeout_seconds: 1800max_retries: 1diff --git a/agent/src/tools/stock_profile_tool.py b/agent/src/tools/stock_profile_tool.pyindex 710458a33..6240102ae 100644--- a/agent/src/tools/stock_profile_tool.py+++ b/agent/src/tools/stock_profile_tool.py@@ -59,6 +59,10 @@ def _key_stats(module: Dict[str, Any]) -> Dict[str, Any]:module,("enterpriseValue",+ # EV multiples arrive in the same payload and were being dropped,+ # leaving no capital-structure-neutral valuation measure at all.+ "enterpriseToEbitda",+ "enterpriseToRevenue","forwardPE","trailingEps","forwardEps",@@ -104,6 +108,11 @@ def _earnings_trend(module: Dict[str, Any]) -> List[Dict[str, Any]]:continueeps = entry.get("earningsEstimate") or {}rev = entry.get("revenueEstimate") or {}+ # The consensus level alone is a snapshot. Its trajectory and the+ # up/down revision counts arrive in the same payload and are what+ # estimate-revision momentum is actually built from.+ trend = entry.get("epsTrend") or {}+ revisions = entry.get("epsRevisions") or {}rows.append({"period": entry.get("period"),@@ -114,6 +123,12 @@ def _earnings_trend(module: Dict[str, Any]) -> List[Dict[str, Any]]:"eps_high": _raw(eps.get("high")),"eps_analysts": _raw(eps.get("numberOfAnalysts")),"revenue_avg": _raw(rev.get("avg")),+ "eps_trend_current": _raw(trend.get("current")),+ "eps_trend_7d_ago": _raw(trend.get("7daysAgo")),+ "eps_trend_30d_ago": _raw(trend.get("30daysAgo")),+ "eps_trend_90d_ago": _raw(trend.get("90daysAgo")),+ "eps_revisions_up_30d": _raw(revisions.get("upLast30days")),+ "eps_revisions_down_30d": _raw(revisions.get("downLast30days")),})return rowsdiff --git a/agent/tests/test_composite_currency_guard.py b/agent/tests/test_composite_currency_guard.pynew file mode 100644index 000000000..b99095088--- /dev/null+++ b/agent/tests/test_composite_currency_guard.py@@ -0,0 +1,107 @@+"""Regression tests for the composite engine's single-currency requirement.++``CompositeEngine`` keeps one shared capital pool: a single cash scalar and one+equity curve. Before this guard a code set spanning CNY, USD, HKD, INR and KRW+was summed into that curve as if the units matched, and every metric derived+from it was reported without a warning. There is no FX translation layer, so+the engine refuses the run instead.+"""++from __future__ import annotations++import pytest++from backtest.engines._market_hooks import code_currency+from backtest.engines.composite import CompositeEngine, _reject_mixed_currency+++class TestCodeCurrency:+ """Every supported market maps to the currency it settles in."""++ @pytest.mark.parametrize(+ ("code", "currency"),+ [+ ("600519.SH", "CNY"),+ ("AAPL.US", "USD"),+ ("00700.HK", "HKD"),+ ("RELIANCE.NS", "INR"),+ ("005930.KS", "KRW"),+ ("IF2406.CFFEX", "CNY"),+ ],+ )+ def test_equity_and_cn_futures_currencies(self, code, currency):+ assert code_currency(code) == currency++ def test_global_futures_default_to_usd(self):+ # The GlobalFuturesEngine's margin, commission and multiplier tables are+ # USD throughout and carry no non-USD product.+ assert code_currency("ESZ4") == "USD"+ assert code_currency("ES.CME") == "USD"++ def test_a_non_usd_futures_venue_is_not_called_usd(self):+ assert code_currency("FDAX.EUREX") == "EUR"++ def test_forex_resolves_to_the_quote_currency(self):+ assert code_currency("EUR/USD") == "USD"+ assert code_currency("USDJPY.FX") == "JPY"++ def test_usdt_is_carried_at_its_usd_peg(self):+ assert code_currency("BTC-USDT") == "USD"+++class TestRejectMixedCurrency:+ """The guard separates a genuinely mixed book from a merely cross-market one."""++ def test_one_currency_across_two_markets_is_allowed(self):+ _reject_mixed_currency(["AAPL.US", "ESZ4", "BTC-USDT"])++ def test_a_single_market_is_allowed(self):+ _reject_mixed_currency(["600519.SH", "000001.SZ"])++ def test_empty_and_single_code_sets_are_allowed(self):+ _reject_mixed_currency([])+ _reject_mixed_currency(["AAPL.US"])++ def test_cny_mixed_with_usd_is_refused(self):+ with pytest.raises(ValueError, match="one settlement currency"):+ _reject_mixed_currency(["600519.SH", "AAPL.US"])++ def test_the_error_names_every_currency_and_its_codes(self):+ with pytest.raises(ValueError) as excinfo:+ _reject_mixed_currency(["600519.SH", "AAPL.US", "005930.KS"])+ message = str(excinfo.value)+ for fragment in ("CNY", "USD", "KRW", "600519.SH", "AAPL.US", "005930.KS"):+ assert fragment in message+++class TestRunBacktestFailsClosed:+ """A mixed run must stop before it fetches data or reports a metric."""++ class _RecordingLoader:+ def __init__(self):+ self.fetched = False++ def fetch(self, *args, **kwargs):+ self.fetched = True+ return {}++ def test_mixed_currency_run_raises_before_fetching(self):+ codes = ["600519.SH", "AAPL.US"]+ engine = CompositeEngine({"initial_cash": 1_000_000, "codes": codes}, codes)+ loader = self._RecordingLoader()++ with pytest.raises(ValueError, match="one settlement currency"):+ engine.run_backtest(+ {"initial_cash": 1_000_000, "codes": codes},+ loader,+ signal_engine=None,+ run_dir=None,+ )+ assert loader.fetched is False++ def test_constructing_a_mixed_engine_is_still_allowed(self):+ # Rule-book routing across markets is a legitimate use; only the shared+ # equity curve is unsound, so construction must not raise.+ codes = ["IF2406.CFFEX", "ESZ4"]+ engine = CompositeEngine({"initial_cash": 1_000_000, "codes": codes}, codes)+ assert engine._rule_for("IF2406.CFFEX") is not engine._rule_for("ESZ4")diff --git a/agent/tests/test_metrics_tracking_error.py b/agent/tests/test_metrics_tracking_error.pynew file mode 100644index 000000000..fe8a856ca--- /dev/null+++ b/agent/tests/test_metrics_tracking_error.py@@ -0,0 +1,87 @@+"""Regression: the information ratio's denominator must be reported.++``calc_metrics`` computed the annualised active-return standard deviation to+form the information ratio and then discarded it, so the 18-key return carried+no tracking error and no benchmark beta — the two numbers a benchmark-relative+mandate is written around.+"""++from __future__ import annotations++import numpy as np+import pandas as pd+import pytest++from backtest.metrics import calc_metrics++_DATES = pd.bdate_range("2025-01-01", periods=60)+++def _series(values):+ return pd.Series(values, index=_DATES)+++def _equity(returns):+ return (1.0 + _series(returns)).cumprod() * 100_000.0+++def _metrics(port_returns, bench_returns):+ # calc_metrics derives portfolio returns with pct_change().fillna(0), so the+ # first bar is always zero. Zero the benchmark's first bar too, or the two+ # series are off by one observation and every comparison is contaminated.+ port = np.asarray(port_returns, dtype=float).copy()+ bench = np.asarray(bench_returns, dtype=float).copy()+ port[0] = 0.0+ bench[0] = 0.0+ return calc_metrics(_equity(port), [], 100_000.0, bench_ret=_series(bench))+++class TestTrackingError:+ def test_a_portfolio_that_tracks_exactly_has_no_tracking_error(self):+ rng = np.random.default_rng(7)+ bench = rng.normal(0.0005, 0.01, len(_DATES))++ metrics = _metrics(bench, bench)++ assert metrics["tracking_error"] == pytest.approx(0.0, abs=1e-9)++ def test_tracking_error_is_annualised(self):+ rng = np.random.default_rng(11)+ bench = rng.normal(0.0005, 0.01, len(_DATES))+ active = rng.normal(0.0, 0.004, len(_DATES))++ metrics = _metrics(bench + active, bench)+ expected = float(pd.Series(active).std()) * np.sqrt(252)++ assert metrics["tracking_error"] == pytest.approx(expected, rel=0.05)++ def test_it_is_present_even_with_no_benchmark(self):+ metrics = calc_metrics(_equity(np.zeros(len(_DATES))), [], 100_000.0)++ assert metrics["tracking_error"] == 0.0+ assert metrics["benchmark_beta"] == 0.0+++class TestBenchmarkBeta:+ def test_a_portfolio_identical_to_the_benchmark_has_beta_one(self):+ rng = np.random.default_rng(3)+ bench = rng.normal(0.0005, 0.01, len(_DATES))++ metrics = _metrics(bench, bench)++ assert metrics["benchmark_beta"] == pytest.approx(1.0, abs=1e-6)++ def test_a_double_exposure_portfolio_has_beta_two(self):+ rng = np.random.default_rng(5)+ bench = rng.normal(0.0005, 0.01, len(_DATES))++ metrics = _metrics(bench * 2.0, bench)++ assert metrics["benchmark_beta"] == pytest.approx(2.0, rel=0.02)++ def test_a_flat_benchmark_yields_zero_rather_than_a_division_blowup(self):+ rng = np.random.default_rng(13)++ metrics = _metrics(rng.normal(0.0, 0.01, len(_DATES)), np.zeros(len(_DATES)))++ assert metrics["benchmark_beta"] == 0.0diff --git a/agent/tests/test_options_smile_consistency.py b/agent/tests/test_options_smile_consistency.pynew file mode 100644index 000000000..2d7c8a898--- /dev/null+++ b/agent/tests/test_options_smile_consistency.py@@ -0,0 +1,180 @@+"""Regression: a leg must be marked at the vol it was opened at.++The engine applied the IV smile when pricing an opening leg but marked every+position at the flat at-the-money vol, so a position booked a profit the instant+it existed. Measured on a 30-day call at ``skew=-0.15``, ``curvature=0.05``,+``S=100``, ``r=0``: +16.7% of premium at 10% out-of-the-money and +93.0% at 20%.+That flows straight into the equity curve and every metric derived from it.++The same flat vol was also used for the Greeks and for the American+early-exercise continuation value, so those are pinned here too.+"""++from __future__ import annotations++from pathlib import Path++import pandas as pd+import pytest++from backtest.engines.options_portfolio import (+ bs_price,+ iv_smile_adjustment,+ leg_iv,+ run_options_backtest,+)++_DATES = pd.bdate_range("2025-01-01", periods=4)+_BARS = pd.DataFrame(+ {+ "open": [100.0, 100.0, 100.0, 100.0],+ "high": [100.0, 100.0, 100.0, 100.0],+ "low": [100.0, 100.0, 100.0, 100.0],+ "close": [100.0, 100.0, 100.0, 100.0],+ "volume": [1000, 1000, 1000, 1000],+ },+ index=_DATES,+)++_INITIAL_CASH = 100_000.0+# Fewer than 30 bars, so historical_volatility falls back to a flat 0.3.+_BASE_IV = 0.3+++class _FlatLoader:+ name = "yfinance"++ def fetch(self, codes, start_date, end_date): # noqa: ANN001+ return {"SPY": _BARS.copy()}+++def _open_call(strike: float):+ class _Engine:+ def generate(self, data_map): # noqa: ANN001+ return [+ {+ "date": "2025-01-01",+ "action": "open",+ "underlying": "SPY",+ "legs": [+ {+ "type": "call",+ "strike": strike,+ "expiry": "2025-02-21",+ "qty": 10,+ }+ ],+ }+ ]++ return _Engine()+++def _run(tmp_path: Path, *, strike: float, skew: float, curvature: float):+ run_options_backtest(+ {+ "codes": ["SPY"],+ "start_date": "2025-01-01",+ "end_date": "2025-01-07",+ "source": "yfinance",+ "engine": "options",+ "initial_cash": _INITIAL_CASH,+ "commission": 0.0,+ "options_config": {+ "risk_free_rate": 0.0,+ "contract_multiplier": 1.0,+ "iv_skew": skew,+ "iv_curvature": curvature,+ },+ },+ _FlatLoader(),+ _open_call(strike),+ tmp_path,+ )+ return pd.read_csv(tmp_path / "artifacts" / "equity.csv")+++class TestLegIv:+ """The single definition of the vol a leg is priced at."""++ def test_a_flat_surface_returns_the_base_vol(self):+ assert leg_iv(100.0, 110.0, _BASE_IV, 0.0, 0.0) == _BASE_IV++ def test_a_smile_matches_the_smile_model(self):+ assert leg_iv(100.0, 110.0, _BASE_IV, -0.15, 0.05) == iv_smile_adjustment(+ 100.0, 110.0, _BASE_IV, -0.15, 0.05+ )++ def test_at_the_money_is_unchanged_by_the_smile(self):+ assert leg_iv(100.0, 100.0, _BASE_IV, -0.15, 0.05) == pytest.approx(_BASE_IV)+++class TestDayZeroPnl:+ """Opening a position must not move equity on the bar that opens it."""++ @pytest.mark.parametrize("strike", [80.0, 95.0, 100.0, 110.0, 120.0])+ def test_day_zero_equity_is_unchanged_under_a_smile(self, tmp_path, strike):+ equity = _run(tmp_path, strike=strike, skew=-0.15, curvature=0.05)++ assert float(equity.iloc[0]["equity"]) == pytest.approx(_INITIAL_CASH, abs=1e-6)++ @pytest.mark.parametrize("strike", [95.0, 110.0])+ def test_day_zero_equity_is_unchanged_without_a_smile(self, tmp_path, strike):+ equity = _run(tmp_path, strike=strike, skew=0.0, curvature=0.0)++ assert float(equity.iloc[0]["equity"]) == pytest.approx(_INITIAL_CASH, abs=1e-6)++ def test_a_flat_underlying_never_moves_equity(self, tmp_path):+ # Spot, vol and rate are all constant, so the only P&L that can appear+ # is time decay — which must be identical under either vol surface.+ smile = _run(tmp_path / "smile", strike=110.0, skew=-0.15, curvature=0.05)+ flat = _run(tmp_path / "flat", strike=110.0, skew=0.0, curvature=0.0)++ assert float(smile.iloc[0]["equity"]) == pytest.approx(+ float(flat.iloc[0]["equity"]), abs=1e-6+ )+++class TestGreeksUseTheLegVol:+ """Greeks priced at a vol the leg is not marked at are a silent error."""++ def test_greeks_are_reported_at_the_smile_vol(self, tmp_path):+ run_options_backtest(+ {+ "codes": ["SPY"],+ "start_date": "2025-01-01",+ "end_date": "2025-01-07",+ "source": "yfinance",+ "engine": "options",+ "initial_cash": _INITIAL_CASH,+ "commission": 0.0,+ "options_config": {+ "risk_free_rate": 0.0,+ "contract_multiplier": 1.0,+ "iv_skew": -0.15,+ "iv_curvature": 0.05,+ },+ },+ _FlatLoader(),+ _open_call(110.0),+ tmp_path,+ )+ greeks = pd.read_csv(tmp_path / "artifacts" / "greeks.csv")++ from backtest.engines.options_portfolio import bs_greeks++ smile_vol = leg_iv(100.0, 110.0, _BASE_IV, -0.15, 0.05)+ expiry = pd.Timestamp("2025-02-21")+ time_to_expiry = max((expiry - _DATES[0]).days / 365.0, 0.001)+ expected = bs_greeks(100.0, 110.0, time_to_expiry, 0.0, smile_vol, "call")++ assert float(greeks.iloc[0]["delta"]) == pytest.approx(+ expected["delta"] * 10, rel=1e-6+ )++ def test_the_smile_vol_differs_from_the_flat_vol_for_this_leg(self):+ # Guards the test above from silently passing on an unchanged surface.+ assert leg_iv(100.0, 110.0, _BASE_IV, -0.15, 0.05) != _BASE_IV+ assert bs_price(100.0, 110.0, 30 / 365, 0.0, _BASE_IV, "call") != bs_price(+ 100.0, 110.0, 30 / 365, 0.0, leg_iv(100.0, 110.0, _BASE_IV, -0.15, 0.05), "call"+ )diff --git a/agent/tests/test_preset_honesty.py b/agent/tests/test_preset_honesty.pynew file mode 100644index 000000000..9a0491ed3--- /dev/null+++ b/agent/tests/test_preset_honesty.py@@ -0,0 +1,125 @@+"""CI gate: a shipped preset must not promise what its node cannot reach.++Swarm workers get a strict tool whitelist and a skill list. Two failure modes+had shipped: ``value_investing_committee`` named three skills that were never+bundled (``load_skill`` returns a soft error envelope, so the worker proceeded+without its methodology and said nothing), and ``derivatives_strategy_desk``+ordered its vol analyst to report ATM IV by tenor, IV-vs-HV premium and 25-delta+risk reversals while granting ``get_options_chain`` to no agent at all.++This gate covers the two mechanizable halves: every ``skills:`` entry resolves,+and every tool *named* in a node's prompt is granted to that node. It cannot+cover the third and hardest half — a prompt that demands a deliverable in prose+that no granted tool can compute — which stays a review obligation.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest+import yaml++from src.tools import build_registry, build_swarm_registry++_PRESET_DIR = Path(__file__).resolve().parents[1] / "src" / "swarm" / "presets"+_SKILL_DIR = Path(__file__).resolve().parents[1] / "src" / "skills"++[email protected](scope="module")+def presets() -> list[tuple[str, dict]]:+ loaded = []+ for path in sorted(_PRESET_DIR.glob("*.yaml")):+ loaded.append((path.name, yaml.safe_load(path.read_text(encoding="utf-8"))))+ assert loaded, "no presets found"+ return loaded++[email protected](scope="module")+def bundled_skills() -> set[str]:+ return {path.parent.name for path in _SKILL_DIR.glob("*/SKILL.md")}++[email protected](scope="module")+def tool_identifiers() -> list[str]:+ # Only snake_case names are unambiguous identifiers. Bare tool names that+ # are also ordinary English words — sentiment, pattern, backtest, remember —+ # appear throughout the prose and would make this gate pure noise.+ return sorted(name for name in build_registry().tool_names if "_" in name)+++def _nodes(presets):+ for filename, doc in presets:+ for node in doc.get("agents") or []:+ yield filename, node.get("id", "?"), node+++def test_every_referenced_skill_is_bundled(presets, bundled_skills):+ missing = [+ f"{filename}:{node_id} -> {skill}"+ for filename, node_id, node in _nodes(presets)+ for skill in (node.get("skills") or [])+ if skill not in bundled_skills+ ]++ assert missing == [], (+ "preset references a skill that is not bundled; load_skill returns a "+ "soft error so the worker would run without its methodology silently"+ )+++def test_every_tool_named_in_a_prompt_is_granted_to_that_node(+ presets, tool_identifiers+):+ ungranted = []+ for filename, node_id, node in _nodes(presets):+ granted = set(node.get("tools") or [])+ prompt = node.get("system_prompt") or ""+ for tool in tool_identifiers:+ named = re.search(rf"(?<![\w-]){re.escape(tool)}(?![\w-])", prompt)+ if named and tool not in granted:+ ungranted.append(f"{filename}:{node_id} names {tool}")++ assert ungranted == [], (+ "preset prompt names a tool the node was not granted; the worker would "+ "be told to call something its whitelist blocks"+ )+++def test_every_granted_tool_resolves(presets):+ # Resolve through the swarm's own builder: shell tools (bash, read_file,+ # write_file) are not in the default agent registry but are legitimate for a+ # worker, so checking against build_registry() alone reports 118 phantoms.+ unresolved = []+ for filename, node_id, node in _nodes(presets):+ requested = list(node.get("tools") or [])+ if not requested:+ continue+ resolved = set(+ build_swarm_registry(requested, include_shell_tools=True).tool_names+ )+ unresolved.extend(+ f"{filename}:{node_id} -> {tool}"+ for tool in requested+ if tool not in resolved+ )++ assert unresolved == [], (+ "preset grants a tool that does not resolve; the runtime drops it with "+ "a warning and the worker runs without it"+ )+++def test_the_derivatives_desk_can_reach_an_options_chain(presets):+ # The audit's sharpest single case: three agents were ordered to report+ # market-implied volatility with no chain tool granted to any of them, so+ # every IV number in that report was necessarily invented.+ desk = next(doc for name, doc in presets if name == "derivatives_strategy_desk.yaml")+ granting = [+ node.get("id")+ for node in desk["agents"]+ if "get_options_chain" in (node.get("tools") or [])+ ]++ assert granting, "no agent on the derivatives desk can fetch an options chain"