Files
qlib/frontend/web/app/experiments/page.tsx
T
Simon 24f98e90c6 feat(web): 按 ui-ux-pro-max 设计系统重构前端(侧边导航 + 组件库 + 图标 + 可视化)
- 设计令牌与组件体系:语义色/间距/圆角/状态 + Card/Metric/Pill/Btn/Field/Empty/Skeleton/Progress 等
- 桌面左侧导航 + 窄屏抽屉(usePathname 高亮、ESC/遮罩关闭);修复抽屉/遮罩占据网格把 main 挤到第二行的问题
- 自绘内联 SVG 图标集替代 emoji;图标/表格/按钮等交互态齐全,空态/加载/错误/禁用态补齐
- 因子研究分层柱状、因子组合与回测净值/回撤双图 + 月度收益热力表、实验页任务状态徽标
- LineChart 主题化并按需引入 echarts(回测/组合首载 JS 448k→281k);next.config 放行局域网 dev 来源
2026-09-08 21:48:20 +08:00

268 lines
8.5 KiB
TypeScript

"use client";
import { useCallback, useEffect, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import type { BacktestResult } from "@/lib/types";
import {
PageHeader,
Card,
Pill,
Btn,
Banner,
Empty,
Metric,
SkeletonLines,
} from "@/components/ui";
import { Icon } from "@/components/icons";
interface ExperimentMeta {
id: string;
kind: string;
factors: string[];
period?: [string, string] | null;
rebalance?: string;
top_n?: number | null;
summary_text?: string | null;
code_version?: string | null;
created_at?: string;
}
interface ExperimentDetail extends ExperimentMeta {
spec: { universe?: Record<string, unknown> };
result: BacktestResult | null;
}
const KIND_MAP: Record<string, { label: string; tone: "accent" | "violet" | "default" }> = {
backtest: { label: "回测", tone: "accent" },
factor_test: { label: "因子测试", tone: "violet" },
};
function kindView(kind: string) {
const k = KIND_MAP[kind] ?? { label: kind, tone: "default" as const };
return <Pill tone={k.tone}>{k.label}</Pill>;
}
function statusView(status: string) {
switch (status) {
case "success":
return (
<Pill tone="pos" icon="check">
完成
</Pill>
);
case "running":
return (
<Pill tone="accent" icon="spinner">
运行中
</Pill>
);
case "queued":
return (
<Pill tone="warn" icon="clock">
排队
</Pill>
);
case "failed":
return (
<Pill tone="neg" icon="alert">
失败
</Pill>
);
case "cancelled":
return <Pill tone="warn">已取消</Pill>;
default:
return <Pill>{status}</Pill>;
}
}
export default function ExperimentsPage() {
const [exps, setExps] = useState<ExperimentMeta[]>([]);
const [loading, setLoading] = useState(true);
const [detail, setDetail] = useState<ExperimentDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [jobId, setJobId] = useState("");
const [jobStatus, setJobStatus] = useState("");
const [error, setError] = useState("");
const load = useCallback(() => {
apiGet<ExperimentMeta[]>("/experiments")
.then(setExps)
.catch((e: Error) => setError(e.message))
.finally(() => setLoading(false));
}, []);
useEffect(load, [load]);
function open(id: string) {
setDetailLoading(true);
setDetail(null);
apiGet<ExperimentDetail>(`/experiments/${id}`)
.then((d) => {
setDetail(d);
})
.catch((e: Error) => setError(e.message))
.finally(() => setDetailLoading(false));
}
function rerun(exp: ExperimentMeta) {
setError("");
setJobId("");
setJobStatus("submitting");
apiPost<{ job_id: string; status: string }>(`/experiments/${exp.id}/rerun`, {})
.then((r) => {
setJobId(r.job_id);
setJobStatus(r.status);
poll(r.job_id);
})
.catch((e: Error) => setError(e.message));
}
function poll(id: string) {
let tries = 0;
const timer = window.setInterval(() => {
tries += 1;
apiGet<{ status: string }>(`/jobs/${id}`)
.then((j) => {
setJobStatus(j.status);
if (j.status === "success" || j.status === "failed" || tries > 60) {
window.clearInterval(timer);
load();
setDetail(null);
}
})
.catch(() => window.clearInterval(timer));
}, 1200);
}
const s = detail?.result?.summary;
return (
<>
<PageHeader
title="实验归档"
sub="每次因子测试与回测自动归档(含 Research Spec 与代码版本),保证可复现;支持一键复跑。"
actions={exps.length > 0 ? <Pill tone="accent" icon="archive">共 {exps.length} 个实验</Pill> : undefined}
/>
{error ? <Banner tone="error">{error}</Banner> : null}
{jobId ? (
<Card
icon="refresh"
title={`复跑任务 ${jobId}`}
tools={statusView(jobStatus === "submitting" ? "queued" : jobStatus)}
>
<div className="hint">
任务状态实时轮询;完成后列表自动刷新,可直接展开查看最新结果。
</div>
</Card>
) : null}
<Card title="实验列表" icon="archive" flush>
{loading ? (
<div style={{ padding: 18 }}>
<SkeletonLines n={6} />
</div>
) : exps.length === 0 ? (
<Empty
icon="archive"
title="暂无实验"
hint="在「回测」或「因子研究」中运行一次,即会自动归档于此。"
/>
) : (
<div className="table-wrap">
<table className="tbl">
<thead>
<tr>
<th>ID</th>
<th>类型</th>
<th>因子</th>
<th>区间</th>
<th>摘要</th>
<th>代码版本</th>
<th style={{ width: 150, textAlign: "right" }}>操作</th>
</tr>
</thead>
<tbody>
{exps.map((e) => (
<tr key={e.id} className={detail?.id === e.id ? "row-active" : undefined}>
<td className="cell-mono cell-strong">{e.id}</td>
<td>{kindView(e.kind)}</td>
<td>
<span className="row" style={{ gap: 4 }}>
{e.factors.map((f) => (
<span key={f} className="tag tag--mono">
{f}
</span>
))}
</span>
</td>
<td className="cell-mono">{e.period ? `${e.period[0]}~${e.period[1]}` : "—"}</td>
<td className="hint">{e.summary_text ?? "—"}</td>
<td>{e.code_version ? <span className="tag tag--mono">{e.code_version}</span> : <span className="hint">—</span>}</td>
<td style={{ textAlign: "right" }}>
<span className="row" style={{ justifyContent: "flex-end", gap: 6 }}>
<Btn size="sm" icon="search" onClick={() => open(e.id)}>
详情
</Btn>
<Btn size="sm" variant="primary" icon="refresh" onClick={() => rerun(e)} disabled={jobStatus === "running" || jobStatus === "queued" || jobStatus === "submitting"}>
复跑
</Btn>
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Card>
{detail ? (
<Card
icon="book"
title={`${detail.id} · ${detail.factors.join("、")}`}
sub={detail.period ? `${detail.period[0]} ~ ${detail.period[1]}` : undefined}
tools={
<Btn size="sm" onClick={() => setDetail(null)}>
<Icon name="x" size={13} />
关闭
</Btn>
}
>
{detailLoading ? (
<SkeletonLines n={3} />
) : (
<>
{s ? (
<div className="metric-grid" style={{ marginBottom: 0 }}>
<Metric
label="区间收益"
tone={s.total_return_pct >= 0 ? "pos" : "neg"}
value={`${s.total_return_pct >= 0 ? "+" : ""}${s.total_return_pct.toFixed(2)}%`}
/>
<Metric
label="年化收益"
tone={s.annual_return_pct >= 0 ? "pos" : "neg"}
value={`${s.annual_return_pct >= 0 ? "+" : ""}${s.annual_return_pct.toFixed(2)}%`}
/>
<Metric label="Sharpe" value={s.sharpe.toFixed(2)} />
<Metric label="最大回撤" tone="neg" value={`${s.max_drawdown_pct.toFixed(2)}%`} />
</div>
) : (
<div className="hint">该实验没有可展示的汇总结果(可能是因子测试或历史版本)。</div>
)}
{detail.spec ? (
<div className="hint" style={{ marginTop: 12 }}>
spec(可复现输入):<span className="mono">{JSON.stringify(detail.spec).slice(0, 500)}</span>
{JSON.stringify(detail.spec).length > 500 ? "…" : ""}
</div>
) : null}
</>
)}
</Card>
) : null}
</>
);
}