1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
|
<script lang="ts">
import Status from '../components/Status.svelte';
import { listDatasets, createRun, getRun, cancelRun, rerunRun, listRuns, getDatasetPreview } from '../lib/client';
import { extractStatusMessage } from '../lib/state';
import {
fmtDateTime,
fmtPct,
formatMoney,
datasetStatusLabel,
runStatusLabel,
runStatusBadge
} from '../lib/format';
import { summarizeCoverage } from '../lib/coverage';
import { go } from '../lib/router';
import type { Run, Dataset } from '../lib/types';
import { Button } from '$lib/components/ui/button';
import { Alert } from '$lib/components/ui/alert';
import { Badge } from '$lib/components/ui/badge';
import * as Card from '$lib/components/ui/card';
import * as Textarea from '$lib/components/ui/textarea';
import * as Table from '$lib/components/ui/table';
import * as Select from '$lib/components/ui/select';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
interface Props {
projectId: string;
}
let { projectId }: Props = $props();
// config inputs
let datasetsReady: Dataset[] = $state([]);
let busyDatasets = $state(true);
let cfgErr = $state<string | null>(null);
let datasetId = $state('');
let capital = $state<number>(1_000_000);
let commission = $state(0.0003);
let slippage = $state(0.001);
let benchmark = $state('');
let paramsText = $state('');
let acknowledged = $state(false);
// life cycle
let latest = $state<Run | null>(null);
let latestErr = $state<string | null>(null);
let cancelBusy = $state(false);
let rerunBusy = $state(false);
let actionMsg = $state<string | null>(null);
let history: Run[] = $state([]);
let historyBusy = $state(false);
let historyErr = $state<string | null>(null);
$effect(() => {
void loadDatasets();
void loadLatest(true);
return () => {
if (pollTimer) clearInterval(pollTimer);
};
});
let pollTimer: ReturnType<typeof setInterval> | null = null;
function isLiveStatus(r: Run | null | undefined) {
return r?.status === 'queued' || r?.status === 'running';
}
async function loadDatasets() {
busyDatasets = true;
cfgErr = null;
try {
const { items } = await listDatasets();
datasetsReady = items.filter((d) => d.status === 'ready');
if (items.some((d) => d.status === 'pending' || d.status === 'running')) {
if (!waitTimer) {
waitTimer = setInterval(() => {
void loadDatasets();
}, 2500);
}
} else {
stopWait();
}
} catch (e) {
cfgErr = extractStatusMessage(e);
} finally {
busyDatasets = false;
}
}
let waitTimer: ReturnType<typeof setInterval> | null = null;
function stopWait() {
if (waitTimer) {
clearInterval(waitTimer);
waitTimer = null;
}
}
async function loadLatest(startPolling: boolean) {
latestErr = null;
try {
const res = await listRuns(projectId);
history = res.items;
latest = res.items[0] ?? null;
if (startPolling && isLiveStatus(latest) && !pollTimer) {
pollTimer = setInterval(() => void loadLatest(false), 2000);
}
if (!isLiveStatus(latest) && pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
await refreshHistory();
}
} catch (e) {
latestErr = extractStatusMessage(e);
}
}
async function refreshHistory() {
historyBusy = true;
historyErr = null;
try {
const res = await listRuns(projectId);
history = res.items;
} catch (e) {
historyErr = extractStatusMessage(e);
} finally {
historyBusy = false;
}
}
async function previewWarningsForDataset(id: string) {
try {
const preview = await getDatasetPreview(id);
const cov = summarizeCoverage(preview.coverage ?? []);
datasetWarnMsgs = [...cov.warnings, ...(preview.warnings ?? [])];
} catch {
datasetWarnMsgs = [];
}
acknowledged = false;
}
let datasetWarnMsgs: string[] = $state([]);
const selectedDataset = $derived(datasetsReady.find((d) => d.id === datasetId) ?? null);
const needAck = $derived(datasetWarnMsgs.length > 0);
$effect(() => {
if (datasetId) void previewWarningsForDataset(datasetId);
});
async function startRun() {
const errs: string[] = [];
if (!datasetId) errs.push('请选择一个就绪的数据集');
if (!(capital > 0) || !Number.isFinite(capital)) errs.push('起始资金必须是正数');
if (!(commission >= 0 && commission < 0.1)) errs.push('佣金率应在 0 与 0.1 之间');
if (!(slippage >= 0 && slippage < 0.1)) errs.push('滑点应在 0 与 0.1 之间');
let parameters: Record<string, unknown> | undefined;
if (paramsText.trim()) {
try {
parameters = JSON.parse(paramsText);
} catch {
errs.push('参数必须是合法 JSON');
}
}
if (errs.length > 0) {
cfgErr = errs.join(';');
return;
}
cfgErr = null;
if (needAck && !acknowledged) {
cfgErr = '数据覆盖有差异,请先勾选确认已知晓后再启动回测';
return;
}
try {
const run = await createRun({
project_id: projectId,
dataset_id: datasetId,
capital,
commission,
slippage,
benchmark_symbol: benchmark.trim() || undefined,
parameters,
acknowledge_warnings: acknowledged
});
latest = run;
await loadLatest(true);
actionMsg = `回测已提交,编号 ${run.id.slice(0, 8)}…`;
void refreshHistory();
} catch (e) {
cfgErr = extractStatusMessage(e);
const details = (e as { details?: { errors?: string[] } }).details?.errors;
if (details) cfgErr = details.join(';');
}
}
async function onCancel() {
if (!latest) return;
cancelBusy = true;
try {
latest = await cancelRun(latest.id);
actionMsg = '已请求取消';
} catch (e) {
actionMsg = extractStatusMessage(e);
} finally {
cancelBusy = false;
}
}
async function onRerun() {
if (!latest) return;
rerunBusy = true;
try {
const run = await rerunRun(latest.id, true);
latest = run;
await loadLatest(true);
actionMsg = `已用原始代码与数据重新提交,编号 ${run.id.slice(0, 8)}…`;
} catch (e) {
actionMsg = extractStatusMessage(e);
} finally {
rerunBusy = false;
}
}
const canCancel = $derived(isLiveStatus(latest));
const canRerun = $derived(latest?.status === 'succeeded' || latest?.status === 'failed' || latest?.status === 'cancelled');
</script>
<div class="flex flex-col gap-4 md:gap-6">
<Card.Root size="sm" class="p-4 flex flex-col gap-4">
<div class="flex justify-between items-center gap-4">
<h2 class="text-lg font-semibold m-0">发起回测</h2>
<Button class="w-fit" onclick={startRun} disabled={!datasetId}>开始回测</Button>
</div>
{#if busyDatasets}
<Status busy skeletonRows={3} busyText="检查就绪的数据集…" empty={null} />
{:else if cfgErr}
<Status busy={false} error={cfgErr} empty={null}/>
{/if}
{#if !busyDatasets && datasetsReady.length === 0 && !cfgErr}
<Status busy={false} empty="没有就绪的数据集" emptyHint="先在「数据」标签创建并等待数据集状态变为【就绪】,再回到这里发起回测">
{#snippet emptyCta()}
<Button onclick={() => go(`/projects/${projectId}/data`)}>去接入数据</Button>
{/snippet}
</Status>
{/if}
{#if datasetsReady.length > 0}
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<div>
<Label for="bt-dataset">数据集</Label>
<Select.Root
type="single"
value={datasetId}
onValueChange={(v) => (datasetId = v)}
>
<Select.Trigger data-testid="dataset-select" id="bt-dataset" class="w-full">
{datasetId
? (() => {
const d = datasetsReady.find((x) => x.id === datasetId);
return d ? `${d.name ?? d.id.slice(0, 8)} · ${d.request.start_date}~${d.request.end_date}` : '选择数据集…';
})()
: '选择数据集…'}
</Select.Trigger>
<Select.Content>
{#each datasetsReady as d (d.id)}
<Select.Item value={d.id}>
{d.name ?? d.id.slice(0, 8)} · {d.request.start_date}~{d.request.end_date} · {d.request.instruments.map((i) => i.symbol).join(',')}
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
<div>
<Label for="bt-capital">起始资金</Label>
<Input id="bt-capital" class="tabular-nums" type="number" bind:value={capital} min="1" step="1000" />
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<Label for="bt-commission">佣金率</Label>
<Input id="bt-commission" class="tabular-nums" type="number" bind:value={commission} min="0" max="0.1" step="0.0001" />
</div>
<div>
<Label for="bt-slippage">滑点率</Label>
<Input id="bt-slippage" class="tabular-nums" type="number" bind:value={slippage} min="0" max="0.1" step="0.0001" />
</div>
</div>
<div>
<Label for="bt-benchmark">基准代码(可选)</Label>
<Input id="bt-benchmark" bind:value={benchmark} placeholder="例如 000300.SH 指数代码" />
</div>
<div class="sm:col-span-2 lg:col-span-3">
<Label for="bt-params">策略参数(JSON,可选)</Label>
<Textarea.Root id="bt-params" class="w-full" rows={1} bind:value={paramsText} placeholder="输入 JSON 参数,例如 fast/slow 周期" />
</div>
</div>
{#if needAck}
<Alert variant="default">
<span aria-hidden="true">⚠</span>
<div>
该数据集存在覆盖/预警信息,需要明确知晓后才能启动:
<ul class="list-disc pl-5 mt-1">
{#each datasetWarnMsgs as m, i (i)}<li>{m}</li>{/each}
</ul>
<label class="inline-flex items-center gap-4 mt-1">
<input type="checkbox" bind:checked={acknowledged} />
我已知晓并用当前数据继续
</label>
</div>
</Alert>
{/if}
<div class="flex items-center gap-4 flex-wrap">
{#if selectedDataset}
<span class="text-xs text-muted-foreground">本次回测与该数据集、当前策略快照一同记录,可按原始条件重跑</span>
{/if}
</div>
{#if cfgErr}
<Status busy={false} error={cfgErr} empty={null} />
{:else if actionMsg}
<Status busy={false} empty={actionMsg} />
{/if}
{/if}
</Card.Root>
<Card.Root size="sm" class="p-4 flex flex-col gap-4">
<div class="flex flex-wrap justify-between items-center gap-4">
<h2 class="text-lg font-semibold m-0">最近一次回测</h2>
{#if latest}
<span class="flex items-center gap-4">
<Badge variant="outline">Run 分支 {latest.version_id?.slice(0,8) ?? '—'}</Badge>
<Badge variant={runStatusBadge[latest.status] === 'ok' ? 'secondary' : runStatusBadge[latest.status] === 'warn' ? 'outline' : 'destructive'}>{runStatusLabel[latest.status]}</Badge>
</span>
{/if}
</div>
{#if latest}
<Status
busy={isLiveStatus(latest)}
busyText="排队/执行中,页面会自动刷新状态…"
empty={null}
error={latestErr}
/>
<div class="overflow-x-auto">
<Table.Root>
<Table.Body>
<Table.Row><Table.Head>启动时间</Table.Head><Table.Cell>{fmtDateTime(latest.created_at)}</Table.Cell></Table.Row>
{#if latest.started_at}<Table.Row><Table.Head>开始执行</Table.Head><Table.Cell>{fmtDateTime(latest.started_at)}</Table.Cell></Table.Row>{/if}
{#if latest.finished_at}<Table.Row><Table.Head>结束时间</Table.Head><Table.Cell>{fmtDateTime(latest.finished_at)}</Table.Cell></Table.Row>{/if}
<Table.Row><Table.Head>代码版本</Table.Head><Table.Cell><span class="tabular-nums">{latest.version_id.slice(0, 10)}</span></Table.Cell></Table.Row>
<Table.Row><Table.Head>数据集</Table.Head><Table.Cell><span class="tabular-nums">{latest.dataset_id?.slice(0, 8)}…</span></Table.Cell></Table.Row>
<Table.Row><Table.Head>资金</Table.Head><Table.Cell>{formatMoney(latest.config.capital)} · 佣金 {fmtPct(latest.config.commission, 4)} · 滑点 {fmtPct(latest.config.slippage, 4)}</Table.Cell></Table.Row>
</Table.Body>
</Table.Root>
</div>
{#if latest.error}
<Alert variant="destructive"><span aria-hidden="true">✕</span><span>{latest.error}</span></Alert>
{/if}
{#if latest.result?.warnings?.length}
<Alert variant="default">
<span aria-hidden="true">⚠</span>
<ul class="list-disc pl-5 mt-0.5">
{#each latest.result.warnings as w, i (i)}<li>{w}</li>{/each}
</ul>
</Alert>
{/if}
{#if latest.status === 'succeeded' && latest.result}
<Button variant="outline" href={`#/projects/${projectId}/results?run=${latest.id}`} class="w-fit">查看完整结果与图表</Button>
{/if}
<div class="flex items-center gap-4 flex-wrap">
{#if canCancel}
<Button variant="destructive" onclick={onCancel} disabled={cancelBusy}>
{cancelBusy ? '取消中…' : '取消回测'}
</Button>
{/if}
{#if canRerun}
<Button variant="outline" onclick={onRerun} disabled={rerunBusy}>
{rerunBusy ? '重新提交…' : '按原始代码&数据重跑'}
</Button>
{/if}
</div>
{:else}
<Status busy={false} empty="项目还没有回测记录" emptyHint="在上方选择数据集并启动一次回测" />
{/if}
</Card.Root>
<div class="flex flex-col gap-4">
<h2 class="text-lg font-semibold">回测历史</h2>
<Status busy={historyBusy} error={historyErr} busyText="载入历史…" empty={null} />
{#if history && history.length > 0}
<Card.Root size="sm">
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head>启动时间</Table.Head>
<Table.Head>状态</Table.Head>
<Table.Head>资金/佣金/滑点</Table.Head>
<Table.Head>数据集</Table.Head>
<Table.Head>结果</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each history as h (h.id)}
<Table.Row>
<Table.Cell>{fmtDateTime(h.created_at)}</Table.Cell>
<Table.Cell>{h.status === 'succeeded' ? '完成' : h.status === 'failed' ? '失败' : h.status === 'running' ? '执行中' : h.status === 'cancelled' ? '已取消' : '排队中'}</Table.Cell>
<Table.Cell>{formatMoney(h.config.capital)} · {fmtPct(h.config.commission, 4)} / {fmtPct(h.config.slippage, 4)}</Table.Cell>
<Table.Cell class="tabular-nums">{h.dataset_id?.slice(0, 8)}…</Table.Cell>
<Table.Cell>
<Button variant="outline" size="sm" href={`#/projects/${projectId}/results?run=${h.id}`}>结果</Button>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
</Card.Root>
{/if}
</div>
</div>
|