stock-bot/apps/stock/web-app/src/features/experiments/components/WalkForwardPreflight.tsx

360 lines
12 KiB
TypeScript

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,
candidate,
disabled,
eligible,
onDirty,
claimSubmission,
releaseSubmission,
}: {
backtestId: string;
name: string;
grid: string;
candidate?: WalkForwardSubmission['candidate'];
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,
candidate,
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),
...(candidate ? { candidate } : {}),
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>
);
}