"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(ui): localize the Shannon portfolio diagnosis in all eleven locales
Haozhe Wub76a77ac70c9
diff --git a/frontend/src/components/charts/ShannonPortfolio.tsx b/frontend/src/components/charts/ShannonPortfolio.tsxindex 682b2d696..f05efa057 100644--- a/frontend/src/components/charts/ShannonPortfolio.tsx+++ b/frontend/src/components/charts/ShannonPortfolio.tsx@@ -2,20 +2,20 @@ 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,+ shannon, parseHoldings, finite, percent, styleFactors,+ type ShannonDiagnosis, type ShannonSnapshot, type StyleFactor,} from "@/lib/shannon";-function Bars({ rows, zh }: {+function Bars({ rows }: {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 { t } = useTranslation();+ if (!rows.length) return <p className="text-sm text-muted-foreground">{t("shannon.noData")}</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>+ <thead className="text-xs text-muted-foreground"><tr><th className="pr-2 text-left font-normal">{t("shannon.colStock")}</th><th className="pr-2 text-right font-normal">{t("shannon.colAllocation")}</th><th className="text-center font-normal">{t("shannon.colContribution")}</th><th className="whitespace-pre-line pl-2 text-right font-normal" aria-label={t("shannon.colShareLabel")}>{t("shannon.colShare")}</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>@@ -29,8 +29,7 @@ function Bars({ rows, zh }: {}export function ShannonPortfolio() {- const { i18n } = useTranslation(); const zh = i18n.language.startsWith("zh");- const tr = (cn: string, en: string) => zh ? cn : en;+ const { t } = useTranslation();const [configured, setConfigured] = useState<boolean | null>(null);const [latest, setLatest] = useState(""); const [catalogError, setCatalogError] = useState("");const [text, setText] = useState(""); const [date, setDate] = useState("");@@ -41,8 +40,8 @@ export function ShannonPortfolio() {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.");+ const label = (key: StyleFactor) => t(`shannon.factors.${key}`);+ const failure = (e: unknown) => e instanceof Error ? e.message : t("shannon.serviceUnavailable");async function loadCatalog(signal?: AbortSignal) {setCatalogError("");@@ -75,7 +74,7 @@ export function ShannonPortfolio() {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 style = styleFactors.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));@@ -89,50 +88,50 @@ export function ShannonPortfolio() {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("基于聚源 MCP 香农服务,查看组合的风格倾向、个股特征,以及组合波动集中在哪些持仓。", "Powered by the Gildata MCP Shannon service. 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>+ return <section className="space-y-6" aria-label={t("shannon.regionLabel")}>+ <header className="space-y-2"><h2 className="text-xl font-semibold">{t("shannon.title")}</h2><p className="text-sm text-muted-foreground">{t("shannon.intro")}</p></header>+ {configured === false ? <div className="rounded-xl border p-5 text-sm">{t("shannon.notConfigured")}</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">{t("shannon.holdingsLabel")}</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">{t("shannon.holdingsHint")}</p>+ {text && !holdings && <p role="alert" className="mt-2 text-sm text-warning">{t("shannon.holdingsInvalid")}</p>}</div>+ <div className="flex flex-col items-start gap-3"><label htmlFor="shannon-date" className="text-sm font-medium">{t("shannon.dateLabel")}</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 ? t("shannon.dateHint") : t("shannon.dateLatestHint")}{latest && <span className="block mt-1">{t("shannon.publishedThrough", { date: latest })}</span>}</p>+ {latest && date !== latest && <button className="text-xs underline underline-offset-4" onClick={() => { invalidate(); setDate(latest); }}>{t("shannon.useLatest")}</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 ? t("shannon.analyzing") : t("shannon.analyze")}</button></div></div>}- {catalogError && <p role="alert" className="text-sm text-warning">{catalogError} <button onClick={() => void loadCatalog()} className="underline">{tr("重新检查", "Retry")}</button></p>}+ {catalogError && <p role="alert" className="text-sm text-warning">{catalogError} <button onClick={() => void loadCatalog()} className="underline">{t("shannon.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="flex flex-wrap gap-x-5 gap-y-2 text-xs text-muted-foreground" role="status"><span>{t("shannon.analysisDate", { date: effective })}</span><span>{t("shannon.included", { included, requested })}</span><span>{analysis.weight_assumption === "equal" ? t("shannon.equalWeight") : t("shannon.enteredWeights")}</span>{analysis.meta?.risk_as_of && <span>{t("shannon.riskDate", { 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">{t("shannon.dateFallback", { requested: analysis.requested_date, actual: effective })}</p>}+ {partial && <p role="alert" className="rounded-lg border border-warning/40 p-3 text-sm">{t("shannon.partial")} {t("shannon.coveredWeight", { weight: 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">{t("shannon.sourceLimitations")}</p>}+ <section className="space-y-4 rounded-xl border p-4 sm:p-5" aria-label={t("shannon.styleTitle")}>+ <div className="flex flex-wrap items-center justify-between gap-2"><h3 className="font-semibold">{t("shannon.styleTitle")}</h3><span className="text-xs text-muted-foreground">{t("shannon.styleAxis")}</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>+ <p className="text-xs leading-relaxed text-muted-foreground">{t("shannon.styleNote")}</p>+ <details className="border-t pt-3"><summary className="cursor-pointer text-sm font-medium">{t("shannon.viewStockStyles")}</summary>+ <div className="mt-4 space-y-3"><h4 className="text-sm font-medium">{t("shannon.heatmapTitle")}</h4><p className="text-xs leading-relaxed text-muted-foreground">{t("shannon.heatmapNote")}</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={t("shannon.heatmapTitle")}>+ <thead><tr><th className="sticky left-0 z-10 min-w-36 bg-card p-3 text-left">{t("shannon.colStock")}</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>;+ 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) : t("shannon.missingData")}>{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>+ </table></div>{!analysis.data.holdings?.some(holding => Object.values(holding.exposures ?? {}).some(finite)) && <p className="text-sm text-muted-foreground">{t("shannon.noStockStyle")}</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]) => {+ <section className="space-y-4 rounded-xl border p-5"><h3 className="font-semibold">{t("shannon.riskTitle")}</h3>{mainContributor && <p className="text-sm">{t("shannon.mainContributor", { name: name(mainContributor[0]) })}</p>}<p className="text-xs text-muted-foreground">{t("shannon.riskNote")}</p><Bars 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>+ return { label: name(code), weight: percent(weight), value, text: percent(share, true), detail: value < 0 ? t("shannon.diversifying") : value > 0 ? t("shannon.addingVolatility") : t("shannon.zeroContribution") };+ })} /><p className="text-xs text-muted-foreground">{t("shannon.riskFootnote")}</p></section></>}</section>;}diff --git a/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsx b/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsxindex f941a6c4d..e76631422 100644--- a/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsx+++ b/frontend/src/components/charts/__tests__/ShannonPortfolio.test.tsx@@ -1,8 +1,15 @@import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { ShannonPortfolio } from "../ShannonPortfolio";-import { shannon, styleLabels, type ShannonDiagnosis } from "@/lib/shannon";+import { shannon, styleFactors, type ShannonDiagnosis } from "@/lib/shannon";+import i18n, { SUPPORTED_LANGUAGES } from "@/i18n";+import en from "@/i18n/locales/en.json";+import zh from "@/i18n/locales/zh-CN.json";-vi.mock("react-i18next", () => ({ useTranslation: () => ({ i18n: { language: "zh" } }) }));+async function useLanguage(code: string) {+ await act(async () => { await i18n.changeLanguage(code); });+ // Non-English locales are lazy chunks; wait until the bundle is registered and active.+ await waitFor(() => expect(i18n.language === code && i18n.hasResourceBundle(code, "translation")).toBe(true));+}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 } },@@ -10,11 +17,13 @@ const diagnosis: ShannonDiagnosis = { status: "completed", requested_date: "2026{ 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(() => {+beforeEach(async () => {+ await useLanguage("zh-CN");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);});+afterEach(async () => { await act(async () => { await i18n.changeLanguage("en"); }); });async function run() {render(<ShannonPortfolio />);@@ -35,7 +44,8 @@ it("shows ten portfolio factors and keeps stock styles collapsed with no extra rfireEvent.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(within(table).getAllByRole("columnheader").map(el => el.textContent)).toEqual(["股票", ...styleFactors.map(key => zh.shannon.factors[key])]);+ expect(within(table).getAllByRole("columnheader").map(el => el.textContent)).toEqual(["股票", "市场贝塔", "价值", "成长", "质量", "动量12月", "动量6月", "波动率", "流动性", "市值", "杠杆"]);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));});@@ -117,3 +127,49 @@ it("keeps the source optional and skips catalog without a token", async () => {expect(shannon.catalog).not.toHaveBeenCalled();expect(shannon.diagnosis).not.toHaveBeenCalled();});++it("renders the Chinese two-line share header without changing its accessible name", async () => {+ await run();+ const header = screen.getByRole("columnheader", { name: "组合波动贡献占比" });+ expect(header.textContent).toBe("组合波动\n贡献占比");+ expect(header).toHaveClass("whitespace-pre-line");+});++it("renders English from en.json", async () => {+ await useLanguage("en");+ render(<ShannonPortfolio />);+ await screen.findByText("Published through 2026-10-28");+ fireEvent.change(screen.getByLabelText("Your A-share holdings"), { target: { value: "600000.SH 60%\n000001.SZ 40%" } });+ fireEvent.click(screen.getByRole("button", { name: "Analyze holdings" }));+ await screen.findByRole("heading", { name: "Risk attribution: volatility sources" });+ expect(screen.getByText("Included 2/2 stocks")).toBeInTheDocument();+ expect(within(screen.getByRole("region", { name: "Portfolio style exposure" })).getByLabelText("Size: +1.50")).toBeInTheDocument();+ expect(screen.getByRole("columnheader", { name: "Portfolio volatility contribution share" })).toHaveTextContent("Portfolio volatility share");+ expect(screen.getByText("甲公司 has the largest estimated volatility contribution among returned stocks.")).toBeInTheDocument();+});++/** English strings a locale translated differently; any of them on screen is an English fallback. */+function englishOnly(locale: typeof en): string[] {+ const pairs: [string, string][] = [+ ...Object.entries(en.shannon).filter((e): e is [string, string] => typeof e[1] === "string").map(([k, v]) => [v, locale.shannon[k as Exclude<keyof typeof en.shannon, "factors">]] as [string, string]),+ ...styleFactors.map(k => [en.shannon.factors[k], locale.shannon.factors[k]] as [string, string]),+ ];+ return pairs.filter(([source, translated]) => source !== translated)+ .flatMap(([source]) => source.split(/\{\{\w+\}\}|\n/)).map(part => part.trim()).filter(part => part.length > 3);+}++it.each(SUPPORTED_LANGUAGES.map(l => l.code).filter(code => code !== "en" && code !== "zh-CN"))("%s renders its own locale, never the English strings", async code => {+ const locale = (await import(`../../../i18n/locales/${code}.json`)).default as typeof en;+ await useLanguage(code);+ const { container } = render(<ShannonPortfolio />);+ await screen.findByText(locale.shannon.publishedThrough.replace("{{date}}", "2026-10-28"));+ fireEvent.change(screen.getByLabelText(locale.shannon.holdingsLabel), { target: { value: "600000.SH 60%\n000001.SZ 40%" } });+ fireEvent.click(screen.getByRole("button", { name: locale.shannon.analyze }));+ await screen.findByRole("heading", { name: locale.shannon.riskTitle });+ fireEvent.click(screen.getByText(locale.shannon.viewStockStyles));+ expect(screen.getByRole("table", { name: locale.shannon.heatmapTitle })).toBeInTheDocument();+ expect(screen.getByRole("columnheader", { name: locale.shannon.colShareLabel })).toBeInTheDocument();+ expect(screen.getByText(locale.shannon.factors.BETA, { selector: "th" })).toBeInTheDocument();+ const text = container.textContent ?? "";+ expect(englishOnly(locale).filter(source => text.includes(source))).toEqual([]);+});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 816642149..77c4250fe 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -2576,5 +2576,65 @@"us": "أسهم أمريكية · USD","hk": "أسهم هونغ كونغ · HKD","cn_a": "أسهم صينية A · CNY"+ },+ "shannon": {+ "regionLabel": "تشخيص المحفظة عبر Shannon",+ "title": "أسلوب المحفظة ومخاطرها",+ "intro": "مدعوم بخدمة Shannon عبر Gildata MCP. استكشف أسلوب المحفظة وخصائص كل سهم والحيازات التي تسهم في تذبذب المحفظة.",+ "notConfigured": "اضبط رمز وصول Gildata لاستخدام التشخيص. يظل تحليل الارتباط الحالي متاحًا.",+ "holdingsLabel": "حيازاتك من أسهم A",+ "holdingsHint": "سهم واحد في كل سطر: الرمز والوزن. اترك جميع الأوزان فارغة لتوزيع متساوٍ، أو أدخل جميع الأوزان بمجموع 100%. أسهم A فقط؛ ولا يُستبعد النقد أو الأصول الأخرى تلقائيًا.",+ "holdingsInvalid": "تحقق من الرموز والتكرارات والأوزان وفق التنسيق أعلاه.",+ "dateLabel": "تاريخ التحليل (اختياري)",+ "dateHint": "تُحلَّل الحيازات المُدخلة ببيانات هذا التاريخ، ولا يعني ذلك أنها حيازاتك الفعلية آنذاك.",+ "dateLatestHint": "اتركه فارغًا لاستخدام أحدث البيانات المتاحة",+ "publishedThrough": "البيانات منشورة حتى {{date}}",+ "useLatest": "استخدام أحدث البيانات",+ "analyze": "تحليل الحيازات",+ "analyzing": "جارٍ التحليل…",+ "retry": "إعادة المحاولة",+ "serviceUnavailable": "الخدمة غير متاحة حاليًا. يُرجى إعادة المحاولة.",+ "analysisDate": "تاريخ التحليل الفعلي {{date}}",+ "included": "أُدرج {{included}}/{{requested}} من الأسهم",+ "equalWeight": "افتراض أوزان متساوية",+ "enteredWeights": "وفق الأوزان المُدخلة",+ "riskDate": "تاريخ تقدير المخاطر {{date}}",+ "dateFallback": "التاريخ المطلوب {{requested}}؛ تاريخ البيانات المتاحة المستخدم فعليًا {{actual}}.",+ "partial": "استُبعدت بعض الأسهم. تصف نتائج النموذج الجزء المغطّى فقط، لا المحفظة بأكملها.",+ "coveredWeight": "الوزن المُدخل المغطّى {{weight}}.",+ "sourceLimitations": "أفاد مصدر البيانات بوجود قيود على هذا التحليل؛ تعامل مع هذه التقديرات بحذر.",+ "styleTitle": "تعرّض المحفظة لعوامل الأسلوب",+ "styleAxis": "أعلى → مرجع النموذج 0 ← أدنى",+ "styleNote": "الأحمر يعني أعلى والأخضر أدنى، وكلما ابتعد الشريط عن خط الصفر كان الميل أوضح. القيم سمات معيارية، وليست أوزانًا ولا تنبؤات؛ وبيتا السوق قيمة معيارية وليست بيتا الانحدار الخام. تُعرض القيم المفقودة أو ذات التغطية غير الكافية بالرمز —.",+ "viewStockStyles": "عرض أسلوب كل سهم",+ "heatmapTitle": "خريطة حرارية لتعرّض الأسهم لعوامل الأسلوب",+ "heatmapNote": "كل صف سهم، وكل عمود عامل بترتيب الرسم أعلاه نفسه. الأحمر أعلى والأخضر أدنى؛ تتشبّع الألوان عند ±2 دون اقتطاع القيم. هذه خصائص الأسهم، وليست تفكيكًا لمساهمة السهم في المخاطر.",+ "missingData": "بيانات مفقودة",+ "noStockStyle": "لا تتوفر بيانات أسلوب للأسهم.",+ "riskTitle": "إسناد المخاطر: مصادر التذبذب",+ "mainContributor": "من بين الأسهم المُعادة، يملك {{name}} أكبر مساهمة تقديرية في تذبذب المحفظة.",+ "riskNote": "يحدد أين يتركّز تذبذب المحفظة لتراجع الأوزان المعنية أولًا. الوزن هو حصة رأس المال؛ وحصة التذبذب هي مساهمة السهم في التذبذب مقسومة على إجمالي تذبذب المحفظة. تُقاس الأشرطة نسبةً إلى أكبر مساهمة معروضة.",+ "diversifying": "يُنوِّع",+ "addingVolatility": "يرفع التذبذب",+ "zeroContribution": "مساهمة صفرية",+ "riskFootnote": "يعرض أكبر خمس مساهمات بالقيمة المطلقة. الحصص ليست احتمالات خسارة ولا تقديرات لانخفاض المخاطر عند البيع؛ قد تكون سالبة أو تتجاوز 100%، وقد لا يبلغ مجموع الخمس الأولى 100%. المساهمات السالبة تعني أثر التنويع. تعتمد المخاطر الخاصة بكل سهم على افتراض تذبذب موحّد.",+ "noData": "لا تتوفر بيانات؛ ولا تُعامل القيم المفقودة على أنها صفر.",+ "colStock": "السهم",+ "colAllocation": "الوزن",+ "colContribution": "المساهمة",+ "colShare": "حصة تذبذب المحفظة",+ "colShareLabel": "حصة المساهمة في تذبذب المحفظة",+ "factors": {+ "BETA": "بيتا السوق",+ "VALUE": "القيمة",+ "GROWTH": "النمو",+ "QUALITY": "الجودة",+ "MOMENTUM_12M": "زخم 12 شهرًا",+ "MOMENTUM_6M": "زخم 6 أشهر",+ "VOLATILITY": "التذبذب",+ "LIQUIDITY": "السيولة",+ "SIZE": "حجم الشركة",+ "LEVERAGE": "الرافعة"+ }}}diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex f8ee376bf..58fd80438 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -2576,5 +2576,65 @@"us": "US-Aktien · USD","hk": "Hongkong-Aktien · HKD","cn_a": "Chinesische A-Aktien · CNY"+ },+ "shannon": {+ "regionLabel": "Shannon-Portfoliodiagnose",+ "title": "Portfoliostil und Risiko",+ "intro": "Bereitgestellt über den Shannon-Dienst von Gildata MCP. Untersuche den Stil des Portfolios, die Merkmale einzelner Aktien und die Positionen, die zur Portfoliovolatilität beitragen.",+ "notConfigured": "Konfiguriere ein Gildata-Token, um die Diagnose zu nutzen. Die bestehende Korrelationsanalyse bleibt verfügbar.",+ "holdingsLabel": "Deine A-Share-Positionen",+ "holdingsHint": "Eine Aktie pro Zeile: Code und Gewichtung. Lass alle Gewichtungen leer für eine Gleichgewichtung oder gib alle Gewichtungen mit einer Summe von 100 % ein. Nur A-Share-Aktien; Bargeld und andere Vermögenswerte werden nicht stillschweigend ausgeschlossen.",+ "holdingsInvalid": "Prüfe Codes, Duplikate und Gewichtungen anhand des obigen Formats.",+ "dateLabel": "Stichtag (optional)",+ "dateHint": "Analysiert die eingegebenen Positionen zu diesem Datum, nicht deine historischen Kontobestände.",+ "dateLatestHint": "Leer lassen für die neuesten verfügbaren Daten",+ "publishedThrough": "Daten veröffentlicht bis {{date}}",+ "useLatest": "Neueste Daten verwenden",+ "analyze": "Positionen analysieren",+ "analyzing": "Analyse läuft…",+ "retry": "Erneut versuchen",+ "serviceUnavailable": "Dienst nicht verfügbar. Bitte erneut versuchen.",+ "analysisDate": "Tatsächliches Analysedatum {{date}}",+ "included": "{{included}}/{{requested}} Aktien einbezogen",+ "equalWeight": "Annahme: Gleichgewichtung",+ "enteredWeights": "Mit eingegebenen Gewichtungen",+ "riskDate": "Datum der Risikoschätzung {{date}}",+ "dateFallback": "Angefordertes Datum {{requested}}; tatsächlich verwendetes Datendatum {{actual}}.",+ "partial": "Einige Aktien wurden ausgeschlossen. Die Modellergebnisse beschreiben nur den abgedeckten Teil, nicht das gesamte Portfolio.",+ "coveredWeight": "Abgedeckte eingegebene Gewichtung {{weight}}.",+ "sourceLimitations": "Die Datenquelle meldet Einschränkungen; interpretiere diese Schätzungen mit Vorsicht.",+ "styleTitle": "Stil-Exposure des Portfolios",+ "styleAxis": "Niedriger ← Modellreferenz 0 → Höher",+ "styleNote": "Rot bedeutet höher, Grün niedriger; der Abstand zur Nulllinie zeigt die Ausprägung. Die Werte sind standardisierte Merkmale, keine Gewichtungen oder Prognosen; das Markt-Beta ist standardisiert, kein rohes Regressions-Beta. Fehlende oder unvollständige Abdeckung wird als — angezeigt.",+ "viewStockStyles": "Stile der Einzelaktien anzeigen",+ "heatmapTitle": "Heatmap der Stil-Exposures je Aktie",+ "heatmapNote": "Zeilen sind Aktien; die Spalten folgen der obigen Faktorreihenfolge. Rot ist höher, Grün niedriger; die Farben sättigen bei ±2, ohne Werte abzuschneiden. Dies sind Merkmale der Aktien, keine Zerlegung ihres Risikobeitrags.",+ "missingData": "Daten fehlen",+ "noStockStyle": "Keine Stildaten für Einzelaktien verfügbar.",+ "riskTitle": "Risikoattribution: Quellen der Volatilität",+ "mainContributor": "{{name}} hat unter den zurückgegebenen Aktien den größten geschätzten Beitrag zur Portfoliovolatilität.",+ "riskNote": "Zeigt, wo sich die Portfoliovolatilität konzentriert, damit du die betreffenden Gewichtungen zuerst prüfen kannst. Die Gewichtung ist der Kapitalanteil; der Volatilitätsanteil ist der Volatilitätsbeitrag der Aktie geteilt durch die gesamte Portfoliovolatilität. Die Balken sind auf den größten gezeigten Beitrag skaliert.",+ "diversifying": "Diversifizierend",+ "addingVolatility": "Erhöht die Volatilität",+ "zeroContribution": "Kein Beitrag",+ "riskFootnote": "Zeigt die fünf betragsmäßig größten Beiträge. Die Anteile sind keine Verlustwahrscheinlichkeiten und keine prognostizierte Risikominderung durch Verkauf; sie können negativ sein oder 100 % übersteigen, und die Top 5 ergeben nicht unbedingt 100 %. Negative Beiträge wirken diversifizierend. Für das titelspezifische Risiko wird eine einheitliche Volatilitätsannahme verwendet.",+ "noData": "Keine Daten verfügbar; fehlende Werte werden nicht als null gewertet.",+ "colStock": "Aktie",+ "colAllocation": "Gewichtung",+ "colContribution": "Beitrag",+ "colShare": "Anteil an der Portfoliovolatilität",+ "colShareLabel": "Anteil am Volatilitätsbeitrag des Portfolios",+ "factors": {+ "BETA": "Markt-Beta",+ "VALUE": "Value",+ "GROWTH": "Wachstum",+ "QUALITY": "Quality",+ "MOMENTUM_12M": "Momentum 12M",+ "MOMENTUM_6M": "Momentum 6M",+ "VOLATILITY": "Volatilität",+ "LIQUIDITY": "Liquidität",+ "SIZE": "Size",+ "LEVERAGE": "Leverage"+ }}}diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 317f618ea..10eb4fe23 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -2576,5 +2576,65 @@"us": "US equities · USD","hk": "Hong Kong equities · HKD","cn_a": "A-shares · CNY"+ },+ "shannon": {+ "regionLabel": "Shannon portfolio diagnosis",+ "title": "Portfolio style and risk",+ "intro": "Powered by the Gildata MCP Shannon service. Explore portfolio style, individual stock characteristics and the holdings that contribute to portfolio volatility.",+ "notConfigured": "Configure a Gildata token to use diagnosis. The existing correlation analysis remains available.",+ "holdingsLabel": "Your A-share holdings",+ "holdingsHint": "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.",+ "holdingsInvalid": "Check symbols, duplicates and weights using the format above.",+ "dateLabel": "As-of date (optional)",+ "dateHint": "Analyze the entered holdings at this date, not your historical account holdings.",+ "dateLatestHint": "Leave blank for the latest available data",+ "publishedThrough": "Published through {{date}}",+ "useLatest": "Use latest data",+ "analyze": "Analyze holdings",+ "analyzing": "Analyzing…",+ "retry": "Retry",+ "serviceUnavailable": "Service unavailable. Please retry.",+ "analysisDate": "Actual analysis date {{date}}",+ "included": "Included {{included}}/{{requested}} stocks",+ "equalWeight": "Equal-weight assumption",+ "enteredWeights": "Using entered weights",+ "riskDate": "Risk estimate date {{date}}",+ "dateFallback": "Requested date {{requested}}; Actual available date {{actual}}.",+ "partial": "Some stocks were excluded. Model results describe only the covered portion, not the entire portfolio.",+ "coveredWeight": "Covered entered allocation {{weight}}.",+ "sourceLimitations": "The source reported limitations; interpret these estimates with caution.",+ "styleTitle": "Portfolio style exposure",+ "styleAxis": "Lower ← Model reference 0 → Higher",+ "styleNote": "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 —.",+ "viewStockStyles": "View stock styles",+ "heatmapTitle": "Stock style exposure heatmap",+ "heatmapNote": "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.",+ "missingData": "Missing data",+ "noStockStyle": "No stock style data is available.",+ "riskTitle": "Risk attribution: volatility sources",+ "mainContributor": "{{name}} has the largest estimated volatility contribution among returned stocks.",+ "riskNote": "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.",+ "diversifying": "Diversifying",+ "addingVolatility": "Adding volatility",+ "zeroContribution": "Zero contribution",+ "riskFootnote": "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.",+ "noData": "No data available; missing values are not zero.",+ "colStock": "Stock",+ "colAllocation": "Allocation",+ "colContribution": "Contribution",+ "colShare": "Portfolio volatility share",+ "colShareLabel": "Portfolio volatility contribution share",+ "factors": {+ "BETA": "Market beta",+ "VALUE": "Value",+ "GROWTH": "Growth",+ "QUALITY": "Quality",+ "MOMENTUM_12M": "12M momentum",+ "MOMENTUM_6M": "6M momentum",+ "VOLATILITY": "Volatility",+ "LIQUIDITY": "Liquidity",+ "SIZE": "Size",+ "LEVERAGE": "Leverage"+ }}}diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 095d19c84..1eea106c9 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -2576,5 +2576,65 @@"us": "Acciones de EE. UU. · USD","hk": "Acciones de Hong Kong · HKD","cn_a": "Acciones A de China · CNY"+ },+ "shannon": {+ "regionLabel": "Diagnóstico de cartera Shannon",+ "title": "Estilo y riesgo de la cartera",+ "intro": "Con tecnología del servicio Shannon de Gildata MCP. Explora el estilo de la cartera, las características de cada acción y las posiciones que contribuyen a la volatilidad de la cartera.",+ "notConfigured": "Configura un token de Gildata para usar el diagnóstico. El análisis de correlación existente sigue disponible.",+ "holdingsLabel": "Tus posiciones en acciones A",+ "holdingsHint": "Una acción por línea: código y peso. Deja todos los pesos vacíos para usar pesos iguales, o introduce todos los pesos con un total de 100%. Solo acciones A; el efectivo y otros activos no se excluyen automáticamente.",+ "holdingsInvalid": "Revisa los códigos, los duplicados y los pesos según el formato anterior.",+ "dateLabel": "Fecha de análisis (opcional)",+ "dateHint": "Analiza las posiciones introducidas con datos de esta fecha; no son las posiciones históricas de tu cuenta.",+ "dateLatestHint": "Déjalo en blanco para usar los datos más recientes disponibles",+ "publishedThrough": "Datos publicados hasta {{date}}",+ "useLatest": "Usar los datos más recientes",+ "analyze": "Analizar posiciones",+ "analyzing": "Analizando…",+ "retry": "Reintentar",+ "serviceUnavailable": "Servicio no disponible. Inténtalo de nuevo.",+ "analysisDate": "Fecha real del análisis {{date}}",+ "included": "Incluidas {{included}}/{{requested}} acciones",+ "equalWeight": "Supuesto de pesos iguales",+ "enteredWeights": "Con los pesos introducidos",+ "riskDate": "Fecha de estimación del riesgo {{date}}",+ "dateFallback": "Fecha solicitada {{requested}}; fecha de datos disponible utilizada {{actual}}.",+ "partial": "Se excluyeron algunas acciones. Los resultados del modelo describen solo la parte cubierta, no la cartera completa.",+ "coveredWeight": "Peso introducido cubierto {{weight}}.",+ "sourceLimitations": "La fuente informó de limitaciones; interpreta estas estimaciones con cautela.",+ "styleTitle": "Exposición de estilo de la cartera",+ "styleAxis": "Menor ← Referencia del modelo 0 → Mayor",+ "styleNote": "Rojo indica mayor y verde menor; la distancia al cero muestra la inclinación. Los valores son rasgos estandarizados, no pesos ni previsiones; la beta de mercado está estandarizada, no es la beta de regresión bruta. La cobertura ausente o incompleta se muestra como —.",+ "viewStockStyles": "Ver estilos por acción",+ "heatmapTitle": "Mapa de calor de exposición de estilo por acción",+ "heatmapNote": "Las filas son acciones; las columnas siguen el orden de factores anterior. Rojo es mayor y verde menor; los colores se saturan en ±2 sin recortar los valores. Son características de cada acción, no un desglose de su contribución al riesgo.",+ "missingData": "Datos ausentes",+ "noStockStyle": "No hay datos de estilo por acción disponibles.",+ "riskTitle": "Atribución de riesgo: fuentes de volatilidad",+ "mainContributor": "{{name}} tiene la mayor contribución estimada a la volatilidad entre las acciones devueltas.",+ "riskNote": "Localiza dónde se concentra la volatilidad de la cartera y revisa primero los pesos correspondientes. El peso es la proporción del capital; la participación en la volatilidad es la contribución de la acción a la volatilidad dividida por la volatilidad total de la cartera. Las barras se escalan a la mayor contribución mostrada.",+ "diversifying": "Diversifica",+ "addingVolatility": "Añade volatilidad",+ "zeroContribution": "Contribución nula",+ "riskFootnote": "Muestra las cinco mayores contribuciones en valor absoluto. Las participaciones no son probabilidades de pérdida ni reducciones de riesgo previstas al vender; pueden ser negativas o superar el 100%, y las cinco primeras pueden no sumar 100%. Las contribuciones negativas diversifican la volatilidad. El riesgo específico de cada acción usa un supuesto de volatilidad común.",+ "noData": "No hay datos disponibles; los valores ausentes no son cero.",+ "colStock": "Acción",+ "colAllocation": "Peso",+ "colContribution": "Contribución",+ "colShare": "Participación en la volatilidad",+ "colShareLabel": "Participación en la contribución a la volatilidad de la cartera",+ "factors": {+ "BETA": "Beta de mercado",+ "VALUE": "Valor",+ "GROWTH": "Crecimiento",+ "QUALITY": "Calidad",+ "MOMENTUM_12M": "Momentum 12M",+ "MOMENTUM_6M": "Momentum 6M",+ "VOLATILITY": "Volatilidad",+ "LIQUIDITY": "Liquidez",+ "SIZE": "Tamaño",+ "LEVERAGE": "Apalancamiento"+ }}}diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.jsonindex eab408b27..ab7d8f056 100644--- a/frontend/src/i18n/locales/fa.json+++ b/frontend/src/i18n/locales/fa.json@@ -2576,5 +2576,65 @@"us": "سهام آمریکا · USD","hk": "سهام هنگکنگ · HKD","cn_a": "سهام A چین · CNY"+ },+ "shannon": {+ "regionLabel": "ارزیابی سبد سهام با Shannon",+ "title": "سبک و ریسک سبد سهام",+ "intro": "مبتنی بر سرویس Shannon در Gildata MCP. گرایش سبکی سبد، ویژگیهای هر سهم و داراییهایی را که در نوسان سبد مشارکت دارند بررسی کنید.",+ "notConfigured": "برای استفاده از ارزیابی، توکن Gildata را پیکربندی کنید. تحلیل همبستگی فعلی همچنان در دسترس است.",+ "holdingsLabel": "سهام A شما",+ "holdingsHint": "در هر سطر یک سهم: کد و وزن. اگر همهٔ وزنها را خالی بگذارید، وزن برابر در نظر گرفته میشود؛ در غیر این صورت وزن همهٔ سهمها را وارد کنید تا جمع آنها ۱۰۰٪ شود. فقط سهام A پشتیبانی میشود؛ وجه نقد و سایر داراییها بهطور خودکار کنار گذاشته نمیشوند.",+ "holdingsInvalid": "کدها، سهمهای تکراری و وزنها را طبق قالب بالا بررسی کنید.",+ "dateLabel": "تاریخ مبنای تحلیل (اختیاری)",+ "dateHint": "داراییهای واردشده با دادههای این تاریخ تحلیل میشوند؛ این به معنای دارایی واقعی شما در آن زمان نیست.",+ "dateLatestHint": "برای استفاده از آخرین دادههای موجود خالی بگذارید",+ "publishedThrough": "دادهها تا {{date}} منتشر شدهاند",+ "useLatest": "استفاده از آخرین دادهها",+ "analyze": "ارزیابی داراییها",+ "analyzing": "در حال تحلیل…",+ "retry": "تلاش دوباره",+ "serviceUnavailable": "سرویس در دسترس نیست. لطفاً دوباره تلاش کنید.",+ "analysisDate": "تاریخ واقعی تحلیل {{date}}",+ "included": "{{included}}/{{requested}} سهم لحاظ شد",+ "equalWeight": "فرض وزن برابر",+ "enteredWeights": "با وزنهای واردشده",+ "riskDate": "تاریخ برآورد ریسک {{date}}",+ "dateFallback": "تاریخ درخواستی {{requested}}؛ تاریخ دادهٔ موجودی که واقعاً استفاده شد {{actual}}.",+ "partial": "برخی سهمها لحاظ نشدند. نتایج مدل فقط بخش پوششدادهشده را توصیف میکند، نه کل سبد را.",+ "coveredWeight": "وزن واردشدهٔ پوششدادهشده {{weight}}.",+ "sourceLimitations": "منبع داده محدودیتهایی را برای این تحلیل گزارش کرده است؛ برآوردها را با احتیاط تفسیر کنید.",+ "styleTitle": "مواجههٔ سبکی سبد",+ "styleAxis": "بالاتر → مبنای مدل ۰ ← پایینتر",+ "styleNote": "قرمز یعنی بالاتر و سبز یعنی پایینتر؛ هرچه از خط صفر دورتر باشد، گرایش آشکارتر است. مقادیر ویژگیهای استانداردشدهاند، نه وزن یا پیشبینی؛ بتای بازار نیز استانداردشده است، نه بتای خام رگرسیون. مقادیر ناموجود یا با پوشش ناکافی با — نمایش داده میشوند.",+ "viewStockStyles": "مشاهدهٔ سبک هر سهم",+ "heatmapTitle": "نقشهٔ حرارتی مواجههٔ سبکی سهمها",+ "heatmapNote": "هر سطر یک سهم و هر ستون یک عامل است، به همان ترتیب نمودار بالا. قرمز بالاتر و سبز پایینتر است؛ رنگها در ±۲ اشباع میشوند و مقادیر بریده نمیشوند. اینها ویژگیهای هر سهماند، نه تفکیک مشارکت آن سهم در ریسک.",+ "missingData": "داده موجود نیست",+ "noStockStyle": "دادهٔ سبکی برای سهمها موجود نیست.",+ "riskTitle": "تفکیک ریسک: منابع نوسان",+ "mainContributor": "در میان سهمهای بازگشتی، {{name}} بیشترین مشارکت برآوردی را در نوسان سبد دارد.",+ "riskNote": "برای یافتن محل تمرکز نوسان سبد و بازبینی اولویتدار وزنهای مربوط. وزن، نسبت سرمایه است؛ درصد مشارکت در نوسان برابر است با مشارکت سهم در نوسان ÷ کل نوسان سبد. میلهها نسبت به بزرگترین مشارکت نمایشدادهشده مقیاس میشوند.",+ "diversifying": "تنوعبخش",+ "addingVolatility": "افزایندهٔ نوسان",+ "zeroContribution": "بدون مشارکت",+ "riskFootnote": "پنج مشارکت بزرگتر از نظر قدر مطلق نمایش داده میشود. این درصدها احتمال زیان یا پیشبینی کاهش ریسک پس از فروش نیستند؛ ممکن است منفی یا بیش از ۱۰۰٪ باشند و جمع پنج مورد اول لزوماً ۱۰۰٪ نیست. مشارکت منفی یعنی اثر تنوعبخشی. ریسک خاص هر سهم با فرض نوسان یکسان محاسبه میشود.",+ "noData": "دادهای موجود نیست؛ مقادیر ناموجود صفر در نظر گرفته نمیشوند.",+ "colStock": "سهم",+ "colAllocation": "وزن",+ "colContribution": "مشارکت در نوسان",+ "colShare": "درصد مشارکت در نوسان سبد",+ "colShareLabel": "درصد مشارکت در نوسان سبد",+ "factors": {+ "BETA": "بتای بازار",+ "VALUE": "ارزش",+ "GROWTH": "رشد",+ "QUALITY": "کیفیت",+ "MOMENTUM_12M": "مومنتوم ۱۲ ماهه",+ "MOMENTUM_6M": "مومنتوم ۶ ماهه",+ "VOLATILITY": "نوسان",+ "LIQUIDITY": "نقدشوندگی",+ "SIZE": "اندازهٔ شرکت",+ "LEVERAGE": "اهرم"+ }}}diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex cedb25cb4..97baba2b4 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -2576,5 +2576,65 @@"us": "Saham AS · USD","hk": "Saham Hong Kong · HKD","cn_a": "Saham A Tiongkok · CNY"+ },+ "shannon": {+ "regionLabel": "Diagnosis portofolio Shannon",+ "title": "Gaya dan risiko portofolio",+ "intro": "Didukung layanan Shannon dari Gildata MCP. Telusuri gaya portofolio, karakteristik tiap saham, dan kepemilikan yang berkontribusi pada volatilitas portofolio.",+ "notConfigured": "Atur token Gildata untuk menggunakan diagnosis. Analisis korelasi yang ada tetap tersedia.",+ "holdingsLabel": "Kepemilikan A-share Anda",+ "holdingsHint": "Satu saham per baris: kode dan bobot. Kosongkan semua bobot untuk bobot yang sama, atau isi semua bobot dengan total 100%. Hanya saham A-share; kas dan aset lain tidak dikeluarkan secara otomatis.",+ "holdingsInvalid": "Periksa kode, duplikat, dan bobot sesuai format di atas.",+ "dateLabel": "Tanggal acuan (opsional)",+ "dateHint": "Menganalisis kepemilikan yang dimasukkan pada tanggal ini, bukan kepemilikan historis akun Anda.",+ "dateLatestHint": "Kosongkan untuk memakai data terbaru yang tersedia",+ "publishedThrough": "Data dipublikasikan hingga {{date}}",+ "useLatest": "Gunakan data terbaru",+ "analyze": "Analisis kepemilikan",+ "analyzing": "Menganalisis…",+ "retry": "Coba lagi",+ "serviceUnavailable": "Layanan tidak tersedia. Silakan coba lagi.",+ "analysisDate": "Tanggal analisis aktual {{date}}",+ "included": "{{included}}/{{requested}} saham disertakan",+ "equalWeight": "Asumsi bobot sama",+ "enteredWeights": "Menggunakan bobot yang dimasukkan",+ "riskDate": "Tanggal estimasi risiko {{date}}",+ "dateFallback": "Tanggal yang diminta {{requested}}; tanggal data tersedia yang digunakan {{actual}}.",+ "partial": "Beberapa saham dikecualikan. Hasil model hanya menggambarkan bagian yang tercakup, bukan seluruh portofolio.",+ "coveredWeight": "Bobot masukan yang tercakup {{weight}}.",+ "sourceLimitations": "Sumber data melaporkan keterbatasan; tafsirkan estimasi ini dengan hati-hati.",+ "styleTitle": "Eksposur gaya portofolio",+ "styleAxis": "Lebih rendah ← Acuan model 0 → Lebih tinggi",+ "styleNote": "Merah berarti lebih tinggi, hijau lebih rendah; jarak dari nol menunjukkan kecenderungan. Nilai adalah karakteristik terstandardisasi, bukan bobot atau prediksi; beta pasar juga terstandardisasi, bukan beta regresi mentah. Data yang hilang atau cakupan yang tidak lengkap ditampilkan sebagai —.",+ "viewStockStyles": "Lihat gaya per saham",+ "heatmapTitle": "Heatmap eksposur gaya per saham",+ "heatmapNote": "Baris adalah saham; kolom mengikuti urutan faktor di atas. Merah lebih tinggi dan hijau lebih rendah; warna jenuh pada ±2 tanpa memotong nilai. Ini adalah karakteristik saham, bukan rincian kontribusi risiko saham tersebut.",+ "missingData": "Data tidak tersedia",+ "noStockStyle": "Tidak ada data gaya per saham yang tersedia.",+ "riskTitle": "Atribusi risiko: sumber volatilitas",+ "mainContributor": "{{name}} memiliki estimasi kontribusi volatilitas terbesar di antara saham yang dikembalikan.",+ "riskNote": "Temukan di mana volatilitas portofolio terkonsentrasi dan tinjau bobot terkait terlebih dahulu. Bobot adalah porsi modal; porsi volatilitas adalah kontribusi volatilitas saham dibagi total volatilitas portofolio. Batang diskalakan terhadap kontribusi terbesar yang ditampilkan.",+ "diversifying": "Mendiversifikasi",+ "addingVolatility": "Menambah volatilitas",+ "zeroContribution": "Kontribusi nol",+ "riskFootnote": "Menampilkan lima kontribusi terbesar menurut nilai absolut. Porsi ini bukan probabilitas kerugian atau prediksi penurunan risiko jika dijual; nilainya bisa negatif atau melebihi 100%, dan lima teratas belum tentu berjumlah 100%. Kontribusi negatif mendiversifikasi volatilitas. Risiko spesifik saham menggunakan asumsi volatilitas yang sama.",+ "noData": "Tidak ada data; nilai yang hilang tidak dianggap nol.",+ "colStock": "Saham",+ "colAllocation": "Bobot",+ "colContribution": "Kontribusi",+ "colShare": "Porsi volatilitas portofolio",+ "colShareLabel": "Porsi kontribusi volatilitas portofolio",+ "factors": {+ "BETA": "Beta pasar",+ "VALUE": "Value",+ "GROWTH": "Pertumbuhan",+ "QUALITY": "Kualitas",+ "MOMENTUM_12M": "Momentum 12 bulan",+ "MOMENTUM_6M": "Momentum 6 bulan",+ "VOLATILITY": "Volatilitas",+ "LIQUIDITY": "Likuiditas",+ "SIZE": "Ukuran",+ "LEVERAGE": "Leverage"+ }}}diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 62e733969..fa3f62d80 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -2576,5 +2576,65 @@"us": "米国株 · USD","hk": "香港株 · HKD","cn_a": "中国A株 · CNY"+ },+ "shannon": {+ "regionLabel": "Shannon 保有銘柄診断",+ "title": "ポートフォリオのスタイルとリスク",+ "intro": "Gildata MCP の Shannon サービスを利用して、ポートフォリオのスタイル傾向、個別銘柄の特徴、ポートフォリオのボラティリティがどの保有銘柄に集中しているかを確認します。",+ "notConfigured": "診断を利用するには Gildata トークンを設定してください。既存の相関分析は引き続き利用できます。",+ "holdingsLabel": "保有する中国A株",+ "holdingsHint": "1行に1銘柄ずつ、コードとウェイトを入力します。ウェイトをすべて空欄にすると等ウェイトで推計します。指定する場合はすべての銘柄に入力し、合計を100%にしてください。A株のみ対応しており、現金やその他の資産を自動で除外することはありません。",+ "holdingsInvalid": "上の形式に従って、コード、重複銘柄、ウェイトを確認してください。",+ "dateLabel": "分析基準日(任意)",+ "dateHint": "入力した保有銘柄をこの日のデータで分析します。当時実際に保有していたことを示すものではありません。",+ "dateLatestHint": "空欄の場合は最新の利用可能データを使用します",+ "publishedThrough": "データ更新:{{date}} まで",+ "useLatest": "最新データを使用",+ "analyze": "保有銘柄を診断",+ "analyzing": "分析中…",+ "retry": "再試行",+ "serviceUnavailable": "サービスを一時的に利用できません。再試行してください。",+ "analysisDate": "実際の分析日 {{date}}",+ "included": "対象 {{included}}/{{requested}} 銘柄",+ "equalWeight": "等ウェイトで推計",+ "enteredWeights": "入力ウェイトで分析",+ "riskDate": "リスク推計日 {{date}}",+ "dateFallback": "指定日 {{requested}}、実際に使用したデータ日 {{actual}}。",+ "partial": "一部の銘柄が対象外になりました。以下のモデル結果はカバーされた部分のみを表しており、ポートフォリオ全体の姿ではありません。",+ "coveredWeight": "カバーされた入力ウェイト {{weight}}。",+ "sourceLimitations": "データソースから今回の分析に制約があると報告されました。結果は参考としてご覧ください。",+ "styleTitle": "ポートフォリオのスタイル・エクスポージャー",+ "styleAxis": "低い ← モデル基準 0 → 高い",+ "styleNote": "赤は高め、緑は低めを示し、中心線から離れるほど傾向が強くなります。値は標準化された特性であり、構成比や騰落の予測ではありません。マーケット・ベータも標準化値で、回帰で求めた生のベータではありません。欠損またはカバー不足は — で表示します。",+ "viewStockStyles": "個別銘柄のスタイルを表示",+ "heatmapTitle": "個別銘柄スタイル・エクスポージャーのヒートマップ",+ "heatmapNote": "各行が銘柄、各列がファクターで、並び順は上図と同じです。赤は高め、緑は低めを示し、色は ±2 で飽和しますが値は切り詰めません。個別銘柄の特徴を示すもので、その銘柄のリスク寄与の分解ではありません。",+ "missingData": "データ欠損",+ "noStockStyle": "利用できる個別銘柄のスタイルデータがありません。",+ "riskTitle": "リスク・アトリビューション:ボラティリティの要因",+ "mainContributor": "返された銘柄のうち、ポートフォリオのボラティリティへの推計寄与が最も大きいのは {{name}} です。",+ "riskNote": "ポートフォリオのボラティリティがどこに集中しているかを把握し、該当する構成比を優先して見直すための表示です。構成比は資金の配分割合、ボラティリティ寄与率は銘柄のボラティリティ寄与 ÷ ポートフォリオ全体のボラティリティです。バーは本図の最大寄与を基準に表示します。",+ "diversifying": "分散効果",+ "addingVolatility": "ボラティリティを押し上げ",+ "zeroContribution": "寄与ゼロ",+ "riskFootnote": "寄与の絶対値が大きい上位5銘柄を表示します。寄与率は損失確率ではなく、売却によるリスク低下幅の予測でもありません。マイナスや100%超になることもあり、上位5銘柄の合計が100%になるとは限りません。マイナスの寄与は分散効果を表します。個別銘柄固有のリスクには共通のボラティリティ仮定を用いています。",+ "noData": "利用できるデータがありません。欠損値をゼロとして扱うことはありません。",+ "colStock": "銘柄",+ "colAllocation": "構成比",+ "colContribution": "寄与",+ "colShare": "ボラティリティ寄与率",+ "colShareLabel": "ポートフォリオのボラティリティ寄与率",+ "factors": {+ "BETA": "マーケット・ベータ",+ "VALUE": "バリュー",+ "GROWTH": "グロース",+ "QUALITY": "クオリティ",+ "MOMENTUM_12M": "12か月モメンタム",+ "MOMENTUM_6M": "6か月モメンタム",+ "VOLATILITY": "ボラティリティ",+ "LIQUIDITY": "流動性",+ "SIZE": "サイズ",+ "LEVERAGE": "レバレッジ"+ }}}diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 58c9670cb..65ad6976a 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -2576,5 +2576,65 @@"us": "미국 주식 · USD","hk": "홍콩 주식 · HKD","cn_a": "중국 A주 · CNY"+ },+ "shannon": {+ "regionLabel": "Shannon 포트폴리오 진단",+ "title": "포트폴리오 스타일과 리스크",+ "intro": "Gildata MCP Shannon 서비스를 기반으로 포트폴리오의 스타일 성향, 개별 종목의 특성, 그리고 포트폴리오 변동성이 어느 보유 종목에 집중되어 있는지 확인합니다.",+ "notConfigured": "진단을 사용하려면 Gildata 토큰을 설정하세요. 기존 상관관계 분석은 계속 사용할 수 있습니다.",+ "holdingsLabel": "보유 중인 A주",+ "holdingsHint": "한 줄에 한 종목씩 코드와 비중을 입력하세요. 비중을 모두 비워 두면 동일 비중으로 추정하며, 직접 입력하려면 모든 종목에 입력하고 합계를 100%로 맞춰야 합니다. A주 주식만 지원하며 현금이나 기타 자산을 자동으로 제외하지 않습니다.",+ "holdingsInvalid": "위 형식에 따라 코드, 중복 종목, 비중을 확인하세요.",+ "dateLabel": "분석 기준일(선택)",+ "dateHint": "입력한 보유 종목을 이 날짜의 데이터로 분석합니다. 당시 실제로 보유했던 내역을 뜻하지 않습니다.",+ "dateLatestHint": "비워 두면 최신 데이터를 사용합니다",+ "publishedThrough": "데이터 기준일 {{date}}",+ "useLatest": "최신 데이터 사용",+ "analyze": "보유 종목 진단",+ "analyzing": "분석 중…",+ "retry": "다시 시도",+ "serviceUnavailable": "서비스를 일시적으로 사용할 수 없습니다. 다시 시도하세요.",+ "analysisDate": "실제 분석일 {{date}}",+ "included": "{{included}}/{{requested}}개 종목 포함",+ "equalWeight": "동일 비중 가정",+ "enteredWeights": "입력 비중으로 분석",+ "riskDate": "리스크 추정일 {{date}}",+ "dateFallback": "요청일 {{requested}}, 실제 사용한 데이터 기준일 {{actual}}.",+ "partial": "일부 종목이 제외되었습니다. 아래 모델 결과는 포함된 부분만 나타내며 전체 포트폴리오의 모습이 아닙니다.",+ "coveredWeight": "포함된 입력 비중 {{weight}}.",+ "sourceLimitations": "데이터 소스가 이번 분석에 제약이 있다고 알렸습니다. 결과는 참고용으로만 보세요.",+ "styleTitle": "포트폴리오 스타일 익스포저",+ "styleAxis": "낮음 ← 모델 기준 0 → 높음",+ "styleNote": "빨간색은 높음, 초록색은 낮음을 뜻하며 중앙선에서 멀수록 성향이 뚜렷합니다. 값은 표준화된 특성이며 비중이나 등락 예측이 아닙니다. 시장 베타도 표준화된 값이며 원래의 회귀 베타가 아닙니다. 누락되었거나 커버리지가 부족한 값은 —로 표시합니다.",+ "viewStockStyles": "개별 종목 스타일 보기",+ "heatmapTitle": "개별 종목 스타일 익스포저 히트맵",+ "heatmapNote": "각 행은 종목, 각 열은 팩터이며 순서는 위 차트와 같습니다. 빨간색은 높음, 초록색은 낮음이며 색은 ±2에서 포화되지만 값은 자르지 않습니다. 개별 종목의 특성을 보여 줄 뿐, 해당 종목의 리스크 기여 분해가 아닙니다.",+ "missingData": "데이터 없음",+ "noStockStyle": "사용할 수 있는 개별 종목 스타일 데이터가 없습니다.",+ "riskTitle": "리스크 귀인: 변동성의 원천",+ "mainContributor": "반환된 종목 중 {{name}}의 포트폴리오 변동성 추정 기여가 가장 큽니다.",+ "riskNote": "포트폴리오 변동성이 어디에 집중되어 있는지 파악하고 관련 비중을 우선 점검하는 데 사용합니다. 비중은 자금 배분 비율이며, 변동성 기여율은 종목의 변동성 기여 ÷ 포트폴리오 전체 변동성입니다. 막대는 이 차트의 최대 기여를 기준으로 표시됩니다.",+ "diversifying": "분산 효과",+ "addingVolatility": "변동성 확대",+ "zeroContribution": "기여 없음",+ "riskFootnote": "기여의 절댓값이 가장 큰 상위 5개 종목을 표시합니다. 기여율은 손실 확률이 아니며 매도 시 리스크 감소 폭의 예측도 아닙니다. 음수이거나 100%를 넘을 수 있고 상위 5개의 합계가 100%가 아닐 수 있습니다. 음의 기여는 분산 효과를 뜻합니다. 개별 종목의 고유 리스크에는 공통 변동성 가정을 사용합니다.",+ "noData": "사용할 수 있는 데이터가 없습니다. 누락된 값을 0으로 대체하지 않습니다.",+ "colStock": "종목",+ "colAllocation": "비중",+ "colContribution": "기여",+ "colShare": "변동성 기여율",+ "colShareLabel": "포트폴리오 변동성 기여율",+ "factors": {+ "BETA": "시장 베타",+ "VALUE": "가치",+ "GROWTH": "성장",+ "QUALITY": "품질",+ "MOMENTUM_12M": "12개월 모멘텀",+ "MOMENTUM_6M": "6개월 모멘텀",+ "VOLATILITY": "변동성",+ "LIQUIDITY": "유동성",+ "SIZE": "규모",+ "LEVERAGE": "레버리지"+ }}}diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex a120edf21..a32eb14cc 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -2576,5 +2576,65 @@"us": "Ações dos EUA · USD","hk": "Ações de Hong Kong · HKD","cn_a": "Ações A da China · CNY"+ },+ "shannon": {+ "regionLabel": "Diagnóstico de carteira Shannon",+ "title": "Estilo e risco da carteira",+ "intro": "Com o serviço Shannon do Gildata MCP. Explore o estilo da carteira, as características de cada ação e as posições que contribuem para a volatilidade da carteira.",+ "notConfigured": "Configure um token do Gildata para usar o diagnóstico. A análise de correlação existente continua disponível.",+ "holdingsLabel": "Suas ações A em carteira",+ "holdingsHint": "Uma ação por linha: código e peso. Deixe todos os pesos em branco para pesos iguais, ou informe todos os pesos somando 100%. Somente ações A; caixa e outros ativos não são excluídos automaticamente.",+ "holdingsInvalid": "Verifique códigos, duplicatas e pesos conforme o formato acima.",+ "dateLabel": "Data de referência (opcional)",+ "dateHint": "Analisa as posições informadas com dados desta data, não as posições históricas da sua conta.",+ "dateLatestHint": "Deixe em branco para usar os dados mais recentes disponíveis",+ "publishedThrough": "Dados publicados até {{date}}",+ "useLatest": "Usar dados mais recentes",+ "analyze": "Analisar carteira",+ "analyzing": "Analisando…",+ "retry": "Tentar novamente",+ "serviceUnavailable": "Serviço indisponível. Tente novamente.",+ "analysisDate": "Data efetiva da análise {{date}}",+ "included": "Incluídas {{included}}/{{requested}} ações",+ "equalWeight": "Premissa de pesos iguais",+ "enteredWeights": "Usando os pesos informados",+ "riskDate": "Data da estimativa de risco {{date}}",+ "dateFallback": "Data solicitada {{requested}}; data de dados disponível utilizada {{actual}}.",+ "partial": "Algumas ações foram excluídas. Os resultados do modelo descrevem apenas a parte coberta, não a carteira inteira.",+ "coveredWeight": "Peso informado coberto {{weight}}.",+ "sourceLimitations": "A fonte informou limitações; interprete estas estimativas com cautela.",+ "styleTitle": "Exposição de estilo da carteira",+ "styleAxis": "Menor ← Referência do modelo 0 → Maior",+ "styleNote": "Vermelho indica maior e verde menor; a distância do zero mostra a inclinação. Os valores são características padronizadas, não pesos nem previsões; o beta de mercado é padronizado, não o beta bruto de regressão. Cobertura ausente ou incompleta aparece como —.",+ "viewStockStyles": "Ver estilos por ação",+ "heatmapTitle": "Mapa de calor de exposição de estilo por ação",+ "heatmapNote": "As linhas são ações; as colunas seguem a ordem dos fatores acima. Vermelho é maior e verde menor; as cores saturam em ±2 sem cortar os valores. São características de cada ação, não uma decomposição da contribuição da ação para o risco.",+ "missingData": "Dados ausentes",+ "noStockStyle": "Não há dados de estilo por ação disponíveis.",+ "riskTitle": "Atribuição de risco: fontes de volatilidade",+ "mainContributor": "{{name}} tem a maior contribuição estimada para a volatilidade entre as ações retornadas.",+ "riskNote": "Identifique onde a volatilidade da carteira está concentrada e revise primeiro os pesos correspondentes. O peso é a fração do capital; a participação na volatilidade é a contribuição da ação para a volatilidade dividida pela volatilidade total da carteira. As barras são escaladas pela maior contribuição exibida.",+ "diversifying": "Diversifica",+ "addingVolatility": "Aumenta a volatilidade",+ "zeroContribution": "Contribuição nula",+ "riskFootnote": "Mostra as cinco maiores contribuições em valor absoluto. As participações não são probabilidades de perda nem reduções de risco previstas com a venda; podem ser negativas ou passar de 100%, e as cinco maiores podem não somar 100%. Contribuições negativas diversificam a volatilidade. O risco específico de cada ação usa uma premissa de volatilidade comum.",+ "noData": "Não há dados disponíveis; valores ausentes não são zero.",+ "colStock": "Ação",+ "colAllocation": "Peso",+ "colContribution": "Contribuição",+ "colShare": "Participação na volatilidade",+ "colShareLabel": "Participação na contribuição para a volatilidade da carteira",+ "factors": {+ "BETA": "Beta de mercado",+ "VALUE": "Valor",+ "GROWTH": "Crescimento",+ "QUALITY": "Qualidade",+ "MOMENTUM_12M": "Momento 12M",+ "MOMENTUM_6M": "Momento 6M",+ "VOLATILITY": "Volatilidade",+ "LIQUIDITY": "Liquidez",+ "SIZE": "Tamanho",+ "LEVERAGE": "Alavancagem"+ }}}diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.jsonindex cd4f5a6b2..799dd02a4 100644--- a/frontend/src/i18n/locales/tr.json+++ b/frontend/src/i18n/locales/tr.json@@ -2576,5 +2576,65 @@"us": "ABD hisseleri · USD","hk": "Hong Kong hisseleri · HKD","cn_a": "Çin A hisseleri · CNY"+ },+ "shannon": {+ "regionLabel": "Shannon portföy analizi",+ "title": "Portföy stili ve riski",+ "intro": "Gildata MCP Shannon hizmetiyle çalışır. Portföyün stil eğilimini, tek tek hisselerin özelliklerini ve portföy oynaklığına katkıda bulunan pozisyonları inceleyin.",+ "notConfigured": "Analizi kullanmak için bir Gildata token'ı yapılandırın. Mevcut korelasyon analizi kullanılmaya devam eder.",+ "holdingsLabel": "A hissesi pozisyonlarınız",+ "holdingsHint": "Her satıra bir hisse: kod ve ağırlık. Eşit ağırlık için tüm ağırlıkları boş bırakın ya da toplamı %100 olacak şekilde tüm ağırlıkları girin. Yalnızca A hisseleri desteklenir; nakit ve diğer varlıklar otomatik olarak hariç tutulmaz.",+ "holdingsInvalid": "Kodları, yinelenen hisseleri ve ağırlıkları yukarıdaki biçime göre kontrol edin.",+ "dateLabel": "Analiz tarihi (isteğe bağlı)",+ "dateHint": "Girilen pozisyonları bu tarihteki verilerle analiz eder; geçmişteki gerçek hesap pozisyonlarınızı göstermez.",+ "dateLatestHint": "En güncel veriler için boş bırakın",+ "publishedThrough": "Veriler {{date}} tarihine kadar yayımlandı",+ "useLatest": "En güncel verileri kullan",+ "analyze": "Pozisyonları analiz et",+ "analyzing": "Analiz ediliyor…",+ "retry": "Tekrar Dene",+ "serviceUnavailable": "Hizmet kullanılamıyor. Lütfen tekrar deneyin.",+ "analysisDate": "Gerçek analiz tarihi {{date}}",+ "included": "{{included}}/{{requested}} hisse dahil edildi",+ "equalWeight": "Eşit ağırlık varsayımı",+ "enteredWeights": "Girilen ağırlıklar kullanılıyor",+ "riskDate": "Risk tahmini tarihi {{date}}",+ "dateFallback": "İstenen tarih {{requested}}; kullanılan mevcut veri tarihi {{actual}}.",+ "partial": "Bazı hisseler dahil edilmedi. Model sonuçları portföyün tamamını değil, yalnızca kapsanan kısmı açıklar.",+ "coveredWeight": "Kapsanan girilmiş ağırlık {{weight}}.",+ "sourceLimitations": "Veri kaynağı bu analizde kısıtlamalar bildirdi; tahminleri dikkatle yorumlayın.",+ "styleTitle": "Portföy stil maruziyeti",+ "styleAxis": "Düşük ← Model referansı 0 → Yüksek",+ "styleNote": "Kırmızı daha yüksek, yeşil daha düşük anlamına gelir; sıfırdan uzaklık eğilimin gücünü gösterir. Değerler standartlaştırılmış özelliklerdir, ağırlık veya tahmin değildir; piyasa betası da standartlaştırılmıştır, ham regresyon betası değildir. Eksik veya yetersiz kapsam — olarak gösterilir.",+ "viewStockStyles": "Hisse stillerini göster",+ "heatmapTitle": "Hisse bazında stil maruziyeti ısı haritası",+ "heatmapNote": "Satırlar hisseleri gösterir; sütunlar yukarıdaki faktör sırasını izler. Kırmızı daha yüksek, yeşil daha düşüktür; renkler ±2'de doygunluğa ulaşır, değerler kırpılmaz. Bunlar hisse özellikleridir, hissenin risk katkısının ayrıştırması değildir.",+ "missingData": "Veri eksik",+ "noStockStyle": "Kullanılabilir hisse stil verisi yok.",+ "riskTitle": "Risk ayrıştırması: oynaklık kaynakları",+ "mainContributor": "Döndürülen hisseler arasında portföy oynaklığına tahmini en büyük katkıyı {{name}} yapıyor.",+ "riskNote": "Portföy oynaklığının nerede yoğunlaştığını bulun ve ilgili ağırlıkları öncelikle gözden geçirin. Ağırlık, sermaye payıdır; oynaklık payı, hissenin oynaklık katkısının toplam portföy oynaklığına bölünmesidir. Çubuklar gösterilen en büyük katkıya göre ölçeklenir.",+ "diversifying": "Çeşitlendirici",+ "addingVolatility": "Oynaklığı artırıyor",+ "zeroContribution": "Sıfır katkı",+ "riskFootnote": "Mutlak değerce en büyük beş katkıyı gösterir. Paylar zarar olasılığı ya da satış sonrası öngörülen risk azalması değildir; negatif olabilir veya %100'ü aşabilir ve ilk beşin toplamı %100 olmayabilir. Negatif katkılar oynaklığı çeşitlendirir. Hisseye özgü risk için ortak bir oynaklık varsayımı kullanılır.",+ "noData": "Kullanılabilir veri yok; eksik değerler sıfır sayılmaz.",+ "colStock": "Hisse",+ "colAllocation": "Ağırlık",+ "colContribution": "Katkı",+ "colShare": "Portföy oynaklık payı",+ "colShareLabel": "Portföy oynaklığına katkı payı",+ "factors": {+ "BETA": "Piyasa betası",+ "VALUE": "Değer",+ "GROWTH": "Büyüme",+ "QUALITY": "Kalite",+ "MOMENTUM_12M": "12 aylık momentum",+ "MOMENTUM_6M": "6 aylık momentum",+ "VOLATILITY": "Oynaklık",+ "LIQUIDITY": "Likidite",+ "SIZE": "Büyüklük",+ "LEVERAGE": "Kaldıraç"+ }}}diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex fa100237d..6f5523e1e 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -2576,5 +2576,65 @@"us": "美股 · USD","hk": "港股 · HKD","cn_a": "A 股 · CNY"+ },+ "shannon": {+ "regionLabel": "香农持仓诊断",+ "title": "持仓风格与风险",+ "intro": "基于聚源 MCP 香农服务,查看组合的风格倾向、个股特征,以及组合波动集中在哪些持仓。",+ "notConfigured": "配置聚源 Token 后可使用持仓诊断,原有相关性分析仍可正常使用。",+ "holdingsLabel": "你的A股持仓",+ "holdingsHint": "每行一只,填写代码和权重。权重全部留空时按等权估算;自定义权重须全部填写且合计100%。仅支持A股股票,不自动剔除现金或其他资产。",+ "holdingsInvalid": "请检查代码、重复股票和权重;按上方格式填写。",+ "dateLabel": "分析截至日期(可选)",+ "dateHint": "用这一天的数据分析当前输入的持仓,不代表你当时实际持有。",+ "dateLatestHint": "留空使用最新可用数据",+ "publishedThrough": "数据更新至 {{date}}",+ "useLatest": "使用最新数据",+ "analyze": "诊断持仓",+ "analyzing": "正在分析持仓…",+ "retry": "重新检查",+ "serviceUnavailable": "服务暂不可用,请重试。",+ "analysisDate": "实际分析日 {{date}}",+ "included": "已纳入 {{included}}/{{requested}} 只股票",+ "equalWeight": "等权估算",+ "enteredWeights": "按输入权重分析",+ "riskDate": "风险估计日 {{date}}",+ "dateFallback": "请求日期 {{requested}};实际使用可用数据日 {{actual}}。",+ "partial": "部分股票未被纳入。下方模型结果只代表已覆盖部分,不能当作完整组合画像。",+ "coveredWeight": "已覆盖输入权重 {{weight}}。",+ "sourceLimitations": "数据源提示本次分析存在限制,结果仅供参考。",+ "styleTitle": "组合风格暴露",+ "styleAxis": "偏低 ← 模型参照0 → 偏高",+ "styleNote": "红色偏高、绿色偏低,距离中线越远倾向越明显。数值为标准化特征,不是仓位或涨跌预测;市场贝塔也不是原始回归β。缺失或覆盖不足显示为—。",+ "viewStockStyles": "查看个股风格",+ "heatmapTitle": "个股风格暴露热力图",+ "heatmapNote": "每行一只股票,每列一个因子,顺序与上图一致。红色偏高、绿色偏低;颜色在±2处饱和,数值不截断。它展示个股特点,不是该股风险贡献的分解。",+ "missingData": "数据缺失",+ "noStockStyle": "本次没有可用的个股风格数据。",+ "riskTitle": "风险归因:谁在影响组合波动",+ "mainContributor": "{{name}}在已返回股票中对组合波动的估计贡献最大。",+ "riskNote": "用于定位组合波动集中在哪里,优先复核相关仓位。仓位是资金占比;组合波动贡献占比=个股波动贡献÷组合总波动。条形按本图最大贡献缩放。",+ "diversifying": "分散波动",+ "addingVolatility": "推高波动",+ "zeroContribution": "贡献为零",+ "riskFootnote": "展示贡献最大的前5只股票。占比不是亏损概率,也不等于减仓后的风险降幅;可为负或超过100%,前5项不一定合计100%。负贡献表示分散作用。个股自身风险采用统一波动率假设。",+ "noData": "本次没有可用数据,不以零代替。",+ "colStock": "股票",+ "colAllocation": "仓位",+ "colContribution": "波动贡献",+ "colShare": "组合波动\n贡献占比",+ "colShareLabel": "组合波动贡献占比",+ "factors": {+ "BETA": "市场贝塔",+ "VALUE": "价值",+ "GROWTH": "成长",+ "QUALITY": "质量",+ "MOMENTUM_12M": "动量12月",+ "MOMENTUM_6M": "动量6月",+ "VOLATILITY": "波动率",+ "LIQUIDITY": "流动性",+ "SIZE": "市值",+ "LEVERAGE": "杠杆"+ }}}diff --git a/frontend/src/lib/shannon.ts b/frontend/src/lib/shannon.tsindex b66087430..d5bb689e3 100644--- a/frontend/src/lib/shannon.ts+++ b/frontend/src/lib/shannon.ts@@ -56,8 +56,8 @@ export function parseHoldings(text: string): ShannonHolding[] | null {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"],-};+/** Style factors in display order; each label is `shannon.factors.<id>` in every locale. */+export const styleFactors = [+ "BETA", "VALUE", "GROWTH", "QUALITY", "MOMENTUM_12M", "MOMENTUM_6M", "VOLATILITY", "LIQUIDITY", "SIZE", "LEVERAGE",+] as const;+export type StyleFactor = (typeof styleFactors)[number];