Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): reject non-finite attribution inputs

Rudy Celekli1d111d932a73
diff --git a/README.md b/README.md
index 9da849c1c..4dfb469fa 100644
--- a/README.md
+++ b/README.md
@@ -1593,6 +1593,8 @@ with `--host` / `--port`.
**MCP tools exposed (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
+`quantlib_call` attribution requires finite sector weights and returns, finite Carino return inputs, and a finite non-negative weight-sum tolerance. Invalid data is rejected explicitly rather than returned as an attribution result containing `NaN`. Missing returns for a zero-weight sector may still be inferred from the other side.
+
### SWARM external MCP tools
`run_swarm` workers can call operator-approved tools from external MCP servers. Configure the server-side allowlist in `VIBE_TRADING_SWARM_AGENT_CONFIG`, `~/.vibe-trading/swarm-agent.json`, or the fallback `~/.vibe-trading/agent.json`; then list remote tools in a swarm preset using the local MCP wrapper name, such as `mcp_internal_kb_search`. Caller-provided `variables` stay template data only and cannot inject MCP URLs, commands, environment variables, or allowlist overrides.
diff --git a/agent/src/quantlib/attribution.py b/agent/src/quantlib/attribution.py
index cb71fd929..a7b220734 100644
--- a/agent/src/quantlib/attribution.py
+++ b/agent/src/quantlib/attribution.py
@@ -247,13 +247,27 @@ def brinson_fachler(
Raises:
ValueError: If no sectors were supplied, if the two weight vectors do not
sum to the same total within ``weight_sum_tolerance``, or if a sector
- carries a non-zero weight on a side but no return on that side.
+ carries a non-zero weight on a side but no return on that side,
+ if a weight or resolved return is non-finite, or if the tolerance
+ is non-finite or negative.
"""
ordered: list[str] = list(portfolio_weights)
ordered.extend(sector for sector in benchmark_weights if sector not in portfolio_weights)
if not ordered:
raise ValueError("brinson_fachler needs at least one sector")
+ if not math.isfinite(weight_sum_tolerance) or weight_sum_tolerance < 0.0:
+ raise ValueError("weight_sum_tolerance must be finite and non-negative")
+ for side, weights in (
+ ("portfolio", portfolio_weights),
+ ("benchmark", benchmark_weights),
+ ):
+ for sector, weight in weights.items():
+ if not math.isfinite(weight):
+ raise ValueError(
+ f"sector {sector!r} has non-finite {side} weight {weight!r}"
+ )
+
portfolio_total = math.fsum(portfolio_weights.values())
benchmark_total = math.fsum(benchmark_weights.values())
if abs(portfolio_total - benchmark_total) > weight_sum_tolerance:
@@ -279,6 +293,11 @@ def brinson_fachler(
if w_b != 0.0:
raise ValueError(f"sector {sector!r} has benchmark weight {w_b!r} but no benchmark return")
r_b = r_p
+ for side, value in (("portfolio", r_p), ("benchmark", r_b)):
+ if not math.isfinite(value):
+ raise ValueError(
+ f"sector {sector!r} has non-finite {side} return {value!r}"
+ )
resolved.append((sector, w_p, w_b, float(r_p), float(r_b)))
total_portfolio_return = math.fsum(w_p * r_p for _, w_p, _, r_p, _ in resolved)
@@ -330,8 +349,11 @@ def carino_factor(portfolio_return: float, benchmark_return: float) -> float:
Raises:
ValueError: If either return is at or below -100%, which would make the
- wealth relative non-positive and the logarithm undefined.
+ wealth relative non-positive and the logarithm undefined, or if
+ either return is non-finite.
"""
+ if not math.isfinite(portfolio_return) or not math.isfinite(benchmark_return):
+ raise ValueError("Carino linking needs finite portfolio and benchmark returns")
portfolio_wealth = 1.0 + portfolio_return
benchmark_wealth = 1.0 + benchmark_return
if portfolio_wealth <= 0.0 or benchmark_wealth <= 0.0:
diff --git a/agent/tests/quantlib/test_attribution_nonfinite.py b/agent/tests/quantlib/test_attribution_nonfinite.py
new file mode 100644
index 000000000..63987544e
--- /dev/null
+++ b/agent/tests/quantlib/test_attribution_nonfinite.py
@@ -0,0 +1,83 @@
+"""Invalid sector data must not masquerade as residual-free attribution."""
+
+import json
+import math
+
+import pytest
+
+from src.quantlib.attribution import brinson_fachler, carino_factor, carino_link
+
+
[email protected]("bad", [math.nan, math.inf, -math.inf])
+def test_matching_nonfinite_weights_do_not_bypass_weight_sum_guard(bad: float) -> None:
+ with pytest.raises(ValueError, match="finite"):
+ brinson_fachler({"A": bad}, {"A": bad}, {"A": 0.1}, {"A": 0.05})
+
+
[email protected]("bad", [math.nan, math.inf, -math.inf])
[email protected]("side", ["portfolio", "benchmark"])
+def test_nonfinite_sector_returns_are_rejected(bad: float, side: str) -> None:
+ portfolio_returns = {"A": bad if side == "portfolio" else 0.1}
+ benchmark_returns = {"A": bad if side == "benchmark" else 0.05}
+ with pytest.raises(ValueError, match="finite"):
+ brinson_fachler({"A": 1.0}, {"A": 1.0}, portfolio_returns, benchmark_returns)
+
+
[email protected]("tolerance", [math.nan, math.inf, -1.0])
+def test_invalid_tolerance_cannot_disable_attribution_reconciliation(
+ tolerance: float,
+) -> None:
+ with pytest.raises(ValueError, match="weight_sum_tolerance"):
+ brinson_fachler({"A": 0.8}, {"A": 1.0}, {"A": 0.1}, {"A": 0.05}, tolerance)
+
+
[email protected]("bad", [math.nan, math.inf])
[email protected]("side", ["portfolio", "benchmark"])
+def test_carino_factor_rejects_nonfinite_returns(bad: float, side: str) -> None:
+ portfolio = bad if side == "portfolio" else 0.1
+ benchmark = bad if side == "benchmark" else 0.05
+ with pytest.raises(ValueError, match="finite"):
+ carino_factor(portfolio, benchmark)
+
+
+def test_finite_short_weights_and_absent_zero_weight_returns_still_reconcile() -> None:
+ result = brinson_fachler(
+ {"A": 1.2, "B": -0.2, "C": 0.0},
+ {"A": 0.8, "B": 0.2, "C": 0.0},
+ {"A": 0.1, "B": -0.05},
+ {"A": 0.08, "B": -0.02, "C": 0.04},
+ weight_sum_tolerance=0.0,
+ )
+ assert result.total_effect == pytest.approx(result.active_return)
+ linked = carino_link([result, result])
+ assert linked.total_effect == pytest.approx(linked.active_return)
+ assert all(math.isfinite(value) for value in linked.scaling_factors)
+
+
+ "function, kwargs",
+ [
+ (
+ "brinson_fachler",
+ {
+ "portfolio_weights": {"A": 1.0},
+ "benchmark_weights": {"A": 1.0},
+ "portfolio_returns": {"A": math.nan},
+ "benchmark_returns": {"A": 0.05},
+ },
+ ),
+ ("carino_factor", {"portfolio_return": math.nan, "benchmark_return": 0.05}),
+ ],
+)
+def test_quantlib_tool_reports_invalid_attribution_as_error(
+ function: str, kwargs: dict
+) -> None:
+ from src.tools.quantlib_tool import QuantlibCallTool
+
+ result = json.loads(
+ QuantlibCallTool().execute(
+ action="call", module="attribution", function=function, kwargs=kwargs
+ )
+ )
+ assert result["ok"] is False
+ assert "finite" in result["error"]