"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(runs): surface Portfolio Studio artifacts in run detail (#966)
Yufeng Hee19619f9cff9
diff --git a/agent/src/api/models.py b/agent/src/api/models.pyindex 81595a17a..18733a45e 100644--- a/agent/src/api/models.py+++ b/agent/src/api/models.py@@ -77,6 +77,12 @@ class RunResponse(BaseModel):artifacts_metrics_csv: Optional[List[Dict[str, Any]]] = Field(None, description="Full metrics rows")artifacts_trades_csv: Optional[List[Dict[str, Any]]] = Field(None, description="Full trade rows")validation: Optional[Dict[str, Any]] = Field(None, description="Statistical validation results")+ risk_xray: Optional[Dict[str, Any]] = Field(+ None, description="Portfolio risk x-ray payload when the run emitted one"+ )+ rebalance_notes: Optional[Dict[str, Any]] = Field(+ None, description="Per-rebalance weight-drift notes when the run emitted them"+ )run_directory: str = Field(..., description="Run directory path")run_stage: Optional[str] = Field(None, description="UI-facing run stage")diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex 39fca62b1..c3e064b73 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -154,6 +154,13 @@ def _build_response_from_run_dir(except (json.JSONDecodeError, OSError):pass+ risk_xray = _load_json_file(run_dir / "artifacts" / "risk_xray.json")+ if risk_xray is not None:+ response.risk_xray = risk_xray+ rebalance_notes = _load_json_file(run_dir / "artifacts" / "rebalance_notes.json")+ if rebalance_notes is not None:+ response.rebalance_notes = rebalance_notes+llm_usage_path = run_dir / "llm_usage.json"if llm_usage_path.exists():try:diff --git a/agent/tests/test_run_card.py b/agent/tests/test_run_card.pyindex 2fa0402bd..41fd553c9 100644--- a/agent/tests/test_run_card.py+++ b/agent/tests/test_run_card.py@@ -315,3 +315,40 @@ def test_options_backtest_writes_run_card(tmp_path: Path) -> None:assert card["data_sources"] == ["yfinance"]assert "greeks.csv" in {Path(artifact["path"]).name for artifact in card["artifacts"]}assert (tmp_path / "run_card.md").exists()+++def test_api_run_response_includes_portfolio_studio_artifacts(tmp_path: Path) -> None:+ import api_server++ run_dir = tmp_path / "run_studio"+ (run_dir / "artifacts").mkdir(parents=True)+ (run_dir / "state.json").write_text('{"status": "success"}\n', encoding="utf-8")+ risk_xray = {+ "concentration": {"hhi": 0.25, "effective_n": 4.0},+ "volatility": {"annualized_vol": 0.18},+ "drawdown": {"max_drawdown": -0.12},+ }+ rebalance_notes = {+ "rebalances": [{"date": "2026-01-05", "turnover": 0.4, "entries": [], "exits": [], "top_moves": []}],+ "summary": {"rebalance_count": 1, "turnover_total": 0.4, "turnover_mean": 0.4, "turnover_max": 0.4, "largest_rebalance_date": "2026-01-05"},+ }+ (run_dir / "artifacts" / "risk_xray.json").write_text(json.dumps(risk_xray), encoding="utf-8")+ (run_dir / "artifacts" / "rebalance_notes.json").write_text(json.dumps(rebalance_notes), encoding="utf-8")++ response = api_server._build_response_from_run_dir(run_dir, elapsed=0.0)++ assert response.risk_xray == risk_xray+ assert response.rebalance_notes == rebalance_notes+++def test_api_run_response_portfolio_studio_fields_none_when_absent(tmp_path: Path) -> None:+ import api_server++ run_dir = tmp_path / "run_plain"+ run_dir.mkdir()+ (run_dir / "state.json").write_text('{"status": "success"}\n', encoding="utf-8")++ response = api_server._build_response_from_run_dir(run_dir, elapsed=0.0)++ assert response.risk_xray is None+ assert response.rebalance_notes is Nonediff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 419c8e196..eeecef54d 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -536,6 +536,23 @@"goBack": "رجوع","chart": "الرسم البياني","trades": "التداولات",+ "studio": "استوديو المحفظة",+ "riskXray": "الأشعة السينية للمخاطر",+ "rebalanceNotes": "ملاحظات إعادة التوازن",+ "hhi": "HHI",+ "effectiveN": "N الفعّال",+ "annualizedVol": "التقلب السنوي",+ "maxDrawdown": "أقصى تراجع",+ "symbol": "الرمز",+ "weight": "الوزن",+ "rebalanceCount": "عدد مرات إعادة التوازن",+ "turnoverMean": "متوسط دوران",+ "turnoverMax": "أقصى دوران",+ "largestRebalance": "أكبر إعادة توازن",+ "date": "التاريخ",+ "turnover": "دوران",+ "entries": "دخول",+ "exits": "خروج","validation": "التحقّق","runCard": "بطاقة التشغيل","code": "الشفرة",@@ -543,7 +560,6 @@"downloadMetricsCsv": "تنزيل CSV للمقاييس","noChartData": "لا توجد بيانات رسم بياني","noChartDataDesc": "لم يحفظ هذا التشغيل بيانات الأسعار، لذلك لا يوجد مخطط. تظل المقاييس أدناه صالحة.",- "symbol": "الرمز","showOnly": "عرض فقط","addSymbol": "إضافة رمز","loadAll": "تحميل الكل",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 727ea17a6..b0342cbed 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -541,6 +541,23 @@"goBack": "Go back","chart": "Chart","trades": "Trades",+ "studio": "Portfolio Studio",+ "riskXray": "Risk X-Ray",+ "rebalanceNotes": "Rebalance Notes",+ "hhi": "HHI",+ "effectiveN": "Effective N",+ "annualizedVol": "Annualized Vol",+ "maxDrawdown": "Max Drawdown",+ "symbol": "Symbol",+ "weight": "Weight",+ "rebalanceCount": "Rebalances",+ "turnoverMean": "Avg Turnover",+ "turnoverMax": "Max Turnover",+ "largestRebalance": "Largest Rebalance",+ "date": "Date",+ "turnover": "Turnover",+ "entries": "Entries",+ "exits": "Exits","validation": "Validation","runCard": "Run Card","code": "Code",@@ -548,7 +565,6 @@"downloadMetricsCsv": "Download Metrics CSV","noChartData": "No chart data available","noChartDataDesc": "This run didn't save price data, so there's no chart. The metrics below are still valid.",- "symbol": "Symbol","showOnly": "Show only","addSymbol": "Add symbol","loadAll": "Load all",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex ba62b1695..de0932c57 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -536,6 +536,23 @@"goBack": "戻る","chart": "チャート","trades": "トレード",+ "studio": "ポートフォリオスタジオ",+ "riskXray": "リスクエックス線",+ "rebalanceNotes": "リバランスノート",+ "hhi": "HHI",+ "effectiveN": "実効N",+ "annualizedVol": "年率ボラティリティ",+ "maxDrawdown": "最大ドローダウン",+ "symbol": "シンボル",+ "weight": "ウェイト",+ "rebalanceCount": "リバランス回数",+ "turnoverMean": "平均ターンオーバー",+ "turnoverMax": "最大ターンオーバー",+ "largestRebalance": "最大リバランス",+ "date": "日付",+ "turnover": "ターンオーバー",+ "entries": "新規",+ "exits": "退出","validation": "検証","runCard": "ランカード","code": "コード",@@ -543,7 +560,6 @@"downloadMetricsCsv": "メトリクス CSV をダウンロード","noChartData": "チャートデータがありません","noChartDataDesc": "この実行では価格データが保存されなかったため、チャートは表示できません。下の指標は引き続き有効です。",- "symbol": "シンボル","showOnly": "のみ表示","addSymbol": "シンボルを追加","loadAll": "すべて読み込む",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 69c69956c..8e5afeff2 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -536,6 +536,23 @@"goBack": "뒤로","chart": "차트","trades": "거래",+ "studio": "포트폴리오 스튜디오",+ "riskXray": "리스크 엑스레이",+ "rebalanceNotes": "리밸런스 노트",+ "hhi": "HHI",+ "effectiveN": "유효 N",+ "annualizedVol": "연율 변동성",+ "maxDrawdown": "최대 낙폭",+ "symbol": "심볼",+ "weight": "비중",+ "rebalanceCount": "리밸런스 횟수",+ "turnoverMean": "평균 회전율",+ "turnoverMax": "최대 회전율",+ "largestRebalance": "최대 리밸런스",+ "date": "날짜",+ "turnover": "회전율",+ "entries": "신규 편입",+ "exits": "편출","validation": "검증","runCard": "런 카드","code": "코드",@@ -543,7 +560,6 @@"downloadMetricsCsv": "지표 CSV 다운로드","noChartData": "차트 데이터가 없습니다","noChartDataDesc": "이 실행에서는 가격 데이터가 저장되지 않아 차트를 표시할 수 없습니다. 아래 지표는 여전히 유효합니다.",- "symbol": "심볼","showOnly": "만 표시","addSymbol": "심볼 추가","loadAll": "전체 로드",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex c00cdd251..485a6fb1c 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -536,6 +536,23 @@"goBack": "返回","chart": "图表","trades": "交易",+ "studio": "组合工作室",+ "riskXray": "风险透视",+ "rebalanceNotes": "调仓笔记",+ "hhi": "HHI 集中度",+ "effectiveN": "有效持仓数",+ "annualizedVol": "年化波动",+ "maxDrawdown": "最大回撤",+ "symbol": "标的",+ "weight": "权重",+ "rebalanceCount": "调仓次数",+ "turnoverMean": "平均换手",+ "turnoverMax": "最大换手",+ "largestRebalance": "最大一次调仓",+ "date": "日期",+ "turnover": "换手率",+ "entries": "新进",+ "exits": "退出","validation": "验证","runCard": "运行卡片","code": "代码",@@ -543,7 +560,6 @@"downloadMetricsCsv": "下载指标 CSV","noChartData": "暂无图表数据","noChartDataDesc": "这次运行没有保存价格数据,所以没有图表;下面的指标依然有效。",- "symbol": "标的","showOnly": "仅显示","addSymbol": "添加标的","loadAll": "加载全部",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 8dd62c6a8..69c412695 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -555,6 +555,42 @@ export interface ValidationData {};}+export interface RiskXRayPayload {+ inputs?: {+ symbols?: string[];+ weights?: Record<string, number>;+ aligned_days?: number;+ return_observations?: number;+ first_date?: string;+ last_date?: string;+ };+ concentration?: { hhi?: number; effective_n?: number; top_weight?: number };+ volatility?: { annualized_vol?: number };+ drawdown?: { max_drawdown?: number };+ tail_risk?: Record<string, unknown>;+ diversification?: Record<string, unknown>;+ correlation?: Record<string, unknown>;+ skipped?: string[];+ warnings?: string[];+}++export interface RebalanceNotesPayload {+ rebalances?: Array<{+ date: string;+ turnover: number;+ entries?: Array<{ code: string; to: number }>;+ exits?: Array<{ code: string; from: number }>;+ top_moves?: Array<{ code: string; from: number; to: number; delta: number }>;+ }>;+ summary?: {+ rebalance_count: number;+ turnover_total: number;+ turnover_mean: number;+ turnover_max: number;+ largest_rebalance_date?: string | null;+ };+}+export interface RunData {status: string;run_id: string;@@ -567,6 +603,8 @@ export interface RunData {metrics?: BacktestMetrics;artifacts?: ArtifactInfo[];run_card?: RunCard;+ risk_xray?: RiskXRayPayload;+ rebalance_notes?: RebalanceNotesPayload;validation?: ValidationData;chart_symbols?: string[];diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex 33b10b9b5..050cf1010 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -14,6 +14,7 @@ import {Download,FileCheck2,Fingerprint,+ Gauge,List,Loader2,ShieldCheck,@@ -22,7 +23,7 @@ import {} from "lucide-react";import { toast } from "sonner";import { cn } from "@/lib/utils";-import { api, type BacktestMetrics, type RunCard, type RunData, type ValidationData } from "@/lib/api";+import { api, type BacktestMetrics, type RebalanceNotesPayload, type RiskXRayPayload, type RunCard, type RunData, type ValidationData } from "@/lib/api";import ReactMarkdown from "react-markdown";import rehypeHighlight from "rehype-highlight";import { CandlestickChart } from "@/components/charts/CandlestickChart";@@ -34,7 +35,7 @@ import { ErrorBoundary } from "@/components/common/ErrorBoundary";const rehypePlugins = [rehypeHighlight];-type Tab = "chart" | "trades" | "runCard" | "code" | "validation";+type Tab = "chart" | "trades" | "runCard" | "code" | "validation" | "studio";type ChartPayload = Pick<RunData, "price_series" | "indicator_series" | "trade_markers">;type ChartCache = Record<string, ChartPayload>;type ChartLoadProgress = { done: number; total: number };@@ -115,9 +116,11 @@ export function RunDetail() {const hasValidation = !!run?.validation;const hasRunCard = !!run?.run_card;+ const hasStudio = !!run?.risk_xray || !!run?.rebalance_notes;const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [{ id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },{ id: "trades", label: i18n.t("runDetail.trades"), icon: List },+ { id: "studio", label: i18n.t("runDetail.studio"), icon: Gauge, hidden: !hasStudio },{ id: "validation", label: i18n.t("runDetail.validation"), icon: ShieldCheck, hidden: !hasValidation },{ id: "runCard", label: i18n.t("runDetail.runCard"), icon: FileCheck2, hidden: !hasRunCard },{ id: "code", label: i18n.t("runDetail.code"), icon: Code2 },@@ -382,6 +385,9 @@ export function RunDetail() {)}{tab === "trades" && <TradesTab run={run} />}{tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}+ {tab === "studio" && hasStudio && (+ <StudioTab xray={run.risk_xray} notes={run.rebalance_notes} />+ )}{tab === "runCard" && run.run_card && <RunCardTab card={run.run_card} />}{tab === "code" && <CodeTab code={code} />}</ErrorBoundary>@@ -477,6 +483,94 @@ function RunCardTab({ card }: { card: RunCard }) {);}+function fmtPct(v: number | undefined, digits = 1): string {+ if (v === undefined || Number.isNaN(v)) return "-";+ return `${(v * 100).toFixed(digits)}%`;+}++function StudioTab({ xray, notes }: { xray?: RiskXRayPayload; notes?: RebalanceNotesPayload }) {+ const concentration = xray?.concentration || {};+ const volatility = xray?.volatility || {};+ const drawdown = xray?.drawdown || {};+ const weights = xray?.inputs?.weights || {};+ const weightEntries = Object.entries(weights).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));+ const summary = notes?.summary;+ const rebalances = notes?.rebalances || [];++ return (+ <div className="space-y-4">+ {xray && (+ <RunCardPanel title={i18n.t("runDetail.riskXray")} icon={Gauge}>+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">+ <RunCardStat label={i18n.t("runDetail.hhi")} value={concentration.hhi !== undefined ? concentration.hhi.toFixed(3) : "-"} />+ <RunCardStat label={i18n.t("runDetail.effectiveN")} value={concentration.effective_n !== undefined ? concentration.effective_n.toFixed(1) : "-"} />+ <RunCardStat label={i18n.t("runDetail.annualizedVol")} value={fmtPct(volatility.annualized_vol)} />+ <RunCardStat label={i18n.t("runDetail.maxDrawdown")} value={fmtPct(drawdown.max_drawdown)} />+ </div>+ {weightEntries.length > 0 && (+ <div className="mt-3 overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b bg-muted/40 text-left text-[11px] uppercase tracking-wide text-muted-foreground [&_th]:font-medium">+ <th className="py-2 ps-4 pr-4">{i18n.t("runDetail.symbol")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.weight")}</th>+ </tr>+ </thead>+ <tbody>+ {weightEntries.map(([sym, w]) => (+ <tr key={sym} className="border-b last:border-0 hover:bg-muted/40">+ <td className="py-1.5 ps-4 pr-4 font-mono text-xs">{sym}</td>+ <td className="py-1.5 pr-4 font-mono tabular-nums">{fmtPct(w)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ {(xray.warnings || []).length > 0 && (+ <p className="mt-2 text-xs text-warning">{(xray.warnings || []).join("; ")}</p>+ )}+ </RunCardPanel>+ )}++ {notes && summary && (+ <RunCardPanel title={i18n.t("runDetail.rebalanceNotes")} icon={Gauge}>+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">+ <RunCardStat label={i18n.t("runDetail.rebalanceCount")} value={String(summary.rebalance_count)} />+ <RunCardStat label={i18n.t("runDetail.turnoverMean")} value={fmtPct(summary.turnover_mean)} />+ <RunCardStat label={i18n.t("runDetail.turnoverMax")} value={fmtPct(summary.turnover_max)} />+ <RunCardStat label={i18n.t("runDetail.largestRebalance")} value={summary.largest_rebalance_date || "-"} />+ </div>+ {rebalances.length > 0 && (+ <div className="mt-3 overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b bg-muted/40 text-left text-[11px] uppercase tracking-wide text-muted-foreground [&_th]:font-medium">+ <th className="py-2 ps-4 pr-4">{i18n.t("runDetail.date")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.turnover")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.entries")}</th>+ <th className="py-2">{i18n.t("runDetail.exits")}</th>+ </tr>+ </thead>+ <tbody>+ {rebalances.map((r) => (+ <tr key={r.date} className="border-b last:border-0 hover:bg-muted/40">+ <td className="py-1.5 ps-4 pr-4 font-mono text-xs">{r.date}</td>+ <td className="py-1.5 pr-4 font-mono tabular-nums">{fmtPct(r.turnover)}</td>+ <td className="py-1.5 pr-4 text-xs">{(r.entries || []).map((e) => e.code).join(", ") || "-"}</td>+ <td className="py-1.5 text-xs">{(r.exits || []).map((e) => e.code).join(", ") || "-"}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </RunCardPanel>+ )}+ </div>+ );+}+function RunCardStat({ label, value, tone = "normal" }: { label: string; value: string; tone?: "normal" | "warning" }) {return (<div className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">diff --git a/frontend/src/pages/__tests__/RunDetail.test.tsx b/frontend/src/pages/__tests__/RunDetail.test.tsxindex 082a4c1d9..090f6e8b7 100644--- a/frontend/src/pages/__tests__/RunDetail.test.tsx+++ b/frontend/src/pages/__tests__/RunDetail.test.tsx@@ -169,3 +169,55 @@ describe("RunDetail page", () => {expect(screen.getByText("artifacts/result.json")).toHaveClass("ps-4");});});++ it("renders the Portfolio Studio tab from risk_xray and rebalance_notes payloads", async () => {+ apiMock.getRun.mockResolvedValue({+ status: "success",+ run_id: "studio-run",+ prompt: "Studio run",+ risk_xray: {+ inputs: { symbols: ["AAPL", "MSFT"], weights: { AAPL: 0.6, MSFT: 0.4 }, aligned_days: 60 },+ concentration: { hhi: 0.52, effective_n: 1.9 },+ volatility: { annualized_vol: 0.22 },+ drawdown: { max_drawdown: -0.11 },+ },+ rebalance_notes: {+ rebalances: [+ { date: "2026-02-02", turnover: 0.35, entries: [{ code: "NVDA", to: 0.6 }], exits: [], top_moves: [] },+ ],+ summary: { rebalance_count: 1, turnover_total: 0.35, turnover_mean: 0.35, turnover_max: 0.35, largest_rebalance_date: "2026-02-02" },+ },+ });+ apiMock.getRunCode.mockResolvedValue({});++ renderRunDetail("/runs/studio-run");++ await screen.findByText("Studio run");+ fireEvent.click(screen.getByRole("tab", { name: "Portfolio Studio" }));++ expect(await screen.findByText("Risk X-Ray")).toBeInTheDocument();+ expect(screen.getByText("0.520")).toBeInTheDocument();+ expect(screen.getByText("22.0%")).toBeInTheDocument();+ expect(screen.getByText("AAPL")).toBeInTheDocument();+ expect(screen.getByText("NVDA")).toBeInTheDocument();+ expect(screen.getByText("Rebalance Notes")).toBeInTheDocument();+ // the date shows up twice: once in the rebalances table, once in the summary card+ expect(screen.getAllByText("2026-02-02")).toHaveLength(2);+ // 35.0% shows up three times: the table row plus the mean and max summary cards+ expect(screen.getAllByText("35.0%")).toHaveLength(3);+ });++ it("hides the Portfolio Studio tab when the payloads are absent", async () => {+ apiMock.getRun.mockResolvedValue({+ status: "success",+ run_id: "plain-run",+ prompt: "Plain run",+ trade_log: [],+ });+ apiMock.getRunCode.mockResolvedValue({});++ renderRunDetail("/runs/plain-run");++ await screen.findByText("Plain run");+ expect(screen.queryByRole("tab", { name: "Portfolio Studio" })).not.toBeInTheDocument();+ });