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
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue