"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(frontend): add tearsheet tab with monthly returns heatmap and top-N drawdowns
shadowinlife3970dc26e5de
diff --git a/frontend/src/components/charts/AnnualReturnsChart.tsx b/frontend/src/components/charts/AnnualReturnsChart.tsxnew file mode 100644index 000000000..92277c4a0--- /dev/null+++ b/frontend/src/components/charts/AnnualReturnsChart.tsx@@ -0,0 +1,102 @@+import { useEffect, useRef } from "react";+import i18n from "@/i18n";+import type { AnnualReturn } from "@/lib/tearsheet";+import { getChartTheme } from "@/lib/chart-theme";+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { useThemeDark } from "@/lib/theme-store";++interface Props {+ data: AnnualReturn[];+ height?: number;+}++export function AnnualReturnsChart({ data, height = 260 }: Props) {+ const ref = useRef<HTMLDivElement>(null);+ const dark = useThemeDark();++ useEffect(() => {+ if (!ref.current || data.length === 0) return;+ const t = getChartTheme();+ const chart = echarts.init(ref.current);+ chart.group = CHART_GROUP;+ connectCharts();++ const seriesName = i18n.t("runDetail.annualReturns");++ chart.setOption({+ backgroundColor: "transparent",+ tooltip: {+ trigger: "axis",+ axisPointer: { type: "shadow" },+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 11 },+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ formatter: (params: any) => {+ if (!Array.isArray(params) || !params.length) return "";+ const p = params[0];+ const v = Number(p.value);+ const pct = `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;+ return `<b>${p.axisValue}</b><br/>${p.marker} ${p.seriesName}: <b>${pct}</b>`;+ },+ },+ grid: { left: 8, right: 8, top: 28, bottom: 8, containLabel: true },+ xAxis: {+ type: "category",+ data: data.map((d) => String(d.year)),+ axisLine: { lineStyle: { color: t.axisColor } },+ axisLabel: { color: t.textColor, fontSize: 10 },+ },+ yAxis: {+ type: "value",+ splitLine: { lineStyle: { color: t.gridColor } },+ axisLabel: { color: t.textColor, fontSize: 10, formatter: "{value}%" },+ },+ series: [+ {+ name: seriesName,+ type: "bar",+ data: data.map((d) => ({+ value: +(d.ret * 100).toFixed(2),+ itemStyle: { color: d.ret >= 0 ? t.upColor : t.downColor },+ label: {+ show: true,+ position: d.ret >= 0 ? "top" : "bottom",+ formatter: `${d.ret > 0 ? "+" : ""}${(d.ret * 100).toFixed(1)}%`,+ fontSize: 10,+ color: t.textColor,+ },+ })),+ barMaxWidth: 36,+ markLine: {+ silent: true,+ symbol: "none",+ data: [{ yAxis: 0 }],+ lineStyle: { color: t.axisColor, width: 1 },+ label: { show: false },+ },+ },+ ],+ });++ let resizeFrame: number | null = null;+ const ro = new ResizeObserver(() => {+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ resizeFrame = requestAnimationFrame(() => {+ resizeFrame = null;+ chart.resize();+ });+ });+ ro.observe(ref.current!);+ return () => {+ ro.disconnect();+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ chart.dispose();+ };+ }, [data, dark]);++ if (data.length === 0) {+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.noTearsheetData")}</div>;+ }+ return <div ref={ref} style={{ height }} />;+}diff --git a/frontend/src/components/charts/EquityChart.tsx b/frontend/src/components/charts/EquityChart.tsxindex d5dfa2586..4cf5a5bc8 100644--- a/frontend/src/components/charts/EquityChart.tsx+++ b/frontend/src/components/charts/EquityChart.tsx@@ -5,13 +5,15 @@ import { getChartTheme } from "@/lib/chart-theme";import { abbreviateNum } from "@/lib/formatters";import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";import { useThemeDark } from "@/lib/theme-store";+import type { DrawdownZone } from "@/lib/tearsheet";interface Props {data: EquityPoint[];height?: number;+ drawdownZones?: DrawdownZone[];}-export function EquityChart({ data, height = 300 }: Props) {+export function EquityChart({ data, height = 300, drawdownZones }: Props) {const ref = useRef<HTMLDivElement>(null);const dark = useThemeDark();@@ -21,6 +23,7 @@ export function EquityChart({ data, height = 300 }: Props) {const chart = echarts.init(ref.current);chart.group = CHART_GROUP;connectCharts();+ const zones = drawdownZones ?? [];const dates = data.map((d) => d.time);const equity = data.map((d) => Number(d.equity));@@ -86,6 +89,19 @@ export function EquityChart({ data, height = 300 }: Props) {areaStyle: {color: { type: "linear", x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: t.infoColor + "40" }, { offset: 1, color: t.infoColor + "00" }] },},+ ...(zones.length > 0 ? {+ markArea: {+ silent: true,+ data: zones.map((zone) => [+ {+ xAxis: zone.startTime,+ itemStyle: { color: t.downColor + "14" },+ label: { show: true, position: "insideTopLeft", formatter: `#${zone.rank}`, fontSize: 9, color: t.downColor },+ },+ { xAxis: zone.endTime },+ ]),+ },+ } : {}),},{name: "Drawdown%", type: "line", xAxisIndex: 1, yAxisIndex: 1,@@ -115,7 +131,7 @@ export function EquityChart({ data, height = 300 }: Props) {if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);chart.dispose();};- }, [data, dark]);+ }, [data, drawdownZones, dark]);if (data.length === 0) {return <div className="text-muted-foreground text-sm p-4">{i18n.t("charts.noEquityData")}</div>;diff --git a/frontend/src/components/charts/MonthlyReturnsHeatmap.tsx b/frontend/src/components/charts/MonthlyReturnsHeatmap.tsxnew file mode 100644index 000000000..bc90f47b8--- /dev/null+++ b/frontend/src/components/charts/MonthlyReturnsHeatmap.tsx@@ -0,0 +1,140 @@+import { useEffect, useRef } from "react";+import i18n from "@/i18n";+import type { AnnualReturn, MonthlyReturn } from "@/lib/tearsheet";+import { getChartTheme } from "@/lib/chart-theme";+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { useThemeDark } from "@/lib/theme-store";++interface Props {+ data: MonthlyReturn[];+ annual: AnnualReturn[];+ height?: number;+}++function fmtSignedPct(v: number, digits = 1): string {+ return `${v > 0 ? "+" : ""}${(v * 100).toFixed(digits)}%`;+}++export function MonthlyReturnsHeatmap({ data, annual, height = 300 }: Props) {+ const ref = useRef<HTMLDivElement>(null);+ const dark = useThemeDark();++ useEffect(() => {+ if (!ref.current || data.length === 0) return;+ const t = getChartTheme();+ const chart = echarts.init(ref.current);+ chart.group = CHART_GROUP;+ connectCharts();++ const monthFmt = new Intl.DateTimeFormat(i18n.language || "en", { month: "short" });+ const monthLabels = Array.from({ length: 12 }, (_, i) => monthFmt.format(new Date(2024, i, 15)));+ const xLabels = [...monthLabels, i18n.t("runDetail.tearsheetYear")];++ const years = [...new Set(data.map((d) => d.year))].sort((a, b) => a - b);+ const yLabels = years.map(String);++ const cells: Array<[number, number, number]> = [];+ for (const m of data) {+ if (m.ret === null || !Number.isFinite(m.ret)) continue;+ const yIdx = years.indexOf(m.year);+ if (yIdx < 0) continue;+ cells.push([m.month - 1, yIdx, m.ret]);+ }+ for (const a of annual) {+ if (!Number.isFinite(a.ret)) continue;+ const yIdx = years.indexOf(a.year);+ if (yIdx < 0) continue;+ cells.push([12, yIdx, a.ret]);+ }++ let maxAbs = 0;+ for (const [, , v] of cells) maxAbs = Math.max(maxAbs, Math.abs(v));+ if (maxAbs === 0) maxAbs = 1;++ const returnLabel = i18n.t("runDetail.returnPct");++ chart.setOption({+ backgroundColor: "transparent",+ tooltip: {+ trigger: "item",+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 11 },+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ formatter: (params: any) => {+ const value = params?.value as [number, number, number] | undefined;+ if (!Array.isArray(value) || value.length < 3) return "";+ const [xIdx, yIdx, v] = value;+ const year = yLabels[yIdx] ?? "";+ const head = xIdx < 12 ? `${year}-${String(xIdx + 1).padStart(2, "0")}` : year;+ return `<b>${head}</b><br/>${returnLabel}: <b>${fmtSignedPct(v, 2)}</b>`;+ },+ },+ grid: { left: 8, right: 8, top: 8, bottom: 8, containLabel: true },+ xAxis: {+ type: "category",+ data: xLabels,+ axisLine: { lineStyle: { color: t.axisColor } },+ axisTick: { show: false },+ axisLabel: { color: t.textColor, fontSize: 10 },+ splitArea: { show: false },+ },+ yAxis: {+ type: "category",+ data: yLabels,+ axisLine: { lineStyle: { color: t.axisColor } },+ axisTick: { show: false },+ axisLabel: { color: t.textColor, fontSize: 10 },+ splitArea: { show: false },+ },+ visualMap: {+ show: false,+ type: "continuous",+ min: -maxAbs,+ max: maxAbs,+ inRange: { color: [t.downColor, t.tooltipBorder || "#9ca3af", t.upColor] },+ },+ series: [+ {+ name: returnLabel,+ type: "heatmap",+ data: cells.map(([x, y, v]) => {+ const saturated = Math.abs(v) > 0.55 * maxAbs;+ return {+ value: [x, y, v],+ label: {+ show: true,+ formatter: fmtSignedPct(v),+ fontSize: 10,+ color: saturated ? "#ffffff" : t.textColor,+ ...(saturated ? { textShadowColor: "rgba(0,0,0,0.45)", textShadowBlur: 2 } : {}),+ },+ };+ }),+ itemStyle: { borderColor: t.gridColor, borderWidth: 1 },+ emphasis: { itemStyle: { borderColor: t.axisColor, borderWidth: 1 } },+ },+ ],+ });++ let resizeFrame: number | null = null;+ const ro = new ResizeObserver(() => {+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ resizeFrame = requestAnimationFrame(() => {+ resizeFrame = null;+ chart.resize();+ });+ });+ ro.observe(ref.current!);+ return () => {+ ro.disconnect();+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ chart.dispose();+ };+ }, [data, annual, dark]);++ if (data.length === 0) {+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.noTearsheetData")}</div>;+ }+ return <div ref={ref} style={{ height }} />;+}diff --git a/frontend/src/components/charts/TopDrawdownsPanel.tsx b/frontend/src/components/charts/TopDrawdownsPanel.tsxnew file mode 100644index 000000000..4b9be0870--- /dev/null+++ b/frontend/src/components/charts/TopDrawdownsPanel.tsx@@ -0,0 +1,46 @@+import i18n from "@/i18n";+import type { DrawdownEpisode } from "@/lib/tearsheet";++interface Props {+ episodes: DrawdownEpisode[];+}++export function TopDrawdownsPanel({ episodes }: Props) {+ if (episodes.length === 0) {+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("runDetail.noTearsheetData")}</div>;+ }+ return (+ <div className="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.ddRank")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.ddDepth")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.ddPeak")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.ddTrough")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.ddRecovery")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.ddPeakToTrough")}</th>+ <th className="py-2">{i18n.t("runDetail.ddTroughToRecovery")}</th>+ </tr>+ </thead>+ <tbody>+ {episodes.map((ep, i) => (+ <tr key={`${ep.peakTime}-${i}`} className="border-b last:border-0 hover:bg-muted/40">+ <td className="py-2 ps-4 pr-4 font-mono tabular-nums text-muted-foreground">{i + 1}</td>+ <td className="py-2 pr-4 font-mono tabular-nums text-danger">{(ep.depth * 100).toFixed(2)}%</td>+ <td className="py-2 pr-4 font-mono text-xs">{ep.peakTime}</td>+ <td className="py-2 pr-4 font-mono text-xs">{ep.troughTime}</td>+ <td className="py-2 pr-4 font-mono text-xs">{ep.recoveryTime ?? i18n.t("runDetail.ddNotRecovered")}</td>+ <td className="py-2 pr-4 font-mono tabular-nums">+ {ep.peakToTroughDays != null ? i18n.t("runDetail.ddDays", { count: ep.peakToTroughDays }) : "—"}+ </td>+ <td className="py-2 font-mono tabular-nums">+ {ep.troughToRecoveryDays != null ? i18n.t("runDetail.ddDays", { count: ep.troughToRecoveryDays }) : "—"}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex fe2ee23fd..6216837f5 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -614,7 +614,22 @@"sideSell": "بيع","copyCode": "نسخ","codeCopied": "تم نسخ الكود",- "codeLines": "{{count}} سطر"+ "codeLines": "{{count}} سطر",+ "tearsheet": "تقرير الأداء",+ "monthlyReturns": "العوائد الشهرية",+ "annualReturns": "العوائد السنوية",+ "topDrawdowns": "أبرز التراجعات",+ "tearsheetYear": "السنة",+ "noTearsheetData": "بيانات حقوق الملكية غير كافية لإعداد تقرير الأداء.",+ "ddRank": "#",+ "ddDepth": "العمق",+ "ddPeak": "القمة",+ "ddTrough": "القاع",+ "ddRecovery": "التعافي",+ "ddPeakToTrough": "القمة إلى القاع",+ "ddTroughToRecovery": "القاع إلى التعافي",+ "ddNotRecovered": "لم يتعافَ",+ "ddDays": "{{count}} يوم"},"compare": {"title": "مقارنة الاستراتيجيات",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex bb60a22c8..242abdc18 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -619,7 +619,22 @@"sideSell": "Sell","copyCode": "Copy","codeCopied": "Code copied",- "codeLines": "{{count}} lines"+ "codeLines": "{{count}} lines",+ "tearsheet": "Tearsheet",+ "monthlyReturns": "Monthly Returns",+ "annualReturns": "Annual Returns",+ "topDrawdowns": "Top Drawdowns",+ "tearsheetYear": "Year",+ "noTearsheetData": "Not enough equity data for a tearsheet.",+ "ddRank": "#",+ "ddDepth": "Depth",+ "ddPeak": "Peak",+ "ddTrough": "Trough",+ "ddRecovery": "Recovery",+ "ddPeakToTrough": "Peak→Trough",+ "ddTroughToRecovery": "Trough→Rec.",+ "ddNotRecovered": "Not recovered",+ "ddDays": "{{count}} d"},"compare": {"title": "Strategy Comparison",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex a974b7870..99e05d993 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -619,7 +619,22 @@"sideSell": "Venta","copyCode": "Copiar","codeCopied": "Código copiado",- "codeLines": "{{count}} líneas"+ "codeLines": "{{count}} líneas",+ "tearsheet": "Informe de rendimiento",+ "monthlyReturns": "Rentabilidad mensual",+ "annualReturns": "Rentabilidad anual",+ "topDrawdowns": "Principales drawdowns",+ "tearsheetYear": "Año",+ "noTearsheetData": "No hay datos de equity suficientes para generar el informe de rendimiento.",+ "ddRank": "#",+ "ddDepth": "Profundidad",+ "ddPeak": "Pico",+ "ddTrough": "Valle",+ "ddRecovery": "Recuperación",+ "ddPeakToTrough": "Pico→Valle",+ "ddTroughToRecovery": "Valle→Rec.",+ "ddNotRecovered": "No recuperado",+ "ddDays": "{{count}} d"},"compare": {"title": "Comparación de estrategias",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 531999099..067aa44f1 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -614,7 +614,22 @@"sideSell": "売り","copyCode": "コピー","codeCopied": "コードをコピーしました",- "codeLines": "{{count}} 行"+ "codeLines": "{{count}} 行",+ "tearsheet": "パフォーマンスレポート",+ "monthlyReturns": "月次リターン",+ "annualReturns": "年次リターン",+ "topDrawdowns": "主要ドローダウン",+ "tearsheetYear": "年間",+ "noTearsheetData": "パフォーマンスレポートを作成するための資産データが不足しています。",+ "ddRank": "#",+ "ddDepth": "下落幅",+ "ddPeak": "高値",+ "ddTrough": "安値",+ "ddRecovery": "回復",+ "ddPeakToTrough": "高値→安値",+ "ddTroughToRecovery": "安値→回復",+ "ddNotRecovered": "未回復",+ "ddDays": "{{count}}日"},"compare": {"title": "戦略比較",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex d4f616167..3f4ccaec1 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -614,7 +614,22 @@"sideSell": "매도","copyCode": "복사","codeCopied": "코드가 복사되었습니다",- "codeLines": "{{count}}줄"+ "codeLines": "{{count}}줄",+ "tearsheet": "성과 보고서",+ "monthlyReturns": "월별 수익률",+ "annualReturns": "연도별 수익률",+ "topDrawdowns": "주요 드로다운",+ "tearsheetYear": "연간",+ "noTearsheetData": "성과 보고서를 생성하기에 자산 데이터가 부족합니다.",+ "ddRank": "#",+ "ddDepth": "낙폭",+ "ddPeak": "고점",+ "ddTrough": "저점",+ "ddRecovery": "회복",+ "ddPeakToTrough": "고점→저점",+ "ddTroughToRecovery": "저점→회복",+ "ddNotRecovered": "미회복",+ "ddDays": "{{count}}일"},"compare": {"title": "전략 비교",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 607e45955..d03ebcca9 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -614,7 +614,22 @@"sideSell": "卖出","copyCode": "复制","codeCopied": "代码已复制",- "codeLines": "{{count}} 行"+ "codeLines": "{{count}} 行",+ "tearsheet": "绩效报告",+ "monthlyReturns": "月度收益",+ "annualReturns": "年度收益",+ "topDrawdowns": "主要回撤",+ "tearsheetYear": "全年",+ "noTearsheetData": "净值数据不足,无法生成绩效报告。",+ "ddRank": "#",+ "ddDepth": "回撤深度",+ "ddPeak": "高点",+ "ddTrough": "低点",+ "ddRecovery": "恢复",+ "ddPeakToTrough": "高点→低点",+ "ddTroughToRecovery": "低点→恢复",+ "ddNotRecovered": "未恢复",+ "ddDays": "{{count}} 天"},"compare": {"title": "策略对比",diff --git a/frontend/src/lib/__tests__/tearsheet.test.ts b/frontend/src/lib/__tests__/tearsheet.test.tsnew file mode 100644index 000000000..5598214eb--- /dev/null+++ b/frontend/src/lib/__tests__/tearsheet.test.ts@@ -0,0 +1,254 @@+import {+ normalizeEquitySeries,+ computeMonthlyReturns,+ computeAnnualReturns,+ computeTopDrawdowns,+ toDrawdownZones,+ type NormalizedEquityPoint,+} from "../tearsheet";++function pt(time: string, equity: number, drawdown = 0): NormalizedEquityPoint {+ return { time, equity, drawdown };+}++describe("normalizeEquitySeries", () => {+ it("parses artifacts_equity_csv string rows into numbers", () => {+ const rows = [+ { timestamp: "2024-01-01 00:00:00", equity: "100.5", drawdown: "-0.01" },+ { timestamp: "2024-01-02 00:00:00", equity: "102", drawdown: "0" },+ ];+ const out = normalizeEquitySeries(rows);+ expect(out).toHaveLength(2);+ expect(out[0]).toEqual({ time: "2024-01-01 00:00:00", equity: 100.5, drawdown: -0.01 });+ expect(out[1]).toEqual({ time: "2024-01-02 00:00:00", equity: 102, drawdown: 0 });+ });++ it("accepts EquityPoint[] input", () => {+ const out = normalizeEquitySeries([+ { time: "2024-01-01", equity: 100, drawdown: 0 },+ { time: "2024-01-02", equity: "101.5", drawdown: "-0.02" },+ ]);+ expect(out).toHaveLength(2);+ expect(out[1].equity).toBe(101.5);+ expect(out[1].drawdown).toBe(-0.02);+ });++ it("drops rows with non-finite equity or missing time", () => {+ const rows = [+ { timestamp: "2024-01-01", equity: "100", drawdown: "0" },+ { timestamp: "2024-01-02", equity: "abc", drawdown: "0" },+ { timestamp: "2024-01-03", equity: "Infinity", drawdown: "0" },+ { timestamp: "", equity: "103", drawdown: "0" },+ { equity: "104", drawdown: "0" },+ { timestamp: "2024-01-05", equity: "105", drawdown: "0" },+ ];+ const out = normalizeEquitySeries(rows);+ expect(out.map((p) => p.time)).toEqual(["2024-01-01", "2024-01-05"]);+ });++ it("returns [] for empty/undefined/null input", () => {+ expect(normalizeEquitySeries([])).toEqual([]);+ expect(normalizeEquitySeries(undefined)).toEqual([]);+ expect(normalizeEquitySeries(null)).toEqual([]);+ });++ it("defensively sorts when first row's date is after last row's date", () => {+ const out = normalizeEquitySeries([+ { timestamp: "2024-01-03", equity: "103", drawdown: "0" },+ { timestamp: "2024-01-01", equity: "101", drawdown: "0" },+ { timestamp: "2024-01-02", equity: "102", drawdown: "0" },+ ]);+ expect(out.map((p) => p.time)).toEqual(["2024-01-01", "2024-01-02", "2024-01-03"]);+ });++ it("preserves input order when already chronological", () => {+ const out = normalizeEquitySeries([+ { timestamp: "2024-01-01", equity: "1", drawdown: "0" },+ { timestamp: "2024-01-02", equity: "2", drawdown: "0" },+ ]);+ expect(out.map((p) => p.equity)).toEqual([1, 2]);+ });+});++describe("computeMonthlyReturns", () => {+ it("computes a hand-computed 3-month series (first month base = first observation)", () => {+ const points = [+ pt("2024-01-15", 100),+ pt("2024-01-31", 110),+ pt("2024-02-29", 121),+ pt("2024-03-31", 114.95),+ ];+ const out = computeMonthlyReturns(points);+ expect(out).toHaveLength(3);+ // Jan: 110 / 100 - 1 = +10% (base is the series' first observation)+ expect(out[0]).toMatchObject({ year: 2024, month: 1 });+ expect(out[0].ret).toBeCloseTo(0.1, 10);+ // Feb: 121 / 110 - 1 = +10%+ expect(out[1].ret).toBeCloseTo(0.1, 10);+ // Mar: 114.95 / 121 - 1 = -5%+ expect(out[2].ret).toBeCloseTo(-0.05, 10);+ });++ it("emits null for a gap month between populated months and does not pad outside", () => {+ const points = [+ pt("2023-12-31", 100),+ pt("2024-01-31", 110),+ // Feb 2024 missing+ pt("2024-03-31", 120),+ ];+ const out = computeMonthlyReturns(points);+ // Dec-2023 .. Mar-2024 inclusive, no padding before/after+ expect(out.map((m) => `${m.year}-${m.month}`)).toEqual([+ "2023-12", "2024-1", "2024-2", "2024-3",+ ]);+ expect(out[0].ret).toBeCloseTo(0, 10); // 100 / first-obs 100 - 1+ expect(out[1].ret).toBeCloseTo(0.1, 10); // 110 / 100 - 1+ expect(out[2].ret).toBeNull(); // gap month+ expect(out[3].ret).toBeNull(); // prior calendar month has no data+ });++ it("emits null when base equity is <= 0", () => {+ const points = [+ pt("2024-01-15", 0),+ pt("2024-01-31", 10),+ pt("2024-02-28", 12),+ ];+ const out = computeMonthlyReturns(points);+ expect(out[0].ret).toBeNull(); // base = first observation = 0+ expect(out[1].ret).toBeCloseTo(0.2, 10); // 12 / 10 - 1+ });++ it("returns [] for empty input", () => {+ expect(computeMonthlyReturns([])).toEqual([]);+ });+});++describe("computeAnnualReturns", () => {+ it("computes a hand-computed 2-year series (first year base = first observation)", () => {+ const points = [+ pt("2023-06-01", 100),+ pt("2023-12-31", 120),+ pt("2024-12-31", 150),+ ];+ const out = computeAnnualReturns(points);+ expect(out).toHaveLength(2);+ expect(out[0]).toMatchObject({ year: 2023 });+ expect(out[0].ret).toBeCloseTo(0.2, 10); // 120 / first-obs 100 - 1+ expect(out[1]).toMatchObject({ year: 2024 });+ expect(out[1].ret).toBeCloseTo(0.25, 10); // 150 / 120 - 1+ });++ it("skips years whose prior calendar year has no data", () => {+ const points = [+ pt("2022-12-31", 100),+ // 2023 missing entirely+ pt("2024-12-31", 150),+ ];+ const out = computeAnnualReturns(points);+ expect(out).toHaveLength(1);+ expect(out[0]).toMatchObject({ year: 2022 });+ expect(out[0].ret).toBeCloseTo(0, 10);+ });++ it("returns [] for empty input", () => {+ expect(computeAnnualReturns([])).toEqual([]);+ });+});++describe("computeTopDrawdowns", () => {+ it("detects two known episodes sorted deepest first", () => {+ const points = [+ pt("2024-01-01", 100),+ pt("2024-01-02", 120),+ pt("2024-01-03", 90),+ pt("2024-01-04", 130),+ pt("2024-01-05", 100),+ pt("2024-01-06", 140),+ ];+ const out = computeTopDrawdowns(points, 5);+ expect(out).toHaveLength(2);+ // Deepest: peak 120 -> trough 90 = -25%+ expect(out[0].peakTime).toBe("2024-01-02");+ expect(out[0].troughTime).toBe("2024-01-03");+ expect(out[0].recoveryTime).toBe("2024-01-04");+ expect(out[0].depth).toBeCloseTo(-0.25, 10);+ expect(out[0].peakToTroughDays).toBe(1);+ expect(out[0].troughToRecoveryDays).toBe(1);+ // Second: peak 130 -> trough 100 = -23.08%+ expect(out[1].peakTime).toBe("2024-01-04");+ expect(out[1].troughTime).toBe("2024-01-05");+ expect(out[1].recoveryTime).toBe("2024-01-06");+ expect(out[1].depth).toBeCloseTo(100 / 130 - 1, 10);+ });++ it("leaves recoveryTime null for a final unrecovered episode", () => {+ const points = [pt("2024-01-01", 100), pt("2024-01-02", 80)];+ const out = computeTopDrawdowns(points, 5);+ expect(out).toHaveLength(1);+ expect(out[0].peakTime).toBe("2024-01-01");+ expect(out[0].troughTime).toBe("2024-01-02");+ expect(out[0].recoveryTime).toBeNull();+ expect(out[0].depth).toBeCloseTo(-0.2, 10);+ expect(out[0].peakToTroughDays).toBe(1);+ expect(out[0].troughToRecoveryDays).toBeNull();+ });++ it("respects the n limit", () => {+ const points = [+ pt("2024-01-01", 100), pt("2024-01-02", 90), pt("2024-01-03", 110),+ pt("2024-01-04", 80), pt("2024-01-05", 120),+ pt("2024-01-06", 70), pt("2024-01-07", 130),+ ];+ const out = computeTopDrawdowns(points, 2);+ expect(out).toHaveLength(2);+ expect(out[0].depth).toBeLessThanOrEqual(out[1].depth);+ });++ it("returns null day spans when times cannot be parsed", () => {+ const points = [pt("not-a-date", 100), pt("also-bad", 80)];+ const out = computeTopDrawdowns(points, 5);+ expect(out).toHaveLength(1);+ expect(out[0].peakToTroughDays).toBeNull();+ expect(out[0].troughToRecoveryDays).toBeNull();+ });++ it("returns [] for empty or single-point input", () => {+ expect(computeTopDrawdowns([], 5)).toEqual([]);+ expect(computeTopDrawdowns([pt("2024-01-01", 100)], 5)).toEqual([]);+ });+});++describe("toDrawdownZones", () => {+ it("maps episodes to zones, falling back to lastTime when unrecovered", () => {+ const episodes = computeTopDrawdowns([+ pt("2024-01-01", 100),+ pt("2024-01-02", 90),+ pt("2024-01-03", 110),+ pt("2024-01-04", 80),+ ], 5);+ expect(episodes).toHaveLength(2);+ const zones = toDrawdownZones(episodes, "2024-01-04");+ expect(zones).toHaveLength(2);+ expect(zones[0].rank).toBe(1);+ expect(zones[1].rank).toBe(2);+ for (const z of zones) {+ expect(z.startTime).toBeTruthy();+ expect(z.endTime).toBeTruthy();+ }+ // The unrecovered episode must end at lastTime+ const unrecovered = episodes.find((e) => e.recoveryTime === null);+ expect(unrecovered).toBeDefined();+ const zone = zones[episodes.indexOf(unrecovered!)];+ expect(zone.endTime).toBe("2024-01-04");+ // The recovered episode keeps its recovery time+ const recovered = episodes.find((e) => e.recoveryTime !== null);+ if (recovered) {+ const z = zones[episodes.indexOf(recovered)];+ expect(z.endTime).toBe(recovered.recoveryTime);+ }+ });++ it("returns [] for no episodes", () => {+ expect(toDrawdownZones([], "2024-01-01")).toEqual([]);+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 69c412695..d196dca6b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -612,6 +612,8 @@ export interface RunData {indicator_series?: Record<string, Record<string, IndicatorPoint[]>>;trade_markers?: TradeMarker[];equity_curve?: EquityPoint[];+ /** Full equity.csv rows (timestamp/equity/drawdown as strings); not capped like equity_curve. */+ artifacts_equity_csv?: Array<Record<string, string>>;trade_log?: Array<Record<string, string>>;run_logs?: Array<{ source?: string; line_number?: number; message?: string }>;}diff --git a/frontend/src/lib/tearsheet.ts b/frontend/src/lib/tearsheet.tsnew file mode 100644index 000000000..11a2d46ab--- /dev/null+++ b/frontend/src/lib/tearsheet.ts@@ -0,0 +1,234 @@+import type { EquityPoint } from "@/lib/api";++/** Equity row normalized to finite numbers, chronological order. */+export interface NormalizedEquityPoint {+ time: string;+ equity: number;+ drawdown: number;+}++/** Calendar-month return; null when not computable (gap month or bad base). */+export interface MonthlyReturn {+ year: number;+ /** 1-12 */+ month: number;+ ret: number | null;+}++export interface AnnualReturn {+ year: number;+ ret: number;+}++/** One drawdown episode detected by the running-peak algorithm. */+export interface DrawdownEpisode {+ peakTime: string;+ troughTime: string;+ recoveryTime: string | null;+ /** Negative fraction, e.g. -0.15 = -15%. */+ depth: number;+ peakToTroughDays: number | null;+ troughToRecoveryDays: number | null;+}++/** Highlight rectangle over the equity chart for one drawdown episode. */+export interface DrawdownZone {+ startTime: string;+ endTime: string;+ rank: number;+}++/** Safari-safe date parse: "YYYY-MM-DD HH:MM:SS" -> "YYYY-MM-DDTHH:MM:SS". */+function parseTime(time: string): Date | null {+ const d = new Date(time.replace(" ", "T"));+ return Number.isNaN(d.getTime()) ? null : d;+}++function monthIndex(year: number, month: number): number {+ return year * 12 + (month - 1);+}++/**+ * Normalize equity rows from either the full `artifacts_equity_csv` payload+ * (string rows keyed timestamp/equity/drawdown) or the capped `equity_curve`+ * (EquityPoint[]). Drops rows with missing time or non-finite equity,+ * preserves input order unless it is visibly reversed (defensive sort).+ */+export function normalizeEquitySeries(+ input: Array<Record<string, string>> | EquityPoint[] | undefined | null,+): NormalizedEquityPoint[] {+ if (!input || input.length === 0) return [];+ const out: NormalizedEquityPoint[] = [];+ for (const row of input) {+ const rec = row as Record<string, unknown>;+ const rawTime = rec.time ?? rec.timestamp;+ const time = rawTime == null ? "" : String(rawTime).trim();+ if (!time) continue;+ const equity = Number(rec.equity);+ if (!Number.isFinite(equity)) continue;+ const dd = Number(rec.drawdown);+ out.push({ time, equity, drawdown: Number.isFinite(dd) ? dd : 0 });+ }+ if (out.length >= 2) {+ const first = parseTime(out[0].time);+ const last = parseTime(out[out.length - 1].time);+ if (first && last && first.getTime() > last.getTime()) {+ out.sort((a, b) => {+ const da = parseTime(a.time)?.getTime() ?? Number.POSITIVE_INFINITY;+ const db = parseTime(b.time)?.getTime() ?? Number.POSITIVE_INFINITY;+ return da - db;+ });+ }+ }+ return out;+}++/**+ * Tearsheet monthly returns: group by calendar month, return =+ * lastEquityOfMonth / prevMonthLastEquity - 1. The first populated month uses+ * the series' first observation as base. Calendar months strictly between the+ * first and last populated month are emitted with ret: null when empty or when+ * the prior calendar month has no data / a non-positive base. No padding+ * before the first or after the last populated month.+ */+export function computeMonthlyReturns(points: NormalizedEquityPoint[]): MonthlyReturn[] {+ if (points.length === 0) return [];+ const monthEnd = new Map<number, number>();+ let firstIdx: number | null = null;+ let lastIdx: number | null = null;+ let seriesBase: number | undefined;+ for (const p of points) {+ const d = parseTime(p.time);+ if (!d) continue;+ if (seriesBase === undefined) seriesBase = p.equity;+ const idx = monthIndex(d.getFullYear(), d.getMonth() + 1);+ monthEnd.set(idx, p.equity);+ if (firstIdx === null || idx < firstIdx) firstIdx = idx;+ if (lastIdx === null || idx > lastIdx) lastIdx = idx;+ }+ if (firstIdx === null || lastIdx === null) return [];+ const result: MonthlyReturn[] = [];+ for (let idx = firstIdx; idx <= lastIdx; idx += 1) {+ const year = Math.floor(idx / 12);+ const month = (idx % 12) + 1;+ const endEquity = monthEnd.get(idx);+ if (endEquity === undefined) {+ result.push({ year, month, ret: null });+ continue;+ }+ const base = idx === firstIdx ? seriesBase : monthEnd.get(idx - 1);+ if (base === undefined || !Number.isFinite(base) || base <= 0 || !Number.isFinite(endEquity)) {+ result.push({ year, month, ret: null });+ } else {+ result.push({ year, month, ret: endEquity / base - 1 });+ }+ }+ return result;+}++/**+ * Tearsheet annual returns: return = lastEquityOfYear / prevYearLastEquity - 1.+ * The first populated year uses the series' first observation as base. Years+ * whose current or prior calendar-year end is missing, or whose base is+ * non-positive, are skipped entirely.+ */+export function computeAnnualReturns(points: NormalizedEquityPoint[]): AnnualReturn[] {+ if (points.length === 0) return [];+ const yearEnd = new Map<number, number>();+ let seriesBase: number | undefined;+ for (const p of points) {+ const d = parseTime(p.time);+ if (!d) continue;+ if (seriesBase === undefined) seriesBase = p.equity;+ yearEnd.set(d.getFullYear(), p.equity);+ }+ if (yearEnd.size === 0) return [];+ const years = [...yearEnd.keys()].sort((a, b) => a - b);+ const result: AnnualReturn[] = [];+ for (let i = 0; i < years.length; i += 1) {+ const year = years[i];+ const endEquity = yearEnd.get(year);+ const base = i === 0 ? seriesBase : yearEnd.get(year - 1);+ if (+ endEquity === undefined || !Number.isFinite(endEquity)+ || base === undefined || !Number.isFinite(base) || base <= 0+ ) {+ continue;+ }+ result.push({ year, ret: endEquity / base - 1 });+ }+ return result;+}++function daySpan(fromTime: string, toTime: string): number | null {+ const from = parseTime(fromTime);+ const to = parseTime(toTime);+ if (!from || !to) return null;+ return Math.round((to.getTime() - from.getTime()) / 86_400_000);+}++/**+ * Top-N drawdown episodes via the running-peak algorithm. An episode starts at+ * the first bar below the running peak (peakTime = the peak bar's time), ends+ * when equity >= the episode's peak level (recoveryTime = that bar's time), or+ * stays open (recoveryTime = null) if the series ends mid-episode.+ * Depth = trough/peak - 1. Sorted deepest first, capped at n.+ */+export function computeTopDrawdowns(points: NormalizedEquityPoint[], n = 5): DrawdownEpisode[] {+ if (points.length < 2 || n <= 0) return [];+ const episodes: DrawdownEpisode[] = [];+ let peakEquity = Number.NEGATIVE_INFINITY;+ let peakTime = "";+ let inEpisode = false;+ let epPeak = 0;+ let epPeakTime = "";+ let trough = 0;+ let troughTime = "";++ const closeEpisode = (recoveryTime: string | null) => {+ const depth = epPeak > 0 ? trough / epPeak - 1 : 0;+ episodes.push({+ peakTime: epPeakTime,+ troughTime,+ recoveryTime,+ depth,+ peakToTroughDays: daySpan(epPeakTime, troughTime),+ troughToRecoveryDays: recoveryTime ? daySpan(troughTime, recoveryTime) : null,+ });+ inEpisode = false;+ };++ for (const p of points) {+ if (p.equity > peakEquity) {+ peakEquity = p.equity;+ peakTime = p.time;+ }+ if (p.equity < peakEquity) {+ if (!inEpisode) {+ inEpisode = true;+ epPeak = peakEquity;+ epPeakTime = peakTime;+ trough = p.equity;+ troughTime = p.time;+ } else if (p.equity < trough) {+ trough = p.equity;+ troughTime = p.time;+ }+ } else if (inEpisode && p.equity >= epPeak) {+ closeEpisode(p.time);+ }+ }+ if (inEpisode) closeEpisode(null);++ episodes.sort((a, b) => a.depth - b.depth);+ return episodes.slice(0, n);+}++/** Map episodes to equity-chart zones; unrecovered episodes run to lastTime. */+export function toDrawdownZones(episodes: DrawdownEpisode[], lastTime: string): DrawdownZone[] {+ return episodes.map((ep, i) => ({+ startTime: ep.peakTime,+ endTime: ep.recoveryTime ?? lastTime,+ rank: i + 1,+ }));+}diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex 050cf1010..4da613f12 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -1,5 +1,5 @@import i18n from '@/i18n';-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import type { ReactNode } from "react";import { useTranslation } from "react-i18next";import { useParams, useNavigate } from "react-router";@@ -7,6 +7,7 @@ import {AlertTriangle,ArrowLeft,BarChart3,+ CalendarRange,CheckCircle2,Code2,Copy,@@ -23,11 +24,21 @@ import {} from "lucide-react";import { toast } from "sonner";import { cn } from "@/lib/utils";-import { api, type BacktestMetrics, type RebalanceNotesPayload, type RiskXRayPayload, type RunCard, type RunData, type ValidationData } from "@/lib/api";+import { api, type BacktestMetrics, type EquityPoint, type RebalanceNotesPayload, type RiskXRayPayload, type RunCard, type RunData, type ValidationData } from "@/lib/api";+import {+ computeAnnualReturns,+ computeMonthlyReturns,+ computeTopDrawdowns,+ normalizeEquitySeries,+ toDrawdownZones,+} from "@/lib/tearsheet";import ReactMarkdown from "react-markdown";import rehypeHighlight from "rehype-highlight";+import { AnnualReturnsChart } from "@/components/charts/AnnualReturnsChart";import { CandlestickChart } from "@/components/charts/CandlestickChart";import { EquityChart } from "@/components/charts/EquityChart";+import { MonthlyReturnsHeatmap } from "@/components/charts/MonthlyReturnsHeatmap";+import { TopDrawdownsPanel } from "@/components/charts/TopDrawdownsPanel";import { MetricsCard } from "@/components/chat/MetricsCard";import { ValidationPanel } from "@/components/charts/ValidationPanel";import { Skeleton, SkeletonMetrics, SkeletonChart } from "@/components/common/Skeleton";@@ -35,7 +46,7 @@ import { ErrorBoundary } from "@/components/common/ErrorBoundary";const rehypePlugins = [rehypeHighlight];-type Tab = "chart" | "trades" | "runCard" | "code" | "validation" | "studio";+type Tab = "chart" | "tearsheet" | "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 };@@ -117,8 +128,10 @@ export function RunDetail() {const hasValidation = !!run?.validation;const hasRunCard = !!run?.run_card;const hasStudio = !!run?.risk_xray || !!run?.rebalance_notes;+ const hasTearsheet = (run?.artifacts_equity_csv?.length ?? 0) > 0 || (run?.equity_curve?.length ?? 0) > 0;const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [{ id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },+ { id: "tearsheet", label: i18n.t("runDetail.tearsheet"), icon: CalendarRange, hidden: !hasTearsheet },{ id: "trades", label: i18n.t("runDetail.trades"), icon: List },{ id: "studio", label: i18n.t("runDetail.studio"), icon: Gauge, hidden: !hasStudio },{ id: "validation", label: i18n.t("runDetail.validation"), icon: ShieldCheck, hidden: !hasValidation },@@ -383,6 +396,7 @@ export function RunDetail() {onCancelLoadAll={handleCancelLoadAllCharts}/>)}+ {tab === "tearsheet" && hasTearsheet && <TearsheetTab run={run} />}{tab === "trades" && <TradesTab run={run} />}{tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}{tab === "studio" && hasStudio && (@@ -571,6 +585,47 @@ function StudioTab({ xray, notes }: { xray?: RiskXRayPayload; notes?: RebalanceN);}+function TearsheetTab({ run }: { run: RunData }) {+ const equityPoints = useMemo(+ () => normalizeEquitySeries(run.artifacts_equity_csv ?? run.equity_curve),+ [run.artifacts_equity_csv, run.equity_curve],+ );+ const monthly = useMemo(() => computeMonthlyReturns(equityPoints), [equityPoints]);+ const annual = useMemo(() => computeAnnualReturns(equityPoints), [equityPoints]);+ const drawdowns = useMemo(() => computeTopDrawdowns(equityPoints, 5), [equityPoints]);+ const zones = useMemo(() => {+ const lastTime = equityPoints.length > 0 ? equityPoints[equityPoints.length - 1].time : "";+ return toDrawdownZones(drawdowns, lastTime);+ }, [drawdowns, equityPoints]);++ if (equityPoints.length < 2) {+ return <div className="p-8 text-muted-foreground text-sm">{i18n.t("runDetail.noTearsheetData")}</div>;+ }++ const chartData: EquityPoint[] = equityPoints.map((p) => ({ time: p.time, equity: p.equity, drawdown: p.drawdown }));+ const yearCount = new Set(monthly.map((m) => m.year)).size;+ const heatmapHeight = Math.min(420, Math.max(200, 40 + 34 * yearCount));++ return (+ <div className="p-4 space-y-4">+ <RunCardPanel title={i18n.t("runDetail.equityDrawdown")} icon={BarChart3}>+ <EquityChart data={chartData} drawdownZones={zones} height={300} />+ </RunCardPanel>+ <RunCardPanel title={i18n.t("runDetail.monthlyReturns")} icon={CalendarRange}>+ <MonthlyReturnsHeatmap data={monthly} annual={annual} height={heatmapHeight} />+ </RunCardPanel>+ <div className="grid gap-4 xl:grid-cols-2">+ <RunCardPanel title={i18n.t("runDetail.annualReturns")} icon={BarChart3}>+ <AnnualReturnsChart data={annual} height={260} />+ </RunCardPanel>+ <RunCardPanel title={i18n.t("runDetail.topDrawdowns")} icon={AlertTriangle}>+ <TopDrawdownsPanel episodes={drawdowns} />+ </RunCardPanel>+ </div>+ </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">