"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: address review feedback for positions structure visualization
shadowinlifeda5b0db9c047
diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex a85afcc2c..6e729627b 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -11,11 +11,13 @@ import mathimport osimport statisticsfrom collections import deque+from concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Deque, Dict, Generator, List, Optional, Tuplefrom fastapi import Depends, FastAPI, HTTPException, Query, status+from fastapi.concurrency import run_in_threadpoolfrom fastapi.responses import JSONResponse@@ -460,6 +462,15 @@ def _factor_ic_correlation(factors: List[Dict[str, Any]]) -> Optional[Dict[str,return {"labels": [str(factor["name"]) for factor in factors], "matrix": matrix}+# Bounded contract for /runs/{run_id}/positions/sectors: at most+# _POSITIONS_SECTOR_MAX_SYMBOLS symbols get a network industry lookup (excess+# symbols degrade to asset-class-only grouping), lookups run on at most+# _POSITIONS_SECTOR_WORKERS threads, and each HTTP call carries the shared+# Eastmoney client's 15-second socket timeout.+_POSITIONS_SECTOR_MAX_SYMBOLS = 200+_POSITIONS_SECTOR_WORKERS = 4++def _read_positions_symbols(path: Path) -> List[str]:"""Read the symbol column names from a wide-format ``positions.csv``.@@ -483,6 +494,30 @@ def _read_positions_symbols(path: Path) -> List[str]:return [name.strip() for name in fieldnames[1:] if name and name.strip()]+def _resolve_industries_concurrent(symbols: List[str]) -> Dict[str, Optional[str]]:+ """Resolve A-share industry boards with bounded concurrency.++ Args:+ symbols: A-share symbols to resolve (already capped by the caller).++ Returns:+ Mapping of symbol -> industry board name, or ``None`` when the lookup+ failed or found no board row. Never raises.+ """+ from src.tools.sector_tool import resolve_industry_board++ results: Dict[str, Optional[str]] = {}+ with ThreadPoolExecutor(max_workers=_POSITIONS_SECTOR_WORKERS) as pool:+ futures = {pool.submit(resolve_industry_board, symbol): symbol for symbol in symbols}+ for future in as_completed(futures):+ symbol = futures[future]+ try:+ results[symbol] = future.result()+ except Exception: # noqa: BLE001 - one failure must not abort the batch+ results[symbol] = None+ return results++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.@@ -490,6 +525,13 @@ def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) ->exists and ``refresh`` is false; otherwise recomputes and rewrites thecache. A corrupt cache file is treated as a cache miss.+ Blocking work here (file reads plus throttled Eastmoney HTTP) is bounded+ by the module-level contract: at most ``_POSITIONS_SECTOR_MAX_SYMBOLS``+ network lookups, ``_POSITIONS_SECTOR_WORKERS`` concurrent workers, and the+ shared Eastmoney client's 15-second per-request socket timeout. Symbols+ beyond the cap keep their asset class but skip industry resolution. The+ caller must run this off the event loop (see ``run_in_threadpool``).+Args:run_dir: Persisted run directory containing ``artifacts/``.run_id: Run identifier echoed back in the response envelope.@@ -497,11 +539,10 @@ def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) ->Returns:The envelope ``{"ok", "run_id", "resolved_at", "cached", "symbols",- "unresolved"}``, or the ``{"ok", "run_id", "symbols", "note"}`` form- when no positions artifact exists.+ "unresolved", "total_symbols", "symbol_limit"}``, 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_boardcache_path = run_dir / "artifacts" / "sector_map.json"if not refresh:@@ -516,22 +557,28 @@ def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) ->return {"ok": True, "run_id": run_id, "symbols": {}, "note": "no positions artifact"}resolved: Dict[str, Any] = {}- unresolved: List[str] = []- for symbol in symbols:+ a_share_to_resolve: List[str] = []+ for index, symbol in enumerate(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 = Noneresolved[symbol] = {"asset_class": asset_class,- "industry": industry,- "industry_source": "eastmoney" if industry is not None else None,+ "industry": None,+ "industry_source": None,}- if asset_class == "a_share" and industry is None:- unresolved.append(symbol)+ if asset_class == "a_share" and index < _POSITIONS_SECTOR_MAX_SYMBOLS:+ a_share_to_resolve.append(symbol)++ if a_share_to_resolve:+ for symbol, industry in _resolve_industries_concurrent(a_share_to_resolve).items():+ if industry is not None:+ resolved[symbol]["industry"] = industry+ resolved[symbol]["industry_source"] = "eastmoney"++ unresolved = [+ symbol+ for symbol in symbols+ if resolved[symbol]["asset_class"] == "a_share" and resolved[symbol]["industry"] is None+ ]payload: Dict[str, Any] = {"ok": True,@@ -540,6 +587,8 @@ def _build_positions_sector_map(run_dir: Path, run_id: str, *, refresh: bool) ->"cached": False,"symbols": resolved,"unresolved": unresolved,+ "total_symbols": len(symbols),+ "symbol_limit": _POSITIONS_SECTOR_MAX_SYMBOLS,}try:cache_path.parent.mkdir(parents=True, exist_ok=True)@@ -895,7 +944,11 @@ def register_runs_routes("""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``.+ ``artifacts/sector_map.json``. The blocking classification (file reads+ plus throttled Eastmoney lookups) runs in the FastAPI threadpool so it+ never stalls the event loop, and is bounded by+ ``_POSITIONS_SECTOR_MAX_SYMBOLS`` / ``_POSITIONS_SECTOR_WORKERS`` /+ the shared client's 15-second per-request timeout.Args:run_id: Run identifier.@@ -916,7 +969,9 @@ def register_runs_routes(detail=f"Run {run_id} not found")- return _build_positions_sector_map(run_dir, run_id, refresh=bool(refresh))+ return await run_in_threadpool(+ _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):diff --git a/agent/tests/api/test_positions_sectors.py b/agent/tests/api/test_positions_sectors.pyindex 4a17425d1..afdb55067 100644--- a/agent/tests/api/test_positions_sectors.py+++ b/agent/tests/api/test_positions_sectors.py@@ -102,6 +102,8 @@ def test_positions_sectors_happy_path(tmp_path: Path, monkeypatch) -> None:assert payload["symbols"]["159913.SZ"]["industry"] is Noneassert payload["symbols"]["159913.SZ"]["industry_source"] is Noneassert payload["unresolved"] == ["159913.SZ"]+ assert payload["total_symbols"] == 3+ assert payload["symbol_limit"] == 200# One spt=1 industry request per A-share symbol; US symbols never resolve.assert get.call_count == 2@@ -248,6 +250,55 @@ def test_unknown_run_id_returns_404(tmp_path: Path, monkeypatch) -> None:assert response.json()["detail"] == "Run no-such-run not found"+# ============================================================================+# Endpoint: bounded contract for large books+# ============================================================================+++def test_large_symbol_list_caps_network_lookups(tmp_path: Path, monkeypatch) -> None:+ total = 250+ symbols = [f"6{i:05d}.SH" for i in range(total)]+ _make_run(+ tmp_path,+ "timestamp," + ",".join(symbols),+ ["2026-08-01T00:00:00," + ",".join(["0.004"] * total)],+ )+ client = _client(tmp_path, monkeypatch)++ def any_secid(symbol: str) -> str | None:+ return f"1.{symbol.split('.')[0]}"++ def any_get_json(url: str, *, params: dict) -> dict:+ code = params["secid"].split(".")[1]+ return {+ "data": {+ "diff": {+ "0": {"f12": code, "f13": 1, "f14": "S"},+ "1": {"f12": "BK0001", "f13": 90, "f14": "银行Ⅱ"},+ }+ }+ }++ with patch(+ "src.tools.sector_tool.resolve_secid", side_effect=any_secid+ ), patch("src.tools.sector_tool.get_json", side_effect=any_get_json) as get:+ response = client.get(f"/runs/{RUN_ID}/positions/sectors")++ assert response.status_code == 200+ payload = response.json()+ assert payload["total_symbols"] == total+ assert payload["symbol_limit"] == 200+ # Bounded: the capped tail never reaches the network.+ assert get.call_count == 200+ # Asset-class grouping still covers every symbol.+ assert len(payload["symbols"]) == total+ assert payload["symbols"][symbols[0]]["industry"] == "银行Ⅱ"+ assert payload["symbols"][symbols[-1]]["industry"] is None+ # The capped tail degrades to unresolved instead of aborting.+ assert len(payload["unresolved"]) == total - 200+ assert payload["unresolved"] == symbols[200:]++# ============================================================================# resolve_industry_board helper# ============================================================================diff --git a/frontend/src/components/run/PositionsTab.tsx b/frontend/src/components/run/PositionsTab.tsxindex f8b0337f7..617ed7566 100644--- a/frontend/src/components/run/PositionsTab.tsx+++ b/frontend/src/components/run/PositionsTab.tsx@@ -40,6 +40,32 @@ function formatPercent(value: number, digits = 1): string {return `${(value * 100).toFixed(digits)}%`;}+function niceAxisCeil(value: number): number {+ if (value <= 0) return 0.01;+ const base = 10 ** Math.floor(Math.log10(value));+ for (const multiplier of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) {+ if (multiplier * base >= value) return multiplier * base;+ }+ return 10 * base;+}++/**+ * Signed axis range: `[0, nice(max)]` when every value is non-negative,+ * otherwise a symmetric `[-nice, +nice]` so short exposure is never clipped+ * by a hard-coded `[0, 1]` window.+ */+function signedAxisBounds(values: Iterable<number>): { min: number; max: number } {+ let lo = 0;+ let hi = 0;+ for (const value of values) {+ if (!Number.isFinite(value)) continue;+ if (value < lo) lo = value;+ if (value > hi) hi = value;+ }+ const bound = niceAxisCeil(Math.max(Math.abs(lo), hi));+ return lo < 0 ? { min: -bound, max: bound } : { min: 0, max: bound };+}+function categoryColors(t: ReturnType<typeof getChartTheme>): string[] {return [t.infoColor, t.warningColor, "#8b5cf6", "#14b8a6", t.upColor, "#f97316",@@ -102,6 +128,8 @@ export function PositionsTab({ run }: { run: RunData }) {const assetClassLabel = (assetClass: AssetClass) => t(ASSET_CLASS_LABEL_KEYS[assetClass]);const cashLabel = t("runDetail.positions.cash");const restLabel = t("runDetail.positions.rest");+ const restLongLabel = t("runDetail.positions.restLong");+ const restShortLabel = t("runDetail.positions.restShort");const shortLabel = t("runDetail.positions.short");const distributionItems = useMemo<DistributionItem[]>(() => {@@ -136,14 +164,18 @@ export function PositionsTab({ run }: { run: RunData }) {const evolution = useMemo(() => {const dates = downsampleDates(panel.dates, MAX_EVOLUTION_DATES);- const averageWeight = new Map<string, number>();+ // Rank by average ABSOLUTE exposure: ranking by the signed average+ // pushes persistent shorts to the bottom and hides them in the remainder.+ const averageAbsWeight = 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);+ for (const date of panel.dates) {+ sum += Math.abs(panel.weightByDate.get(date)?.[symbol] ?? 0);+ }+ averageAbsWeight.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),+ (a, b) => (averageAbsWeight.get(b) ?? 0) - (averageAbsWeight.get(a) ?? 0),);const top = ranked.slice(0, MAX_LEGEND_SYMBOLS);const rest = new Set(ranked.slice(MAX_LEGEND_SYMBOLS));@@ -153,18 +185,31 @@ export function PositionsTab({ run }: { run: RunData }) {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;- }),+ // Separate long/short remainder series: one signed aggregate would let+ // omitted longs and shorts cancel each other out.+ const restLong = dates.map((date) => {+ const weights = panel.weightByDate.get(date);+ let sum = 0;+ for (const symbol of rest) {+ const weight = weights?.[symbol] ?? 0;+ if (weight > 0) sum += weight;+ }+ return sum;+ });+ const restShort = dates.map((date) => {+ const weights = panel.weightByDate.get(date);+ let sum = 0;+ for (const symbol of rest) {+ const weight = weights?.[symbol] ?? 0;+ if (weight < 0) sum += weight;+ }+ return sum;});+ if (restLong.some((value) => value !== 0)) series.push({ name: restLongLabel, data: restLong });+ if (restShort.some((value) => value !== 0)) series.push({ name: restShortLabel, data: restShort });}return { dates, series };- }, [panel, restLabel]);+ }, [panel, restLongLabel, restShortLabel]);async function handleResolve(refresh: boolean) {if (!run.run_id || resolving) return;@@ -258,25 +303,47 @@ export function PositionsTab({ run }: { run: RunData }) {</PositionsPanelCard><div className="grid gap-4 xl:grid-cols-2">- <PositionsPanelCard title={t("runDetail.positions.weightDistribution")}>+ <PositionsPanelCard+ title={t("runDetail.positions.weightDistribution")}+ subtitle={t("runDetail.positions.basisGross")}+ ><WeightDistributionChart items={distributionItems} mode={mode} cashLabel={cashLabel} shortLabel={shortLabel} /></PositionsPanelCard>- <PositionsPanelCard title={t("runDetail.positions.sectorDistribution")}>+ <PositionsPanelCard+ title={t("runDetail.positions.sectorDistribution")}+ subtitle={t("runDetail.positions.basisNet")}+ ><SectorDistributionChart items={sectorItems} cashLabel={cashLabel} /></PositionsPanelCard></div>- <PositionsPanelCard title={t("runDetail.positions.weightEvolution")}>+ <PositionsPanelCard+ title={t("runDetail.positions.weightEvolution")}+ subtitle={t("runDetail.positions.basisNet")}+ ><WeightEvolutionChart dates={evolution.dates} series={evolution.series} /></PositionsPanelCard></div>);}-function PositionsPanelCard({ title, children }: { title?: string; children: ReactNode }) {+function PositionsPanelCard({+ title,+ subtitle,+ children,+}: {+ title?: string;+ subtitle?: 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>}+ {(title || subtitle) && (+ <header className="mb-3">+ {title && <h3 className="text-sm font-semibold">{title}</h3>}+ {subtitle && <p className="mt-0.5 text-xs text-muted-foreground">{subtitle}</p>}+ </header>+ )}{children}</section>);@@ -418,6 +485,7 @@ function SectorDistributionChart({ items, cashLabel }: { items: GroupedItem[]; c: palette[index % palette.length],},})).reverse();+ const { min, max } = signedAxisBounds(ordered.map((item) => item.weight));return {backgroundColor: "transparent",@@ -437,8 +505,8 @@ function SectorDistributionChart({ items, cashLabel }: { items: GroupedItem[]; cgrid: { left: 8, right: 40, top: 8, bottom: 8, containLabel: true },xAxis: {type: "value",- min: 0,- max: 1,+ min,+ max,axisLabel: {color: t.textColor,fontSize: 10,@@ -478,6 +546,20 @@ function WeightEvolutionChart({ dates, series }: { dates: string[]; series: EvoluseChartLifecycle(ref, () => {const t = getChartTheme();const palette = categoryColors(t);+ // ECharts stacks positives above zero and negatives below; bound the axis+ // by the per-date cumulative stack so neither side is clipped.+ const stackExtremes: number[] = [];+ for (let i = 0; i < dates.length; i += 1) {+ let positive = 0;+ let negative = 0;+ for (const s of series) {+ const value = s.data[i] ?? 0;+ if (value > 0) positive += value;+ else negative += value;+ }+ stackExtremes.push(positive, negative);+ }+ const { min, max } = signedAxisBounds(stackExtremes);return {backgroundColor: "transparent",tooltip: {@@ -513,8 +595,8 @@ function WeightEvolutionChart({ dates, series }: { dates: string[]; series: Evol},yAxis: {type: "value",- min: 0,- max: 1,+ min,+ max,axisLabel: {color: t.textColor,fontSize: 10,diff --git a/frontend/src/components/run/__tests__/PositionsTab.test.tsx b/frontend/src/components/run/__tests__/PositionsTab.test.tsxindex 81f861cfa..397355ef4 100644--- a/frontend/src/components/run/__tests__/PositionsTab.test.tsx+++ b/frontend/src/components/run/__tests__/PositionsTab.test.tsx@@ -45,6 +45,63 @@ function barCategoryAxes(): string[][] {);}+interface AxisBounds {+ min?: number;+ max?: number;+}++function valueXAxes(): AxisBounds[] {+ return charts.flatMap((chart) =>+ chart.setOption.mock.calls+ .map((call) => {+ const option = call[0] as { xAxis?: { type?: string; min?: number; max?: number } };+ return option.xAxis && option.xAxis.type === "value"+ ? { min: option.xAxis.min, max: option.xAxis.max }+ : null;+ })+ .filter((axis): axis is AxisBounds => axis !== null),+ );+}++function valueYAxes(): AxisBounds[] {+ return charts.flatMap((chart) =>+ chart.setOption.mock.calls+ .map((call) => {+ const option = call[0] as { yAxis?: { type?: string; min?: number; max?: number } };+ return option.yAxis && option.yAxis.type === "value"+ ? { min: option.yAxis.min, max: option.yAxis.max }+ : null;+ })+ .filter((axis): axis is AxisBounds => axis !== null),+ );+}++function pieSliceNames(): string[] {+ return 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));+ }),+ );+}++function evolutionSeriesNames(): string[] {+ return charts.flatMap((chart) =>+ chart.setOption.mock.calls.flatMap((call) => {+ const option = call[0] as {+ series?: Array<{ type?: string; name?: string; stack?: string }>;+ };+ return (option.series ?? [])+ .filter((s) => s.type === "line" && s.stack === "weights")+ .map((s) => s.name ?? "");+ }),+ );+}+function sectorMapResponse(body: Record<string, unknown>): Response {return new Response(JSON.stringify(body), {status: 200,@@ -182,4 +239,91 @@ describe("PositionsTab", () => {});expect(fetchMock.mock.calls[1][0]).toBe("/runs/run-test/positions/sectors?refresh=1");});++ const marketNeutralRows = [+ { timestamp: "2024-05-01", "600519.SH": "0.5", "000858.SZ": "-0.5" },+ { timestamp: "2024-05-02", "600519.SH": "0.5", "000858.SZ": "-0.5" },+ ];++ it("renders a market-neutral book instead of the empty state", () => {+ render(<PositionsTab run={makeRun(marketNeutralRows)} />);++ expect(+ screen.queryByText("No position weights recorded for this run."),+ ).not.toBeInTheDocument();+ expect(screen.getByText("2 holdings")).toBeInTheDocument();+ expect(seriesTypes()).toContain("pie");+ });++ it("does not fabricate a cash slice for a market-neutral book", () => {+ render(<PositionsTab run={makeRun(marketNeutralRows)} />);++ const names = pieSliceNames();+ expect(names).toContain("600519.SH");+ expect(names).toContain("000858.SZ Short");+ expect(names).not.toContain("Cash");+ });++ it("keeps a gross-basis cash slice for a short-only book", () => {+ const shortOnlyRows = [+ { timestamp: "2024-06-01", "000858.SZ": "-0.4" },+ { timestamp: "2024-06-03", "000858.SZ": "-0.4" },+ ];+ render(<PositionsTab run={makeRun(shortOnlyRows)} />);++ const names = pieSliceNames();+ expect(names).toContain("000858.SZ Short");+ expect(names).toContain("Cash");+ });++ it("uses a symmetric sector axis when the book is net short", () => {+ const netShortRows = [+ { timestamp: "2024-07-01", "600519.SH": "0.3", "000858.SZ": "-0.5" },+ { timestamp: "2024-07-02", "600519.SH": "0.3", "000858.SZ": "-0.5" },+ ];+ render(<PositionsTab run={makeRun(netShortRows)} />);++ const axes = valueXAxes();+ expect(axes.length).toBeGreaterThan(0);+ for (const axis of axes) {+ expect(axis.min).toBeLessThan(0);+ expect(axis.max).toBeGreaterThan(0);+ expect(axis.min).toBe(-(axis.max as number));+ }+ });++ it("keeps a zero-based sector axis for long-only books", () => {+ render(<PositionsTab run={makeRun(multiSymbolRows)} />);++ const axes = valueXAxes();+ expect(axes.length).toBeGreaterThan(0);+ for (const axis of axes) {+ expect(axis.min).toBe(0);+ expect(axis.max).toBeGreaterThan(0);+ }+ });++ it("ranks persistent shorts into the evolution top set and splits the remainder", () => {+ const weights: Record<string, string> = { "000001.SZ": "-0.4" };+ for (let i = 0; i < 10; i += 1) weights[`L${i}.US`] = "0.02";+ weights["000002.SZ"] = "-0.01";+ const rows = [+ { timestamp: "2024-01-01", ...weights },+ { timestamp: "2024-01-02", ...weights },+ ];+ render(<PositionsTab run={makeRun(rows)} />);++ const names = evolutionSeriesNames();+ expect(names).toContain("000001.SZ");+ expect(names).toContain("Other (long)");+ expect(names).toContain("Other (short)");+ expect(names).not.toContain("Other");++ const axes = valueYAxes();+ expect(axes.length).toBeGreaterThan(0);+ for (const axis of axes) {+ expect(axis.min).toBeLessThan(0);+ expect(axis.max).toBeGreaterThan(0);+ }+ });});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 234c02d13..a9cf6c59f 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -644,6 +644,10 @@"treemap": "خريطة شجرية","cash": "نقد","rest": "أخرى",+ "restLong": "أخرى (شراء)",+ "restShort": "أخرى (بيع)",+ "basisGross": "الشرائح هي |الوزن| (الهامش ÷ صافي الأصول)؛ النقد هو المتبقي غير المستثمر ويُحذف عندما تكون المحفظة مستثمرة بالكامل أو برافعة مالية.",+ "basisNet": "الصافي المكشوف: الوزن الموقّع ÷ صافي الأصول. القيم السالبة تعني صافي بيع.","short": "بيع على المكشوف","resolveIndustries": "جلب الصناعات","resolving": "جارٍ الجلب...",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 91b5a6234..4c6a66a29 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -649,6 +649,10 @@"treemap": "Treemap","cash": "Cash","rest": "Other",+ "restLong": "Other (long)",+ "restShort": "Other (short)",+ "basisGross": "Slices are |weight| (margin ÷ NAV); cash is the uncommitted remainder and is omitted when the book is fully committed or levered.",+ "basisNet": "Net exposure: signed weight ÷ NAV. Negative values mean net short.","short": "Short","resolveIndustries": "Resolve industries","resolving": "Resolving...",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex e7ea5550c..0bdb07f4e 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -649,6 +649,10 @@"treemap": "Mapa de árbol","cash": "Efectivo","rest": "Otros",+ "restLong": "Otros (largos)",+ "restShort": "Otros (cortos)",+ "basisGross": "Las porciones son |peso| (margen ÷ NAV); el efectivo es el resto no comprometido y se omite cuando la cartera está totalmente invertida o apalancada.",+ "basisNet": "Exposición neta: peso con signo ÷ NAV. Los valores negativos indican posición corta neta.","short": "Corto","resolveIndustries": "Resolver industrias","resolving": "Resolviendo...",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex e9c9bcf98..33a9fbbb5 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -644,6 +644,10 @@"treemap": "ツリーマップ","cash": "キャッシュ","rest": "その他",+ "restLong": "その他(ロング)",+ "restShort": "その他(ショート)",+ "basisGross": "スライスは |ウェート|(証拠金 ÷ 純資産)。現金は未使用残高で、フル投資・レバレッジ時は非表示。",+ "basisNet": "ネットエクスポージャー:符号付きウェート ÷ 純資産。負の値はネットショート。","short": "空売り","resolveIndustries": "業種を解決","resolving": "解決中...",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex f06b62886..22e05fa2f 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -644,6 +644,10 @@"treemap": "트리맵","cash": "현금","rest": "기타",+ "restLong": "기타(롱)",+ "restShort": "기타(숏)",+ "basisGross": "슬라이스는 |가중치|(증거금 ÷ 순자산). 현금은 미사용 잔액이며, 풀 투자 또는 레버리지 시 표시되지 않습니다.",+ "basisNet": "넷 익스포저: 부호 있는 가중치 ÷ 순자산. 음수는 넷 숏을 의미합니다.","short": "공매도","resolveIndustries": "업종 조회","resolving": "조회 중...",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 56587c46f..84fc6f761 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -644,6 +644,10 @@"treemap": "矩形树图","cash": "现金","rest": "其他",+ "restLong": "其他(多头)",+ "restShort": "其他(空头)",+ "basisGross": "切片为 |权重|(保证金 ÷ 净值);现金为未占用部分,满仓或杠杆时不显示。",+ "basisNet": "净敞口:带符号权重 ÷ 净值,负值为净空头。","short": "做空","resolveIndustries": "解析行业","resolving": "解析中...",diff --git a/frontend/src/lib/__tests__/positions.test.ts b/frontend/src/lib/__tests__/positions.test.tsindex e5b6dc7d2..9ac2fd7c4 100644--- a/frontend/src/lib/__tests__/positions.test.ts+++ b/frontend/src/lib/__tests__/positions.test.ts@@ -81,6 +81,22 @@ describe("latestHoldingDate", () => {const panel = panelFrom([{ timestamp: "2024-01-01", "AAPL.US": "0.0005" }]);expect(latestHoldingDate(panel)).toBeNull();});++ it("detects a market-neutral book whose signed sum is zero", () => {+ const panel = panelFrom([+ { timestamp: "2024-01-01", "600519.SH": "0.5", "000858.SZ": "-0.5" },+ { timestamp: "2024-01-02", "600519.SH": "0.0", "000858.SZ": "0.0" },+ ]);+ expect(latestHoldingDate(panel)).toBe("2024-01-01");+ });++ it("detects a short-only book", () => {+ const panel = panelFrom([+ { timestamp: "2024-01-01", "000858.SZ": "-0.4" },+ { timestamp: "2024-01-02", "000858.SZ": "0.0" },+ ]);+ expect(latestHoldingDate(panel)).toBe("2024-01-01");+ });});describe("classifyAssetClass parity with backend rules", () => {@@ -197,6 +213,26 @@ describe("withCashSlice", () => {withCashSlice(input);expect(input).toEqual({ A: 0.5 });});++ it("adds no invented cash for a market-neutral book", () => {+ const result = withCashSlice({ "600519.SH": 0.5, "000858.SZ": -0.5 });+ expect(CASH_SYMBOL in result).toBe(false);+ });++ it("derives cash from gross exposure for a short-only book", () => {+ const result = withCashSlice({ "000858.SZ": -0.4 });+ expect(result[CASH_SYMBOL]).toBeCloseTo(0.6, 10);+ });++ it("derives cash from gross exposure for a mixed long-short book", () => {+ const result = withCashSlice({ "600519.SH": 0.4, "000858.SZ": -0.2 });+ expect(result[CASH_SYMBOL]).toBeCloseTo(0.4, 10);+ });++ it("omits cash when the book is levered (gross above 1)", () => {+ const result = withCashSlice({ "600519.SH": 0.8, "000858.SZ": -0.5 });+ expect(CASH_SYMBOL in result).toBe(false);+ });});describe("downsampleDates", () => {diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4d4b99f25..f66d6c3f9 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -706,6 +706,10 @@ export interface SectorMapResponse {cached?: boolean;symbols: Record<string, SectorInfo>;unresolved?: string[];+ /** Total symbol columns in positions.csv (may exceed `symbol_limit`). */+ total_symbols?: number;+ /** Max symbols that receive a network industry lookup per resolve. */+ symbol_limit?: number;/** Present when the run has no positions artifact. */note?: string;}diff --git a/frontend/src/lib/positions.ts b/frontend/src/lib/positions.tsindex 5d0fece9b..7112f14a3 100644--- a/frontend/src/lib/positions.ts+++ b/frontend/src/lib/positions.ts@@ -84,13 +84,22 @@ export function parsePositionsPanel(rows: Array<Record<string, string>>): Positireturn { dates, symbols, weightByDate };}+/**+ * Last date that holds any position. Presence is decided by finite GROSS+ * exposure (`sum(|weight|)`), never the signed sum: a market-neutral book+ * (+50% / -50%) nets to zero while fully invested, so a signed test would+ * render the whole tab as empty.+ */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;+ const gross = Object.values(weights).reduce(+ (acc, w) => acc + Math.abs(Number.isFinite(w) ? w : 0),+ 0,+ );+ if (gross > 0.001) latest = date;}return latest;}@@ -158,12 +167,23 @@ export function aggregateWeights(}/**- * Adds a `__cash__` pseudo-symbol for the uninvested remainder- * (1 - sum(weights)) when it exceeds 0.5% of the portfolio.+ * Adds a `__cash__` pseudo-symbol for the uncommitted remainder on the same+ * GROSS basis the pie slices use (`|weight|`): `cash = 1 - sum(|weight|)`,+ * added only when it exceeds 0.5% of NAV.+ *+ * The artifact contract is `weight = direction × margin_value / equity`+ * (engine normalises `sum(|weight|) <= 1`), so the signed sum is NOT a valid+ * cash basis: a +50% / -50% market-neutral book would otherwise show 100%+ * gross positions plus 100% invented cash. When the book is fully committed+ * or levered (`sum(|weight|) >= 1`) no residual exists and the slice is+ * omitted rather than fabricated.*/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;+ const gross = Object.values(weights).reduce(+ (acc, w) => acc + Math.abs(Number.isFinite(w) ? w : 0),+ 0,+ );+ const cash = 1 - gross;if (cash <= 0.005) return { ...weights };return { ...weights, [CASH_SYMBOL]: cash };}