"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add positions structure visualization to Run Detail
shadowinlife1451135541be
diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex 27161373e..a85afcc2c 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -11,7 +11,7 @@ import mathimport osimport statisticsfrom collections import deque-from datetime import datetime+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Deque, Dict, Generator, List, Optional, Tuple@@ -460,6 +460,95 @@ def _factor_ic_correlation(factors: List[Dict[str, Any]]) -> Optional[Dict[str,return {"labels": [str(factor["name"]) for factor in factors], "matrix": matrix}+def _read_positions_symbols(path: Path) -> List[str]:+ """Read the symbol column names from a wide-format ``positions.csv``.++ Args:+ path: Path to ``artifacts/positions.csv`` (header+ ``timestamp,<sym1>,<sym2>,...``).++ Returns:+ Symbol column names in file order; empty when the file is missing,+ empty, or unreadable.+ """+ try:+ if not path.exists():+ return []+ with path.open("r", encoding="utf-8", newline="") as handle:+ fieldnames = csv.DictReader(handle).fieldnames+ except Exception:+ return []+ if not fieldnames:+ return []+ return [name.strip() for name in fieldnames[1:] if name and name.strip()]+++def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) -> Dict[str, Any]:+ """Resolve asset class + A-share industry for a run's position symbols.++ Serves from the ``artifacts/sector_map.json`` cache when a valid cache+ exists and ``refresh`` is false; otherwise recomputes and rewrites the+ cache. A corrupt cache file is treated as a cache miss.++ Args:+ run_dir: Persisted run directory containing ``artifacts/``.+ run_id: Run identifier echoed back in the response envelope.+ refresh: True bypasses the disk cache.++ Returns:+ The envelope ``{"ok", "run_id", "resolved_at", "cached", "symbols",+ "unresolved"}``, or the ``{"ok", "run_id", "symbols", "note"}`` form+ when no positions artifact exists.+ """+ from backtest.engines._market_hooks import _detect_market+ from src.tools.sector_tool import resolve_industry_board++ cache_path = run_dir / "artifacts" / "sector_map.json"+ if not refresh:+ cached = _load_json_file(cache_path)+ if isinstance(cached, dict) and isinstance(cached.get("symbols"), dict):+ cached["cached"] = True+ cached["run_id"] = run_id+ return cached++ symbols = _read_positions_symbols(run_dir / "artifacts" / "positions.csv")+ if not symbols:+ return {"ok": True, "run_id": run_id, "symbols": {}, "note": "no positions artifact"}++ resolved: Dict[str, Any] = {}+ unresolved: List[str] = []+ for symbol in symbols:+ asset_class = _detect_market(symbol)+ industry = None+ if asset_class == "a_share":+ try:+ industry = resolve_industry_board(symbol)+ except Exception: # noqa: BLE001 - one failure must not abort the batch+ industry = None+ resolved[symbol] = {+ "asset_class": asset_class,+ "industry": industry,+ "industry_source": "eastmoney" if industry is not None else None,+ }+ if asset_class == "a_share" and industry is None:+ unresolved.append(symbol)++ payload: Dict[str, Any] = {+ "ok": True,+ "run_id": run_id,+ "resolved_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),+ "cached": False,+ "symbols": resolved,+ "unresolved": unresolved,+ }+ 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")+ except OSError:+ pass+ return payload++def _run_response_payload(response: Any) -> Dict[str, Any]:"""Return a JSON-ready payload for opt-in run response variants."""return response.model_dump(mode="json")@@ -798,6 +887,37 @@ def register_runs_routes(return response+ @app.get("/runs/{run_id}/positions/sectors", dependencies=[Depends(require_auth)])+ async def get_run_positions_sectors(+ run_id: str,+ refresh: int = Query(0, description="Set to 1 to bypass the disk cache and recompute."),+ ):+ """Resolve asset class + A-share industry for a run's position symbols.++ Read-only classification over ``artifacts/positions.csv``, cached in+ ``artifacts/sector_map.json``.++ Args:+ run_id: Run identifier.+ refresh: ``1`` bypasses the disk cache, ``0`` (default) serves it.++ Returns:+ The sector-map envelope built by ``_build_positions_sector_map``.++ Raises:+ HTTPException: 404 when the run directory does not exist.+ """+ _host_validate_path_param(run_id, "run_id")+ run_dir = _host_RUNS_DIR() / run_id++ if not run_dir.exists():+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Run {run_id} not found"+ )++ return _build_positions_sector_map(run_dir, run_id, refresh=bool(refresh))+@app.get("/runs", response_model=List[RunInfo], dependencies=[Depends(require_auth)])async def list_runs(limit: int = 20):"""List recent runs with summary fields."""diff --git a/agent/src/tools/sector_tool.py b/agent/src/tools/sector_tool.pyindex f3956b935..34dde820c 100644--- a/agent/src/tools/sector_tool.py+++ b/agent/src/tools/sector_tool.py@@ -23,6 +23,7 @@ import jsonimport loggingfrom typing import Any+from backtest.engines._market_hooks import _detect_marketfrom backtest.loaders.eastmoney_client import get_json, resolve_secidfrom src.agent.tools import BaseTool@@ -38,6 +39,10 @@ _RANKING_URL = "https://push2.eastmoney.com/api/qt/clist/get"_MEMBERSHIP_FIELDS = "f12,f13,f14,f3,f2"_RANKING_FIELDS = "f12,f14,f3,f2,f104,f105,f128,f140"+# Industry-only selector (f13 = market marker distinguishing the stock row+# from its board row in the spt=1 single-industry response).+_INDUSTRY_FIELDS = "f12,f13,f14"+# Industry-board universe selector for the ranking view (m:90 = board market,# t:2 = industry board sub-type). Sort by f3 (change percent), descending._RANKING_FS = "m:90+t:2"@@ -198,6 +203,57 @@ def _fetch_membership(code: str) -> str:return json.dumps(envelope, ensure_ascii=False)+def resolve_industry_board(code: str) -> str | None:+ """Resolve the single Eastmoney industry board (行业板块) name for an A-share.++ Unlike the membership view (``spt=3``), which mixes industry and concept+ boards into one list, the ``slist`` endpoint with ``spt=1`` returns the+ stock itself plus its single industry board. The board row is the one with+ ``f13 == 90`` (the board-market marker); the stock row carries ``f13`` of+ ``1``/``0`` instead.++ Args:+ code: Vibe-Trading symbol (e.g. ``"600519.SH"``).++ Returns:+ The industry board name (e.g. ``"白酒Ⅱ"``), or ``None`` when the symbol+ is not an A-share, is unresolvable, the request fails, or the payload+ carries no board row. Never raises.+ """+ if _detect_market(code) != "a_share":+ return None++ secid = resolve_secid(code)+ if secid is None:+ return None++ try:+ payload = get_json(+ _MEMBERSHIP_URL,+ params={+ "secid": secid,+ "spt": "1",+ "pi": "0",+ "pz": "100",+ "fields": _INDUSTRY_FIELDS,+ "fltt": "2",+ "po": "1",+ },+ )+ except Exception as exc: # noqa: BLE001 - a failed lookup degrades to None+ logger.warning("industry board fetch failed for %s: %s", code, exc)+ return None++ for row in _diff_rows(payload):+ if not isinstance(row, dict):+ continue+ if row.get("f13") in (90, "90"):+ board_name = row.get("f14")+ if board_name and board_name != "-":+ return str(board_name)+ return None++def _fetch_ranking(limit: int) -> str:"""Fetch the industry-board ranking by intraday percent change.diff --git a/agent/tests/api/__init__.py b/agent/tests/api/__init__.pynew file mode 100644index 000000000..ae5ee13fd--- /dev/null+++ b/agent/tests/api/__init__.py@@ -0,0 +1 @@+"""Tests for the FastAPI route modules under ``src/api``."""diff --git a/agent/tests/api/test_positions_sectors.py b/agent/tests/api/test_positions_sectors.pynew file mode 100644index 000000000..4a17425d1--- /dev/null+++ b/agent/tests/api/test_positions_sectors.py@@ -0,0 +1,289 @@+"""Tests for GET /runs/{run_id}/positions/sectors and resolve_industry_board.++All Eastmoney HTTP is mocked at the import sites in ``src.tools.sector_tool``+(:func:`get_json` / :func:`resolve_secid`), so no test touches a live endpoint.+Run directories are fabricated under ``tmp_path`` mirroring the layout the+run-detail handler expects (``RUNS_DIR/<run_id>/artifacts/positions.csv``).+"""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import patch++from fastapi.testclient import TestClient++import api_server+from src.tools.sector_tool import resolve_industry_board++RUN_ID = "run_20260801_120000"++# Verified spt=1 shape: diff keyed by string index, row "0" the stock itself+# (f13 = 1/0), row "1" the industry board (f13 = 90).+_SLIST_600519 = {+ "data": {+ "diff": {+ "0": {"f12": "600519", "f13": 1, "f14": "贵州茅台"},+ "1": {"f12": "BK1277", "f13": 90, "f14": "白酒Ⅱ"},+ }+ }+}++# A-share payload with no board row -> industry stays unresolved.+_SLIST_159913_NO_BOARD = {+ "data": {"diff": {"0": {"f12": "159913", "f13": 0, "f14": "创业板ETF"}}}+}++_SECIDS = {"600519.SH": "1.600519", "159913.SZ": "0.159913"}+++def _client(tmp_path: Path, monkeypatch) -> TestClient:+ monkeypatch.setattr(api_server, "RUNS_DIR", tmp_path / "runs")+ return TestClient(api_server.app, client=("127.0.0.1", 50000))+++def _make_run(tmp_path: Path, header: str, rows: list[str] | None = None) -> Path:+ run_dir = tmp_path / "runs" / RUN_ID+ artifacts = run_dir / "artifacts"+ artifacts.mkdir(parents=True)+ lines = [header, *(rows or [])]+ (artifacts / "positions.csv").write_text("\n".join(lines) + "\n", encoding="utf-8")+ return run_dir+++def _fake_resolve_secid(symbol: str) -> str | None:+ return _SECIDS.get(symbol)+++def _fake_get_json(url: str, *, params: dict) -> dict:+ secid = params["secid"]+ if secid == "1.600519":+ return _SLIST_600519+ if secid == "0.159913":+ return _SLIST_159913_NO_BOARD+ raise AssertionError(f"unexpected secid: {secid}")+++# ============================================================================+# Endpoint: happy path+# ============================================================================+++def test_positions_sectors_happy_path(tmp_path: Path, monkeypatch) -> None:+ _make_run(+ tmp_path,+ "timestamp,600519.SH,AAPL.US,159913.SZ",+ ["2026-08-01T00:00:00,0.5,0.3,0.2"],+ )+ client = _client(tmp_path, monkeypatch)++ with patch(+ "src.tools.sector_tool.resolve_secid", side_effect=_fake_resolve_secid+ ) as resolve, patch("src.tools.sector_tool.get_json", side_effect=_fake_get_json) as get:+ response = client.get(f"/runs/{RUN_ID}/positions/sectors")++ assert response.status_code == 200+ payload = response.json()+ assert payload["ok"] is True+ assert payload["run_id"] == RUN_ID+ assert payload["cached"] is False+ assert payload["resolved_at"].endswith("Z")+ assert payload["symbols"]["600519.SH"] == {+ "asset_class": "a_share",+ "industry": "白酒Ⅱ",+ "industry_source": "eastmoney",+ }+ assert payload["symbols"]["AAPL.US"] == {+ "asset_class": "us_equity",+ "industry": None,+ "industry_source": None,+ }+ assert payload["symbols"]["159913.SZ"]["industry"] is None+ assert payload["symbols"]["159913.SZ"]["industry_source"] is None+ assert payload["unresolved"] == ["159913.SZ"]++ # One spt=1 industry request per A-share symbol; US symbols never resolve.+ assert get.call_count == 2+ for call in get.call_args_list:+ assert call.kwargs["params"]["spt"] == "1"+ assert "slist/get" in call.args[0]+ assert resolve.call_count == 2++ cache_path = tmp_path / "runs" / RUN_ID / "artifacts" / "sector_map.json"+ cache = json.loads(cache_path.read_text(encoding="utf-8"))+ assert cache["symbols"]["600519.SH"]["industry"] == "白酒Ⅱ"+++def test_non_a_share_symbols_never_call_eastmoney(tmp_path: Path, monkeypatch) -> None:+ _make_run(+ tmp_path,+ "timestamp,AAPL.US,00700.HK,BTC-USDT",+ ["2026-08-01T00:00:00,0.4,0.3,0.3"],+ )+ 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+ payload = response.json()+ assert payload["symbols"]["AAPL.US"]["asset_class"] == "us_equity"+ assert payload["symbols"]["00700.HK"] == {+ "asset_class": "hk_equity",+ "industry": None,+ "industry_source": None,+ }+ assert payload["symbols"]["BTC-USDT"]["asset_class"] == "crypto"+ assert payload["unresolved"] == []+ resolve.assert_not_called()+ get.assert_not_called()+++# ============================================================================+# Endpoint: cache behaviour+# ============================================================================+++def test_positions_sectors_cache_hit_makes_zero_network_calls(tmp_path: Path, monkeypatch) -> None:+ _make_run(tmp_path, "timestamp,600519.SH", ["2026-08-01T00:00:00,1.0"])+ client = _client(tmp_path, monkeypatch)++ with patch(+ "src.tools.sector_tool.resolve_secid", side_effect=_fake_resolve_secid+ ), patch("src.tools.sector_tool.get_json", side_effect=_fake_get_json):+ first = client.get(f"/runs/{RUN_ID}/positions/sectors")+ assert first.status_code == 200+ assert first.json()["cached"] is False++ with patch("src.tools.sector_tool.resolve_secid") as resolve, patch(+ "src.tools.sector_tool.get_json"+ ) as get:+ second = client.get(f"/runs/{RUN_ID}/positions/sectors")++ assert second.status_code == 200+ payload = second.json()+ assert payload["cached"] is True+ assert payload["resolved_at"] == first.json()["resolved_at"]+ assert payload["symbols"]["600519.SH"]["industry"] == "白酒Ⅱ"+ resolve.assert_not_called()+ get.assert_not_called()+++def test_positions_sectors_refresh_bypasses_cache(tmp_path: Path, monkeypatch) -> None:+ _make_run(tmp_path, "timestamp,600519.SH", ["2026-08-01T00:00:00,1.0"])+ client = _client(tmp_path, monkeypatch)++ with patch(+ "src.tools.sector_tool.resolve_secid", side_effect=_fake_resolve_secid+ ), patch("src.tools.sector_tool.get_json", side_effect=_fake_get_json) as get:+ first = client.get(f"/runs/{RUN_ID}/positions/sectors")+ second = client.get(f"/runs/{RUN_ID}/positions/sectors?refresh=1")++ assert first.json()["cached"] is False+ assert second.json()["cached"] is False+ assert second.json()["symbols"]["600519.SH"]["industry"] == "白酒Ⅱ"+ assert get.call_count == 2+++def test_positions_sectors_corrupt_cache_recomputes(tmp_path: Path, monkeypatch) -> None:+ run_dir = _make_run(tmp_path, "timestamp,600519.SH", ["2026-08-01T00:00:00,1.0"])+ (run_dir / "artifacts" / "sector_map.json").write_text("{not json", encoding="utf-8")+ client = _client(tmp_path, monkeypatch)++ with patch(+ "src.tools.sector_tool.resolve_secid", side_effect=_fake_resolve_secid+ ), patch("src.tools.sector_tool.get_json", side_effect=_fake_get_json) as get:+ response = client.get(f"/runs/{RUN_ID}/positions/sectors")++ assert response.status_code == 200+ payload = response.json()+ assert payload["cached"] is False+ assert payload["symbols"]["600519.SH"]["industry"] == "白酒Ⅱ"+ assert get.call_count == 1+++# ============================================================================+# Endpoint: degenerate runs+# ============================================================================+++def test_missing_positions_csv_returns_note(tmp_path: Path, monkeypatch) -> None:+ (tmp_path / "runs" / RUN_ID).mkdir(parents=True)+ client = _client(tmp_path, monkeypatch)++ 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",+ }+++def test_empty_positions_csv_returns_note(tmp_path: Path, monkeypatch) -> None:+ run_dir = tmp_path / "runs" / RUN_ID+ (run_dir / "artifacts").mkdir(parents=True)+ (run_dir / "artifacts" / "positions.csv").write_text("", encoding="utf-8")+ client = _client(tmp_path, monkeypatch)++ response = client.get(f"/runs/{RUN_ID}/positions/sectors")++ assert response.status_code == 200+ payload = response.json()+ assert payload["symbols"] == {}+ assert payload["note"] == "no positions artifact"+++def test_unknown_run_id_returns_404(tmp_path: Path, monkeypatch) -> None:+ client = _client(tmp_path, monkeypatch)++ response = client.get("/runs/no-such-run/positions/sectors")++ assert response.status_code == 404+ assert response.json()["detail"] == "Run no-such-run not found"+++# ============================================================================+# resolve_industry_board helper+# ============================================================================+++class TestResolveIndustryBoard:+ """Direct unit tests for the sector_tool helper."""++ def test_returns_board_row_name_with_spt_1(self) -> None:+ with patch(+ "src.tools.sector_tool.resolve_secid", return_value="1.600519"+ ), patch("src.tools.sector_tool.get_json", return_value=_SLIST_600519) as get:+ assert resolve_industry_board("600519.SH") == "白酒Ⅱ"++ params = get.call_args.kwargs["params"]+ assert params["spt"] == "1"+ assert params["secid"] == "1.600519"+ assert params["fltt"] == "2"++ def test_non_a_share_returns_none_without_any_call(self) -> None:+ with patch("src.tools.sector_tool.resolve_secid") as resolve, patch(+ "src.tools.sector_tool.get_json"+ ) as get:+ assert resolve_industry_board("AAPL.US") is None++ resolve.assert_not_called()+ get.assert_not_called()++ def test_request_failure_returns_none(self) -> None:+ with patch(+ "src.tools.sector_tool.resolve_secid", return_value="1.600519"+ ), patch("src.tools.sector_tool.get_json", side_effect=RuntimeError("HTTP 429")):+ assert resolve_industry_board("600519.SH") is None++ def test_missing_board_row_returns_none(self) -> None:+ with patch(+ "src.tools.sector_tool.resolve_secid", return_value="0.159913"+ ), patch("src.tools.sector_tool.get_json", return_value=_SLIST_159913_NO_BOARD):+ assert resolve_industry_board("159913.SZ") is Nonediff --git a/frontend/src/components/run/PositionsTab.tsx b/frontend/src/components/run/PositionsTab.tsxnew file mode 100644index 000000000..f8b0337f7--- /dev/null+++ b/frontend/src/components/run/PositionsTab.tsx@@ -0,0 +1,540 @@+import { useEffect, useMemo, useRef, useState } from "react";+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Loader2 } from "lucide-react";+import type { EChartsCoreOption } from "echarts/core";+import { fetchRunSectorMap, type RunData, type SectorMapResponse } from "@/lib/api";+import { getChartTheme } from "@/lib/chart-theme";+import { echarts } from "@/lib/echarts";+import { useThemeDark } from "@/lib/theme-store";+import { cn } from "@/lib/utils";+import {+ CASH_SYMBOL,+ aggregateWeights,+ classifyAssetClass,+ downsampleDates,+ latestHoldingDate,+ parsePositionsPanel,+ withCashSlice,+ type AssetClass,+} from "@/lib/positions";++const CASH_COLOR = "#9ca3af";+const MAX_EVOLUTION_DATES = 500;+const MAX_LEGEND_SYMBOLS = 10;++const ASSET_CLASS_LABEL_KEYS = {+ a_share: "runDetail.positions.assetClass.a_share",+ us_equity: "runDetail.positions.assetClass.us_equity",+ hk_equity: "runDetail.positions.assetClass.hk_equity",+ ca_equity: "runDetail.positions.assetClass.ca_equity",+ kr_equity: "runDetail.positions.assetClass.kr_equity",+ india_equity: "runDetail.positions.assetClass.india_equity",+ crypto: "runDetail.positions.assetClass.crypto",+ futures: "runDetail.positions.assetClass.futures",+ forex: "runDetail.positions.assetClass.forex",+ other: "runDetail.positions.assetClass.other",+} as const satisfies Record<AssetClass, string>;++function formatPercent(value: number, digits = 1): string {+ return `${(value * 100).toFixed(digits)}%`;+}++function categoryColors(t: ReturnType<typeof getChartTheme>): string[] {+ return [+ t.infoColor, t.warningColor, "#8b5cf6", "#14b8a6", t.upColor, "#f97316",+ "#06b6d4", t.downColor, "#84cc16", "#ec4899", "#6366f1", "#10b981",+ ];+}++interface DistributionItem {+ symbol: string;+ sliceSize: number;+ weight: number;+ assetClassLabel: string;+}++interface GroupedItem {+ group: string;+ weight: number;+ isCash?: boolean;+}++interface EvolutionSeries {+ name: string;+ data: number[];+}++export function PositionsTab({ run }: { run: RunData }) {+ const { t } = useTranslation();++ const panel = useMemo(+ () => parsePositionsPanel(run.artifacts_positions_csv ?? []),+ [run.artifacts_positions_csv],+ );+ const latestDate = useMemo(() => latestHoldingDate(panel), [panel]);+ const hasAShare = useMemo(+ () => panel.symbols.some((symbol) => classifyAssetClass(symbol) === "a_share"),+ [panel.symbols],+ );++ const [dateIndex, setDateIndex] = useState<number>(() => {+ const target = latestDate ?? panel.dates[panel.dates.length - 1] ?? "";+ return Math.max(0, panel.dates.indexOf(target));+ });+ const [mode, setMode] = useState<"pie" | "treemap">(() => (panel.symbols.length <= 8 ? "pie" : "treemap"));+ const [sectorMap, setSectorMap] = useState<SectorMapResponse | null>(null);+ const [resolving, setResolving] = useState(false);+ const [resolveError, setResolveError] = useState("");++ const selectedDate = panel.dates[dateIndex] ?? "";++ const selectedWeights = useMemo(() => {+ const date = panel.dates[dateIndex];+ return date ? panel.weightByDate.get(date) ?? {} : {};+ }, [panel, dateIndex]);++ const holdingsCount = useMemo(+ () => Object.values(selectedWeights).filter((w) => w !== 0).length,+ [selectedWeights],+ );++ const assetClassLabel = (assetClass: AssetClass) => t(ASSET_CLASS_LABEL_KEYS[assetClass]);+ const cashLabel = t("runDetail.positions.cash");+ const restLabel = t("runDetail.positions.rest");+ const shortLabel = t("runDetail.positions.short");++ const distributionItems = useMemo<DistributionItem[]>(() => {+ const withCash = withCashSlice(selectedWeights);+ return Object.entries(withCash)+ .filter(([, weight]) => weight !== 0)+ .sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]))+ .map(([symbol, weight]) => ({+ symbol,+ sliceSize: Math.abs(weight),+ weight,+ assetClassLabel: symbol === CASH_SYMBOL ? cashLabel : assetClassLabel(classifyAssetClass(symbol)),+ }));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selectedWeights, cashLabel, t]);++ const sectorItems = useMemo<GroupedItem[]>(() => {+ const withCash = withCashSlice(selectedWeights);+ const grouping = (symbol: string): string => {+ if (symbol === CASH_SYMBOL) return cashLabel;+ const info = sectorMap?.symbols?.[symbol];+ if (info?.industry && info.industry_source === "eastmoney") return info.industry;+ return assetClassLabel(classifyAssetClass(symbol));+ };+ return aggregateWeights(withCash, grouping).map((item) => ({+ group: item.group === "other" ? restLabel : item.group,+ weight: item.weight,+ isCash: item.group === cashLabel,+ }));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selectedWeights, sectorMap, cashLabel, restLabel, t]);++ const evolution = useMemo(() => {+ const dates = downsampleDates(panel.dates, MAX_EVOLUTION_DATES);+ const averageWeight = new Map<string, number>();+ for (const symbol of panel.symbols) {+ let sum = 0;+ for (const date of panel.dates) sum += panel.weightByDate.get(date)?.[symbol] ?? 0;+ averageWeight.set(symbol, panel.dates.length > 0 ? sum / panel.dates.length : 0);+ }+ const ranked = [...panel.symbols].sort(+ (a, b) => (averageWeight.get(b) ?? 0) - (averageWeight.get(a) ?? 0),+ );+ const top = ranked.slice(0, MAX_LEGEND_SYMBOLS);+ const rest = new Set(ranked.slice(MAX_LEGEND_SYMBOLS));++ const series: EvolutionSeries[] = top.map((symbol) => ({+ name: symbol,+ data: dates.map((date) => panel.weightByDate.get(date)?.[symbol] ?? 0),+ }));+ if (rest.size > 0) {+ series.push({+ name: restLabel,+ data: dates.map((date) => {+ const weights = panel.weightByDate.get(date);+ let sum = 0;+ for (const symbol of rest) sum += weights?.[symbol] ?? 0;+ return sum;+ }),+ });+ }+ return { dates, series };+ }, [panel, restLabel]);++ async function handleResolve(refresh: boolean) {+ if (!run.run_id || resolving) return;+ setResolving(true);+ setResolveError("");+ try {+ const result = await fetchRunSectorMap(run.run_id, refresh);+ setSectorMap(result);+ } catch (error) {+ setResolveError(error instanceof Error ? error.message : String(error));+ } finally {+ setResolving(false);+ }+ }++ if (panel.symbols.length === 0 || panel.dates.length === 0 || !latestDate) {+ return (+ <div className="p-8 text-center text-sm text-muted-foreground">+ {t("runDetail.positions.noPositions")}+ </div>+ );+ }++ return (+ <div className="p-4 space-y-4">+ <PositionsPanelCard>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <span className="text-xs text-muted-foreground">+ {t("runDetail.positions.asOf", { date: selectedDate })}+ </span>+ <span className="text-xs text-muted-foreground">+ {t("runDetail.positions.holdingsCount", { count: holdingsCount })}+ </span>+ <div className="ms-auto flex flex-wrap items-center gap-2">+ <div className="flex gap-1 rounded-md border border-border/60 p-0.5" role="group">+ {(["pie", "treemap"] as const).map((m) => (+ <button+ key={m}+ type="button"+ onClick={() => setMode(m)}+ aria-pressed={mode === m}+ className={cn(+ "rounded px-2.5 py-1 text-xs transition-colors",+ mode === m+ ? "bg-primary/10 font-medium text-primary"+ : "text-muted-foreground hover:bg-muted/60",+ )}+ >+ {t(m === "pie" ? "runDetail.positions.pie" : "runDetail.positions.treemap")}+ </button>+ ))}+ </div>+ {hasAShare && (+ <button+ type="button"+ onClick={() => void handleResolve(false)}+ disabled={resolving}+ className="flex items-center gap-1.5 rounded-md border border-border/60 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-muted/60 disabled:opacity-60"+ >+ {resolving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {resolving ? t("runDetail.positions.resolving") : t("runDetail.positions.resolveIndustries")}+ </button>+ )}+ </div>+ </div>+ <div className="mt-3 flex items-center gap-3">+ <input+ type="range"+ min={0}+ max={Math.max(0, panel.dates.length - 1)}+ value={dateIndex}+ onChange={(event) => setDateIndex(Number(event.target.value))}+ aria-label={t("runDetail.positions.asOf", { date: selectedDate })}+ className="w-full accent-primary"+ />+ <span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">{selectedDate}</span>+ </div>+ {resolveError && (+ <p className="mt-2 flex flex-wrap items-center gap-2 text-xs text-danger">+ <span>{t("runDetail.positions.resolveFailed")}: {resolveError}</span>+ <button+ type="button"+ onClick={() => void handleResolve(true)}+ disabled={resolving}+ className="rounded-md border border-danger/40 px-2 py-0.5 font-medium transition-colors hover:bg-danger/10 disabled:opacity-60"+ >+ {t("runDetail.positions.retry")}+ </button>+ </p>+ )}+ </PositionsPanelCard>++ <div className="grid gap-4 xl:grid-cols-2">+ <PositionsPanelCard title={t("runDetail.positions.weightDistribution")}>+ <WeightDistributionChart items={distributionItems} mode={mode} cashLabel={cashLabel} shortLabel={shortLabel} />+ </PositionsPanelCard>+ <PositionsPanelCard title={t("runDetail.positions.sectorDistribution")}>+ <SectorDistributionChart items={sectorItems} cashLabel={cashLabel} />+ </PositionsPanelCard>+ </div>++ <PositionsPanelCard title={t("runDetail.positions.weightEvolution")}>+ <WeightEvolutionChart dates={evolution.dates} series={evolution.series} />+ </PositionsPanelCard>+ </div>+ );+}++function PositionsPanelCard({ title, children }: { title?: string; children: ReactNode }) {+ return (+ <section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ {title && <h3 className="mb-3 text-sm font-semibold">{title}</h3>}+ {children}+ </section>+ );+}++function useChartLifecycle(+ ref: React.RefObject<HTMLDivElement | null>,+ buildOption: () => EChartsCoreOption,+ deps: unknown[],+) {+ const dark = useThemeDark();+ useEffect(() => {+ if (!ref.current) return;+ const chart = echarts.init(ref.current);+ chart.setOption(buildOption());++ 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();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [...deps, dark]);+}++function WeightDistributionChart({+ items,+ mode,+ cashLabel,+ shortLabel,+}: {+ items: DistributionItem[];+ mode: "pie" | "treemap";+ cashLabel: string;+ shortLabel: string;+}) {+ const ref = useRef<HTMLDivElement>(null);++ useChartLifecycle(ref, () => {+ const t = getChartTheme();+ const palette = categoryColors(t);+ const data = items.map((item, index) => ({+ name:+ item.symbol === CASH_SYMBOL+ ? cashLabel+ : item.weight < 0+ ? `${item.symbol} ${shortLabel}`+ : item.symbol,+ value: item.sliceSize,+ assetClassLabel: item.assetClassLabel,+ weight: item.weight,+ itemStyle: {+ color: item.symbol === CASH_SYMBOL ? CASH_COLOR : palette[index % palette.length],+ },+ }));+ const tooltip = {+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 11 },+ formatter: (params: unknown) => {+ const p = params as { name: string; value: number; data?: { assetClassLabel?: string; weight?: number } };+ const label = p.data?.assetClassLabel ?? "";+ const signed = p.data?.weight ?? p.value;+ return `<b>${p.name}</b><br/>${label}: <b>${formatPercent(signed, 2)}</b>`;+ },+ };++ if (mode === "treemap") {+ return {+ backgroundColor: "transparent",+ tooltip: { ...tooltip, trigger: "item" },+ series: [+ {+ type: "treemap",+ data,+ width: "100%",+ height: "92%",+ top: 8,+ breadcrumb: { show: false },+ roam: false,+ nodeClick: false,+ label: { show: true, formatter: "{b}", fontSize: 11, color: "#ffffff" },+ itemStyle: { borderColor: t.tooltipBg, borderWidth: 1, gapWidth: 1 },+ },+ ],+ };+ }++ return {+ backgroundColor: "transparent",+ tooltip: { ...tooltip, trigger: "item" },+ legend: {+ type: "scroll",+ bottom: 0,+ textStyle: { color: t.textColor, fontSize: 10 },+ pageTextStyle: { color: t.textColor },+ pageIconColor: t.infoColor,+ pageIconInactiveColor: t.gridColor,+ },+ series: [+ {+ type: "pie",+ radius: ["32%", "62%"],+ center: ["50%", "44%"],+ data,+ label: { show: true, formatter: "{b} {d}%", fontSize: 10, color: t.textColor },+ labelLayout: { hideOverlap: true },+ itemStyle: { borderColor: t.tooltipBg, borderWidth: 1 },+ },+ ],+ };+ }, [items, mode]);++ return <div ref={ref} style={{ height: 320 }} />;+}++function SectorDistributionChart({ items, cashLabel }: { items: GroupedItem[]; cashLabel: string }) {+ const ref = useRef<HTMLDivElement>(null);++ useChartLifecycle(ref, () => {+ const t = getChartTheme();+ const palette = categoryColors(t);+ const ordered = [...items];+ const names = ordered.map((item) => item.group).reverse();+ const data = ordered.map((item, index) => ({+ value: item.weight,+ itemStyle: {+ color: item.isCash || item.group === cashLabel+ ? CASH_COLOR+ : palette[index % palette.length],+ },+ })).reverse();++ return {+ backgroundColor: "transparent",+ tooltip: {+ trigger: "axis",+ axisPointer: { type: "shadow" },+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 11 },+ formatter: (params: unknown) => {+ const list = params as Array<{ name: string; value: number }>;+ if (!Array.isArray(list) || list.length === 0) return "";+ const p = list[0];+ return `<b>${p.name}</b>: <b>${formatPercent(p.value, 2)}</b>`;+ },+ },+ grid: { left: 8, right: 40, top: 8, bottom: 8, containLabel: true },+ xAxis: {+ type: "value",+ min: 0,+ max: 1,+ axisLabel: {+ color: t.textColor,+ fontSize: 10,+ formatter: (value: number) => formatPercent(value, 0),+ },+ splitLine: { lineStyle: { color: t.gridColor } },+ },+ yAxis: {+ type: "category",+ data: names,+ axisLabel: { color: t.textColor, fontSize: 10 },+ axisLine: { lineStyle: { color: t.axisColor } },+ },+ series: [+ {+ type: "bar",+ data,+ barMaxWidth: 16,+ label: {+ show: true,+ position: "right",+ fontSize: 10,+ color: t.textColor,+ formatter: (params: unknown) => formatPercent((params as { value: number }).value, 1),+ },+ },+ ],+ };+ }, [items, cashLabel]);++ return <div ref={ref} style={{ height: 320 }} />;+}++function WeightEvolutionChart({ dates, series }: { dates: string[]; series: EvolutionSeries[] }) {+ const ref = useRef<HTMLDivElement>(null);++ useChartLifecycle(ref, () => {+ const t = getChartTheme();+ const palette = categoryColors(t);+ return {+ backgroundColor: "transparent",+ tooltip: {+ trigger: "axis",+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 11 },+ formatter: (params: unknown) => {+ const list = params as Array<{ seriesName: string; value: number; marker: string }>;+ if (!Array.isArray(list) || list.length === 0) return "";+ const rows = [...list]+ .sort((a, b) => b.value - a.value)+ .map((p) => `${p.marker} ${p.seriesName}: <b>${formatPercent(p.value, 2)}</b>`)+ .join("<br/>");+ return `<b>${list[0] && (list[0] as { axisValue?: string }).axisValue}</b><br/>${rows}`;+ },+ },+ legend: {+ type: "scroll",+ top: 0,+ textStyle: { color: t.textColor, fontSize: 10 },+ pageTextStyle: { color: t.textColor },+ pageIconColor: t.infoColor,+ pageIconInactiveColor: t.gridColor,+ },+ grid: { left: 8, right: 16, top: 32, bottom: 24, containLabel: true },+ xAxis: {+ type: "category",+ data: dates,+ boundaryGap: false,+ axisLine: { lineStyle: { color: t.axisColor } },+ axisLabel: { color: t.textColor, fontSize: 10 },+ },+ yAxis: {+ type: "value",+ min: 0,+ max: 1,+ axisLabel: {+ color: t.textColor,+ fontSize: 10,+ formatter: (value: number) => formatPercent(value, 0),+ },+ splitLine: { lineStyle: { color: t.gridColor } },+ },+ series: series.map((s, index) => ({+ name: s.name,+ type: "line",+ stack: "weights",+ symbol: "none",+ smooth: false,+ data: s.data,+ lineStyle: { width: 1, color: palette[index % palette.length] },+ itemStyle: { color: palette[index % palette.length] },+ areaStyle: { opacity: 0.55 },+ })),+ };+ }, [dates, series]);++ return <div ref={ref} style={{ height: 360 }} />;+}diff --git a/frontend/src/components/run/__tests__/PositionsTab.test.tsx b/frontend/src/components/run/__tests__/PositionsTab.test.tsxnew file mode 100644index 000000000..81f861cfa--- /dev/null+++ b/frontend/src/components/run/__tests__/PositionsTab.test.tsx@@ -0,0 +1,185 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { Mock } from "vitest";+import type { RunData } from "@/lib/api";+import { PositionsTab } from "../PositionsTab";++vi.mock("@/lib/echarts", () => ({+ echarts: { init: vi.fn() },+ CHART_GROUP: "quant-charts",+ connectCharts: vi.fn(),+}));++import { echarts } from "@/lib/echarts";++interface FakeChart {+ setOption: Mock;+ resize: Mock;+ dispose: Mock;+ group: string;+}++const charts: FakeChart[] = [];++function makeRun(rows: Array<Record<string, string>>): RunData {+ return { status: "success", run_id: "run-test", artifacts_positions_csv: rows };+}++function seriesTypes(): string[] {+ return charts.flatMap((chart) =>+ chart.setOption.mock.calls.map((call) => {+ const option = call[0] as { series?: Array<{ type?: string }> };+ return option.series?.[0]?.type ?? "";+ }),+ );+}++function barCategoryAxes(): string[][] {+ return charts.flatMap((chart) =>+ chart.setOption.mock.calls+ .map((call) => {+ const option = call[0] as { yAxis?: { type?: string; data?: string[] } };+ return option.yAxis && option.yAxis.type === "category" ? option.yAxis.data ?? [] : null;+ })+ .filter((names): names is string[] => names !== null),+ );+}++function sectorMapResponse(body: Record<string, unknown>): Response {+ return new Response(JSON.stringify(body), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+}++describe("PositionsTab", () => {+ beforeEach(() => {+ charts.length = 0;+ vi.mocked(echarts.init).mockImplementation((() => {+ const chart: FakeChart = { setOption: vi.fn(), resize: vi.fn(), dispose: vi.fn(), group: "" };+ charts.push(chart);+ return chart;+ }) as typeof echarts.init);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const multiSymbolRows = [+ { timestamp: "2023-07-31", "159913.SZ": "0.0", "AAPL.US": "0.0" },+ { timestamp: "2023-08-01", "159913.SZ": "0.6", "AAPL.US": "0.3" },+ { timestamp: "2023-08-02", "159913.SZ": "0.0", "AAPL.US": "0.0" },+ ];++ it("shows the selected date label and holdings count", () => {+ render(<PositionsTab run={makeRun(multiSymbolRows)} />);++ expect(screen.getByText("As of 2023-08-01")).toBeInTheDocument();+ expect(screen.getByText("2 holdings")).toBeInTheDocument();+ });++ it("renders short legs as labelled slices and counts them in holdings", () => {+ const shortRows = [+ { timestamp: "2024-03-01", "600519.SH": "0.4", "000858.SZ": "-0.2" },+ { timestamp: "2024-03-04", "600519.SH": "0.4", "000858.SZ": "-0.2" },+ ];+ render(<PositionsTab run={makeRun(shortRows)} />);++ expect(screen.getByText("2 holdings")).toBeInTheDocument();++ const pieNames = charts.flatMap((chart) =>+ chart.setOption.mock.calls.flatMap((call) => {+ const option = call[0] as {+ series?: Array<{ type?: string; data?: Array<{ name: string }> }>;+ };+ return (option.series ?? [])+ .filter((s) => s.type === "pie")+ .flatMap((s) => (s.data ?? []).map((d) => d.name));+ }),+ );+ expect(pieNames).toContain("000858.SZ Short");+ expect(pieNames).toContain("600519.SH");+ });++ it("renders pie by default and switches to treemap via the toggle", () => {+ render(<PositionsTab run={makeRun(multiSymbolRows)} />);++ expect(seriesTypes()).toContain("pie");+ expect(seriesTypes()).not.toContain("treemap");++ fireEvent.click(screen.getByRole("button", { name: "Treemap" }));++ expect(seriesTypes()).toContain("treemap");+ });++ it("hides the resolve button for a crypto-only payload", () => {+ const cryptoRows = [+ { timestamp: "2024-01-01", "BTC-USDT": "0.6", "ETH-USDT": "0.4" },+ { timestamp: "2024-01-02", "BTC-USDT": "0.5", "ETH-USDT": "0.5" },+ ];+ render(<PositionsTab run={makeRun(cryptoRows)} />);++ expect(screen.queryByText("Resolve industries")).not.toBeInTheDocument();+ });++ it("shows the empty-state note and no charts for an all-zero payload", () => {+ const zeroRows = [+ { timestamp: "2024-01-01", "159913.SZ": "0.0" },+ { timestamp: "2024-01-02", "159913.SZ": "0" },+ ];+ render(<PositionsTab run={makeRun(zeroRows)} />);++ expect(screen.getByText("No position weights recorded for this run.")).toBeInTheDocument();+ expect(charts).toHaveLength(0);+ });++ it("resolves industries and re-renders the sector chart with resolved names", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ sectorMapResponse({+ ok: true,+ run_id: "run-test",+ symbols: {+ "600519.SH": { asset_class: "a_share", industry: "白酒Ⅱ", industry_source: "eastmoney" },+ },+ unresolved: [],+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ render(<PositionsTab run={makeRun([{ timestamp: "2024-01-01", "600519.SH": "0.7" }])} />);++ fireEvent.click(screen.getByRole("button", { name: "Resolve industries" }));++ await waitFor(() => {+ expect(screen.queryByText("Resolving...")).not.toBeInTheDocument();+ });++ expect(fetchMock).toHaveBeenCalledWith(+ "/runs/run-test/positions/sectors",+ expect.objectContaining({ headers: expect.anything() }),+ );+ expect(barCategoryAxes().some((names) => names.includes("白酒Ⅱ"))).toBe(true);+ });++ it("shows an inline retryable error when sector resolution fails", async () => {+ const fetchMock = vi.fn().mockRejectedValue(new Error("boom"));+ vi.stubGlobal("fetch", fetchMock);++ render(<PositionsTab run={makeRun([{ timestamp: "2024-01-01", "600519.SH": "0.7" }])} />);++ fireEvent.click(screen.getByRole("button", { name: "Resolve industries" }));++ await waitFor(() => {+ expect(screen.getByText(/Failed to resolve industries/)).toBeInTheDocument();+ });++ fetchMock.mockResolvedValue(sectorMapResponse({ ok: true, symbols: {}, unresolved: [] }));+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));++ await waitFor(() => {+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+ expect(fetchMock.mock.calls[1][0]).toBe("/runs/run-test/positions/sectors?refresh=1");+ });+});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 47b1df14d..234c02d13 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -634,7 +634,37 @@"ddTroughToRecovery": "القاع إلى التعافي","ddNotRecovered": "لم يتعافَ","ddDays": "{{count}} يوم",- "dashboard": "لوحة البحث"+ "dashboard": "لوحة البحث",+ "positions": {+ "tab": "المراكز",+ "weightDistribution": "توزيع الأوزان",+ "sectorDistribution": "توزيع القطاعات",+ "weightEvolution": "تطور الأوزان",+ "pie": "دائري",+ "treemap": "خريطة شجرية",+ "cash": "نقد",+ "rest": "أخرى",+ "short": "بيع على المكشوف",+ "resolveIndustries": "جلب الصناعات",+ "resolving": "جارٍ الجلب...",+ "resolveFailed": "فشل جلب الصناعات",+ "retry": "إعادة المحاولة",+ "asOf": "اعتبارًا من {{date}}",+ "noPositions": "لم يتم تسجيل أوزان المراكز لهذا التشغيل.",+ "holdingsCount": "{{count}} من المراكز",+ "assetClass": {+ "a_share": "أسهم صينية (A)",+ "us_equity": "أسهم أمريكية",+ "hk_equity": "أسهم هونغ كونغ",+ "ca_equity": "أسهم كندية",+ "kr_equity": "أسهم كورية",+ "india_equity": "أسهم هندية",+ "crypto": "عملات رقمية",+ "futures": "عقود آجلة",+ "forex": "عملات أجنبية",+ "other": "أخرى"+ }+ }},"compare": {"title": "مقارنة الاستراتيجيات",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex e2be81a00..91b5a6234 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -639,7 +639,37 @@"ddTroughToRecovery": "Trough→Rec.","ddNotRecovered": "Not recovered","ddDays": "{{count}} d",- "dashboard": "Research dashboard"+ "dashboard": "Research dashboard",+ "positions": {+ "tab": "Positions",+ "weightDistribution": "Weight distribution",+ "sectorDistribution": "Sector distribution",+ "weightEvolution": "Weight evolution",+ "pie": "Pie",+ "treemap": "Treemap",+ "cash": "Cash",+ "rest": "Other",+ "short": "Short",+ "resolveIndustries": "Resolve industries",+ "resolving": "Resolving...",+ "resolveFailed": "Failed to resolve industries",+ "retry": "Retry",+ "asOf": "As of {{date}}",+ "noPositions": "No position weights recorded for this run.",+ "holdingsCount": "{{count}} holdings",+ "assetClass": {+ "a_share": "A-share",+ "us_equity": "US equity",+ "hk_equity": "HK equity",+ "ca_equity": "Canada equity",+ "kr_equity": "Korea equity",+ "india_equity": "India equity",+ "crypto": "Crypto",+ "futures": "Futures",+ "forex": "Forex",+ "other": "Other"+ }+ }},"compare": {"title": "Strategy Comparison",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex b3ad58e71..e7ea5550c 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -639,7 +639,37 @@"ddTroughToRecovery": "Valle→Rec.","ddNotRecovered": "No recuperado","ddDays": "{{count}} d",- "dashboard": "Panel de investigación"+ "dashboard": "Panel de investigación",+ "positions": {+ "tab": "Posiciones",+ "weightDistribution": "Distribución de pesos",+ "sectorDistribution": "Distribución sectorial",+ "weightEvolution": "Evolución de pesos",+ "pie": "Circular",+ "treemap": "Mapa de árbol",+ "cash": "Efectivo",+ "rest": "Otros",+ "short": "Corto",+ "resolveIndustries": "Resolver industrias",+ "resolving": "Resolviendo...",+ "resolveFailed": "Error al resolver industrias",+ "retry": "Reintentar",+ "asOf": "A fecha de {{date}}",+ "noPositions": "No se registraron pesos de posiciones para esta ejecución.",+ "holdingsCount": "{{count}} posiciones",+ "assetClass": {+ "a_share": "Acciones A (China)",+ "us_equity": "Renta variable EE. UU.",+ "hk_equity": "Renta variable HK",+ "ca_equity": "Renta variable Canadá",+ "kr_equity": "Renta variable Corea",+ "india_equity": "Renta variable India",+ "crypto": "Criptomonedas",+ "futures": "Futuros",+ "forex": "Divisas",+ "other": "Otros"+ }+ }},"compare": {"title": "Comparación de estrategias",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex f9f48ab1b..e9c9bcf98 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -634,7 +634,37 @@"ddTroughToRecovery": "安値→回復","ddNotRecovered": "未回復","ddDays": "{{count}}日",- "dashboard": "リサーチダッシュボード"+ "dashboard": "リサーチダッシュボード",+ "positions": {+ "tab": "ポジション",+ "weightDistribution": "ウェイト分布",+ "sectorDistribution": "セクター分布",+ "weightEvolution": "ウェイト推移",+ "pie": "円グラフ",+ "treemap": "ツリーマップ",+ "cash": "キャッシュ",+ "rest": "その他",+ "short": "空売り",+ "resolveIndustries": "業種を解決",+ "resolving": "解決中...",+ "resolveFailed": "業種の解決に失敗しました",+ "retry": "再試行",+ "asOf": "{{date}} 時点",+ "noPositions": "この実行にはポジションのウェイトが記録されていません。",+ "holdingsCount": "{{count}} 銘柄",+ "assetClass": {+ "a_share": "A株",+ "us_equity": "米国株",+ "hk_equity": "香港株",+ "ca_equity": "カナダ株",+ "kr_equity": "韓国株",+ "india_equity": "インド株",+ "crypto": "暗号資産",+ "futures": "先物",+ "forex": "外国為替",+ "other": "その他"+ }+ }},"compare": {"title": "戦略比較",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex e00f8ace1..f06b62886 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -634,7 +634,37 @@"ddTroughToRecovery": "저점→회복","ddNotRecovered": "미회복","ddDays": "{{count}}일",- "dashboard": "리서치 대시보드"+ "dashboard": "리서치 대시보드",+ "positions": {+ "tab": "포지션",+ "weightDistribution": "비중 분포",+ "sectorDistribution": "섹터 분포",+ "weightEvolution": "비중 변화",+ "pie": "원형",+ "treemap": "트리맵",+ "cash": "현금",+ "rest": "기타",+ "short": "공매도",+ "resolveIndustries": "업종 조회",+ "resolving": "조회 중...",+ "resolveFailed": "업종 조회에 실패했습니다",+ "retry": "재시도",+ "asOf": "{{date}} 기준",+ "noPositions": "이 실행에는 포지션 비중이 기록되어 있지 않습니다.",+ "holdingsCount": "{{count}}개 종목",+ "assetClass": {+ "a_share": "A주",+ "us_equity": "미국 주식",+ "hk_equity": "홍콩 주식",+ "ca_equity": "캐나다 주식",+ "kr_equity": "한국 주식",+ "india_equity": "인도 주식",+ "crypto": "암호화폐",+ "futures": "선물",+ "forex": "외환",+ "other": "기타"+ }+ }},"compare": {"title": "전략 비교",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex ffa85fa8d..56587c46f 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -634,7 +634,37 @@"ddTroughToRecovery": "低点→恢复","ddNotRecovered": "未恢复","ddDays": "{{count}} 天",- "dashboard": "研究仪表盘"+ "dashboard": "研究仪表盘",+ "positions": {+ "tab": "持仓",+ "weightDistribution": "权重分布",+ "sectorDistribution": "行业分布",+ "weightEvolution": "权重演变",+ "pie": "饼图",+ "treemap": "矩形树图",+ "cash": "现金",+ "rest": "其他",+ "short": "做空",+ "resolveIndustries": "解析行业",+ "resolving": "解析中...",+ "resolveFailed": "行业解析失败",+ "retry": "重试",+ "asOf": "截至 {{date}}",+ "noPositions": "该运行未记录持仓权重。",+ "holdingsCount": "{{count}} 个持仓",+ "assetClass": {+ "a_share": "A股",+ "us_equity": "美股",+ "hk_equity": "港股",+ "ca_equity": "加股",+ "kr_equity": "韩股",+ "india_equity": "印股",+ "crypto": "加密货币",+ "futures": "期货",+ "forex": "外汇",+ "other": "其他"+ }+ }},"compare": {"title": "策略对比",diff --git a/frontend/src/lib/__tests__/positions.test.ts b/frontend/src/lib/__tests__/positions.test.tsnew file mode 100644index 000000000..e5b6dc7d2--- /dev/null+++ b/frontend/src/lib/__tests__/positions.test.ts@@ -0,0 +1,227 @@+import {+ CASH_SYMBOL,+ aggregateWeights,+ classifyAssetClass,+ downsampleDates,+ latestHoldingDate,+ parsePositionsPanel,+ withCashSlice,+ type PositionsPanel,+} from "../positions";++describe("parsePositionsPanel", () => {+ it("parses string weights per date and collects symbols in first-seen order", () => {+ const panel = parsePositionsPanel([+ { timestamp: "2023-07-31", "159913.SZ": "0.0", "AAPL.US": "0.5" },+ { timestamp: "2023-08-01", "159913.SZ": "0.95", "BTC-USDT": "0.05" },+ ]);++ expect(panel.dates).toEqual(["2023-07-31", "2023-08-01"]);+ expect(panel.symbols).toEqual(["159913.SZ", "AAPL.US", "BTC-USDT"]);+ expect(panel.weightByDate.get("2023-07-31")).toEqual({ "159913.SZ": 0, "AAPL.US": 0.5 });+ expect(panel.weightByDate.get("2023-08-01")).toEqual({ "159913.SZ": 0.95, "BTC-USDT": 0.05 });+ });++ it("treats missing and NaN cells as 0", () => {+ const panel = parsePositionsPanel([+ { timestamp: "2024-01-02", "600519.SH": "not-a-number" },+ { timestamp: "2024-01-03" },+ ]);++ expect(panel.weightByDate.get("2024-01-02")).toEqual({ "600519.SH": 0 });+ expect(panel.weightByDate.get("2024-01-03")).toEqual({});+ expect(panel.symbols).toEqual(["600519.SH"]);+ });++ it("skips date columns case-insensitively and tolerates a date alias", () => {+ const panel = parsePositionsPanel([+ { Timestamp: "2024-02-01", "AAPL.US": "0.4" } as unknown as Record<string, string>,+ { date: "2024-02-02", "AAPL.US": "0.6" },+ ]);++ expect(panel.dates).toEqual(["2024-02-01", "2024-02-02"]);+ expect(panel.symbols).toEqual(["AAPL.US"]);+ });++ it("returns an empty panel for empty input", () => {+ const panel = parsePositionsPanel([]);+ expect(panel.dates).toEqual([]);+ expect(panel.symbols).toEqual([]);+ expect(panel.weightByDate.size).toBe(0);+ });+});++describe("latestHoldingDate", () => {+ function panelFrom(rows: Array<Record<string, string>>): PositionsPanel {+ return parsePositionsPanel(rows);+ }++ it("returns the last date whose weight sum exceeds 0.001", () => {+ const panel = panelFrom([+ { timestamp: "2024-01-01", "AAPL.US": "0.5" },+ { timestamp: "2024-01-02", "AAPL.US": "0.9" },+ { timestamp: "2024-01-03", "AAPL.US": "0.0" },+ ]);+ expect(latestHoldingDate(panel)).toBe("2024-01-02");+ });++ it("returns null when all weights are zero", () => {+ const panel = panelFrom([+ { timestamp: "2024-01-01", "AAPL.US": "0.0" },+ { timestamp: "2024-01-02", "AAPL.US": "0" },+ ]);+ expect(latestHoldingDate(panel)).toBeNull();+ });++ it("returns null for an empty panel", () => {+ expect(latestHoldingDate(parsePositionsPanel([]))).toBeNull();+ });++ it("treats a dust sum below the threshold as flat", () => {+ const panel = panelFrom([{ timestamp: "2024-01-01", "AAPL.US": "0.0005" }]);+ expect(latestHoldingDate(panel)).toBeNull();+ });+});++describe("classifyAssetClass parity with backend rules", () => {+ const cases: Array<[string, ReturnType<typeof classifyAssetClass>]> = [+ ["600519.SH", "a_share"],+ ["000001.SZ", "a_share"],+ ["830799.BJ", "a_share"],+ ["159913.SZ", "a_share"],+ ["00700.HK", "hk_equity"],+ ["AAPL.US", "us_equity"],+ ["BRK-B.US", "us_equity"],+ ["TD.TO", "ca_equity"],+ ["PNG.V", "ca_equity"],+ ["005930.KS", "kr_equity"],+ ["035720.KQ", "kr_equity"],+ ["RELIANCE.NS", "india_equity"],+ ["TCS.BO", "india_equity"],+ ["BTC-USDT", "crypto"],+ ["ETH-USDC", "crypto"],+ ["SOL-USD", "crypto"],+ ["ETH/USDT", "crypto"],+ ["BTC-USDT-PERP", "crypto"],+ ["EURUSD", "forex"],+ ["USDCNH", "forex"],+ ["XAUUSD.FX", "forex"],+ ["IF2406.CFFEX", "futures"],+ ["RB2510.SHFE", "futures"],+ ["M2509.DCE", "futures"],+ ["CL2512.NYMEX", "futures"],+ ["GC2512.COMEX", "futures"],+ ["AAPL", "us_equity"],+ ["NVDA", "us_equity"],+ ["", "other"],+ ["12345", "other"],+ ["BTCUSDT", "other"],+ ];++ it.each(cases)("classifies %s as %s", (symbol, expected) => {+ expect(classifyAssetClass(symbol)).toBe(expected);+ });++ it("covers at least 18 parity cases", () => {+ expect(cases.length).toBeGreaterThanOrEqual(18);+ });+});++describe("aggregateWeights", () => {+ it("groups by the provided function and sorts descending", () => {+ const result = aggregateWeights(+ { "600519.SH": 0.4, "000858.SZ": 0.2, "AAPL.US": 0.3 },+ (symbol) => (symbol.endsWith(".US") ? "us" : "cn"),+ );+ expect(result.map((item) => item.group)).toEqual(["cn", "us"]);+ expect(result[0].weight).toBeCloseTo(0.6, 10);+ expect(result[1].weight).toBeCloseTo(0.3, 10);+ });++ it("keeps up to 12 groups untouched", () => {+ const weights: Record<string, number> = {};+ for (let i = 0; i < 12; i += 1) weights[`S${i}`] = 0.05;+ const result = aggregateWeights(weights, (symbol) => symbol);+ expect(result).toHaveLength(12);+ });++ it("merges the remainder into other when groups exceed 12", () => {+ const weights: Record<string, number> = {};+ for (let i = 0; i < 15; i += 1) weights[`S${i}`] = (15 - i) / 100;+ const result = aggregateWeights(weights, (symbol) => symbol);++ expect(result).toHaveLength(12);+ const other = result.find((item) => item.group === "other");+ expect(other).toBeDefined();+ expect(other!.weight).toBeCloseTo(0.01 + 0.02 + 0.03 + 0.04, 10);+ const total = result.reduce((sum, item) => sum + item.weight, 0);+ expect(total).toBeCloseTo(1.2, 10);+ for (let i = 1; i < result.length; i += 1) {+ expect(result[i - 1].weight).toBeGreaterThanOrEqual(result[i].weight);+ }+ });++ it("ignores zero and non-finite weights", () => {+ const result = aggregateWeights(+ { A: 0.5, B: 0, C: Number.NaN },+ (symbol) => symbol,+ );+ expect(result).toEqual([{ group: "A", weight: 0.5 }]);+ });+});++describe("withCashSlice", () => {+ it("adds a cash pseudo-symbol for the uninvested remainder", () => {+ const result = withCashSlice({ "AAPL.US": 0.6, "BTC-USDT": 0.2 });+ expect(result[CASH_SYMBOL]).toBeCloseTo(0.2, 10);+ expect(result["AAPL.US"]).toBe(0.6);+ });++ it("adds no cash when weights sum to exactly 1", () => {+ const result = withCashSlice({ A: 0.5, B: 0.5 });+ expect(CASH_SYMBOL in result).toBe(false);+ });++ it("adds no cash when the remainder is within the 0.005 tolerance", () => {+ const result = withCashSlice({ A: 0.996 });+ expect(CASH_SYMBOL in result).toBe(false);+ });++ it("adds cash when the remainder just exceeds the tolerance", () => {+ const result = withCashSlice({ A: 0.99 });+ expect(result[CASH_SYMBOL]).toBeCloseTo(0.01, 10);+ });++ it("does not mutate the input", () => {+ const input = { A: 0.5 };+ withCashSlice(input);+ expect(input).toEqual({ A: 0.5 });+ });+});++describe("downsampleDates", () => {+ it("returns all dates when under the cap", () => {+ const dates = ["2024-01-01", "2024-01-02", "2024-01-03"];+ expect(downsampleDates(dates, 500)).toEqual(dates);+ });++ it("keeps first and last and stays within the cap", () => {+ const dates = Array.from({ length: 1234 }, (_, i) => `d${i}`);+ const result = downsampleDates(dates, 500);++ expect(result[0]).toBe("d0");+ expect(result[result.length - 1]).toBe("d1233");+ expect(result.length).toBeLessThanOrEqual(500);+ expect(new Set(result).size).toBe(result.length);+ for (let i = 1; i < result.length; i += 1) {+ expect(dates.indexOf(result[i])).toBeGreaterThan(dates.indexOf(result[i - 1]));+ }+ });++ it("returns a copy, not the original array", () => {+ const dates = ["a", "b"];+ const result = downsampleDates(dates);+ expect(result).toEqual(dates);+ expect(result).not.toBe(dates);+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e7328a6a2..4d4b99f25 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -670,9 +670,56 @@ export interface RunData {artifacts_equity_csv?: Array<Record<string, string>>;artifacts_metrics_csv?: Array<Record<string, string>>;artifacts_trades_csv?: Array<Record<string, string>>;+ /** Filled portfolio weights per date (rows: {timestamp, <symbol>: weight-string}). */+ artifacts_positions_csv?: Array<Record<string, string>>;+ /** Requested target weights per date, same row shape as artifacts_positions_csv. */+ artifacts_target_positions_csv?: Array<Record<string, string>>;run_logs?: Array<{ source?: string; line_number?: number; message?: string }>;}+// --- Positions sector-map types (GET /runs/{runId}/positions/sectors) ---++/** Asset classes reported by the backend sector-map endpoint. */+export type SectorAssetClass =+ | "a_share"+ | "us_equity"+ | "hk_equity"+ | "india_equity"+ | "kr_equity"+ | "ca_equity"+ | "crypto"+ | "futures"+ | "forex";++export interface SectorInfo {+ asset_class: SectorAssetClass;+ /** Resolved industry name, or null when unresolved / not applicable. */+ industry: string | null;+ /** Provenance of `industry` (e.g. "eastmoney"), null when unresolved. */+ industry_source: string | null;+}++export interface SectorMapResponse {+ ok: boolean;+ run_id?: string;+ resolved_at?: string;+ cached?: boolean;+ symbols: Record<string, SectorInfo>;+ unresolved?: string[];+ /** Present when the run has no positions artifact. */+ note?: string;+}++/**+ * Fetch the resolved sector map for one run's positions artifact.+ * Uses the same auth-header + error-envelope conventions as every other+ * fetcher in this module (via the shared `request` helper).+ */+export function fetchRunSectorMap(runId: string, refresh?: boolean): Promise<SectorMapResponse> {+ const qs = refresh ? "?refresh=1" : "";+ return request<SectorMapResponse>(`/runs/${encodeURIComponent(runId)}/positions/sectors${qs}`);+}+export interface RunCard {schema_version?: string;generated_at?: string;diff --git a/frontend/src/lib/echarts.ts b/frontend/src/lib/echarts.tsindex 4c9bd644a..29d906c4f 100644--- a/frontend/src/lib/echarts.ts+++ b/frontend/src/lib/echarts.ts@@ -1,5 +1,5 @@import * as echarts from "echarts/core";-import { CandlestickChart, LineChart, BarChart, HeatmapChart } from "echarts/charts";+import { CandlestickChart, LineChart, BarChart, HeatmapChart, PieChart, TreemapChart } from "echarts/charts";import {GridComponent,TooltipComponent,@@ -14,7 +14,7 @@ import {import { CanvasRenderer } from "echarts/renderers";echarts.use([- CandlestickChart, LineChart, BarChart, HeatmapChart,+ CandlestickChart, LineChart, BarChart, HeatmapChart, PieChart, TreemapChart,GridComponent, TooltipComponent, LegendComponent,DataZoomComponent, MarkPointComponent,ToolboxComponent, MarkLineComponent, MarkAreaComponent,diff --git a/frontend/src/lib/positions.ts b/frontend/src/lib/positions.tsnew file mode 100644index 000000000..5d0fece9b--- /dev/null+++ b/frontend/src/lib/positions.ts@@ -0,0 +1,190 @@+export interface PositionsPanel {+ dates: string[];+ symbols: string[];+ weightByDate: Map<string, Record<string, number>>;+}++export type AssetClass =+ | "a_share"+ | "us_equity"+ | "hk_equity"+ | "ca_equity"+ | "kr_equity"+ | "india_equity"+ | "crypto"+ | "futures"+ | "forex"+ | "other";++export interface GroupWeight {+ group: string;+ weight: number;+}++export const CASH_SYMBOL = "__cash__";++const DATE_COLUMNS = new Set(["timestamp", "date", "time"]);++const EQUITY_SUFFIX_MAP: Record<string, AssetClass> = {+ SH: "a_share",+ SZ: "a_share",+ BJ: "a_share",+ HK: "hk_equity",+ US: "us_equity",+ TO: "ca_equity",+ V: "ca_equity",+ KS: "kr_equity",+ KQ: "kr_equity",+ NS: "india_equity",+ BO: "india_equity",+};++const CRYPTO_QUOTE_SUFFIXES = new Set(["USDT", "USDC", "USD"]);++const FUTURES_EXCHANGE_SUFFIXES = new Set([+ "CFFEX", "SHFE", "DCE", "ZCE", "CZCE", "INE", "GFEX",+ "CBOT", "CME", "NYMEX", "COMEX", "ICE",+ "EUREX", "LME", "SGX", "TOCOM", "MCX",+]);++function parseWeightCell(raw: string | undefined): number {+ if (raw === undefined || raw === null || raw === "") return 0;+ const value = Number(raw);+ return Number.isFinite(value) ? value : 0;+}++export function parsePositionsPanel(rows: Array<Record<string, string>>): PositionsPanel {+ const dates: string[] = [];+ const symbols: string[] = [];+ const seenSymbols = new Set<string>();+ const weightByDate = new Map<string, Record<string, number>>();++ for (const row of rows) {+ let date = "";+ for (const [key, value] of Object.entries(row)) {+ if (DATE_COLUMNS.has(key.toLowerCase())) {+ date = value ?? "";+ break;+ }+ }+ if (!date) continue;+ if (!weightByDate.has(date)) dates.push(date);+ const weights: Record<string, number> = weightByDate.get(date) ?? {};+ for (const [key, raw] of Object.entries(row)) {+ if (DATE_COLUMNS.has(key.toLowerCase())) continue;+ if (!seenSymbols.has(key)) {+ seenSymbols.add(key);+ symbols.push(key);+ }+ weights[key] = parseWeightCell(raw);+ }+ weightByDate.set(date, weights);+ }++ return { dates, symbols, weightByDate };+}++export function latestHoldingDate(panel: PositionsPanel): string | null {+ let latest: string | null = null;+ for (const date of panel.dates) {+ const weights = panel.weightByDate.get(date);+ if (!weights) continue;+ const sum = Object.values(weights).reduce((acc, w) => acc + w, 0);+ if (sum > 0.001) latest = date;+ }+ return latest;+}++/**+ * Heuristic asset-class classification mirroring the backend symbol rules.+ * Order matters: exchange suffixes first, then crypto quote pairs, then+ * forex shapes, then futures exchange suffixes, then bare alpha tickers.+ */+export function classifyAssetClass(symbol: string): AssetClass {+ const trimmed = symbol.trim();+ if (!trimmed) return "other";+ const upper = trimmed.toUpperCase();++ const dot = upper.lastIndexOf(".");+ if (dot >= 0) {+ const suffix = upper.slice(dot + 1);+ const equity = EQUITY_SUFFIX_MAP[suffix];+ if (equity) return equity;+ if (suffix === "FX") return "forex";+ if (FUTURES_EXCHANGE_SUFFIXES.has(suffix)) return "futures";+ }++ if (upper.endsWith("-PERP")) return "crypto";+ const hyphen = upper.lastIndexOf("-");+ if (hyphen >= 0 && CRYPTO_QUOTE_SUFFIXES.has(upper.slice(hyphen + 1))) return "crypto";+ const slash = upper.lastIndexOf("/");+ if (slash >= 0 && CRYPTO_QUOTE_SUFFIXES.has(upper.slice(slash + 1))) return "crypto";++ if (/^[A-Z]{6}$/.test(upper)) return "forex";+ if (/^[A-Z]{1,5}$/.test(upper)) return "us_equity";++ return "other";+}++/**+ * Groups weights, sorted descending. When more than 12 groups exist, the+ * bottom groups are merged into a single "other" bucket so at most 12+ * entries (11 named + other) remain.+ */+export function aggregateWeights(+ weights: Record<string, number>,+ grouping: (symbol: string) => string,+): GroupWeight[] {+ const totals = new Map<string, number>();+ for (const [symbol, weight] of Object.entries(weights)) {+ if (!Number.isFinite(weight) || weight === 0) continue;+ const group = grouping(symbol);+ totals.set(group, (totals.get(group) ?? 0) + weight);+ }++ const sorted: GroupWeight[] = [...totals.entries()]+ .map(([group, weight]) => ({ group, weight }))+ .sort((a, b) => b.weight - a.weight);++ const MAX_GROUPS = 12;+ if (sorted.length <= MAX_GROUPS) return sorted;++ const kept = sorted.slice(0, MAX_GROUPS - 1);+ const rest = sorted.slice(MAX_GROUPS - 1);+ const otherWeight = rest.reduce((acc, item) => acc + item.weight, 0);+ const merged = [...kept, { group: "other", weight: otherWeight }];+ merged.sort((a, b) => b.weight - a.weight);+ return merged;+}++/**+ * Adds a `__cash__` pseudo-symbol for the uninvested remainder+ * (1 - sum(weights)) when it exceeds 0.5% of the portfolio.+ */+export function withCashSlice(weights: Record<string, number>): Record<string, number> {+ const sum = Object.values(weights).reduce((acc, w) => acc + (Number.isFinite(w) ? w : 0), 0);+ const cash = 1 - sum;+ if (cash <= 0.005) return { ...weights };+ return { ...weights, [CASH_SYMBOL]: cash };+}++/**+ * Even-stride downsample that always keeps the first and last date.+ */+export function downsampleDates(dates: string[], maxPoints = 500): string[] {+ if (dates.length <= maxPoints || maxPoints < 2) return [...dates];+ const step = (dates.length - 1) / (maxPoints - 1);+ const picked: string[] = [];+ const seen = new Set<number>();+ for (let i = 0; i < maxPoints; i += 1) {+ const index = Math.round(i * step);+ if (!seen.has(index)) {+ seen.add(index);+ picked.push(dates[index]);+ }+ }+ if (picked[picked.length - 1] !== dates[dates.length - 1]) {+ picked.push(dates[dates.length - 1]);+ }+ return picked;+}diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex 6fda80347..1e332223b 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -19,6 +19,7 @@ import {List,LayoutDashboard,Loader2,+ PieChart,ShieldCheck,Sigma,XCircle,@@ -47,10 +48,11 @@ import { Skeleton, SkeletonMetrics, SkeletonChart } from "@/components/common/Skimport { ErrorBoundary } from "@/components/common/ErrorBoundary";import { getStrategyReportIdentity, StrategyResearchDashboard } from "@/components/charts/StrategyResearchDashboard";import { FactorResearchPanel } from "@/components/charts/FactorResearchPanel";+import { PositionsTab } from "@/components/run/PositionsTab";const rehypePlugins = [rehypeHighlight];-type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "runCard" | "code" | "validation" | "studio" | "factor";+type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "positions" | "runCard" | "code" | "validation" | "studio" | "factor";type ChartPayload = Pick<RunData, "price_series" | "indicator_series" | "trade_markers">;type ChartCache = Record<string, ChartPayload>;type ChartLoadProgress = { done: number; total: number };@@ -136,11 +138,15 @@ export function RunDetail() {const hasStudio = !!run?.risk_xray || !!run?.rebalance_notes;const hasTearsheet = (run?.artifacts_equity_csv?.length ?? 0) > 0 || (run?.equity_curve?.length ?? 0) > 0;const hasFactor = !!run?.has_factor_artifacts;+ const hasPositions = !!run?.artifacts_positions_csv?.some(+ (row) => Object.keys(row).some((key) => key.toLowerCase() !== "timestamp" && key.toLowerCase() !== "date"),+ );const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [{ id: "dashboard", label: i18n.t("runDetail.dashboard"), icon: LayoutDashboard },{ id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },{ id: "tearsheet", label: i18n.t("runDetail.tearsheet"), icon: CalendarRange, hidden: !hasTearsheet },{ id: "trades", label: i18n.t("runDetail.trades"), icon: List },+ { id: "positions", label: i18n.t("runDetail.positions.tab"), icon: PieChart, hidden: !hasPositions },{ id: "factor", label: i18n.t("runDetail.factor"), icon: Sigma, hidden: !hasFactor },{ id: "studio", label: i18n.t("runDetail.studio"), icon: Gauge, hidden: !hasStudio },{ id: "validation", label: i18n.t("runDetail.validation"), icon: ShieldCheck, hidden: !hasValidation },@@ -412,6 +418,7 @@ export function RunDetail() {)}{tab === "tearsheet" && hasTearsheet && <TearsheetTab run={run} />}{tab === "trades" && <TradesTab run={run} />}+ {tab === "positions" && hasPositions && <PositionsTab run={run} />}{tab === "factor" && run.has_factor_artifacts && runId && <FactorTab runId={runId} />}{tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}{tab === "studio" && hasStudio && (