Files
qlib/frontend/web/app/factors/compose/page.tsx
T
Simon f13b34c59e feat(web): 字段库页 + 界面单位换算 + 因子目录参数化 + 选股策略条件表单
字段库与单位:
- `/fields`:字段库管理页(中文名/说明可改、可停用;kind 是引擎事实不可改);
  单位只在字段自己的阶梯里选(总市值 = 万元/亿元),越界 422 原样展示。
- `lib/units.ts`:界面单位 ⇄ 基准单位换算集中一处,条件输入按界面单位回显、
  提交前换回基准单位(引擎只认基准单位,库里存的也永远是基准单位)。
- `SelectionStrategyForm` 取代 `StrategyParamsForm`:一个策略只定义「怎么选」
  (股票池 + 因子 + 过滤条件),条件字段来自字段库接口而不是前端硬编码枚举。

因子参数化(名字即身份,界面不许藏):
- `/factors` 新增「参数」列与展开行:精确引擎键、每个参数的允许范围、来源、依赖列
  (依赖列标明「引擎事实,不可改」);说明文案从「不可修改」改为
  「改参数 = 新建参数化因子 = 新身份,旧因子/既有策略不变义」。
- 「新建参数化因子」卡片:模板下拉 + 受控窗口(min/max)+ 方向枚举下拉,
  实时预览规范键/中文名/渲染公式;后端 422 的原文原样展示,不静默截断。
- 因子下拉显示中文名(含参数)与短键,**value 一律是完整引擎键**;
  停用的因子从各页候选里消失(/strategies、/selection、/signals、/factors/compose),
  既有策略/归档仍按名字解析;`/factors/compose` 顺手修了勾选框点击目标过小。
- `/fields` 加提示:字段库只列内置因子名,参数化因子在 /factors 管理,
  选股策略条件下拉里会一并出现。

tsc --noEmit 0 error;verify_ui_alignment 8 页 160 项全过(另跑 3 个选因子页 51/54)。
2026-10-01 16:38:29 +08:00

375 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect, useState } from "react";
import { apiGet } from "@/lib/api";
import { submitJob, waitJob } from "@/lib/jobs";
import { factorLabel, pickableFactors } from "@/lib/factors";
import type { BacktestResult, FactorMeta, ResearchSpec } from "@/lib/types";
import { recentRange } from "@/lib/dates";
import {
PageHeader,
Card,
Pill,
Field,
Btn,
Banner,
Progress,
Signed,
BacktestMetrics,
MonthlyReturnsTable,
UnimplementedNote,
} from "@/components/ui";
import { LwChart, type LwSeries } from "@/components/charts/LwChart";
import { CHART, fmtNum, fmtPct } from "@/components/charts/theme";
import { Icon } from "@/components/icons";
interface Pick {
name: string;
weight: number;
}
export default function ComposePage() {
const [factors, setFactors] = useState<FactorMeta[]>([]);
const [picks, setPicks] = useState<Pick[]>([]);
const [topN, setTopN] = useState(10);
const [rebalance, setRebalance] = useState<"monthly" | "weekly">("monthly");
const [excludeSt, setExcludeSt] = useState(true);
const [start, setStart] = useState("");
const [end, setEnd] = useState("");
const [result, setResult] = useState<BacktestResult | null>(null);
const [running, setRunning] = useState(false);
const [jobId, setJobId] = useState("");
const [error, setError] = useState("");
useEffect(() => {
let alive = true;
apiGet<FactorMeta[]>("/factors")
.then((list) => {
if (!alive) return;
// 停用/算不出来的因子不摆进候选(停用仍可被既有策略解析,只是不该再被选中)
setFactors(pickableFactors(list));
setPicks([
{ name: "momentum_60", weight: 1.5 },
{ name: "volatility_60", weight: 1.0 },
]);
})
.catch((e: Error) => alive && setError(e.message));
const { start: s, end: e } = recentRange();
setStart(s);
setEnd(e);
return () => {
alive = false;
};
}, []);
function togglePick(name: string) {
setPicks((prev) =>
prev.some((p) => p.name === name)
? prev.filter((p) => p.name !== name)
: [...prev, { name, weight: 1 }],
);
}
function setWeight(name: string, weight: number) {
setPicks((prev) => prev.map((p) => (p.name === name ? { ...p, weight } : p)));
}
function removePick(name: string) {
setPicks((prev) => prev.filter((p) => p.name !== name));
}
async function run() {
const valid = picks.filter((p) => Number.isFinite(p.weight) && p.weight > 0);
if (valid.length === 0) {
setError("请选择至少一个因子并设置大于 0 的权重");
return;
}
setRunning(true);
setError("");
setJobId("");
setResult(null);
try {
const spec: ResearchSpec = {
type: "backtest",
universe: { exclude_st: excludeSt, min_listing_days: 0 },
factors: valid.map((p) => ({ name: p.name, weight: p.weight })),
selection: { top_n: topN },
rebalance,
period: [start, end],
};
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);
setJobId("");
}
}
return (
<>
<PageHeader
title="因子组合"
sub="多因子横截面 z-score 标准化后按权重叠加成综合分,每期取 Top N 等权持有。"
actions={
<Pill tone="accent" icon="layers">
{picks.length} 个因子
</Pill>
}
/>
<Card title="组合方式(如何合成一个分数)" icon="scale">
<ol className="steplist">
<li>选择若干因子并设置权重(默认 1;低为好方向由引擎自动反向)。</li>
<li>
每个交易日:每个因子在全体股票横截面上做 <b>z-score 标准化</b>(当日缺失因子值的股票不参与该因子得分)。
</li>
<li>
综合得分 = <b>Σ(权重 × 标准化后因子得分)</b>,得分越高越优先。
</li>
<li>每期按综合得分取 Top N 等权持有,到下一调仓日再平衡(含成本 / 涨跌停 / 停牌近似)。</li>
</ol>
</Card>
<Card
title="选择因子并设置权重"
icon="target"
sub="权重可为小数(如 1.5 = 更侧重该因子)"
flush
>
<div className="table-wrap">
<table className="tbl">
<thead>
<tr>
<th style={{ width: 46 }}></th>
<th>因子</th>
<th>方向</th>
<th style={{ width: 120 }}>权重</th>
<th>简介</th>
</tr>
</thead>
<tbody>
{factors.map((f) => {
const pick = picks.find((p) => p.name === f.name);
return (
<tr key={f.name} className={pick ? "row-active" : undefined}>
<td>
{/* 勾选框要用 .check--cell 包一层:裸 16px 的 checkbox 点击目标太小
(本项目 UI 自检要求 ≥28px,且与同排输入框等高) */}
<label className="check check--cell">
<input
type="checkbox"
checked={!!pick}
onChange={() => togglePick(f.name)}
aria-label={`选择因子 ${f.name}`}
/>
</label>
</td>
<td className="cell-strong">
{factorLabel(f)}
{/* 名字即身份:中文名旁边的引擎键必须看得见(含参数,如 momentum(window=90,…)) */}
<span className="hint mono cell-hint" style={{ fontWeight: 400, overflowWrap: "anywhere" }}>
{f.name}
</span>
</td>
<td>
<Pill tone={f.direction === "higher_is_better" ? "accent" : "violet"}>
{f.direction === "higher_is_better" ? "高为好" : "低为好"}
</Pill>
</td>
<td>
<input
type="number"
className="input"
step="0.1"
min="0.1"
style={{ width: 92 }}
value={pick?.weight ?? 1}
disabled={!pick}
onChange={(e) => setWeight(f.name, Number(e.target.value))}
aria-label={`${f.name} 权重`}
/>
</td>
<td className="hint">{f.brief ?? f.description}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Card>
<Card title="回测条件" icon="gauge">
{picks.length > 0 ? (
<div className="chips" style={{ marginBottom: 14 }}>
{picks.map((p) => (
<span className="chip" key={p.name}>
<b className="mono">{p.name}</b>
权重 {p.weight}
<button
type="button"
className="chip__x"
aria-label={`移除 ${p.name}`}
onClick={() => removePick(p.name)}
>
<Icon name="x" size={12} />
</button>
</span>
))}
</div>
) : (
<div className="hint" style={{ marginBottom: 14 }}>
尚未选择因子 —— 在上方勾选并设置权重。
</div>
)}
<div className="form-grid">
<Field label="Top N">
<input
type="number"
className="input"
min={1}
max={200}
value={topN}
onChange={(e) => setTopN(Number(e.target.value))}
/>
</Field>
<Field label="调仓频率">
<select
className="input"
value={rebalance}
onChange={(e) => setRebalance(e.target.value as "monthly" | "weekly")}
>
<option value="monthly">月度</option>
<option value="weekly">周度</option>
</select>
</Field>
<Field label="开始日期">
<input type="date" className="input" value={start} onChange={(e) => setStart(e.target.value)} />
</Field>
<Field label="结束日期">
<input type="date" className="input" value={end} onChange={(e) => setEnd(e.target.value)} />
</Field>
<Field label="标的范围">
<label className="row" style={{ gap: 6, color: "var(--text-2)", fontSize: 13, cursor: "pointer" }}>
<input type="checkbox" checked={excludeSt} onChange={(e) => setExcludeSt(e.target.checked)} />
剔除 ST
</label>
</Field>
<Btn
variant="primary"
icon="play"
loading={running}
disabled={running || picks.length === 0}
onClick={run}
>
{running ? "后台运行中…" : `回测组合(${picks.length} 个因子)`}
</Btn>
</div>
{running ? (
<div style={{ marginTop: 14 }}>
<Progress
value={30}
label={
<>
任务 <span className="mono">{jobId || "排队中…"}</span> 后台执行中,完成后结果自动展示在本页。
</>
}
/>
</div>
) : null}
{error ? <div style={{ marginTop: 12 }}><Banner tone="error">{error}</Banner></div> : null}
</Card>
{result ? <ResultView result={result} params={{ picks, topN, rebalance, excludeSt, start, end }} /> : null}
</>
);
}
function ResultView({
result,
params,
}: {
result: BacktestResult;
params: { picks: Pick[]; topN: number; rebalance: string; excludeSt: boolean; start: string; end: string };
}) {
const s = result.summary;
// 曲线数据点:LwChart 的 time 用 "YYYY-MM-DD" 字符串,向后端 CurvePoint 的 date 直接映射
const equitySeries: LwSeries[] = [
{
key: "equity",
label: "净值",
type: "area",
color: CHART.pos,
data: result.equity_curve.map((p) => ({ time: p.date, value: p.value })),
},
];
const drawdownSeries: LwSeries[] = [
{
key: "drawdown",
label: "回撤",
type: "line",
color: CHART.neg,
data: result.drawdown.map((p) => ({ time: p.date, value: p.value })),
},
];
return (
<>
<div className="between" style={{ margin: "6px 0 14px" }}>
<div className="row">
<Pill tone="pos" icon="check">
回测完成
</Pill>
<Pill tone="violet" icon="target">Top {params.topN}</Pill>
<Pill>{params.rebalance === "monthly" ? "月度调仓" : "周度调仓"}</Pill>
{params.excludeSt ? <Pill>剔除 ST</Pill> : null}
<Pill>{params.start} ~ {params.end}</Pill>
</div>
<div className="row" style={{ fontSize: 22, fontWeight: 700 }}>
区间收益 <Signed value={s.total_return_pct} suffix="%" />
</div>
</div>
<BacktestMetrics s={s} />
<div className="chart-grid">
<Card icon="chartLine" title="净值曲线" tools={<Pill tone="pos">期末 {s.final_equity.toLocaleString()}</Pill>}>
<LwChart
series={equitySeries}
height={300}
valueFormat={(v) => fmtNum(v, 2)}
ariaLabel="净值曲线"
emptyHint="该区间没有净值数据"
/>
</Card>
<Card icon="chartLine" title="回撤(%)" tools={<Pill tone="neg">最大 {s.max_drawdown_pct.toFixed(2)}%</Pill>}>
<LwChart
series={drawdownSeries}
height={300}
zeroLine
valueFormat={(v) => fmtPct(v, 2)}
ariaLabel="回撤曲线"
emptyHint="该区间没有回撤数据"
/>
</Card>
</div>
<Card icon="calendar" title="月度收益(%)">
<MonthlyReturnsTable rows={result.monthly_returns} />
</Card>
<UnimplementedNote items={result.unimplemented} />
</>
);
}