feat(research): run durable chronological validation and retain reports
This commit is contained in:
parent
67ab30cb7a
commit
abd1c5b83d
42 changed files with 5345 additions and 74 deletions
|
|
@ -1,7 +1,9 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
|
|
@ -9,6 +11,10 @@ import {
|
|||
chronologicalValidationApi,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '../services/chronologicalValidationApi';
|
||||
import {
|
||||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
} from '../services/chronologicalValidationDurableApi';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
|
|
@ -55,6 +61,8 @@ export function ChronologicalValidationPreflight({
|
|||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
|
|
@ -62,7 +70,20 @@ export function ChronologicalValidationPreflight({
|
|||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
claimSubmission: (owner: 'ordinary' | 'chronological') => boolean;
|
||||
releaseSubmission: (owner: 'ordinary' | 'chronological') => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const trainingIntent = useRef<{
|
||||
body: ChronologicalValidationSubmission;
|
||||
key: string;
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
} | null>(null);
|
||||
const trainingPending = useRef(false);
|
||||
const [hasTrainingIntent, setHasTrainingIntent] = useState(false);
|
||||
const [submittingTraining, setSubmittingTraining] = useState(false);
|
||||
const [trainingError, setTrainingError] = useState('');
|
||||
const [trainingAmbiguous, setTrainingAmbiguous] = useState(false);
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
|
|
@ -77,8 +98,10 @@ export function ChronologicalValidationPreflight({
|
|||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
|
||||
const currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview = prepared?.identity === identity ? prepared.preview : null;
|
||||
const dirty = phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
const preview =
|
||||
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty =
|
||||
hasTrainingIntent || phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
|
|
@ -99,7 +122,7 @@ export function ChronologicalValidationPreflight({
|
|||
setError('');
|
||||
}, [identity]);
|
||||
const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
|
||||
if (disabled) {
|
||||
if (disabled || trainingIntent.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
|
|
@ -107,7 +130,7 @@ export function ChronologicalValidationPreflight({
|
|||
setWindows(previous => ({ ...previous, [phase]: { ...previous[phase], [field]: value } }));
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !eligible || pending.current) {
|
||||
if (disabled || trainingIntent.current || !eligible || pending.current) {
|
||||
return;
|
||||
}
|
||||
const captured = identity;
|
||||
|
|
@ -166,6 +189,66 @@ export function ChronologicalValidationPreflight({
|
|||
}
|
||||
}
|
||||
};
|
||||
const submitTraining = async () => {
|
||||
if (
|
||||
trainingPending.current ||
|
||||
pending.current ||
|
||||
(!trainingIntent.current && (!preview || disabled || !eligible)) ||
|
||||
!claimSubmission('chronological')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!trainingIntent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
trainingIntent.current = {
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
preview,
|
||||
};
|
||||
}
|
||||
const captured = trainingIntent.current;
|
||||
trainingPending.current = true;
|
||||
setHasTrainingIntent(true);
|
||||
setSubmittingTraining(true);
|
||||
setTrainingError('');
|
||||
try {
|
||||
const accepted = await chronologicalValidationDurableApi.submit(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
trainingIntent.current = null;
|
||||
setHasTrainingIntent(false);
|
||||
releaseSubmission('chronological');
|
||||
navigate(`/experiments/validation/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setTrainingError(message(cause));
|
||||
setTrainingAmbiguous(!(cause instanceof ValidationApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
trainingPending.current = false;
|
||||
if (alive.current) {
|
||||
setSubmittingTraining(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const discardTraining = () => {
|
||||
if (
|
||||
trainingPending.current ||
|
||||
!window.confirm(
|
||||
'Discard this training submission? It may already exist. Inspect saved chronological validations before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
trainingIntent.current = null;
|
||||
setHasTrainingIntent(false);
|
||||
setTrainingError('');
|
||||
setTrainingAmbiguous(false);
|
||||
setPrepared(null);
|
||||
releaseSubmission('chronological');
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Chronological validation preflight"
|
||||
|
|
@ -173,8 +256,8 @@ export function ChronologicalValidationPreflight({
|
|||
>
|
||||
<h3 className="font-semibold text-text-primary">Chronological validation preflight</h3>
|
||||
<p>
|
||||
Preview only. No datasets, experiments or runs are saved. Staged execution and immutable
|
||||
reports are not available yet.
|
||||
Previewing does not save datasets, experiments or runs. Submit training runs explicitly to
|
||||
start a durable validation; selection and report finalization require separate actions.
|
||||
</p>
|
||||
<p className="text-text-secondary">
|
||||
Uses the saved backtest, experiment name and parameter grid above. Enter explicit UTC
|
||||
|
|
@ -185,7 +268,7 @@ export function ChronologicalValidationPreflight({
|
|||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">{phaseLabels[phase]} window</legend>
|
||||
|
|
@ -212,7 +295,7 @@ export function ChronologicalValidationPreflight({
|
|||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || !eligible || !name.trim() || loading}
|
||||
disabled={disabled || hasTrainingIntent || !eligible || !name.trim() || loading}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview chronological validation
|
||||
|
|
@ -223,6 +306,36 @@ export function ChronologicalValidationPreflight({
|
|||
{error}
|
||||
</p>
|
||||
)}
|
||||
{trainingError && (
|
||||
<p role="alert" className="text-error">
|
||||
{trainingError}
|
||||
</p>
|
||||
)}
|
||||
{hasTrainingIntent && (
|
||||
<p role="status">
|
||||
{trainingAmbiguous ? 'Training admission is unconfirmed. ' : ''}The exact training input
|
||||
and submission key are retained. Retry this submission to recover the same validation.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasTrainingIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={submittingTraining || (!hasTrainingIntent && (disabled || loading))}
|
||||
onClick={() => void submitTraining()}
|
||||
>
|
||||
{submittingTraining
|
||||
? 'Submitting training runs...'
|
||||
: hasTrainingIntent
|
||||
? 'Retry training submission'
|
||||
: 'Submit training runs'}
|
||||
</Button>
|
||||
{hasTrainingIntent && (
|
||||
<Button variant="outline" disabled={submittingTraining} onClick={discardTraining}>
|
||||
Discard training submission
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!preview && !loading && !error && (
|
||||
<p className="text-text-secondary">
|
||||
No chronological preview prepared for the current inputs.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
|
|
@ -49,6 +49,28 @@ 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') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner === 'chronological') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
}
|
||||
}, []);
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
|
|
@ -117,7 +139,7 @@ export function ExperimentEditor({
|
|||
}, [initialBacktestId, templateReload, limit]);
|
||||
|
||||
const invalidate = (change: () => void) => {
|
||||
if (intent.current) {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
|
|
@ -128,7 +150,7 @@ export function ExperimentEditor({
|
|||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (intent.current || previewLoading) {
|
||||
if (submissionOwner.current || previewLoading) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
|
|
@ -155,7 +177,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !preview)) {
|
||||
if (pending.current || (!intent.current && !preview) || !claimSubmission('ordinary')) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
|
|
@ -177,6 +199,7 @@ export function ExperimentEditor({
|
|||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
|
|
@ -202,6 +225,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
setPreview(null);
|
||||
setError('');
|
||||
|
|
@ -240,7 +264,7 @@ export function ExperimentEditor({
|
|||
<select
|
||||
className={fieldClass}
|
||||
value={backtestId}
|
||||
disabled={hasIntent || templateLoading}
|
||||
disabled={Boolean(lockedBy) || templateLoading}
|
||||
onChange={event => invalidate(() => setBacktestId(event.target.value))}
|
||||
>
|
||||
<option value="">Select a saved canonical backtest</option>
|
||||
|
|
@ -259,7 +283,7 @@ export function ExperimentEditor({
|
|||
<input
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
disabled={hasIntent}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setName(event.target.value))}
|
||||
/>
|
||||
</label>
|
||||
|
|
@ -268,7 +292,7 @@ export function ExperimentEditor({
|
|||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={templateLoading || hasIntent}
|
||||
disabled={templateLoading || Boolean(lockedBy)}
|
||||
onClick={() => setLimit(value => value + 50)}
|
||||
>
|
||||
Load more backtests
|
||||
|
|
@ -280,7 +304,7 @@ export function ExperimentEditor({
|
|||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
disabled={hasIntent}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
|
|
@ -299,7 +323,7 @@ export function ExperimentEditor({
|
|||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
hasIntent ||
|
||||
Boolean(lockedBy) ||
|
||||
previewLoading ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
|
|
@ -324,7 +348,10 @@ export function ExperimentEditor({
|
|||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting} onClick={() => void submit()}>
|
||||
<Button
|
||||
disabled={submitting || lockedBy === 'chronological'}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
? 'Submitting experiment...'
|
||||
: hasIntent
|
||||
|
|
@ -342,9 +369,11 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={hasIntent}
|
||||
disabled={lockedBy === 'ordinary'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,84 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { ChronologicalValidationSummary } from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { chronologicalValidationDurableApi } from '../services/chronologicalValidationDurableApi';
|
||||
|
||||
export function SavedChronologicalValidations({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<ChronologicalValidationSummary[]>([]);
|
||||
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 chronologicalValidationDurableApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(
|
||||
cause instanceof Error ? cause.message : 'Could not load chronological validations'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<section aria-label="Saved chronological validations" className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved chronological validations</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh chronological validations
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading chronological validations...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No saved chronological 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/validation/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{item.stage === 'reported'
|
||||
? 'Execution complete · report saved'
|
||||
: item.stage === 'holdouts'
|
||||
? 'Validation and test admitted'
|
||||
: 'Training candidates admitted'}{' '}
|
||||
· {item.trainingCandidateCount} training candidates
|
||||
</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,86 @@
|
|||
import { Link } from 'react-router-dom';
|
||||
import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation';
|
||||
|
||||
export function ValidationEvidence({
|
||||
title,
|
||||
items,
|
||||
backtestId,
|
||||
}: {
|
||||
title: string;
|
||||
items: ValidationResultEvidence[];
|
||||
backtestId: string;
|
||||
}) {
|
||||
const metric = (
|
||||
item: ValidationResultEvidence,
|
||||
key: keyof ValidationResultEvidence['metrics']
|
||||
) =>
|
||||
item.metrics[key] === null
|
||||
? `Unavailable${item.unavailable[key] ? `: ${item.unavailable[key]}` : ''}`
|
||||
: String(item.metrics[key]);
|
||||
return (
|
||||
<section aria-label={title} className="space-y-2">
|
||||
<h3 className="font-semibold">{title}</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Phase / source candidate',
|
||||
'Parameters',
|
||||
'Total return (fraction)',
|
||||
'Max drawdown (fraction)',
|
||||
'Sharpe ratio',
|
||||
'Samples / evidence',
|
||||
].map(label => (
|
||||
<th className="p-2 border-b border-border" key={label}>
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map(item => (
|
||||
<tr key={`${item.phase}:${item.runId}`} className="align-top">
|
||||
<td className="p-2 border-b border-border">
|
||||
{item.phase} · candidate {item.sourceCandidateIndex + 1}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(item.parameters, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'totalReturn')}</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'maxDrawdown')}</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'sharpeRatio')}</td>
|
||||
<td className="p-2 border-b border-border space-y-1 min-w-64">
|
||||
<p>
|
||||
Complete periods: {item.completePeriodCount} · Periodic samples:{' '}
|
||||
{item.periodicSampleCount} · Fills: {item.fillCount}
|
||||
</p>
|
||||
{item.periodicSampleCount < 2 && (
|
||||
<p>Insufficient periodic samples for variance-based statistics.</p>
|
||||
)}
|
||||
{item.limitations.map((value, index) => (
|
||||
<p key={index}>{value}</p>
|
||||
))}
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/backtests/${encodeURIComponent(backtestId)}/run/${encodeURIComponent(item.runId)}`}
|
||||
>
|
||||
Open {item.phase} candidate {item.sourceCandidateIndex + 1} run
|
||||
</Link>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained evidence</summary>
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(item, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue