feat: Phase 3 Web — 业务 API(stocks/factors/backtests)+ Next.js 前端
- 后端业务 API:GET /api/stocks(搜索/分页)、GET /api/factors(因子目录)、POST /api/factor-tests 与 /api/backtests(Research Spec 驱动同步执行)、GET /api/backtests/last;Annotated 依赖注入 + CORS(dev) - Repository 批量查询 get_range_many(研究装配一次查询,避免逐只拉取) - 前端 frontend/web:Next.js 15(TS) + ECharts —— 总览 / 股票池 / 因子研究(IC·RankIC·分层展示) / 回测(净值·回撤·月度·持仓·未建模标注) - 前端只消费业务 API 与标准化 BacktestResult,无 Qlib/SQL 概念泄漏 - 真实数据:同步 20 只权重股 2023-2024 日线(9680 根)支撑截面研究 - 验证:API 集成测试 8 项(DTO 校验/装配/引擎/标准结果,内存 repo 全链路)+ 全量 pytest 68 passed;前端 tsc + next build 通过;无头浏览器端到端(factors/backtest 页面渲染后端数据) - ruff clean
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet, apiPost } from "@/lib/api";
|
||||
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 [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
apiGet<FactorMeta[]>("/factors")
|
||||
.then(setFactors)
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, []);
|
||||
|
||||
function run() {
|
||||
setRunning(true);
|
||||
setError("");
|
||||
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],
|
||||
};
|
||||
apiPost<BacktestResult>("/backtests", spec)
|
||||
.then(setResult)
|
||||
.catch((e: Error) => setError(e.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>
|
||||
{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>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet, apiPost } from "@/lib/api";
|
||||
import type { FactorMeta, FactorTestReport, ResearchSpec } from "@/lib/types";
|
||||
|
||||
export default function FactorsPage() {
|
||||
const [factors, setFactors] = useState<FactorMeta[]>([]);
|
||||
const [name, setName] = useState("momentum_60");
|
||||
const [start, setStart] = useState("2024-03-01");
|
||||
const [end, setEnd] = useState("2024-12-31");
|
||||
const [report, setReport] = useState<FactorTestReport | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
apiGet<FactorMeta[]>("/factors")
|
||||
.then(setFactors)
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, []);
|
||||
|
||||
function run() {
|
||||
setRunning(true);
|
||||
setError("");
|
||||
const spec: ResearchSpec = {
|
||||
type: "factor_test",
|
||||
universe: { exclude_st: true, min_listing_days: 0 },
|
||||
factors: [{ name, weight: 1 }],
|
||||
selection: { top_n: 10 },
|
||||
rebalance: "monthly",
|
||||
period: [start, end],
|
||||
};
|
||||
apiPost<FactorTestReport>("/factor-tests", spec)
|
||||
.then(setReport)
|
||||
.catch((e: Error) => setError(e.message))
|
||||
.finally(() => setRunning(false));
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1>因子研究</h1>
|
||||
<div className="card">
|
||||
<h2>因子目录(行情因子 · 无未来函数)</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>描述</th>
|
||||
<th>公式</th>
|
||||
<th>回看</th>
|
||||
<th>方向</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{factors.map((f) => (
|
||||
<tr key={f.name}>
|
||||
<td>{f.name}</td>
|
||||
<td>{f.description}</td>
|
||||
<td className="muted">{f.formula}</td>
|
||||
<td>{f.lookback}</td>
|
||||
<td>{f.direction === "higher_is_better" ? "高为好" : "低为好"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<h2>运行单因子测试(IC / RankIC / 分层)</h2>
|
||||
<div className="row">
|
||||
<select value={name} onChange={(e) => setName(e.target.value)}>
|
||||
{factors.map((f) => (
|
||||
<option key={f.name} value={f.name}>
|
||||
{f.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<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>
|
||||
<button className="primary" onClick={run} disabled={running}>
|
||||
{running ? "运行中…" : "运行因子测试"}
|
||||
</button>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
{report && (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<div className="stat-grid">
|
||||
<div className="stat">
|
||||
<div className="label">IC 均值</div>
|
||||
<div className="value">{report.ic_mean.toFixed(4)}</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="label">RankIC 均值</div>
|
||||
<div className="value">{report.rank_ic_mean.toFixed(4)}</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="label">ICIR</div>
|
||||
<div className="value">{report.icir.toFixed(3)}</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="label">正收益占比</div>
|
||||
<div className="value">{report.positive_ratio_pct.toFixed(1)}%</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="label">样本日数</div>
|
||||
<div className="value">{report.sample_days}</div>
|
||||
</div>
|
||||
</div>
|
||||
{report.quantile_returns.length > 0 && (
|
||||
<table style={{ marginTop: 12 }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>分层(1 最低 → 5 最高)</th>
|
||||
{report.quantile_returns.map((q) => (
|
||||
<th key={q.quantile}>Q{q.quantile + 1}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>未来 21 日平均收益</td>
|
||||
{report.quantile_returns.map((q) => (
|
||||
<td key={q.quantile}>{q.return_pct.toFixed(2)}%</td>
|
||||
))}
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap");
|
||||
|
||||
:root {
|
||||
--bg: #0f172a;
|
||||
--panel: #1e293b;
|
||||
--panel-2: #273449;
|
||||
--text: #e2e8f0;
|
||||
--muted: #94a3b8;
|
||||
--accent: #38bdf8;
|
||||
--good: #34d399;
|
||||
--bad: #f87171;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: "Noto Sans SC", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
nav {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
align-items: center;
|
||||
padding: 12px 24px;
|
||||
background: var(--panel);
|
||||
border-bottom: 1px solid #334155;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
nav a {
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
nav a:hover,
|
||||
nav a.active {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
nav .brand {
|
||||
color: var(--text);
|
||||
font-weight: 700;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
main {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--panel);
|
||||
border: 1px solid #334155;
|
||||
border-radius: 10px;
|
||||
padding: 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 22px;
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 16px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.stat {
|
||||
background: var(--panel-2);
|
||||
border-radius: 8px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.stat .label {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stat .value {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.good { color: var(--good); }
|
||||
.bad { color: var(--bad); }
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid #334155;
|
||||
}
|
||||
|
||||
th {
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
button {
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
border: 1px solid #475569;
|
||||
border-radius: 6px;
|
||||
padding: 8px 10px;
|
||||
font-size: 13px;
|
||||
margin: 2px 6px 2px 0;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
color: #0f172a;
|
||||
font-weight: 700;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--bad);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 10px;
|
||||
align-items: end;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "qlib-platform · A股量化研究",
|
||||
description: "个人 A 股量化研究平台:股票池 / 因子 / 回测",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body>
|
||||
<nav>
|
||||
<span className="brand">qlib-platform</span>
|
||||
<Link href="/">总览</Link>
|
||||
<Link href="/stocks">股票池</Link>
|
||||
<Link href="/factors">因子研究</Link>
|
||||
<Link href="/backtest">回测</Link>
|
||||
</nav>
|
||||
<main>{children}</main>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet } from "@/lib/api";
|
||||
import type { Stock, FactorMeta } from "@/lib/types";
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [stockCount, setStockCount] = useState<number | null>(null);
|
||||
const [factorCount, setFactorCount] = useState<number | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
apiGet<Stock[]>("/stocks?limit=500"),
|
||||
apiGet<FactorMeta[]>("/factors"),
|
||||
])
|
||||
.then(([stocks, factors]) => {
|
||||
setStockCount(stocks.length);
|
||||
setFactorCount(factors.length);
|
||||
})
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1>总览</h1>
|
||||
{error && <div className="error">后端不可达:{error}</div>}
|
||||
<div className="stat-grid">
|
||||
<div className="stat">
|
||||
<div className="label">股票池</div>
|
||||
<div className="value">{stockCount ?? "—"}</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="label">内置因子</div>
|
||||
<div className="value">{factorCount ?? "—"}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card" style={{ marginTop: 16 }}>
|
||||
<h2>说明</h2>
|
||||
<div className="muted">
|
||||
个人 A 股量化研究平台(Phase 3 Web)。
|
||||
顶部导航进入「股票池 / 因子研究 / 回测」;研究基于本地 SQLite 行情
|
||||
(Tushare 同步,20 只权重股 2023–2024 日线),因子测试与回测均由后端
|
||||
Research Specification 驱动并返回标准化结果。
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet } from "@/lib/api";
|
||||
import type { Stock } from "@/lib/types";
|
||||
|
||||
export default function StocksPage() {
|
||||
const [stocks, setStocks] = useState<Stock[]>([]);
|
||||
const [q, setQ] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
apiGet<Stock[]>(`/stocks?limit=300&q=${encodeURIComponent(q)}`)
|
||||
.then(setStocks)
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, [q]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1>股票池</h1>
|
||||
<div className="row" style={{ marginBottom: 12 }}>
|
||||
<input
|
||||
placeholder="按代码 / 名称搜索(如 600519 或 茅台)"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
/>
|
||||
<span className="muted">共 {stocks.length} 条</span>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<div className="card">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>代码</th>
|
||||
<th>名称</th>
|
||||
<th>行业</th>
|
||||
<th>地区</th>
|
||||
<th>上市日</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{stocks.map((s) => (
|
||||
<tr key={s.symbol}>
|
||||
<td>{s.symbol}</td>
|
||||
<td>{s.name}</td>
|
||||
<td>{s.industry ?? "—"}</td>
|
||||
<td>{s.area ?? "—"}</td>
|
||||
<td>{s.list_date}</td>
|
||||
<td>{s.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user