- 根因:全市场因子测试同步执行约 47s,经 Next 同源代理转发时长请求被 socket 中断(前端日志:Failed to proxy .../api/factor-tests [socket hang up])
- factors/backtest 页改为 POST /api/jobs 提交 → 轮询 GET /api/jobs/{id} → 取内嵌结果(AGENT §19 异步化)
- 新增 lib/jobs.ts(submitJob / waitJob,超时 10 分钟),运行中显示 Job 号
- 端到端验证:全市场 momentum_60 测试 JOB-93479087 → success(IC -0.0598,样本 323 日)+ Experiment 归档
- tsc + next build 通过;同步接口保留(适合小样本/脚本调用)
222 lines
7.5 KiB
TypeScript
222 lines
7.5 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useState } from "react";
|
||
import { apiGet } from "@/lib/api";
|
||
import { submitJob, waitJob } from "@/lib/jobs";
|
||
import type { BacktestResult, FactorMeta, ResearchSpec } from "@/lib/types";
|
||
import { LineChart } from "@/components/LineChart";
|
||
|
||
export default function BacktestPage() {
|
||
const [factors, setFactors] = useState<FactorMeta[]>([]);
|
||
const [factor, setFactor] = useState("momentum_60");
|
||
const [topN, setTopN] = useState(5);
|
||
const [rebalance, setRebalance] = useState<"monthly" | "weekly">("monthly");
|
||
const [start, setStart] = useState("2024-03-01");
|
||
const [end, setEnd] = useState("2024-12-31");
|
||
const [excludeSt, setExcludeSt] = useState(true);
|
||
const [result, setResult] = useState<BacktestResult | null>(null);
|
||
const [running, setRunning] = useState(false);
|
||
const [jobId, setJobId] = useState("");
|
||
const [error, setError] = useState("");
|
||
|
||
useEffect(() => {
|
||
apiGet<FactorMeta[]>("/factors")
|
||
.then(setFactors)
|
||
.catch((e: Error) => setError(e.message));
|
||
}, []);
|
||
|
||
async function run() {
|
||
setRunning(true);
|
||
setError("");
|
||
setJobId("");
|
||
setResult(null);
|
||
try {
|
||
const spec: ResearchSpec = {
|
||
type: "backtest",
|
||
universe: { exclude_st: excludeSt, min_listing_days: 0 },
|
||
factors: [{ name: factor, weight: 1 }],
|
||
selection: { top_n: topN },
|
||
rebalance,
|
||
period: [start, end],
|
||
};
|
||
// 异步 Job:后台执行(全市场可能数十秒),轮询到终态
|
||
const { job_id } = await submitJob(spec);
|
||
setJobId(job_id);
|
||
const out = await waitJob<BacktestResult>(job_id);
|
||
if (out.status === "success" && out.result) {
|
||
setResult(out.result);
|
||
} else {
|
||
setError(`任务${out.status}${out.error ? `:${out.error}` : ""}`);
|
||
}
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
} finally {
|
||
setRunning(false);
|
||
}
|
||
}
|
||
|
||
const s = result?.summary;
|
||
return (
|
||
<>
|
||
<h1>选股回测</h1>
|
||
<div className="card">
|
||
<h2>研究参数(Research Specification)</h2>
|
||
<div className="form-grid">
|
||
<label className="muted">
|
||
因子
|
||
<select value={factor} onChange={(e) => setFactor(e.target.value)}>
|
||
{factors.map((f) => (
|
||
<option key={f.name} value={f.name}>
|
||
{f.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label className="muted">
|
||
Top N
|
||
<input
|
||
type="number"
|
||
min={1}
|
||
max={50}
|
||
value={topN}
|
||
onChange={(e) => setTopN(Number(e.target.value))}
|
||
/>
|
||
</label>
|
||
<label className="muted">
|
||
调仓
|
||
<select
|
||
value={rebalance}
|
||
onChange={(e) => setRebalance(e.target.value as "monthly" | "weekly")}
|
||
>
|
||
<option value="monthly">月度</option>
|
||
<option value="weekly">周度</option>
|
||
</select>
|
||
</label>
|
||
<label className="muted">
|
||
开始
|
||
<input type="date" value={start} onChange={(e) => setStart(e.target.value)} />
|
||
</label>
|
||
<label className="muted">
|
||
结束
|
||
<input type="date" value={end} onChange={(e) => setEnd(e.target.value)} />
|
||
</label>
|
||
<label className="muted">
|
||
<input
|
||
type="checkbox"
|
||
checked={excludeSt}
|
||
onChange={(e) => setExcludeSt(e.target.checked)}
|
||
/>{" "}
|
||
剔除 ST
|
||
</label>
|
||
<button className="primary" onClick={run} disabled={running}>
|
||
{running ? "后台运行中…" : "运行回测"}
|
||
</button>
|
||
</div>
|
||
{running && jobId && <div className="muted">任务 {jobId} 后台执行中,请稍候…</div>}
|
||
{error && <div className="error">{error}</div>}
|
||
</div>
|
||
|
||
{result && s && (
|
||
<>
|
||
<div className="card">
|
||
<h2>
|
||
结果 · {s.total_return_pct.toFixed(2)}%{" "}
|
||
<span className={s.total_return_pct >= 0 ? "good" : "bad"}>
|
||
{s.total_return_pct >= 0 ? "▲" : "▼"}
|
||
</span>
|
||
</h2>
|
||
<div className="stat-grid">
|
||
<div className="stat">
|
||
<div className="label">期末净值</div>
|
||
<div className="value">{s.final_equity.toLocaleString()}</div>
|
||
</div>
|
||
<div className="stat">
|
||
<div className="label">年化收益</div>
|
||
<div className="value">{s.annual_return_pct.toFixed(2)}%</div>
|
||
</div>
|
||
<div className="stat">
|
||
<div className="label">Sharpe</div>
|
||
<div className="value">{s.sharpe.toFixed(2)}</div>
|
||
</div>
|
||
<div className="stat">
|
||
<div className="label">最大回撤</div>
|
||
<div className="value bad">{s.max_drawdown_pct.toFixed(2)}%</div>
|
||
</div>
|
||
<div className="stat">
|
||
<div className="label">胜率(按交易)</div>
|
||
<div className="value">{s.win_rate_pct.toFixed(1)}%</div>
|
||
</div>
|
||
<div className="stat">
|
||
<div className="label">交易笔数 / 换手</div>
|
||
<div className="value">
|
||
{s.total_trades} / {s.avg_turnover_pct.toFixed(0)}%
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div style={{ marginTop: 12 }}>
|
||
<LineChart title="净值曲线" data={result.equity_curve} color="#34d399" />
|
||
</div>
|
||
<LineChart
|
||
title="回撤(%)"
|
||
data={result.drawdown}
|
||
color="#f87171"
|
||
/>
|
||
</div>
|
||
|
||
<div className="card">
|
||
<h2>月度收益(%)</h2>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>月份</th>
|
||
<th>收益</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{result.monthly_returns.map((m) => (
|
||
<tr key={`${m.year}-${m.month}`}>
|
||
<td>
|
||
{m.year}-{String(m.month).padStart(2, "0")}
|
||
</td>
|
||
<td className={m.return_pct >= 0 ? "good" : "bad"}>
|
||
{m.return_pct.toFixed(2)}%
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div className="card">
|
||
<h2>最新持仓</h2>
|
||
{(() => {
|
||
const last = new Map<string, number>();
|
||
for (const p of result.positions) last.set(p.date, 0);
|
||
const lastDate = [...last.keys()].at(-1);
|
||
const pos = result.positions.filter((p) => p.date === lastDate);
|
||
return (
|
||
<div className="row">
|
||
{pos.map((p) => (
|
||
<span key={p.symbol} className="stat">
|
||
{p.symbol} · {(p.weight * 100).toFixed(0)}%
|
||
</span>
|
||
))}
|
||
</div>
|
||
);
|
||
})()}
|
||
</div>
|
||
|
||
<div className="card">
|
||
<h2>未建模约束(如实标注)</h2>
|
||
<ul className="muted">
|
||
{result.unimplemented.map((u, i) => (
|
||
<li key={i}>{u}</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
</>
|
||
)}
|
||
</>
|
||
);
|
||
}
|