feat(research): add durable walk-forward validation workflows
This commit is contained in:
parent
abd1c5b83d
commit
3ed7b98f7c
45 changed files with 5188 additions and 199 deletions
|
|
@ -5,6 +5,7 @@ import { Button } from '@/components/ui/Button';
|
|||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentEditor } from './components/ExperimentEditor';
|
||||
import { SavedChronologicalValidations } from './components/SavedChronologicalValidations';
|
||||
import { SavedWalkForwards } from './components/SavedWalkForwards';
|
||||
import { experimentApi } from './services/experimentApi';
|
||||
|
||||
export function ExperimentListPage() {
|
||||
|
|
@ -73,6 +74,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
</div>
|
||||
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
|
||||
<SavedChronologicalValidations backtestId={backtestId} />
|
||||
<SavedWalkForwards backtestId={backtestId} />
|
||||
<section aria-label="Saved experiments" className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved experiments</h2>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,383 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ValidationEvidence } from './components/ValidationEvidence';
|
||||
import {
|
||||
walkForwardApi,
|
||||
WalkForwardApiError,
|
||||
type WalkForwardDetailView,
|
||||
} from './services/walkForwardApi';
|
||||
|
||||
export function WalkForwardDetailPage() {
|
||||
const { walkForwardId = '' } = useParams<{ walkForwardId: string }>();
|
||||
return <WalkForwardDetail key={walkForwardId} walkForwardId={walkForwardId} />;
|
||||
}
|
||||
type Intent = { id: string; body: { previewHash: string }; key: string };
|
||||
function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
reading = useRef(true),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null),
|
||||
captured = useRef<Intent | null>(null);
|
||||
const [value, setValue] = useState<WalkForwardDetailView | null>(null),
|
||||
[intent, setIntent] = useState<Intent | null>(null),
|
||||
[receipt, setReceipt] = useState<WalkForwardReceipt | null>(null);
|
||||
const [loading, setLoading] = useState(true),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reload, setReload] = useState(0),
|
||||
[readError, setReadError] = useState(''),
|
||||
[actionError, setActionError] = useState(''),
|
||||
[ambiguous, setAmbiguous] = useState(false);
|
||||
useUnsavedWarning(Boolean(intent));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (pending.current) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
const revision = ++generation.current,
|
||||
controller = new AbortController();
|
||||
read.current = controller;
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setReadError('');
|
||||
void walkForwardApi
|
||||
.get(walkForwardId, controller.signal)
|
||||
.then(result => {
|
||||
if (current && revision === generation.current) {
|
||||
setValue(result);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current && revision === generation.current) {
|
||||
setReadError(
|
||||
cause instanceof Error ? cause.message : 'Could not load walk-forward validation'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current && revision === generation.current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [walkForwardId, reload]);
|
||||
const begin = () => {
|
||||
if (pending.current || reading.current) {
|
||||
return false;
|
||||
}
|
||||
pending.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
return true;
|
||||
};
|
||||
const finish = () => {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const finalize = async () => {
|
||||
if (pending.current || reading.current || !value) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (!value.actions.finalize.available) {
|
||||
return;
|
||||
}
|
||||
captured.current = {
|
||||
id: walkForwardId,
|
||||
body: { previewHash: value.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
};
|
||||
setIntent(captured.current);
|
||||
setReceipt(null);
|
||||
}
|
||||
const original = captured.current;
|
||||
if (!begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await walkForwardApi.finalize(original.id, original.body, original.key);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setReceipt(result.receipt);
|
||||
setValue(result.walkForward);
|
||||
setAmbiguous(false);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
cause instanceof Error ? cause.message : 'Could not save walk-forward report'
|
||||
);
|
||||
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const cancel = async () => {
|
||||
if (!value || !begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await walkForwardApi.cancel(walkForwardId);
|
||||
if (alive.current) {
|
||||
setValue(result);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
`${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
pending.current ||
|
||||
!window.confirm(
|
||||
'Discard this report request? It may already have succeeded. Refresh the saved walk-forward validation before preparing another action.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setActionError('');
|
||||
setAmbiguous(false);
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className="h-full overflow-auto p-1 space-y-4"
|
||||
onClickCapture={event => {
|
||||
if (
|
||||
(event.target as HTMLElement).closest('a') &&
|
||||
captured.current &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!window.confirm(
|
||||
'Leave this unconfirmed walk-forward report request? Its exact body and key will be discarded. You can inspect evidence in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Link to="/experiments" className="text-primary-500 text-sm">
|
||||
All experiments
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-lg font-bold">{value?.name ?? 'Walk-forward validation'}</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || busy}
|
||||
onClick={() => {
|
||||
if (!pending.current && !reading.current) {
|
||||
reading.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setReload(current => current + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Refresh walk-forward
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading walk-forward validation...</p>}
|
||||
{readError && (
|
||||
<p role="alert" className="text-error">
|
||||
{readError}
|
||||
{value && ' Showing the last loaded state.'}
|
||||
</p>
|
||||
)}
|
||||
{actionError && (
|
||||
<p role="alert" className="text-error">
|
||||
{actionError}
|
||||
</p>
|
||||
)}
|
||||
{intent && (
|
||||
<div className="space-y-2">
|
||||
<p role="status">
|
||||
{ambiguous ? 'Report acceptance is unconfirmed. ' : ''}This request retains its exact
|
||||
walk-forward identity, preview and key.
|
||||
</p>
|
||||
<Button disabled={busy || loading} onClick={() => void finalize()}>
|
||||
Retry walk-forward report request
|
||||
</Button>{' '}
|
||||
<Button variant="outline" disabled={busy} onClick={discard}>
|
||||
Discard walk-forward report request
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{receipt && (
|
||||
<p role="status">
|
||||
Walk-forward report accepted. Receipt {receipt.id} · {receipt.createdAt}
|
||||
</p>
|
||||
)}
|
||||
{value && (
|
||||
<>
|
||||
<p className="font-semibold">
|
||||
{value.report
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
: 'Window validations admitted · walk-forward report not yet saved'}
|
||||
</p>
|
||||
<p>
|
||||
{value.reportedWindowCount}/{value.windowCount} window reports saved ·{' '}
|
||||
{value.trainingRunCount} training runs · {value.plannedRunCount} total planned runs,
|
||||
including future holdouts.
|
||||
</p>
|
||||
<p>
|
||||
Each phase and window resets initial capital and positions. These are ordered
|
||||
independent reset segments, not a continuous portfolio equity curve. No returns are
|
||||
compounded and no window metrics are averaged.
|
||||
</p>
|
||||
{value.cancelRequested && (
|
||||
<p>
|
||||
Cancellation requested for all windows. Completed evidence remains retained; active
|
||||
work may still finish.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!intent && !value.report && (
|
||||
<Button
|
||||
disabled={loading || busy || !value.actions.finalize.available}
|
||||
onClick={() => void finalize()}
|
||||
>
|
||||
Save walk-forward report
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={loading || busy || value.cancelRequested}
|
||||
onClick={() => void cancel()}
|
||||
>
|
||||
Cancel remaining walk-forward work
|
||||
</Button>
|
||||
</div>
|
||||
{!value.report && value.actions.finalize.reason && <p>{value.actions.finalize.reason}</p>}
|
||||
<section aria-label="Walk-forward windows" className="space-y-3">
|
||||
<h2 className="font-semibold">Window progress and evidence</h2>
|
||||
{value.windows.map(member => (
|
||||
<article key={member.index} className="rounded border border-border p-3 space-y-2">
|
||||
<h3 className="font-medium">Window {member.index + 1}</h3>
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/experiments/validation/${encodeURIComponent(member.validationId)}`}
|
||||
>
|
||||
Open window {member.index + 1} validation
|
||||
</Link>
|
||||
{member.status === 'missing' ? (
|
||||
<p role="alert">
|
||||
Window {member.index + 1} validation is missing. Its outcome has not been
|
||||
omitted.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{member.validation?.report
|
||||
? 'Window report saved'
|
||||
: member.validation?.selection
|
||||
? 'Fixed winner selected · validation and test admitted'
|
||||
: 'Training candidates admitted · selection not yet frozen'}
|
||||
</p>
|
||||
{member.validation?.cancelRequested && (
|
||||
<p>Cancellation requested for this window.</p>
|
||||
)}
|
||||
{member.validation?.phases.map(phase => (
|
||||
<div key={phase.phase}>
|
||||
<p>
|
||||
{phase.phase}:{' '}
|
||||
{phase.status === 'not-admitted'
|
||||
? 'Not admitted'
|
||||
: phase.status === 'missing'
|
||||
? 'Experiment missing'
|
||||
: phase.experiment
|
||||
? `${phase.experiment.counts.completed} completed, ${phase.experiment.counts.failed} failed, ${phase.experiment.counts.cancelled} cancelled, ${phase.experiment.counts.pending} pending, ${phase.experiment.counts.running} running, ${phase.experiment.counts.paused} paused`
|
||||
: 'Unavailable'}
|
||||
</p>
|
||||
{phase.experiment &&
|
||||
phase.experiment.trials
|
||||
.filter(
|
||||
trial =>
|
||||
trial.status === 'missing' ||
|
||||
trial.error ||
|
||||
(trial.status === 'completed' && !trial.comparable)
|
||||
)
|
||||
.map(trial => (
|
||||
<p key={trial.index}>
|
||||
Candidate {trial.index + 1}: {trial.status};{' '}
|
||||
{trial.error ?? trial.diagnostic ?? 'Evidence unavailable'}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Frozen walk-forward inputs</summary>
|
||||
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(value.preview, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
{value.report && (
|
||||
<section aria-label="Saved walk-forward report" className="space-y-3">
|
||||
<h2 className="font-semibold">Saved walk-forward report</h2>
|
||||
<p className="break-all">
|
||||
Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}
|
||||
</p>
|
||||
{value.report.limitations.map((limitation, index) => (
|
||||
<p key={index}>{limitation}</p>
|
||||
))}
|
||||
{value.report.segments.map(segment => (
|
||||
<section key={segment.index} className="space-y-2">
|
||||
<h3 className="font-medium">Window {segment.index + 1} reset segment</h3>
|
||||
<p className="break-all">
|
||||
Window report {segment.reportId} · {segment.reportHash}
|
||||
</p>
|
||||
<p className="break-all">Selection {segment.selectionHash}</p>
|
||||
<ValidationEvidence
|
||||
title={`Window ${segment.index + 1} validation and test evidence`}
|
||||
items={[segment.validation, segment.test]}
|
||||
backtestId={value.backtestId}
|
||||
/>
|
||||
</section>
|
||||
))}
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained walk-forward report</summary>
|
||||
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(value.report, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -15,38 +15,15 @@ import {
|
|||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
} from '../services/chronologicalValidationDurableApi';
|
||||
import {
|
||||
emptyValidationWindows,
|
||||
parseValidationWindows,
|
||||
ValidationWindowFields,
|
||||
validationWindowsDirty,
|
||||
type ValidationWindows,
|
||||
} from './ValidationWindowFields';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
const labels = {
|
||||
warmupStart: 'warmup start',
|
||||
tradeStart: 'trading start',
|
||||
tradeEnd: 'trading end',
|
||||
};
|
||||
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
||||
type Windows = Record<ValidationPhase, Record<(typeof fields)[number], string>>;
|
||||
const empty = (): Windows => ({
|
||||
train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
});
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
function parseInstant(raw: string, label: string) {
|
||||
const text = raw.trim();
|
||||
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text);
|
||||
const value = Date.parse(text);
|
||||
if (
|
||||
!match ||
|
||||
!Number.isFinite(value) ||
|
||||
new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
|
|
@ -84,7 +61,7 @@ export function ChronologicalValidationPreflight({
|
|||
const [submittingTraining, setSubmittingTraining] = useState(false);
|
||||
const [trainingError, setTrainingError] = useState('');
|
||||
const [trainingAmbiguous, setTrainingAmbiguous] = useState(false);
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
const [windows, setWindows] = useState<ValidationWindows>(emptyValidationWindows);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
|
|
@ -100,8 +77,7 @@ export function ChronologicalValidationPreflight({
|
|||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty =
|
||||
hasTrainingIntent || phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
const dirty = hasTrainingIntent || validationWindowsDirty(windows);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
|
|
@ -121,7 +97,7 @@ export function ChronologicalValidationPreflight({
|
|||
setLoading(false);
|
||||
setError('');
|
||||
}, [identity]);
|
||||
const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
|
||||
const edit = (phase: ValidationPhase, field: keyof ValidationWindows['train'], value: string) => {
|
||||
if (disabled || trainingIntent.current) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -143,24 +119,11 @@ export function ChronologicalValidationPreflight({
|
|||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const bounds = (phase: ValidationPhase) =>
|
||||
Object.fromEntries(
|
||||
fields.map(field => [
|
||||
field,
|
||||
parseInstant(windows[phase][field], `${phaseLabels[phase]} ${labels[field]} (UTC)`),
|
||||
])
|
||||
);
|
||||
const input = chronologicalValidationInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
recipe: {
|
||||
version: 1,
|
||||
train: bounds('train'),
|
||||
validation: bounds('validation'),
|
||||
test: bounds('test'),
|
||||
labelHorizonMs: 0,
|
||||
},
|
||||
recipe: parseValidationWindows(windows),
|
||||
});
|
||||
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
||||
if (
|
||||
|
|
@ -264,33 +227,14 @@ export function ChronologicalValidationPreflight({
|
|||
instants ending in Z; no local-time conversion or automatic date split is applied. Trading
|
||||
windows exclude their end instant. Warmup may overlap earlier phases.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">{phaseLabels[phase]} window</legend>
|
||||
{fields.map(field => (
|
||||
<label key={field} className="block text-xs">
|
||||
{phaseLabels[phase]} {labels[field]} (UTC)
|
||||
<input
|
||||
className={fieldClass}
|
||||
type="text"
|
||||
value={windows[phase][field]}
|
||||
placeholder="2024-01-01T09:00:00Z"
|
||||
onChange={event => edit(phase, field, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
<ValidationWindowFields
|
||||
windows={windows}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
onChange={edit}
|
||||
/>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the ordinary sweep submission before preparing chronological
|
||||
inputs.
|
||||
Resolve or explicitly release the other submission before preparing chronological inputs.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
} from '../services/experimentApi';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import { WalkForwardPreflight } from './WalkForwardPreflight';
|
||||
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
|
|
@ -49,15 +50,17 @@ export function ExperimentEditor({
|
|||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | null>(null);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner === 'chronological') {
|
||||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
|
|
@ -65,7 +68,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
|
|
@ -87,9 +90,11 @@ export function ExperimentEditor({
|
|||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [validationDirty, setValidationDirty] = useState(false);
|
||||
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
|
||||
const dirty =
|
||||
hasIntent ||
|
||||
validationDirty ||
|
||||
walkForwardDirty ||
|
||||
Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
|
|
@ -349,7 +354,7 @@ export function ExperimentEditor({
|
|||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={submitting || lockedBy === 'chronological'}
|
||||
disabled={submitting || (lockedBy !== null && lockedBy !== 'ordinary')}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
|
|
@ -369,12 +374,22 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy === 'ordinary'}
|
||||
disabled={lockedBy !== null && lockedBy !== 'chronological'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'walk-forward'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { WalkForwardSummary } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { walkForwardApi } from '../services/walkForwardApi';
|
||||
|
||||
export function SavedWalkForwards({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<WalkForwardSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void walkForwardApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(
|
||||
cause instanceof Error ? cause.message : 'Could not load walk-forward validations'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<section aria-label="Saved walk-forward validations" className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved walk-forward validations</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh walk-forward validations
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading walk-forward validations...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No saved walk-forward validations.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-1">
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/walk-forward/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{item.stage === 'reported'
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
: 'Window validations admitted'}{' '}
|
||||
· {item.reportedWindowCount}/{item.windowCount} window reports saved ·{' '}
|
||||
{item.trainingRunCount} training runs · {item.plannedRunCount} planned runs
|
||||
</p>
|
||||
{item.cancelRequested && <p className="text-sm">Cancellation requested</p>}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import type {
|
||||
ChronologicalValidationInput,
|
||||
ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
const labels = {
|
||||
warmupStart: 'warmup start',
|
||||
tradeStart: 'trading start',
|
||||
tradeEnd: 'trading end',
|
||||
};
|
||||
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
||||
export type ValidationWindows = Record<ValidationPhase, Record<(typeof fields)[number], string>>;
|
||||
export const emptyValidationWindows = (): ValidationWindows => ({
|
||||
train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
});
|
||||
export const validationWindowsDirty = (windows: ValidationWindows) =>
|
||||
phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
function parseInstant(raw: string, label: string) {
|
||||
const text = raw.trim(),
|
||||
match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text),
|
||||
value = Date.parse(text);
|
||||
if (
|
||||
!match ||
|
||||
!Number.isFinite(value) ||
|
||||
new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export function parseValidationWindows(
|
||||
windows: ValidationWindows,
|
||||
prefix = ''
|
||||
): ChronologicalValidationInput['recipe'] {
|
||||
const bounds = (phase: ValidationPhase) => ({
|
||||
warmupStart: parseInstant(
|
||||
windows[phase].warmupStart,
|
||||
`${prefix}${phaseLabels[phase]} warmup start (UTC)`
|
||||
),
|
||||
tradeStart: parseInstant(
|
||||
windows[phase].tradeStart,
|
||||
`${prefix}${phaseLabels[phase]} trading start (UTC)`
|
||||
),
|
||||
tradeEnd: parseInstant(
|
||||
windows[phase].tradeEnd,
|
||||
`${prefix}${phaseLabels[phase]} trading end (UTC)`
|
||||
),
|
||||
});
|
||||
return {
|
||||
version: 1,
|
||||
train: bounds('train'),
|
||||
validation: bounds('validation'),
|
||||
test: bounds('test'),
|
||||
labelHorizonMs: 0,
|
||||
};
|
||||
}
|
||||
export function ValidationWindowFields({
|
||||
windows,
|
||||
disabled,
|
||||
prefix = '',
|
||||
onChange,
|
||||
}: {
|
||||
windows: ValidationWindows;
|
||||
disabled: boolean;
|
||||
prefix?: string;
|
||||
onChange: (phase: ValidationPhase, field: (typeof fields)[number], value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">
|
||||
{prefix}
|
||||
{phaseLabels[phase]} window
|
||||
</legend>
|
||||
{fields.map(field => (
|
||||
<label key={field} className="block text-xs">
|
||||
{prefix}
|
||||
{phaseLabels[phase]} {labels[field]} (UTC)
|
||||
<input
|
||||
className="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60"
|
||||
type="text"
|
||||
value={windows[phase][field]}
|
||||
placeholder="2024-01-01T09:00:00Z"
|
||||
onChange={event => onChange(phase, field, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,349 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
type WalkForwardSubmission,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import {
|
||||
walkForwardApi,
|
||||
WalkForwardApiError,
|
||||
type WalkForwardPreviewView,
|
||||
} from '../services/walkForwardApi';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import {
|
||||
emptyValidationWindows,
|
||||
parseValidationWindows,
|
||||
ValidationWindowFields,
|
||||
validationWindowsDirty,
|
||||
type ValidationWindows,
|
||||
} from './ValidationWindowFields';
|
||||
|
||||
type Owner = 'ordinary' | 'chronological' | 'walk-forward';
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: 'Could not prepare walk-forward validation';
|
||||
export function WalkForwardPreflight({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (value: boolean) => void;
|
||||
claimSubmission: (owner: Owner) => boolean;
|
||||
releaseSubmission: (owner: Owner) => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const [windows, setWindows] = useState<ValidationWindows[]>(() => [
|
||||
emptyValidationWindows(),
|
||||
emptyValidationWindows(),
|
||||
]);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
preview: WalkForwardPreviewView;
|
||||
} | null>(null);
|
||||
const [hasIntent, setHasIntent] = useState(false),
|
||||
[loading, setLoading] = useState(false),
|
||||
[submitting, setSubmitting] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[ambiguous, setAmbiguous] = useState(false);
|
||||
const captured = useRef<{
|
||||
body: WalkForwardSubmission;
|
||||
key: string;
|
||||
preview: WalkForwardPreviewView;
|
||||
} | null>(null);
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
posting = useRef(false),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }),
|
||||
currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
captured.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty = hasIntent || windows.length !== 2 || windows.some(validationWindowsDirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
pending.current = false;
|
||||
setPrepared(null);
|
||||
setLoading(false);
|
||||
if (!captured.current) {
|
||||
setError('');
|
||||
}
|
||||
}, [identity]);
|
||||
const edit = (change: (current: ValidationWindows[]) => ValidationWindows[]) => {
|
||||
if (disabled || captured.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setWindows(change);
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !eligible || captured.current || pending.current) {
|
||||
return;
|
||||
}
|
||||
const revision = ++generation.current,
|
||||
original = identity,
|
||||
controller = new AbortController();
|
||||
read.current?.abort();
|
||||
read.current = controller;
|
||||
pending.current = true;
|
||||
setPrepared(null);
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const input = walkForwardInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
windows: windows.map((window, index) =>
|
||||
parseValidationWindows(window, `Window ${index + 1} `)
|
||||
),
|
||||
});
|
||||
const value = await walkForwardApi.preview(input, controller.signal);
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
setPrepared({ identity: original, preview: value });
|
||||
}
|
||||
} catch (cause) {
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
pending.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (
|
||||
posting.current ||
|
||||
pending.current ||
|
||||
(!captured.current && (!preview || disabled || !eligible)) ||
|
||||
!claimSubmission('walk-forward')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
captured.current = {
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
preview,
|
||||
};
|
||||
}
|
||||
const original = captured.current;
|
||||
posting.current = true;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await walkForwardApi.submit(original.body, original.key);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('walk-forward');
|
||||
navigate(`/experiments/walk-forward/${encodeURIComponent(value.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
posting.current = false;
|
||||
if (alive.current) {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
posting.current ||
|
||||
!window.confirm(
|
||||
'Discard this walk-forward submission? It may already exist. Inspect saved walk-forward validations before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setHasIntent(false);
|
||||
setPrepared(null);
|
||||
setError('');
|
||||
setAmbiguous(false);
|
||||
releaseSubmission('walk-forward');
|
||||
};
|
||||
return (
|
||||
<details className="border-t border-border pt-4 text-sm">
|
||||
<summary className="cursor-pointer font-semibold">Walk-forward validation</summary>
|
||||
<section aria-label="Walk-forward setup" className="space-y-3 pt-3">
|
||||
<p>
|
||||
Uses the saved backtest, name and parameter grid above. Enter explicit UTC instants ending
|
||||
in Z. Preview saves nothing; submission freezes all windows and admits training together.
|
||||
Each window selects independently from training, with separate validation and test runs.
|
||||
</p>
|
||||
<p>
|
||||
Every phase resets initial capital and positions. Warmup may overlap earlier windows;
|
||||
held-out trading windows cannot overlap. Up to {MAX_WALK_FORWARD_WINDOWS} windows and{' '}
|
||||
{MAX_WALK_FORWARD_RUNS} total planned runs, including both future holdouts per window.
|
||||
</p>
|
||||
{windows.map((window, index) => (
|
||||
<section
|
||||
key={index}
|
||||
aria-label={`Walk-forward window ${index + 1}`}
|
||||
className="space-y-2"
|
||||
>
|
||||
<h4 className="font-medium">Window {index + 1}</h4>
|
||||
<ValidationWindowFields
|
||||
windows={window}
|
||||
prefix={`Window ${index + 1} `}
|
||||
disabled={disabled || hasIntent}
|
||||
onChange={(phase, field, value) =>
|
||||
edit(current =>
|
||||
current.map((item, i) =>
|
||||
i === index ? { ...item, [phase]: { ...item[phase], [field]: value } } : item
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled || hasIntent || windows.length <= 2}
|
||||
onClick={() => edit(current => current.filter((_, i) => i !== index))}
|
||||
>
|
||||
Remove window {index + 1}
|
||||
</Button>
|
||||
</section>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || hasIntent || windows.length >= MAX_WALK_FORWARD_WINDOWS}
|
||||
onClick={() => edit(current => [...current, emptyValidationWindows()])}
|
||||
>
|
||||
Add walk-forward window
|
||||
</Button>{' '}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || hasIntent || !eligible || !name.trim() || loading}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview walk-forward
|
||||
</Button>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the other submission before preparing walk-forward inputs.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Preparing walk-forward inputs...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{preview && (
|
||||
<section aria-label="Prepared walk-forward inputs" className="space-y-3">
|
||||
<p className="font-medium">
|
||||
{preview.counts.windows} windows · {preview.counts.trainingRuns} training runs ·{' '}
|
||||
{preview.counts.holdoutRuns} future holdout runs · {preview.counts.totalRuns} total
|
||||
planned runs
|
||||
</p>
|
||||
<ExperimentInputs preview={preview.source} />
|
||||
{preview.windows.map(item => (
|
||||
<details key={item.index}>
|
||||
<summary className="cursor-pointer">
|
||||
Window {item.index + 1} prepared inputs
|
||||
</summary>
|
||||
<p className="break-all">Preview {item.preview.previewHash}</p>
|
||||
{item.preview.partitions.map(part => (
|
||||
<div key={part.phase} className="py-2">
|
||||
<p>
|
||||
{part.phase}: {new Date(part.dataset.bounds.tradeStart).toISOString()} to{' '}
|
||||
{new Date(part.dataset.bounds.tradeEnd).toISOString()} (end excluded)
|
||||
</p>
|
||||
<p>
|
||||
Warmup starts {new Date(part.dataset.bounds.warmupStart).toISOString()};
|
||||
admitted warmup {part.counts.admittedWarmup}, required {part.requiredWarmup};
|
||||
evaluation observations {part.counts.availableEvaluation}; terminal-at-end
|
||||
observations {part.counts.terminalAtEnd}; completed observations unavailable
|
||||
at end {part.counts.unavailableAtEnd}.
|
||||
</p>
|
||||
<p className="break-all">Dataset {part.dataset.hash}</p>
|
||||
{part.warnings.map((warning, index) => (
|
||||
<p key={index}>{warning}</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(item.preview, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
))}
|
||||
<p className="break-all">Walk-forward preview {preview.previewHash}</p>
|
||||
</section>
|
||||
)}
|
||||
{hasIntent && (
|
||||
<p role="status">
|
||||
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission retains its exact
|
||||
windows, inputs and key. Retry to recover the same walk-forward validation.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting || (disabled && !hasIntent)} onClick={() => void submit()}>
|
||||
{hasIntent ? 'Retry walk-forward submission' : 'Submit walk-forward training'}
|
||||
</Button>
|
||||
{hasIntent && (
|
||||
<Button variant="outline" disabled={submitting} onClick={discard}>
|
||||
Discard walk-forward submission
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
|
||||
export { WalkForwardDetailPage } from './WalkForwardDetailPage';
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ const summary = z.object({
|
|||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
const evidence = z.object({
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
|
|
@ -87,7 +87,7 @@ const selection = z.object({
|
|||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
|
|
@ -100,9 +100,9 @@ const report = z.object({
|
|||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
validation: evidence,
|
||||
test: evidence,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
|
|
@ -134,7 +134,7 @@ const invalid = () =>
|
|||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
function parseDetail(raw: unknown): ValidationDetailView {
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
|
|
@ -198,7 +198,7 @@ function parseDetail(raw: unknown): ValidationDetailView {
|
|||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof evidence>,
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
|
|
@ -330,7 +330,7 @@ export const chronologicalValidationDurableApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -338,7 +338,7 @@ export const chronologicalValidationDurableApi = {
|
|||
}),
|
||||
submit: (input: ChronologicalValidationSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
|
|
@ -353,7 +353,7 @@ export const chronologicalValidationDurableApi = {
|
|||
) =>
|
||||
request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => {
|
||||
const accepted = receipt.parse(envelope(body, 'receipt'));
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
const record = operation === 'select' ? value.selection : value.report;
|
||||
if (
|
||||
accepted.validationId !== id ||
|
||||
|
|
@ -378,7 +378,7 @@ export const chronologicalValidationDurableApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,426 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
type WalkForwardDetail,
|
||||
type WalkForwardFinalizationInput,
|
||||
type WalkForwardInput,
|
||||
type WalkForwardSubmission,
|
||||
type WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
parseValidationDetail,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from './chronologicalValidationDurableApi';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type WalkForwardPreviewView = {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreviewView;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
};
|
||||
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
||||
preview: WalkForwardPreviewView;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ValidationDetailView | null;
|
||||
}[];
|
||||
};
|
||||
export class WalkForwardApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new WalkForwardApiError(
|
||||
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
const prepared = z.object({
|
||||
version: z.literal('walk-forward-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: hash,
|
||||
input: walkForwardInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
windows: z
|
||||
.array(z.object({ index: count, preview: z.unknown() }))
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
counts: z.object({
|
||||
windows: count,
|
||||
trainingRuns: count,
|
||||
holdoutRuns: count,
|
||||
totalRuns: count,
|
||||
maxRuns: count,
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardPreview(
|
||||
raw: unknown,
|
||||
expected?: WalkForwardInput
|
||||
): WalkForwardPreviewView {
|
||||
const value = prepared.parse(raw),
|
||||
source = parseExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = value.input;
|
||||
const size = recipes.length,
|
||||
candidates = source.candidates.length;
|
||||
if (
|
||||
(expected && !same(value.input, expected)) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, walkForwardPolicy) ||
|
||||
value.windows.length !== size ||
|
||||
!same(value.counts, {
|
||||
windows: size,
|
||||
trainingRuns: size * candidates,
|
||||
holdoutRuns: size * 2,
|
||||
totalRuns: size * (candidates + 2),
|
||||
maxRuns: MAX_WALK_FORWARD_RUNS,
|
||||
}) ||
|
||||
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
const recipe = recipes[index],
|
||||
previous = recipes[index - 1];
|
||||
if (
|
||||
!recipe ||
|
||||
item.index !== index ||
|
||||
(previous &&
|
||||
(recipe.train.tradeStart < previous.train.tradeStart ||
|
||||
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
recipe.validation.tradeStart < previous.test.tradeEnd))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const name = `${value.input.name} · window ${index + 1}`;
|
||||
const preview = parseChronologicalValidationPreview(
|
||||
{ preview: item.preview },
|
||||
{ ...sourceInput, name, recipe }
|
||||
);
|
||||
const { previewHash: _windowHash, ...childSource } = preview.source;
|
||||
const { previewHash: _sourceHash, ...originalSource } = source;
|
||||
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
||||
throw invalid();
|
||||
}
|
||||
return { index, preview };
|
||||
});
|
||||
return { ...value, source, windows, policy: walkForwardPolicy };
|
||||
}
|
||||
const summary = z
|
||||
.object({
|
||||
id: uuid,
|
||||
backtestId: uuid,
|
||||
name: z.string().min(1),
|
||||
previewHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
||||
reportedWindowCount: count,
|
||||
trainingRunCount: count,
|
||||
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
||||
stage: z.enum(['windows', 'reported']),
|
||||
})
|
||||
.superRefine((item, context) => {
|
||||
if (
|
||||
item.reportedWindowCount > item.windowCount ||
|
||||
item.trainingRunCount < item.windowCount ||
|
||||
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Inconsistent walk-forward counts',
|
||||
});
|
||||
}
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('walk-forward-report/v1'),
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: z.enum(['operator', 'service']),
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
segments: z
|
||||
.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportId: uuid,
|
||||
reportHash: hash,
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = z.object({
|
||||
preview: z.unknown(),
|
||||
windows: z.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
status: z.enum(['admitted', 'missing']),
|
||||
validation: z.unknown(),
|
||||
})
|
||||
),
|
||||
report: report.nullable(),
|
||||
actions: z.object({
|
||||
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
||||
const base = summary.parse(raw),
|
||||
value = detail.parse(raw),
|
||||
preview = parseWalkForwardPreview(value.preview);
|
||||
if (
|
||||
base.backtestId !== preview.input.backtestId ||
|
||||
base.name !== preview.input.name ||
|
||||
base.previewHash !== preview.previewHash ||
|
||||
base.windowCount !== preview.counts.windows ||
|
||||
base.trainingRunCount !== preview.counts.trainingRuns ||
|
||||
base.plannedRunCount !== preview.counts.totalRuns ||
|
||||
value.windows.length !== base.windowCount ||
|
||||
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
||||
(base.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
||||
if (
|
||||
validation &&
|
||||
(validation.id !== item.validationId ||
|
||||
validation.backtestId !== base.backtestId ||
|
||||
!same(validation.preview, preview.windows[index]?.preview))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...item, validation };
|
||||
});
|
||||
if (
|
||||
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
||||
(value.actions.finalize.available &&
|
||||
(base.cancelRequested ||
|
||||
value.report ||
|
||||
windows.some(
|
||||
item =>
|
||||
!item.validation?.report ||
|
||||
item.validation.cancelRequested ||
|
||||
item.validation.phases.some(
|
||||
phase =>
|
||||
phase.status !== 'admitted' ||
|
||||
!phase.experiment ||
|
||||
phase.experiment.cancelRequested ||
|
||||
phase.experiment.trials.some(
|
||||
trial =>
|
||||
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
||||
)
|
||||
)
|
||||
)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
saved.walkForwardId !== base.id ||
|
||||
saved.previewHash !== base.previewHash ||
|
||||
saved.segments.length !== base.windowCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const [index, segment] of saved.segments.entries()) {
|
||||
const member = windows[index],
|
||||
frozen = preview.windows[index]?.preview,
|
||||
child = member?.validation?.report;
|
||||
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
||||
if (
|
||||
!member ||
|
||||
!frozen ||
|
||||
!candidate ||
|
||||
segment.index !== index ||
|
||||
segment.validationId !== member.validationId ||
|
||||
segment.previewHash !== frozen.previewHash ||
|
||||
segment.validation.phase !== 'validation' ||
|
||||
segment.test.phase !== 'test' ||
|
||||
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
||||
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
||||
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
||||
[segment.validation, segment.test].some(
|
||||
item =>
|
||||
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
||||
) ||
|
||||
(member.validation &&
|
||||
(!child ||
|
||||
segment.reportId !== child.id ||
|
||||
segment.reportHash !== child.reportHash ||
|
||||
segment.selectionHash !== child.selectionHash ||
|
||||
!same(segment.validation, child.validation) ||
|
||||
!same(segment.test, child.test)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, ...value, preview, windows };
|
||||
}
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new WalkForwardApiError(
|
||||
'The walk-forward response was lost. Retry the same request to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new WalkForwardApiError(
|
||||
error.success ? error.data.error : `Walk-forward request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== status) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
const post = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
});
|
||||
export const walkForwardApi = {
|
||||
preview: (input: WalkForwardInput, signal?: AbortSignal) =>
|
||||
request('/preview', { ...post(input), signal }, 200, body =>
|
||||
parseWalkForwardPreview(envelope(body, 'preview'), input)
|
||||
),
|
||||
list: (backtestId?: string, signal?: AbortSignal) =>
|
||||
request(
|
||||
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
|
||||
{ signal },
|
||||
200,
|
||||
body => {
|
||||
const rows = z.array(summary).parse(envelope(body, 'walkForwards'));
|
||||
if (
|
||||
new Set(rows.map(item => item.id)).size !== rows.length ||
|
||||
(backtestId && rows.some(item => item.backtestId !== backtestId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return rows as WalkForwardSummary[];
|
||||
}
|
||||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
submit: (input: WalkForwardSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
finalize: (id: string, input: WalkForwardFinalizationInput, key: string) =>
|
||||
request(`/${encodeURIComponent(id)}/finalize`, post(input, key), 202, body => {
|
||||
const accepted = z
|
||||
.object({
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
operation: z.literal('finalize-walk-forward-report'),
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: z.enum(['operator', 'service']),
|
||||
})
|
||||
.parse(envelope(body, 'receipt'));
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward')),
|
||||
saved = value.report;
|
||||
if (
|
||||
value.id !== id ||
|
||||
accepted.walkForwardId !== id ||
|
||||
value.previewHash !== input.previewHash ||
|
||||
accepted.previewHash !== input.previewHash ||
|
||||
!saved ||
|
||||
accepted.id !== saved.id ||
|
||||
accepted.reportHash !== saved.reportHash ||
|
||||
accepted.createdAt !== saved.createdAt ||
|
||||
accepted.principal !== saved.principal
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { receipt: accepted, walkForward: value };
|
||||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue