Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(shannon): add optional portfolio style and risk diagnosis

tangwj4695805d6e3d7a7c4
diff --git a/README.md b/README.md
index a9ef75558..7c359ee0d 100644
--- a/README.md
+++ b/README.md
@@ -666,6 +666,8 @@ One `get_market_data` call, **29 market-data sources**, one of them the optional
Setting `GILDATA_TOKEN` enables combined queries via `gildata_fin_query`, stock screening with cross-period indicators via `gildata_stock_selection`, and Gildata stock candidates in `search_symbol`.
+The optional Shannon portfolio diagnosis tab on the correlation page uses `GILDATA_TOKEN` to show A-share portfolio style exposures, a stock exposure heatmap and volatility contribution shares. An optional as-of date and entered weights define the snapshot; these shares are not loss probabilities.
+
Local sources can read bar dates from a `DatetimeIndex`, with or without a
configured `date_format`; an explicitly mapped date column takes precedence.
diff --git a/README_ar.md b/README_ar.md
index 500a47be5..fa6cc279f 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -531,6 +531,8 @@ vibe-trading connector install /tmp/my-broker
يؤدي ضبط `GILDATA_TOKEN` إلى تفعيل الاستعلامات المجمعة عبر `gildata_fin_query`، وفرز الأسهم مع مؤشرات لفترات تقارير متعددة عبر `gildata_stock_selection`، وإضافة مرشحي الأسهم من Gildata إلى `search_symbol`.
+تستخدم علامة تبويب تشخيص المحفظة الاختيارية Shannon في صفحة الارتباط `GILDATA_TOKEN` لعرض تعرض محفظة أسهم A لعوامل النمط، وخريطة حرارية لكل سهم، وحصص المساهمة في التقلب. يمكن تحديد تاريخ التحليل وأوزان الحيازات؛ وهذه الحصص ليست احتمالات خسارة.
+
**سلاسل التراجع (بحسب خطر حظر عنوان IP):**
- **أسهم A** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`
diff --git a/README_es.md b/README_es.md
index f9a3e6dc2..3c81cca62 100644
--- a/README_es.md
+++ b/README_es.md
@@ -530,6 +530,8 @@ Una sola llamada `get_market_data`, **29 fuentes de datos de mercado**, una de e
Al configurar `GILDATA_TOKEN`, se habilitan las consultas combinadas con `gildata_fin_query`, el filtrado de acciones con indicadores de varios periodos mediante `gildata_stock_selection` y los candidatos de acciones de Gildata en `search_symbol`.
+La pestaña opcional de diagnóstico Shannon en la página de correlación usa `GILDATA_TOKEN` para mostrar exposiciones de estilo de una cartera de acciones A, un mapa de calor por acción y contribuciones a la volatilidad. Admite fecha y pesos de cartera; estas contribuciones no son probabilidades de pérdida.
+
**Cadenas de fallback (por riesgo de bloqueo de IP):**
- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`
diff --git a/README_id.md b/README_id.md
index 0888c194a..51f40a6e0 100644
--- a/README_id.md
+++ b/README_id.md
@@ -692,6 +692,8 @@ Satu call `get_market_data`, **29 sumber data market**, salah satunya marketplac
Mengatur `GILDATA_TOKEN` mengaktifkan kueri gabungan melalui `gildata_fin_query`, penyaringan saham dengan indikator lintas periode melalui `gildata_stock_selection`, dan kandidat saham Gildata di `search_symbol`.
+Tab diagnosis portofolio Shannon opsional pada halaman korelasi menggunakan `GILDATA_TOKEN` untuk menampilkan eksposur gaya portofolio saham A, peta panas eksposur per saham, dan porsi kontribusi volatilitas. Tanggal analisis dan bobot kepemilikan dapat ditentukan; kontribusi ini bukan probabilitas kerugian.
+
**Fallback chain (berdasarkan risiko IP-ban):**
- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`
diff --git a/README_ja.md b/README_ja.md
index 1a353805e..71fcbba4d 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -531,6 +531,8 @@ vibe-trading connector install /tmp/my-broker
`GILDATA_TOKEN` を設定すると、複合照会の `gildata_fin_query`、複数報告期間の指標を取得できる銘柄スクリーニングの `gildata_stock_selection`、および `search_symbol` の聚源銘柄候補を利用できます。
+相関分析ページの任意機能「Shannon保有診断」は `GILDATA_TOKEN` を使用し、A株ポートフォリオのスタイル・エクスポージャー、個別銘柄のヒートマップ、ボラティリティ寄与率を表示します。基準日と保有比率を指定でき、寄与率は損失確率を意味しません。
+
**フォールバックチェーン(IP 規制リスク順):**
- **A 株** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`
diff --git a/README_ko.md b/README_ko.md
index 5b2c63af3..b3b82b80a 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -531,6 +531,8 @@ vibe-trading connector install /tmp/my-broker
`GILDATA_TOKEN`을 설정하면 통합 질의용 `gildata_fin_query`, 여러 보고기간의 지표를 함께 조회하는 종목 선별용 `gildata_stock_selection`, `search_symbol`의 Gildata 종목 후보를 사용할 수 있습니다.
+상관관계 페이지의 선택 기능인 Shannon 포트폴리오 진단은 `GILDATA_TOKEN`을 사용해 A주 포트폴리오의 스타일 노출, 종목별 노출 히트맵, 변동성 기여 비중을 보여줍니다. 기준일과 보유 비중을 지정할 수 있으며, 기여 비중은 손실 확률이 아닙니다.
+
**폴백 체인 (IP 차단 위험 순):**
- **A주** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`
diff --git a/README_zh.md b/README_zh.md
index 872e1e236..77bcbb834 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -555,6 +555,8 @@ vibe-trading research-artifact search --query "NVDA"
配置 `GILDATA_TOKEN` 后,可使用聚源综合问数 `gildata_fin_query`、支持跨期指标的智能选股 `gildata_stock_selection`,并为证券检索 `search_symbol` 增加聚源候选来源。
+相关性页面提供可选的香农持仓诊断:配置 `GILDATA_TOKEN` 后,可查看 A 股组合风格暴露、个股暴露热力图和组合波动贡献占比;支持可选截至日期及持仓权重,波动贡献占比不是亏损概率。
+
**Fallback 链(按被封 IP 风险排序):**
- **A股** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`
diff --git a/agent/api_server.py b/agent/api_server.py
index b1583497f..e3618940d 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -319,6 +319,9 @@ register_alpha_routes(app)
from src.api.options_routes import register_options_routes # noqa: E402
register_options_routes(app)
+from src.api.shannon_routes import register_shannon_routes # noqa: E402
+register_shannon_routes(app, require_auth)
+
# --- Auth helpers (SSE tickets) ---
from src.api.auth_routes import register_auth_routes # noqa: E402
register_auth_routes(app)
diff --git a/agent/src/api/shannon_routes.py b/agent/src/api/shannon_routes.py
new file mode 100644
index 000000000..60ce08d00
--- /dev/null
+++ b/agent/src/api/shannon_routes.py
@@ -0,0 +1,102 @@
+"""Optional, read-only Shannon portfolio analysis; independent of the agent loop."""
+from __future__ import annotations
+
+from datetime import date as Date
+import math
+
+from fastapi import Depends, FastAPI, HTTPException
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+from src.config.accessor import get_env_config
+from src.tools.gildata_srv import call_srv_arguments
+
+
+class Holding(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ code: str = Field(pattern=r"^\d{6}\.(SH|SZ|BJ)$")
+ weight: float | None = Field(default=None, gt=0, le=1, allow_inf_nan=False)
+
+
+class Snapshot(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ date: Date | None = None
+ holdings: list[Holding] = Field(min_length=1, max_length=2000)
+
+ @model_validator(mode="after")
+ def validate_holdings(self):
+ from backtest.loaders.gildata_loader import _is_cn_index
+
+ if len({h.code for h in self.holdings}) != len(self.holdings):
+ raise ValueError("持仓不能有重复股票 / Duplicate holdings")
+ if any(_is_cn_index(h.code) for h in self.holdings):
+ raise ValueError("请填写A股股票,不要填写指数 / Stocks only, not indices")
+ supplied = [h.weight is not None for h in self.holdings]
+ if any(supplied) and not all(supplied):
+ raise ValueError("权重请全部填写,或全部留空按等权估算 / Supply all weights or none")
+ if all(supplied) and not math.isclose(sum(h.weight for h in self.holdings), 1, abs_tol=1e-6):
+ raise ValueError("权重合计必须为100%,不自动排除现金 / Weights must total 100%")
+ return self
+
+ def positions(self, day: str) -> list[dict]:
+ return [{"date": day, "holdings": [{"code": h.code, "weight": h.weight if h.weight is not None else 1 / len(self.holdings)} for h in self.holdings]}]
+
+
+def configured() -> bool:
+ return get_env_config().data.gildata_token.strip() not in {"", "your-gildata-token"}
+
+
+def invoke(arguments: dict) -> dict:
+ if not configured():
+ raise HTTPException(503, "请先配置聚源Token / Configure GILDATA_TOKEN first")
+ try:
+ return call_srv_arguments("ShannonAnalyze", arguments)
+ except Exception:
+ raise HTTPException(502, "香农分析暂不可用,请检查服务权限或稍后重试 / Shannon unavailable; check entitlement or retry") from None
+
+
+def effective_date(requested: Date | None) -> str:
+ if requested:
+ return requested.isoformat()
+ result = invoke({"intent": "catalog"})
+ universes = (result.get("data") or {}).get("universes", [])
+ latest = next((u.get("current_as_of") for u in universes if u.get("id") == "all" and u.get("ready")), None)
+ try:
+ return Date.fromisoformat(latest).isoformat()
+ except (ValueError, TypeError):
+ raise HTTPException(502, "暂无可用分析日期 / No published analysis date") from None
+
+
+def check_dates(payload: dict, requested: str) -> None:
+ """Never silently use future observations for a historical request."""
+ meta = payload.get("meta") or {}
+ # as_of can name the publication version, rather than an observation date.
+ for key in ("actual_factor_date", "risk_as_of", "actual_as_of"):
+ actual = meta.get(key)
+ if actual:
+ try:
+ if Date.fromisoformat(actual) > Date.fromisoformat(requested):
+ raise HTTPException(502, "返回数据晚于请求日期,未作为历史诊断展示 / Data is later than requested")
+ except (ValueError, TypeError):
+ raise HTTPException(502, "分析日期格式不可核验 / Invalid analysis date") from None
+
+
+def register_shannon_routes(app: FastAPI, require_auth) -> None:
+ @app.get("/api/shannon/status", dependencies=[Depends(require_auth)])
+ def status():
+ return {"configured": configured()}
+
+ @app.get("/api/shannon/catalog", dependencies=[Depends(require_auth)])
+ def catalog():
+ return invoke({"intent": "catalog"})
+
+ @app.post("/api/shannon/diagnosis", dependencies=[Depends(require_auth)])
+ def diagnosis(request: Snapshot):
+ day = effective_date(request.date)
+ payload = invoke({"intent": "portfolio_diagnosis", "date": day, "universe": "all", "positions": request.positions(day)})
+ if payload.get("status") != "completed" or not isinstance(payload.get("data"), dict):
+ raise HTTPException(502, "未取得完整诊断 / No completed diagnosis")
+ check_dates(payload, day)
+ if not (payload.get("meta") or {}).get("actual_factor_date"):
+ raise HTTPException(502, "未返回实际诊断日期 / Actual diagnosis date missing")
+ return {**payload, "requested_date": day,
+ "weight_assumption": "equal" if request.holdings[0].weight is None else "custom"}
diff --git a/agent/src/tools/gildata_srv.py b/agent/src/tools/gildata_srv.py
index 6f077d9c2..33dc53dd9 100644
--- a/agent/src/tools/gildata_srv.py
+++ b/agent/src/tools/gildata_srv.py
@@ -17,6 +17,7 @@ Accept header) but goes through its own throttle bucket: these calls cost
from __future__ import annotations
+import json
import logging
import math
from typing import Any
@@ -59,6 +60,14 @@ def call_srv_tool_results(name: str, query: str, *, timeout: float = _TIMEOUT_S,
requests.RequestException: Propagated from the HTTP layer.
ValueError: Unrecognizable response shape.
"""
+ arguments = {"query": query}
+ if topk is not None:
+ arguments["topk"] = topk
+ return _response_results(_call_srv(name, arguments, timeout=timeout))
+
+
+def _call_srv(name: str, arguments: dict[str, Any], *, timeout: float) -> Any:
+ """Share authenticated MCP transport without changing existing table callers."""
token = get_env_config().data.gildata_token
if not token:
raise RuntimeError("GILDATA_TOKEN is not configured")
@@ -70,10 +79,8 @@ def call_srv_tool_results(name: str, query: str, *, timeout: float = _TIMEOUT_S,
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
- "params": {"name": name, "arguments": {"query": query}},
+ "params": {"name": name, "arguments": arguments},
}
- if topk is not None:
- payload["params"]["arguments"]["topk"] = topk
outer = throttled_post_json(
url,
host_key=_HOST_KEY,
@@ -86,7 +93,28 @@ def call_srv_tool_results(name: str, query: str, *, timeout: float = _TIMEOUT_S,
timeout=timeout,
)
- return _response_results(outer)
+ return outer
+
+
+def call_srv_arguments(name: str, arguments: dict[str, Any], *, timeout: float = _TIMEOUT_S) -> dict[str, Any]:
+ """Preserve analysis status, metadata and asynchronous job IDs."""
+ outer = _call_srv(name, arguments, timeout=timeout)
+ result = outer.get("result") if isinstance(outer, dict) else None
+ if not isinstance(result, dict) or result.get("isError"):
+ raise RuntimeError("Gildata analysis failed; check access and parameters")
+ content = result.get("content")
+ if not isinstance(content, list) or len(content) != 1 or not isinstance(content[0], dict):
+ raise ValueError("Unsupported analysis envelope")
+
+ def invalid_constant(value):
+ raise ValueError("Non-finite analysis data")
+
+ inner = json.loads(content[0].get("text", ""), parse_constant=invalid_constant)
+ if not isinstance(inner, dict) or inner.get("error") or inner.get("status") not in {
+ "completed", "queued", "pending", "running", "submitted",
+ }:
+ raise RuntimeError("Gildata analysis unavailable; check access and parameters")
+ return inner
def call_srv_tool(name: str, query: str, *, timeout: float = _TIMEOUT_S) -> dict[str, Any]:
diff --git a/agent/tests/test_shannon_routes.py b/agent/tests/test_shannon_routes.py
new file mode 100644
index 000000000..1195ae042
--- /dev/null
+++ b/agent/tests/test_shannon_routes.py
@@ -0,0 +1,134 @@
+"""Snapshot diagnosis preserves explicit weights and actual dates."""
+import copy
+import json
+from unittest.mock import Mock
+
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+import pytest
+
+from src.api import shannon_routes as sr
+from src.tools import gildata_srv
+
+
+def diagnosis():
+ return {"status": "completed", "intent": "portfolio_diagnosis", "data": {
+ "exposures": {"portfolio": {"SIZE": 1.2, "VOLATILITY": -.7}},
+ "holdings": [{"ts_code": "600000.SH", "name": "甲公司", "normalized_weight": .6},
+ {"ts_code": "000001.SZ", "name": "乙公司", "normalized_weight": .4}],
+ "missing": [], "risk_attribution": {"top_stock_contributions": {"600000.SH": .2, "000001.SZ": -.01}}},
+ "meta": {"actual_factor_date": "2026-10-28", "risk_as_of": "2026-10-28", "requested_holding_count": 2, "included_holding_count": 2}, "warnings": []}
+
+
+def client(monkeypatch, diagnosis):
+ monkeypatch.setenv("GILDATA_TOKEN", "test-token")
+ vendor = Mock(return_value=diagnosis)
+ monkeypatch.setattr(sr, "call_srv_arguments", vendor)
+ app = FastAPI()
+ sr.register_shannon_routes(app, lambda: None)
+ with TestClient(app) as test_client:
+ yield test_client, vendor
+
+
+def body(**kwargs):
+ return {"date": "2026-10-28", "holdings": [{"code": "600000.SH", "weight": .6}, {"code": "000001.SZ", "weight": .4}], **kwargs}
+
+
+def test_latest_catalog_and_equal_weights_are_explicit(client, diagnosis):
+ c, vendor = client
+ vendor.side_effect = [{"status": "completed", "data": {"universes": [{"id": "all", "ready": True, "current_as_of": "2026-10-28"}]}}, diagnosis]
+ result = c.post("/api/shannon/diagnosis", json={"holdings": [{"code": "600000.SH"}, {"code": "000001.SZ"}]}).json()
+ assert result["weight_assumption"] == "equal" and result["requested_date"] == "2026-10-28"
+ args = vendor.call_args.args[1]
+ assert args["date"] == "2026-10-28" and [h["weight"] for h in args["positions"][0]["holdings"]] == [.5, .5]
+ assert vendor.call_count == 2
+
+
+def test_selected_date_does_not_require_catalog(client, diagnosis):
+ c, vendor = client
+ original = copy.deepcopy(diagnosis)
+ result = c.post("/api/shannon/diagnosis", json=body()).json()
+ assert result["weight_assumption"] == "custom"
+ assert "analysis_id" not in result
+ assert diagnosis == original
+ vendor.assert_called_once()
+ assert vendor.call_args.args[1]["positions"][0]["date"] == "2026-10-28"
+
+
[email protected]("holdings", [
+ [{"code": "600000.SH", "weight": .6}, {"code": "000001.SZ"}],
+ [{"code": "600000.SH", "weight": .4}, {"code": "000001.SZ", "weight": .4}],
+ [{"code": "600000.SH"}, {"code": "600000.SH"}],
+ [{"code": "000300.SH"}], [{"code": "00700.HK"}], [{"code": "AAPL.US"}],
+ [{"code": "600000.SH", "weight": 0}], [{"code": "600000.SH", "weight": -1}],
+])
+def test_invalid_or_partial_allocations_never_reach_vendor(client, holdings):
+ c, vendor = client
+ assert c.post("/api/shannon/diagnosis", json=body(holdings=holdings)).status_code == 422
+ vendor.assert_not_called()
+
+
+def test_non_trading_date_fallback_is_explicit_but_future_data_rejected(client):
+ c, vendor = client
+ result = c.post("/api/shannon/diagnosis", json=body(date="2026-10-31"))
+ assert result.status_code == 200
+ assert result.json()["requested_date"] == "2026-10-31"
+ assert result.json()["meta"]["actual_factor_date"] == "2026-10-28"
+ assert c.post("/api/shannon/diagnosis", json=body(date="2026-10-27")).status_code == 502
+
+
+def test_missing_actual_date_is_not_invented(client):
+ c, vendor = client
+ vendor.return_value = {"status": "completed", "data": {}, "meta": {}}
+ assert c.post("/api/shannon/diagnosis", json=body()).status_code == 502
+
+
+def test_optional_source_never_calls_network_without_token(client, monkeypatch):
+ c, vendor = client
+ monkeypatch.setenv("GILDATA_TOKEN", "")
+ assert c.get("/api/shannon/status").json() == {"configured": False}
+ assert c.post("/api/shannon/diagnosis", json=body()).status_code == 503
+ vendor.assert_not_called()
+
+
+def test_vendor_error_is_sanitized(client):
+ c, vendor = client
+ vendor.side_effect = RuntimeError("secret-token authenticated response")
+ result = c.post("/api/shannon/diagnosis", json=body())
+ assert result.status_code == 502 and "secret-token" not in result.text
+
+
[email protected]("path", ["market", "stress", "interpretation", "period", "jobs/unowned"])
+def test_removed_features_have_no_routes(client, path):
+ c, vendor = client
+ assert c.post(f"/api/shannon/{path}", json=body()).status_code == 404
+ vendor.assert_not_called()
+ if path.startswith("jobs/"):
+ assert c.get(f"/api/shannon/{path}").status_code == 404
+
+
+def test_routes_keep_authentication():
+ def auth():
+ raise HTTPException(401, "authentication required")
+ app = FastAPI()
+ sr.register_shannon_routes(app, auth)
+ with TestClient(app) as c:
+ assert c.get("/api/shannon/status").status_code == 401
+ assert c.post("/api/shannon/diagnosis", json=body()).status_code == 401
+
+
[email protected]("status", ["completed", "queued", "running"])
+def test_transport_preserves_status_and_rejects_rpc_errors(monkeypatch, status):
+ monkeypatch.setenv("GILDATA_TOKEN", "test-token")
+ payload = {"status": status, "job_id": "job-123", "data": {}, "meta": {"as_of": "2026-10-28"}}
+ outer = {"result": {"content": [{"type": "text", "text": json.dumps(payload)}]}}
+ post = Mock(return_value=outer)
+ monkeypatch.setattr(gildata_srv, "throttled_post_json", post)
+ assert gildata_srv.call_srv_arguments("ShannonAnalyze", {"intent": "catalog"}) == payload
+ assert post.call_args.kwargs["headers"]["Authorization"] == "Bearer test-token"
+ assert "test-token" not in post.call_args.args[0]
+ post.return_value = {"result": {"isError": True, "content": [{"text": "secret-token"}]}}
+ with pytest.raises(RuntimeError, match="Gildata analysis failed"):
+ gildata_srv.call_srv_arguments("ShannonAnalyze", {"intent": "catalog"})
diff --git a/frontend/src/components/charts/ShannonPortfolio.tsx b/frontend/src/components/charts/ShannonPortfolio.tsx
new file mode 100644
index 000000000..41f635402
--- /dev/null
+++ b/frontend/src/components/charts/ShannonPortfolio.tsx
@@ -0,0 +1,138 @@
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ArrowRight, RefreshCw } from "lucide-react";
+import {
+ shannon, parseHoldings, finite, percent, styleLabels,
+ type ShannonDiagnosis, type ShannonSnapshot,
+} from "@/lib/shannon";
+
+function Bars({ rows, zh }: {
+ rows: { label: string; value: number; text: string; weight?: string; detail?: string }[];
+ zh: boolean;
+}) {
+ if (!rows.length) return <p className="text-sm text-muted-foreground">{zh ? "本次没有可用数据,不以零代替。" : "No data available; missing values are not zero."}</p>;
+ const max = Math.max(...rows.map(r => Math.abs(r.value)), .000001);
+ const signed = rows.some(r => r.value < 0);
+ return <table className="w-full table-fixed border-separate border-spacing-y-3 text-sm">
+ <colgroup><col className="w-16 sm:w-20" /><col className="w-14 sm:w-16" /><col /><col className="w-16 sm:w-20" /></colgroup>
+ <thead className="text-xs text-muted-foreground"><tr><th className="pr-2 text-left font-normal">{zh ? "股票" : "Stock"}</th><th className="pr-2 text-right font-normal">{zh ? "仓位" : "Allocation"}</th><th className="text-center font-normal">{zh ? "波动贡献" : "Contribution"}</th><th className="pl-2 text-right font-normal" aria-label={zh ? "组合波动贡献占比" : "Portfolio volatility contribution share"}>{zh ? <>组合波动<br />贡献占比</> : "Portfolio volatility share"}</th></tr></thead>
+ <tbody>{rows.map((r, i) => <tr key={`${r.label}-${i}`}>
+ <td className="break-words pr-2 align-middle text-xs sm:text-sm">{r.label}</td>
+ <td className="pr-2 text-right align-middle text-xs tabular-nums whitespace-nowrap">{r.weight ?? "—"}</td>
+ <td className="align-middle"><div className="relative h-5 rounded bg-muted/60" aria-hidden="true">
+ <span className={`absolute inset-y-0 ${signed ? "left-1/2" : "left-0"} w-px bg-muted-foreground/40`} />
+ <span className={`absolute inset-y-1 rounded-sm ${r.value >= 0 ? "bg-rose-500/70" : "bg-teal-500/75"}`} style={{ left: `${signed ? r.value < 0 ? 50 - Math.abs(r.value) / max * 50 : 50 : 0}%`, width: `${Math.abs(r.value) / max * (signed ? 50 : 100)}%` }} />
+ </div></td>
+ <td className="break-words pl-2 text-right align-middle text-xs tabular-nums"><span className="block">{r.text}</span>{r.detail && <span className="mt-0.5 block text-muted-foreground">{r.detail}</span>}</td>
+ </tr>)}</tbody>
+ </table>;
+}
+
+export function ShannonPortfolio() {
+ const { i18n } = useTranslation(); const zh = i18n.language.startsWith("zh");
+ const tr = (cn: string, en: string) => zh ? cn : en;
+ const [configured, setConfigured] = useState<boolean | null>(null);
+ const [latest, setLatest] = useState(""); const [catalogError, setCatalogError] = useState("");
+ const [text, setText] = useState(""); const [date, setDate] = useState("");
+ const [analysis, setAnalysis] = useState<ShannonDiagnosis | null>(null);
+ const [snapshot, setSnapshot] = useState<ShannonSnapshot | null>(null);
+ const [loading, setLoading] = useState(false); const [error, setError] = useState("");
+ const generation = useRef(0); const controller = useRef<AbortController | null>(null);
+ const holdings = parseHoldings(text);
+ const effective = analysis?.meta?.actual_factor_date ?? "";
+ const name = (code: string) => analysis?.data.holdings?.find(h => h.ts_code === code)?.name || code;
+ const label = (key: string) => styleLabels[key]?.[zh ? 0 : 1] ?? key;
+ const failure = (e: unknown) => e instanceof Error ? e.message : tr("服务暂不可用,请重试。", "Service unavailable. Please retry.");
+
+ async function loadCatalog(signal?: AbortSignal) {
+ setCatalogError("");
+ try {
+ const state = await shannon.status(signal); if (signal?.aborted) return; setConfigured(state.configured);
+ if (state.configured) {
+ const result = await shannon.catalog(signal); if (signal?.aborted) return;
+ const published = result.data?.universes?.find(u => u.id === "all" && u.ready)?.current_as_of ?? "";
+ setLatest(published); setDate(current => current || published);
+ }
+ } catch (e) { if (!signal?.aborted) setCatalogError(failure(e)); }
+ }
+ useEffect(() => { const abort = new AbortController(); void loadCatalog(abort.signal); return () => abort.abort(); }, []);
+ useEffect(() => () => { generation.current++; controller.current?.abort(); }, []);
+ function invalidate() {
+ generation.current++; controller.current?.abort(); setLoading(false); setError("");
+ setAnalysis(null); setSnapshot(null);
+ }
+ async function diagnose() {
+ if (!holdings) return;
+ invalidate(); const id = generation.current; const abort = new AbortController(); controller.current = abort;
+ setLoading(true);
+ try {
+ const result = await shannon.diagnosis({ holdings, ...(date ? { date } : {}) }, abort.signal);
+ if (id !== generation.current) return;
+ const body = { holdings, date: result.meta?.actual_factor_date };
+ setAnalysis(result); setSnapshot(body);
+
+ } catch (e) { if (!abort.signal.aborted && id === generation.current) setError(failure(e)); }
+ finally { if (id === generation.current) setLoading(false); }
+ }
+ const exposures = analysis?.data.exposures?.portfolio ?? {};
+ const style = Object.keys(styleLabels).map(key => ({ key, value: finite(exposures[key]) && (analysis?.meta?.factor_coverage?.[key]?.ratio ?? 1) >= 1 ? exposures[key] as number : null }));
+ const styleMax = Math.max(1, ...style.map(row => Math.abs(row.value ?? 0)));
+ const exposureText = (value: number, decimals: number) => {
+ const rounded = Number(value.toFixed(decimals));
+ return `${rounded > 0 ? "+" : ""}${rounded.toFixed(decimals)}`;
+ };
+ const contributions = Object.entries(analysis?.data.risk_attribution?.top_stock_contributions ?? {}).filter((r): r is [string, number] => finite(r[1])).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
+ const mainContributor = contributions.find(([, value]) => value > 0);
+ const included = analysis?.meta?.included_holding_count ?? analysis?.data.holdings?.length ?? 0;
+ const requested = snapshot?.holdings.length ?? 0;
+ const partial = included < requested || !!analysis?.data.missing?.length;
+ const includedCodes = new Set(analysis?.data.holdings?.map(h => h.ts_code));
+ const coveredWeight = (snapshot?.holdings ?? []).filter(h => includedCodes.has(h.code)).reduce((sum, h) => sum + (h.weight ?? 1 / requested), 0);
+
+ return <section className="space-y-6" aria-label={tr("香农持仓诊断", "Shannon portfolio diagnosis")}>
+ <header className="space-y-2"><h2 className="text-xl font-semibold">{tr("持仓风格与风险", "Portfolio style and risk")}</h2><p className="text-sm text-muted-foreground">{tr("查看组合的风格倾向、个股特征,以及组合波动集中在哪些持仓。", "Explore portfolio style, individual stock characteristics and the holdings that contribute to portfolio volatility.")}</p></header>
+ {configured === false ? <div className="rounded-xl border p-5 text-sm">{tr("配置聚源 Token 后可使用持仓诊断,原有相关性分析仍可正常使用。", "Configure a Gildata token to use diagnosis. The existing correlation analysis remains available.")}</div> : <div className="grid gap-5 rounded-xl border bg-card p-5 md:grid-cols-[1fr_17rem]">
+ <div><label htmlFor="shannon-holdings" className="text-sm font-medium">{tr("你的A股持仓", "Your A-share holdings")}</label><textarea id="shannon-holdings" className="mt-2 min-h-36 w-full rounded-lg border bg-background p-3 font-mono text-sm" value={text} onChange={e => { invalidate(); setText(e.target.value); }} placeholder={"600519.SH 40%\n300750.SZ 30%\n600036.SH 30%"} />
+ <p className="mt-2 text-xs leading-relaxed text-muted-foreground">{tr("每行一只,填写代码和权重。权重全部留空时按等权估算;自定义权重须全部填写且合计100%。仅支持A股股票,不自动剔除现金或其他资产。", "One stock per line: code and weight. Omit all weights for equal allocation, or enter all weights totaling 100%. A-share stocks only; cash and other assets are not silently excluded.")}</p>
+ {text && !holdings && <p role="alert" className="mt-2 text-sm text-warning">{tr("请检查代码、重复股票和权重;按上方格式填写。", "Check symbols, duplicates and weights using the format above.")}</p>}</div>
+ <div className="flex flex-col items-start gap-3"><label htmlFor="shannon-date" className="text-sm font-medium">{tr("分析截至日期(可选)", "As-of date (optional)")}</label><input id="shannon-date" type="date" max={latest || undefined} value={date} onChange={e => { invalidate(); setDate(e.target.value); }} className="w-full rounded-lg border bg-background px-3 py-2 text-sm" />
+ <p className="text-xs leading-relaxed text-muted-foreground">{date ? tr("用这一天的数据分析当前输入的持仓,不代表你当时实际持有。", "Analyze the entered holdings at this date, not your historical account holdings.") : tr("留空使用最新可用数据", "Leave blank for the latest available data")}{latest && <span className="block mt-1">{tr("数据更新至", "Published through")} {latest}</span>}</p>
+ {latest && date !== latest && <button className="text-xs underline underline-offset-4" onClick={() => { invalidate(); setDate(latest); }}>{tr("使用最新数据", "Use latest data")}</button>}
+ <button onClick={diagnose} disabled={loading || !holdings || !configured} className="mt-auto inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground disabled:opacity-50">{loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : <ArrowRight className="h-4 w-4" />}{loading ? tr("正在分析持仓…", "Analyzing…") : tr("诊断持仓", "Analyze holdings")}</button>
+ </div>
+ </div>}
+ {catalogError && <p role="alert" className="text-sm text-warning">{catalogError} <button onClick={() => void loadCatalog()} className="underline">{tr("重新检查", "Retry")}</button></p>}
+ {error && <p role="alert" className="rounded-lg border border-danger/30 p-4 text-sm text-danger">{error}</p>}
+ {analysis && <>
+ <div className="flex flex-wrap gap-x-5 gap-y-2 text-xs text-muted-foreground" role="status"><span>{tr("实际分析日", "Actual analysis date")} {effective}</span><span>{tr("已纳入", "Included")} {included}/{requested} {tr("只股票", "stocks")}</span><span>{analysis.weight_assumption === "equal" ? tr("等权估算", "Equal-weight assumption") : tr("按输入权重分析", "Using entered weights")}</span>{analysis.meta?.risk_as_of && <span>{tr("风险估计日", "Risk estimate date")} {analysis.meta.risk_as_of}</span>}</div>
+ {analysis.requested_date !== effective && <p role="status" className="rounded-lg border border-warning/40 p-3 text-sm">{tr("请求日期", "Requested date")} {analysis.requested_date};{tr("实际使用可用数据日", "Actual available date")} {effective}。</p>}
+ {partial && <p role="alert" className="rounded-lg border border-warning/40 p-3 text-sm">{tr("部分股票未被纳入。下方模型结果只代表已覆盖部分,不能当作完整组合画像。", "Some stocks were excluded. Model results describe only the covered portion, not the entire portfolio.")} {tr("已覆盖输入权重", "Covered entered allocation")} {percent(coveredWeight)}。 {(analysis.data.missing ?? []).map((m, i) => <span className="ml-1" key={i}>{typeof m === "string" ? m : typeof m === "object" && m && "ts_code" in m ? String(m.ts_code) : typeof m === "object" && m && "code" in m ? String(m.code) : ""}</span>)}</p>}
+ {!!analysis.warnings?.length && <p role="status" className="text-sm text-warning">{tr("数据源提示本次分析存在限制,结果仅供参考。", "The source reported limitations; interpret these estimates with caution.")}</p>}
+ <section className="space-y-4 rounded-xl border p-4 sm:p-5" aria-label={tr("组合风格暴露", "Portfolio style exposure")}>
+ <div className="flex flex-wrap items-center justify-between gap-2"><h3 className="font-semibold">{tr("组合风格暴露", "Portfolio style exposure")}</h3><span className="text-xs text-muted-foreground">{tr("偏低 ← 模型参照0 → 偏高", "Lower ← Model reference 0 → Higher")}</span></div>
+ <div className="space-y-2">{style.map(row => <div key={row.key} className="grid grid-cols-[5.5rem_minmax(0,1fr)_3.5rem] items-center gap-2 text-xs sm:text-sm" aria-label={`${label(row.key)}: ${finite(row.value) ? exposureText(row.value, 2) : "—"}`}>
+ <span>{label(row.key)}</span><div className="relative h-5 rounded bg-muted/60" aria-hidden="true"><span className="absolute inset-y-0 left-1/2 w-px bg-muted-foreground/40" />{finite(row.value) && <span className={`absolute inset-y-1 rounded-sm ${row.value >= 0 ? "bg-rose-400" : "bg-emerald-500/70"}`} style={{ left: `${row.value >= 0 ? 50 : 50 - Math.abs(row.value) / styleMax * 50}%`, width: `${Math.abs(row.value) / styleMax * 50}%` }} />}</div><span className="text-right font-mono tabular-nums">{finite(row.value) ? exposureText(row.value, 2) : "—"}</span>
+ </div>)}</div>
+ <p className="text-xs leading-relaxed text-muted-foreground">{tr("红色偏高、绿色偏低,距离中线越远倾向越明显。数值为标准化特征,不是仓位或涨跌预测;市场贝塔也不是原始回归β。缺失或覆盖不足显示为—。", "Red means higher, green lower; distance from zero shows the tilt. Values are standardized traits, not allocations or forecasts; market beta is standardized, not raw regression beta. Missing or incomplete coverage is shown as —.")}</p>
+ <details className="border-t pt-3"><summary className="cursor-pointer text-sm font-medium">{tr("查看个股风格", "View stock styles")}</summary>
+ <div className="mt-4 space-y-3"><h4 className="text-sm font-medium">{tr("个股风格暴露热力图", "Stock style exposure heatmap")}</h4><p className="text-xs leading-relaxed text-muted-foreground">{tr("每行一只股票,每列一个因子,顺序与上图一致。红色偏高、绿色偏低;颜色在±2处饱和,数值不截断。它展示个股特点,不是该股风险贡献的分解。", "Rows are stocks; columns follow the factor order above. Red is higher and green lower; colors saturate at ±2 without clipping values. These are stock characteristics, not a breakdown of the stock's risk contribution.")}</p>
+ <div className="max-h-[28rem] overflow-auto rounded-lg border"><table className="w-full min-w-[58rem] border-separate border-spacing-1 text-xs" aria-label={tr("个股风格暴露热力图", "Stock style exposure heatmap")}>
+ <thead><tr><th className="sticky left-0 z-10 min-w-36 bg-card p-3 text-left">{tr("股票", "Stock")}</th>{style.map(row => <th key={row.key} className="whitespace-nowrap px-2 py-3 font-medium">{label(row.key)}</th>)}</tr></thead>
+ <tbody>{analysis.data.holdings?.map(holding => <tr key={holding.ts_code}><th scope="row" className="sticky left-0 z-10 bg-card p-3 text-left font-normal"><span className="block">{holding.name || holding.ts_code}</span><span className="mt-1 block text-muted-foreground">{holding.ts_code}</span></th>{style.map(row => {
+ const value = holding.exposures?.[row.key];
+ const color = finite(value) && value !== 0 ? `rgba(${value > 0 ? "244, 63, 94" : "16, 145, 112"}, ${.08 + .52 * Math.min(Math.abs(value) / 2, 1)})` : undefined;
+ return <td key={row.key} className="rounded bg-muted/30 px-2 py-4 text-center font-mono tabular-nums" style={{ backgroundColor: color }} title={finite(value) ? String(value) : tr("数据缺失", "Missing data")}>{finite(value) ? exposureText(value, 1) : "—"}</td>;
+ })}</tr>)}</tbody>
+ </table></div>{!analysis.data.holdings?.some(holding => Object.values(holding.exposures ?? {}).some(finite)) && <p className="text-sm text-muted-foreground">{tr("本次没有可用的个股风格数据。", "No stock style data is available.")}</p>}</div>
+ </details>
+ </section>
+ <section className="space-y-4 rounded-xl border p-5"><h3 className="font-semibold">{tr("风险归因:谁在影响组合波动", "Risk attribution: volatility sources")}</h3>{mainContributor && <p className="text-sm">{tr(`${name(mainContributor[0])}在已返回股票中对组合波动的估计贡献最大。`, `${name(mainContributor[0])} has the largest estimated volatility contribution among returned stocks.`)}</p>}<p className="text-xs text-muted-foreground">{tr("用于定位组合波动集中在哪里,优先复核相关仓位。仓位是资金占比;组合波动贡献占比=个股波动贡献÷组合总波动。条形按本图最大贡献缩放。", "Locate where portfolio volatility is concentrated and review the relevant allocations. Allocation is the capital weight; volatility share is stock volatility contribution divided by total portfolio volatility. Bars scale to the largest contribution shown.")}</p><Bars zh={zh} rows={contributions.slice(0, 5).map(([code, value]) => {
+ const holding = snapshot?.holdings.find(h => h.code === code);
+ const weight = holding ? holding.weight ?? 1 / requested : undefined;
+ const total = analysis.data.risk_attribution?.total_risk;
+ const share = finite(total) && total > 0 ? value / total : null;
+ return { label: name(code), weight: percent(weight), value, text: percent(share, true), detail: value < 0 ? tr("分散波动", "Diversifying") : value > 0 ? tr("推高波动", "Adding volatility") : tr("贡献为零", "Zero contribution") };
+ })} /><p className="text-xs text-muted-foreground">{tr("展示贡献最大的前5只股票。占比不是亏损概率,也不等于减仓后的风险降幅;可为负或超过100%,前5项不一定合计100%。负贡献表示分散作用。个股自身风险采用统一波动率假设。", "Shows the five largest contributions by magnitude. Shares are not loss probabilities or predicted risk reductions from selling; they can be negative or exceed 100%, and the top five may not sum to 100%. Negative contributions diversify volatility. Stock-specific risk uses a common volatility assumption.")}</p></section>
+ </>}
+ </section>;
+}
diff --git a/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsx b/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsx
new file mode 100644
index 000000000..f941a6c4d
--- /dev/null
+++ b/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsx
@@ -0,0 +1,119 @@
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { ShannonPortfolio } from "../ShannonPortfolio";
+import { shannon, styleLabels, type ShannonDiagnosis } from "@/lib/shannon";
+
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ i18n: { language: "zh" } }) }));
+const diagnosis: ShannonDiagnosis = { status: "completed", requested_date: "2026-10-28", weight_assumption: "custom",
+ meta: { actual_factor_date: "2026-10-28", risk_as_of: "2026-10-27", included_holding_count: 2, requested_holding_count: 2 },
+ data: { exposures: { portfolio: { SIZE: 1.5, VOLATILITY: -.6, BETA: -.2, VALUE: 0 } },
+ holdings: [{ ts_code: "600000.SH", name: "甲公司", normalized_weight: .6, exposures: { BETA: 3.7, VALUE: -3.9, SIZE: 1.5, VOLATILITY: -.6 } },
+ { ts_code: "000001.SZ", name: "乙公司", normalized_weight: .4, exposures: { BETA: 2.1, VALUE: -2.4, SIZE: -.002, VOLATILITY: null } }],
+ risk_attribution: { total_risk: .23, top_stock_contributions: { "600000.SH": .25, "000001.SZ": -.02 } } } };
+
+beforeEach(() => {
+ vi.spyOn(shannon, "status").mockResolvedValue({ configured: true });
+ vi.spyOn(shannon, "catalog").mockResolvedValue({ data: { universes: [{ id: "all", ready: true, current_as_of: "2026-10-28" }] } });
+ vi.spyOn(shannon, "diagnosis").mockResolvedValue(diagnosis);
+});
+
+async function run() {
+ render(<ShannonPortfolio />);
+ await screen.findByText("数据更新至 2026-10-28");
+ fireEvent.change(screen.getByLabelText("你的A股持仓"), { target: { value: "600000.SH 60%\n000001.SZ 40%" } });
+ fireEvent.click(screen.getByRole("button", { name: "诊断持仓" }));
+ await screen.findByRole("heading", { name: "风险归因:谁在影响组合波动" });
+}
+
+it("shows ten portfolio factors and keeps stock styles collapsed with no extra request", async () => {
+ await run();
+ const style = screen.getByRole("region", { name: "组合风格暴露" });
+ expect(within(style).getByLabelText("市值: +1.50")).toBeInTheDocument();
+ expect(within(style).getByLabelText("市场贝塔: -0.20")).toBeInTheDocument();
+ expect(within(style).getByLabelText("价值: 0.00")).toBeInTheDocument();
+ expect(style.querySelector("details")).not.toHaveAttribute("open");
+ expect(screen.queryByText("本期主要助力与拖累")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText("查看个股风格"));
+ await waitFor(() => expect(style.querySelector("details")).toHaveAttribute("open"));
+ const table = screen.getByRole("table", { name: "个股风格暴露热力图" });
+ expect(within(table).getAllByRole("columnheader").map(el => el.textContent)).toEqual(["股票", ...Object.values(styleLabels).map(names => names[0])]);
+ expect(shannon.diagnosis).toHaveBeenCalledTimes(1);
+ expect(shannon.diagnosis).toHaveBeenCalledWith({ date: "2026-10-28", holdings: [{ code: "600000.SH", weight: .6 }, { code: "000001.SZ", weight: .4 }] }, expect.any(AbortSignal));
+});
+
+it("saturates heatmap colors without clipping values and preserves missing values", async () => {
+ await run();
+ fireEvent.click(screen.getByText("查看个股风格"));
+ const table = screen.getByRole("table", { name: "个股风格暴露热力图" });
+ const cells = within(table).getAllByRole("cell");
+ const plusHigh = cells.find(cell => cell.title === "3.7")!;
+ const plusLow = cells.find(cell => cell.title === "2.1")!;
+ expect(plusHigh).toHaveTextContent("+3.7");
+ expect(plusHigh.style.backgroundColor).toBe(plusLow.style.backgroundColor);
+ expect(cells.find(cell => cell.title === "-3.9")!.style.backgroundColor).toBe(cells.find(cell => cell.title === "-2.4")!.style.backgroundColor);
+ expect(cells.find(cell => cell.title === "-0.002")).toHaveTextContent("0.0");
+ expect(cells.filter(cell => cell.title === "数据缺失").every(cell => cell.textContent === "—")).toBe(true);
+ expect(table.textContent).not.toContain("-0.0");
+ expect(screen.getByText(/不是该股风险贡献的分解/)).toBeInTheDocument();
+});
+
+it("retains signed risk shares separately from allocation", async () => {
+ await run();
+ expect(screen.getByRole("row", { name: /甲公司 60.00%/ })).toHaveTextContent("+108.70%");
+ expect(screen.getByRole("row", { name: /乙公司 40.00%/ })).toHaveTextContent("-8.70%");
+ expect(screen.getByText("分散波动")).toBeInTheDocument();
+ expect(screen.getByRole("columnheader", { name: "组合波动贡献占比" })).toBeInTheDocument();
+ expect(screen.getByText(/不是亏损概率,也不等于减仓后的风险降幅/)).toBeInTheDocument();
+ expect(screen.getByText(/优先复核相关仓位/)).toBeInTheDocument();
+});
+
+it("does not fill missing or incomplete portfolio exposures with zero", async () => {
+ vi.mocked(shannon.diagnosis).mockResolvedValue({ ...diagnosis, meta: { ...diagnosis.meta, factor_coverage: { SIZE: { ratio: .5 } } } });
+ await run();
+ const style = screen.getByRole("region", { name: "组合风格暴露" });
+ expect(within(style).getByLabelText("市值: —")).toBeInTheDocument();
+ expect(within(style).getByLabelText("质量: —")).toBeInTheDocument();
+ expect(within(style).getByLabelText("价值: 0.00")).toBeInTheDocument();
+});
+
+it("keeps coverage exclusions and original entered weights visible", async () => {
+ vi.mocked(shannon.diagnosis).mockResolvedValue({ ...diagnosis, meta: { ...diagnosis.meta, included_holding_count: 1 }, data: { ...diagnosis.data, holdings: [diagnosis.data.holdings![0]], missing: [{ ts_code: "000001.SZ" }] } });
+ await run();
+ expect(screen.getByText(/已覆盖输入权重.*60.00%/)).toBeInTheDocument();
+ expect(screen.getByRole("row", { name: /000001.SZ 40.00%/ })).toBeInTheDocument();
+});
+
+it("does not invent shares when total risk is unavailable", async () => {
+ vi.mocked(shannon.diagnosis).mockResolvedValue({ ...diagnosis, data: { ...diagnosis.data, risk_attribution: { top_stock_contributions: { "600000.SH": .25 } } } });
+ await run();
+ expect(screen.getByRole("row", { name: /甲公司 60.00%/ }).querySelectorAll("td")[3]).toHaveTextContent("—");
+});
+
+it("defaults to the published date and clears old results on date changes", async () => {
+ await run();
+ const date = screen.getByLabelText("分析截至日期(可选)");
+ expect(date).toHaveValue("2026-10-28");
+ fireEvent.change(date, { target: { value: "2026-10-23" } });
+ expect(screen.queryByRole("region", { name: "组合风格暴露" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "使用最新数据" }));
+ expect(date).toHaveValue("2026-10-28");
+});
+
+it("discards a late diagnosis after holdings change", async () => {
+ let resolve: (value: ShannonDiagnosis) => void = () => {};
+ vi.mocked(shannon.diagnosis).mockReturnValue(new Promise(r => { resolve = r; }));
+ render(<ShannonPortfolio />);
+ await screen.findByText("数据更新至 2026-10-28");
+ fireEvent.change(screen.getByLabelText("你的A股持仓"), { target: { value: "600000.SH" } });
+ fireEvent.click(screen.getByRole("button", { name: "诊断持仓" }));
+ fireEvent.change(screen.getByLabelText("你的A股持仓"), { target: { value: "000001.SZ" } });
+ await act(async () => resolve(diagnosis));
+ expect(screen.queryByRole("region", { name: "组合风格暴露" })).not.toBeInTheDocument();
+});
+
+it("keeps the source optional and skips catalog without a token", async () => {
+ vi.mocked(shannon.status).mockResolvedValue({ configured: false });
+ render(<ShannonPortfolio />);
+ await screen.findByText(/配置聚源 Token 后可使用/);
+ expect(shannon.catalog).not.toHaveBeenCalled();
+ expect(shannon.diagnosis).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/lib/__tests__/shannon.test.ts b/frontend/src/lib/__tests__/shannon.test.ts
new file mode 100644
index 000000000..b6d485209
--- /dev/null
+++ b/frontend/src/lib/__tests__/shannon.test.ts
@@ -0,0 +1,15 @@
+import { parseHoldings, percent } from "../shannon";
+
+it("preserves explicit percent allocations and permits equal weights only when all omitted", () => {
+ expect(parseHoldings("600000.SH 60%\n000001.SZ 40")).toEqual([{ code: "600000.SH", weight: .6 }, { code: "000001.SZ", weight: .4 }]);
+ expect(parseHoldings("600000.sh\n000001.sz")).toEqual([{ code: "600000.SH" }, { code: "000001.SZ" }]);
+});
+
+it.each(["", "600000.SH 60%\n000001.SZ", "600000.SH 40%\n000001.SZ 40%", "600000.SH\n600000.SH", "00700.HK", "000300.SH", "399001.SZ", "600000.SH -10%", "600000.SH 0%", "600000.SH 100% more"])("rejects unsupported or ambiguous allocations: %s", value => {
+ expect(parseHoldings(value)).toBeNull();
+});
+
+it("distinguishes missing percentages from zero", () => {
+ expect(percent(null)).toBe("—"); expect(percent(0)).toBe("0.00%");
+});
+
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 2194f50b9..78c4a1381 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -426,7 +426,7 @@ async function errorFromResponse(res: Response): Promise<ApiError> {
return new ApiError(detail, res.status, code);
}
-async function request<T>(path: string, options?: RequestInit, timeoutMs?: number): Promise<T> {
+export async function request<T>(path: string, options?: RequestInit, timeoutMs?: number): Promise<T> {
const { headers, ...rest } = options ?? {};
const mergedHeaders: Record<string, string> = { "Content-Type": "application/json", ...authHeaders() };
if (headers) {
diff --git a/frontend/src/lib/shannon.ts b/frontend/src/lib/shannon.ts
new file mode 100644
index 000000000..b66087430
--- /dev/null
+++ b/frontend/src/lib/shannon.ts
@@ -0,0 +1,63 @@
+import { request } from "./api";
+
+export interface ShannonHolding { code: string; weight?: number }
+export interface ShannonSnapshot { date?: string; holdings: ShannonHolding[] }
+export interface ShannonHoldingResult {
+ ts_code: string; name?: string; industry?: string; normalized_weight?: number;
+ exposures?: Record<string, number | null>;
+}
+export interface ShannonMeta {
+ as_of?: string; actual_factor_date?: string; risk_as_of?: string; actual_as_of?: string;
+ requested_holding_count?: number; included_holding_count?: number; excluded_holding_count?: number;
+ risk_window_days?: number; specific_risk_method?: string;
+ factor_coverage?: Record<string, { ratio: number }>;
+}
+export interface ShannonDiagnosis {
+ status: string; requested_date: string; weight_assumption: "equal" | "custom";
+ data: {
+ exposures?: { portfolio?: Record<string, number | null> };
+ holdings?: ShannonHoldingResult[]; missing?: unknown[];
+ risk_attribution?: { total_risk?: number | null; top_stock_contributions?: Record<string, number | null> };
+ };
+ meta?: ShannonMeta; warnings?: unknown[];
+}
+export interface ShannonCatalog {
+ data?: { universes?: { id: string; ready: boolean; current_as_of: string }[] };
+}
+
+const post = <T>(path: string, body: unknown, signal?: AbortSignal) =>
+ request<T>(`/api/shannon/${path}`, { method: "POST", body: JSON.stringify(body), signal });
+export const shannon = {
+ status: (signal?: AbortSignal) => request<{ configured: boolean }>("/api/shannon/status", { signal }),
+ catalog: (signal?: AbortSignal) => request<ShannonCatalog>("/api/shannon/catalog", { signal }),
+ diagnosis: (body: ShannonSnapshot, signal?: AbortSignal) => post<ShannonDiagnosis>("diagnosis", body, signal),
+};
+
+/** Explicit percent weights; never silently normalize partial allocations or cash. */
+export function parseHoldings(text: string): ShannonHolding[] | null {
+ const lines = text.trim().split(/\r?\n/);
+ if (!text.trim() || lines.length > 2000) return null;
+ const holdings: ShannonHolding[] = [];
+ for (const line of lines) {
+ const fields = line.trim().split(/[,,\s]+/);
+ if (fields.length > 2 || !/^\d{6}\.(SH|SZ|BJ)$/i.test(fields[0])) return null;
+ const code = fields[0].toUpperCase();
+ if (/^(000\d{3}\.SH|399\d{3}\.SZ|899\d{3}\.BJ)$/.test(code)) return null;
+ if (fields[1] && !/^\d+(\.\d+)?%?$/.test(fields[1])) return null;
+ const weight = fields[1] ? Number(fields[1].replace("%", "")) / 100 : undefined;
+ if (weight !== undefined && (!Number.isFinite(weight) || weight <= 0 || weight > 1)) return null;
+ holdings.push({ code, ...(weight === undefined ? {} : { weight }) });
+ }
+ if (new Set(holdings.map(h => h.code)).size !== holdings.length) return null;
+ const supplied = holdings.filter(h => h.weight !== undefined).length;
+ if (supplied && (supplied !== holdings.length || Math.abs(holdings.reduce((s, h) => s + (h.weight ?? 0), 0) - 1) > 1e-6)) return null;
+ return holdings;
+}
+
+export const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n);
+export const percent = (n: number | null | undefined, signed = false) => finite(n) ? `${signed && n > 0 ? "+" : ""}${(n * 100).toFixed(2)}%` : "—";
+export const styleLabels: Record<string, [string, string]> = {
+ BETA: ["市场贝塔", "Market beta"], VALUE: ["价值", "Value"], GROWTH: ["成长", "Growth"],
+ QUALITY: ["质量", "Quality"], MOMENTUM_12M: ["动量12月", "12M momentum"], MOMENTUM_6M: ["动量6月", "6M momentum"],
+ VOLATILITY: ["波动率", "Volatility"], LIQUIDITY: ["流动性", "Liquidity"], SIZE: ["市值", "Size"], LEVERAGE: ["杠杆", "Leverage"],
+};
diff --git a/frontend/src/pages/Correlation.tsx b/frontend/src/pages/Correlation.tsx
index 0effde913..03bd44988 100644
--- a/frontend/src/pages/Correlation.tsx
+++ b/frontend/src/pages/Correlation.tsx
@@ -5,10 +5,22 @@ import { CorrelationMatrix } from "@/components/charts/CorrelationMatrix";
import { RegimeTimeline } from "@/components/charts/RegimeTimeline";
import { api, type CorrelationAnalysisResponse } from "@/lib/api";
import { useAnalysisState } from "@/hooks/useAnalysisState";
+import { ShannonPortfolio } from "@/components/charts/ShannonPortfolio";
const WINDOWS = [30, 60, 90, 180, 365] as const;
export function Correlation() {
+ const [tab, setTab] = useState("correlation");
+ return <>
+ <div className="mx-auto flex max-w-5xl gap-2 px-6 pt-6" role="tablist" aria-label={i18n.language.startsWith("zh") ? "分析类型" : "Analysis type"}>
+ {[["correlation", i18n.t("correlation.title")], ["shannon", i18n.language.startsWith("zh") ? "持仓诊断(香农)" : "Portfolio diagnosis (Shannon)"]].map(([key, label]) => <button key={key} role="tab" aria-selected={tab === key} onClick={() => setTab(key)} className={`rounded-lg border px-4 py-2 text-sm ${tab === key ? "bg-primary text-primary-foreground" : "hover:bg-muted"}`}>{label}</button>)}
+ </div>
+ <div hidden={tab !== "correlation"}><CorrelationAnalysis /></div>
+ {tab === "shannon" && <div className="mx-auto max-w-5xl p-6"><ShannonPortfolio /></div>}
+ </>;
+}
+
+function CorrelationAnalysis() {
const [draft, setDraft] = useAnalysisState("correlation", {
codes: "000001.SZ,600519.SH,000858.SZ,601318.SH", days: 90,
method: "pearson" as "pearson" | "spearman", showRegime: false,
diff --git a/frontend/src/pages/__tests__/Correlation.test.tsx b/frontend/src/pages/__tests__/Correlation.test.tsx
index 68a155a87..16cebbc6f 100644
--- a/frontend/src/pages/__tests__/Correlation.test.tsx
+++ b/frontend/src/pages/__tests__/Correlation.test.tsx
@@ -8,6 +8,7 @@ vi.mock("@/lib/api", () => ({ api: apiMock }));
vi.mock("@/components/charts/CorrelationMatrix", () => ({
CorrelationMatrix: ({ labels }: { labels: string[] }) => <div data-testid="correlation-result">{labels.join(",")}</div>,
}));
+vi.mock("@/components/charts/ShannonPortfolio", () => ({ ShannonPortfolio: () => <div>Shannon diagnosis panel</div> }));
vi.mock("@/components/charts/RegimeTimeline", () => ({ RegimeTimeline: () => <div>timeline</div> }));
function response(label: string): CorrelationAnalysisResponse {
@@ -50,3 +51,17 @@ it("rejects duplicate assets and accepts Chinese delimiters", () => {
fireEvent.click(screen.getByRole("button", { name: "Compute" }));
expect(apiMock.getCorrelationAnalysis).toHaveBeenCalledWith("AAPL,SPY,MSFT", 90, "pearson", false, expect.any(AbortSignal));
});
+
+it("keeps correlation as default and retains its result across diagnosis tab switches", async () => {
+ apiMock.getCorrelationAnalysis.mockResolvedValue(response("RETAINED"));
+ render(<Correlation />);
+ expect(screen.queryByText("Shannon diagnosis panel")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Compute" }));
+ expect(await screen.findByTestId("correlation-result")).toHaveTextContent("RETAINED");
+ fireEvent.click(screen.getByRole("tab", { name: "Portfolio diagnosis (Shannon)" }));
+ expect(screen.getByText("Shannon diagnosis panel")).toBeVisible();
+ expect(screen.getByTestId("correlation-result")).not.toBeVisible();
+ fireEvent.click(screen.getByRole("tab", { name: "Correlation Matrix" }));
+ expect(screen.getByTestId("correlation-result")).toBeVisible();
+ expect(apiMock.getCorrelationAnalysis).toHaveBeenCalledTimes(1);
+});