"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: guard zero-weight Brinson divisions, contain artifact symbols, unify chart lifecycle
shadowinlife564c783d4b56
diff --git a/agent/src/api/attribution_core.py b/agent/src/api/attribution_core.pyindex 518115c04..f4b3995a1 100644--- a/agent/src/api/attribution_core.py+++ b/agent/src/api/attribution_core.py@@ -39,6 +39,10 @@ _ATTRIBUTION_BENCHMARK_VARIANCE_FLOOR = 1e-16_ATTRIBUTION_CASH_WEIGHT_TOLERANCE = 1e-6#: Smallest invested weight still reported in the invested/cash fallback._ATTRIBUTION_MIN_INVESTED_WEIGHT = 1e-9+#: Net asset-class weight below which asset-class Brinson degrades to the+#: invested/cash fallback instead of dividing by the class weight (a+#: market-neutral pair inside one class nets to zero and would crash).+_ATTRIBUTION_CLASS_WEIGHT_FLOOR = 1e-9#: Annualization factor used when the run's interval is unknown._ATTRIBUTION_DEFAULT_BARS_PER_YEAR = 252@@ -225,12 +229,30 @@ def _attribution_benchmark_returns_from_equity(benchmark_equity: List[float]) ->return returns+def _attribution_symbol_is_path_safe(symbol: str) -> bool:+ """Reject symbols that could escape the artifacts directory when used in paths.++ Symbols come from ``positions.csv`` headers and ``config.json`` codes and+ are interpolated into ``ohlcv_<symbol>.csv`` file names, so path+ separators, ``..`` sequences, and NUL bytes must never reach the path join.+ """+ return (+ bool(symbol)+ and "\x00" not in symbol+ and "/" not in symbol+ and "\\" not in symbol+ and ".." not in symbol+ )++def _attribution_symbol_cumulative_return(run_dir: Path, symbol: str) -> Optional[float]:"""Buy-and-hold close-to-close return for one symbol from its OHLCV artifact.Returns ``last_close / first_close - 1`` over the date-sorted rows, or``None`` when the artifact is missing, too short, or starts non-positive."""+ if not _attribution_symbol_is_path_safe(symbol):+ return Nonefieldnames, rows = _attribution_read_csv(run_dir / "artifacts" / f"ohlcv_{symbol}.csv")if fieldnames is None or "close" not in fieldnames or not rows:return None@@ -256,12 +278,15 @@ def _attribution_equal_weight_returns(Used as the auto-benchmark series when ``equity.csv`` carries no``benchmark_equity`` column. A symbol's first observed date contributes- 0.0. Returns ``None`` when any date lacks symbol coverage.+ 0.0. A date with no symbol coverage at all fails the whole series+ (``None``); dates with partial coverage average the available subset."""if not codes or not dates:return Noneper_symbol: List[Dict[str, float]] = []for symbol in codes:+ if not _attribution_symbol_is_path_safe(symbol):+ continuefieldnames, rows = _attribution_read_csv(run_dir / "artifacts" / f"ohlcv_{symbol}.csv")if fieldnames is None or "close" not in fieldnames or not rows:continue@@ -541,7 +566,7 @@ def _attribution_brinson_section(weights = _attribution_load_position_weights(run_dir, notes)if weights is None:return None- if all(abs(weight) <= 0.0 for weight in weights.values()):+ if all(weight == 0.0 for weight in weights.values()):notes.append("brinson attribution skipped: all position weights are zero")return None@@ -574,7 +599,9 @@ def _attribution_brinson_symbol_mode(returns[symbol] = symbol_returnincluded = [symbol for symbol in symbols if symbol in returns]if not included:- notes.append("brinson attribution skipped: positions.csv could not be parsed")+ notes.append(+ "brinson attribution skipped: no per-symbol returns could be resolved from ohlcv artifacts"+ )return Noneportfolio_weights = {symbol: weights.get(symbol, 0.0) for symbol in included}@@ -618,13 +645,16 @@ def _attribution_brinson_asset_class_mode(if benchmark_equity_state != "ok" or not benchmark_equity:notes.append("brinson attribution skipped: no benchmark_equity series in equity.csv")return None+ if benchmark_equity[0] <= 0.0:+ notes.append("brinson attribution skipped: benchmark_equity starts at a non-positive value")+ return Nonebenchmark_cumulative = benchmark_equity[-1] / benchmark_equity[0] - 1.0benchmark_class = str(_detect_market(benchmark_ticker))class_weights: Dict[str, float] = {}class_return_sums: Dict[str, float] = {}for symbol, weight in weights.items():- if abs(weight) <= 0.0:+ if weight == 0.0:continueasset_class = str(_detect_market(symbol))class_weights[asset_class] = class_weights.get(asset_class, 0.0) + weight@@ -636,7 +666,9 @@ def _attribution_brinson_asset_class_mode(portfolio_returns_by_class: Dict[str, float] = {}degraded = Falsefor asset_class, class_weight in class_weights.items():- if asset_class not in class_return_sums:+ # A class whose long/short weights net to zero (market-neutral pair+ # inside one class) would divide by zero below; degrade instead.+ if asset_class not in class_return_sums or abs(class_weight) <= _ATTRIBUTION_CLASS_WEIGHT_FLOOR:degraded = Truebreakportfolio_weights[asset_class] = class_weightdiff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex 821f7e462..48525148e 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -505,10 +505,10 @@ def _read_positions_symbols(path: Path) -> List[str]:Returns:Symbol column names in file order; empty when the file is missing,- empty, or unreadable.+ a symlink, empty, or unreadable."""try:- if not path.exists():+ if not path.exists() or path.is_symlink():return []with path.open("r", encoding="utf-8", newline="") as handle:fieldnames = csv.DictReader(handle).fieldnames@@ -630,11 +630,16 @@ def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) ->"total_symbols": len(symbols),"symbol_limit": _POSITIONS_SECTOR_MAX_SYMBOLS,}+ tmp_path = cache_path.with_name(f".sector_map.{os.getpid()}.{threading.get_ident()}.tmp")try:cache_path.parent.mkdir(parents=True, exist_ok=True)- cache_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")+ tmp_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")+ os.replace(tmp_path, cache_path)except OSError:- pass+ try:+ tmp_path.unlink(missing_ok=True)+ except OSError:+ passreturn payloaddiff --git a/agent/tests/api/test_positions_sectors.py b/agent/tests/api/test_positions_sectors.pyindex dcb033c0a..83aeca727 100644--- a/agent/tests/api/test_positions_sectors.py+++ b/agent/tests/api/test_positions_sectors.py@@ -309,6 +309,37 @@ def test_symlinked_cache_file_rejected_without_write_through(tmp_path: Path, monassert target.read_text(encoding="utf-8") == "sentinel"+def test_symlinked_positions_csv_rejected_without_read(tmp_path: Path, monkeypatch) -> None:+ """A symlinked ``positions.csv`` is rejected like a symlinked artifacts dir.++ The artifacts directory itself is real here; only positions.csv is a+ symlink. Following it would disclose the target file's header line in the+ response, so the endpoint must treat it as having no positions artifact.+ """+ run_dir = tmp_path / "runs" / RUN_ID+ (run_dir / "artifacts").mkdir(parents=True)+ target = tmp_path / "secret.csv"+ target.write_text("timestamp,LEAKED.SECRET\n2026-08-01T00:00:00,1.0\n", encoding="utf-8")+ (run_dir / "artifacts" / "positions.csv").symlink_to(target)+ client = _client(tmp_path, monkeypatch)++ with patch("src.tools.sector_tool.resolve_secid") as resolve, patch(+ "src.tools.sector_tool.get_json"+ ) as get:+ response = client.get(f"/runs/{RUN_ID}/positions/sectors")++ assert response.status_code == 200+ assert response.json() == {+ "ok": True,+ "run_id": RUN_ID,+ "symbols": {},+ "note": "no positions artifact",+ }+ resolve.assert_not_called()+ get.assert_not_called()+ assert target.read_text(encoding="utf-8").startswith("timestamp,LEAKED.SECRET")++# ============================================================================# Endpoint: bounded contract for large books# ============================================================================diff --git a/agent/tests/test_attribution_api.py b/agent/tests/test_attribution_api.pyindex 65b5eb11e..57851c651 100644--- a/agent/tests/test_attribution_api.py+++ b/agent/tests/test_attribution_api.py@@ -301,3 +301,124 @@ def test_attribution_long_series_downsampled_with_last_point_pinned(benchmark[0] = 0.0expected_total = float(np.prod(1.0 + (0.001 + 1.2 * benchmark)) - 1.0)assert factor["cumulative"][-1]["portfolio"] == pytest.approx(expected_total, abs=1e-6)+++def _build_market_neutral_run(tmp_path: Path, run_id: str) -> Path:+ """Explicit-benchmark run whose only asset class nets to zero (+0.5/-0.5 pair)."""+ run_dir = tmp_path / "runs" / run_id+ benchmark = np.array([0.001 if i % 2 else -0.001 for i in range(N_BARS)])+ benchmark[0] = 0.0+ portfolio = 0.0005 + 0.8 * benchmark+ dates = _trading_dates(N_BARS)++ _write_equity(run_dir, dates, portfolio, benchmark)+ _write_csv(+ run_dir / "artifacts" / "positions.csv",+ ["timestamp", SYMBOL_A, SYMBOL_B],+ [[day, "0.5", "-0.5"] for day in dates],+ )+ _write_ohlcv(run_dir, SYMBOL_A, dates, 100.0, 110.0)+ _write_ohlcv(run_dir, SYMBOL_B, dates, 100.0, 95.0)+ _write_config(run_dir, [SYMBOL_A, SYMBOL_B], benchmark="SPY.US")+ _write_metrics(run_dir, extra={"benchmark_ticker": "SPY.US"})+ return run_dir+++def test_attribution_market_neutral_pair_degrades_instead_of_crashing(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A +0.5/-0.5 pair nets its asset-class weight to zero: the class return+ would divide by zero, so asset-class mode must degrade, not 500."""+ client = _client(tmp_path, monkeypatch)+ _build_market_neutral_run(tmp_path, "attr-pair")++ response = client.get("/runs/attr-pair/attribution")++ assert response.status_code == 200+ data = response.json()+ assert data["exists"] is True+ assert data["factor"] is not None+ assert data["factor"]["beta"] == pytest.approx(0.8, abs=1e-6)+ brinson = data["brinson"]+ assert brinson is not None+ assert brinson["mode"] == "invested_cash"+ sectors = {sector["sector"]: sector for sector in brinson["sectors"]}+ assert sectors["invested"]["portfolio_weight"] == pytest.approx(1.0, abs=1e-9)+ assert any("invested/cash" in note for note in data["notes"])+++def test_attribution_benchmark_equity_starting_at_zero_skips_brinson(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """benchmark_equity[0] == 0 would divide by zero in the cumulative return;+ the endpoint must skip Brinson with a note instead of crashing."""+ client = _client(tmp_path, monkeypatch)+ run_dir = tmp_path / "runs" / "attr-zero-bench"+ dates = _trading_dates(N_BARS)+ rows = [+ [day, "0.001", f"{1_000_000.0 + index:.6f}", "0.0", f"{index:.6f}", "0.0005"]+ for index, day in enumerate(dates)+ ]+ _write_csv(+ run_dir / "artifacts" / "equity.csv",+ ["timestamp", "ret", "equity", "drawdown", "benchmark_equity", "active_ret"],+ rows,+ )+ _write_csv(+ run_dir / "artifacts" / "positions.csv",+ ["timestamp", SYMBOL_A],+ [[day, "0.6"] for day in dates],+ )+ _write_ohlcv(run_dir, SYMBOL_A, dates, 100.0, 110.0)+ _write_config(run_dir, [SYMBOL_A], benchmark="SPY.US")+ _write_metrics(run_dir, extra={"benchmark_ticker": "SPY.US"})++ response = client.get("/runs/attr-zero-bench/attribution")++ assert response.status_code == 200+ data = response.json()+ assert data["exists"] is True+ assert data["brinson"] is None+ assert any("non-positive" in note for note in data["notes"])+++def test_attribution_artifact_symbol_path_traversal_is_contained(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Symbols from positions.csv headers are interpolated into ohlcv file+ names; traversal-shaped symbols must be ignored, not resolved as paths.++ The fixture plants ``run_dir/target.csv`` plus an ``artifacts/ohlcv_x``+ directory so that on unpatched code the symbol ``x/../../target`` would+ resolve to ``ohlcv_x/../../target.csv`` == ``run_dir/target.csv`` and leak+ its return series into the Brinson sectors.+ """+ client = _client(tmp_path, monkeypatch)+ run_dir = tmp_path / "runs" / "attr-traversal"+ dates = _trading_dates(N_BARS)+ rng = np.random.default_rng(13)+ benchmark = rng.normal(0.0004, 0.008, N_BARS)+ benchmark[0] = 0.0+ portfolio = 0.0002 + 0.9 * benchmark+ _write_equity(run_dir, dates, portfolio, benchmark)+ (run_dir / "artifacts" / "ohlcv_x").mkdir(parents=True)+ _write_csv(run_dir / "target.csv", ["trade_date", "close"], [[dates[0], "100.0"], [dates[-1], "999.0"]])+ _write_csv(+ run_dir / "artifacts" / "positions.csv",+ ["timestamp", SYMBOL_A, "x/../../target"],+ [[day, "0.6", "0.4"] for day in dates],+ )+ _write_ohlcv(run_dir, SYMBOL_A, dates, 100.0, 110.0)+ _write_config(run_dir, [SYMBOL_A, "x/../../target"])+ _write_metrics(run_dir)++ response = client.get("/runs/attr-traversal/attribution")++ assert response.status_code == 200+ data = response.json()+ assert data["exists"] is True+ brinson = data["brinson"]+ assert brinson is not None+ assert brinson["mode"] == "symbol"+ sectors = {sector["sector"]: sector for sector in brinson["sectors"]}+ assert set(sectors) == {SYMBOL_A, "Cash"}diff --git a/frontend/src/components/charts/AttributionCumulativeChart.tsx b/frontend/src/components/charts/AttributionCumulativeChart.tsxindex 1c0660dfe..62c57095c 100644--- a/frontend/src/components/charts/AttributionCumulativeChart.tsx+++ b/frontend/src/components/charts/AttributionCumulativeChart.tsx@@ -1,11 +1,10 @@-import { useEffect, useRef } from "react";+import { useRef } from "react";import i18n from "@/i18n";import type { AttributionCumulativePoint } from "@/lib/api";import { getChartTheme } from "@/lib/chart-theme";import { getPnlColors } from "@/lib/pnl-colors";-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { useChartLifecycle } from "@/hooks/useChartLifecycle";import { escapeHtml } from "@/lib/escapeHtml";-import { useThemeDark } from "@/lib/theme-store";interface Props {data: AttributionCumulativePoint[];@@ -14,22 +13,17 @@ interface Props {export function AttributionCumulativeChart({ data, height = 300 }: Props) {const ref = useRef<HTMLDivElement>(null);- const dark = useThemeDark();- useEffect(() => {- if (!ref.current || data.length === 0) return;+ useChartLifecycle(ref, () => {const t = getChartTheme();const pnl = getPnlColors();- const chart = echarts.init(ref.current);- chart.group = CHART_GROUP;- connectCharts();const portfolioLabel = i18n.t("runDetail.attrPortfolio");const benchmarkLabel = i18n.t("runDetail.attrBenchmark");const activeLabel = i18n.t("runDetail.attrActive");const dates = data.map((d) => d.date);- chart.setOption({+ return {backgroundColor: "transparent",tooltip: {trigger: "axis",@@ -103,23 +97,8 @@ export function AttributionCumulativeChart({ data, height = 300 }: Props) {lineStyle: { color: pnl.profit, width: 1.5, type: "dashed" },},],- });-- let resizeFrame: number | null = null;- const ro = new ResizeObserver(() => {- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);- resizeFrame = requestAnimationFrame(() => {- resizeFrame = null;- chart.resize();- });- });- ro.observe(ref.current!);- return () => {- ro.disconnect();- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);- chart.dispose();};- }, [data, dark]);+ }, [data]);if (data.length === 0) {return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.attrNoFactor")}</div>;diff --git a/frontend/src/components/charts/AttributionWaterfallChart.tsx b/frontend/src/components/charts/AttributionWaterfallChart.tsxindex 2fc1b9706..c56f9cc7e 100644--- a/frontend/src/components/charts/AttributionWaterfallChart.tsx+++ b/frontend/src/components/charts/AttributionWaterfallChart.tsx@@ -1,10 +1,9 @@-import { useEffect, useRef } from "react";+import { useRef } from "react";import i18n from "@/i18n";import type { AttributionBrinson } from "@/lib/api";import { getChartTheme } from "@/lib/chart-theme";import { getPnlColors } from "@/lib/pnl-colors";-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";-import { useThemeDark } from "@/lib/theme-store";+import { useChartLifecycle } from "@/hooks/useChartLifecycle";export interface WaterfallBar {base: number;@@ -41,15 +40,10 @@ interface Props {export function AttributionWaterfallChart({ brinson, height = 300 }: Props) {const ref = useRef<HTMLDivElement>(null);- const dark = useThemeDark();- useEffect(() => {- if (!ref.current) return;+ useChartLifecycle(ref, () => {const t = getChartTheme();const pnl = getPnlColors();- const chart = echarts.init(ref.current);- chart.group = CHART_GROUP;- connectCharts();const bars = buildWaterfallBars(brinson);const categories = [@@ -77,7 +71,7 @@ export function AttributionWaterfallChart({ brinson, height = 300 }: Props) {},}));- chart.setOption({+ return {backgroundColor: "transparent",tooltip: {trigger: "axis",@@ -125,23 +119,8 @@ export function AttributionWaterfallChart({ brinson, height = 300 }: Props) {barWidth: "45%",},],- });-- let resizeFrame: number | null = null;- const ro = new ResizeObserver(() => {- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);- resizeFrame = requestAnimationFrame(() => {- resizeFrame = null;- chart.resize();- });- });- ro.observe(ref.current!);- return () => {- ro.disconnect();- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);- chart.dispose();};- }, [brinson, dark]);+ }, [brinson]);return <div ref={ref} style={{ height }} />;}diff --git a/frontend/src/components/charts/CandlestickChart.tsx b/frontend/src/components/charts/CandlestickChart.tsxindex 1bbc30d85..777b0727c 100644--- a/frontend/src/components/charts/CandlestickChart.tsx+++ b/frontend/src/components/charts/CandlestickChart.tsx@@ -7,6 +7,7 @@ import { calcMA, calcBOLL, calcMACD, calcRSI, calcKDJ, calcEMA } from "@/lib/indimport { getChartTheme } from "@/lib/chart-theme";import { abbreviateNum } from "@/lib/formatters";import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { escapeHtml } from "@/lib/escapeHtml";import { useThemeDark } from "@/lib/theme-store";type Sub = "vol" | "macd" | "rsi" | "kdj";@@ -150,11 +151,16 @@ export function CandlestickChart({ data, markers, indicators, height = 500 }: PrlegendNames.push("BOLL");}- // Trade markers+ // Trade markers (name renders as markPoint tooltip HTML, so every+ // artifact-derived field is escaped before interpolation)const marks = (markers || []).map(m => ({coord: [m.time, m.price],value: m.side === "BUY" ? "B" : "S",- name: [`${m.side} @ ${m.price}`, m.qty ? `Qty: ${m.qty}` : "", m.reason || ""].filter(Boolean).join("\n"),+ name: [+ `${escapeHtml(m.side)} @ ${escapeHtml(String(m.price))}`,+ m.qty ? `Qty: ${escapeHtml(String(m.qty))}` : "",+ escapeHtml(m.reason || ""),+ ].filter(Boolean).join("\n"),itemStyle: { color: m.side === "BUY" ? t.upColor : t.downColor },label: { color: "#fff", fontSize: 10, fontWeight: "bold" as const },}));diff --git a/frontend/src/components/charts/RollingBetaAlphaChart.tsx b/frontend/src/components/charts/RollingBetaAlphaChart.tsxindex bd308914c..431839ee8 100644--- a/frontend/src/components/charts/RollingBetaAlphaChart.tsx+++ b/frontend/src/components/charts/RollingBetaAlphaChart.tsx@@ -1,10 +1,9 @@-import { useEffect, useRef } from "react";+import { useRef } from "react";import i18n from "@/i18n";import type { AttributionRollingPoint } from "@/lib/api";import { getChartTheme } from "@/lib/chart-theme";-import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { useChartLifecycle } from "@/hooks/useChartLifecycle";import { escapeHtml } from "@/lib/escapeHtml";-import { useThemeDark } from "@/lib/theme-store";interface Props {data: AttributionRollingPoint[];@@ -13,14 +12,9 @@ interface Props {export function RollingBetaAlphaChart({ data, height = 280 }: Props) {const ref = useRef<HTMLDivElement>(null);- const dark = useThemeDark();- useEffect(() => {- if (!ref.current || data.length === 0) return;+ useChartLifecycle(ref, () => {const t = getChartTheme();- const chart = echarts.init(ref.current);- chart.group = CHART_GROUP;- connectCharts();const betaLabel = i18n.t("runDetail.attrBeta");const alphaLabel = i18n.t("runDetail.attrAlpha");@@ -28,7 +22,7 @@ export function RollingBetaAlphaChart({ data, height = 280 }: Props) {const betas = data.map((d) => +d.beta.toFixed(4));const alphas = data.map((d) => +(d.alpha_annualized * 100).toFixed(4));- chart.setOption({+ return {backgroundColor: "transparent",tooltip: {trigger: "axis",@@ -105,23 +99,8 @@ export function RollingBetaAlphaChart({ data, height = 280 }: Props) {lineStyle: { color: t.warningColor, width: 1.5 },},],- });-- let resizeFrame: number | null = null;- const ro = new ResizeObserver(() => {- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);- resizeFrame = requestAnimationFrame(() => {- resizeFrame = null;- chart.resize();- });- });- ro.observe(ref.current!);- return () => {- ro.disconnect();- if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);- chart.dispose();};- }, [data, dark]);+ }, [data]);if (data.length === 0) {return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.attrNoFactor")}</div>;