443 lines
16 KiB
TypeScript
443 lines
16 KiB
TypeScript
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';
|
|
import {
|
|
chronologicalValidationApi,
|
|
type ChronologicalValidationPreviewView,
|
|
} from '../services/chronologicalValidationApi';
|
|
import {
|
|
chronologicalValidationDurableApi,
|
|
ValidationApiError,
|
|
} from '../services/chronologicalValidationDurableApi';
|
|
import {
|
|
emptyValidationWindows,
|
|
parseValidationWindows,
|
|
ValidationWindowFields,
|
|
validationWindowsDirty,
|
|
type ValidationWindows,
|
|
} from './ValidationWindowFields';
|
|
|
|
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
|
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 chronological validation inputs';
|
|
|
|
export function ChronologicalValidationPreflight({
|
|
backtestId,
|
|
name,
|
|
grid,
|
|
candidate,
|
|
disabled,
|
|
eligible,
|
|
onDirty,
|
|
claimSubmission,
|
|
releaseSubmission,
|
|
}: {
|
|
backtestId: string;
|
|
name: string;
|
|
grid: string;
|
|
candidate?: ChronologicalValidationSubmission['candidate'];
|
|
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<ValidationWindows>(emptyValidationWindows);
|
|
const [prepared, setPrepared] = useState<{
|
|
identity: string;
|
|
preview: ChronologicalValidationPreviewView;
|
|
} | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState('');
|
|
const generation = useRef(0);
|
|
const request = useRef<AbortController | null>(null);
|
|
const pending = useRef(false);
|
|
const alive = useRef(false);
|
|
const identity = JSON.stringify({
|
|
backtestId,
|
|
name,
|
|
grid,
|
|
candidate,
|
|
windows,
|
|
disabled,
|
|
eligible,
|
|
});
|
|
const currentIdentity = useRef(identity);
|
|
currentIdentity.current = identity;
|
|
const preview =
|
|
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
|
const dirty = hasTrainingIntent || validationWindowsDirty(windows);
|
|
useEffect(() => {
|
|
onDirty(dirty);
|
|
}, [dirty, onDirty]);
|
|
useEffect(() => {
|
|
alive.current = true;
|
|
return () => {
|
|
alive.current = false;
|
|
generation.current++;
|
|
request.current?.abort();
|
|
};
|
|
}, []);
|
|
useEffect(() => {
|
|
generation.current++;
|
|
request.current?.abort();
|
|
pending.current = false;
|
|
setPrepared(null);
|
|
setLoading(false);
|
|
setError('');
|
|
}, [identity]);
|
|
const edit = (phase: ValidationPhase, field: keyof ValidationWindows['train'], value: string) => {
|
|
if (disabled || trainingIntent.current) {
|
|
return;
|
|
}
|
|
generation.current++;
|
|
request.current?.abort();
|
|
setWindows(previous => ({ ...previous, [phase]: { ...previous[phase], [field]: value } }));
|
|
};
|
|
const prepare = async () => {
|
|
if (disabled || trainingIntent.current || !eligible || pending.current) {
|
|
return;
|
|
}
|
|
const captured = identity;
|
|
const revision = ++generation.current;
|
|
request.current?.abort();
|
|
const controller = new AbortController();
|
|
request.current = controller;
|
|
pending.current = true;
|
|
setPrepared(null);
|
|
setError('');
|
|
setLoading(true);
|
|
try {
|
|
const input = chronologicalValidationInputSchema.parse({
|
|
backtestId,
|
|
name,
|
|
grid: JSON.parse(grid),
|
|
...(candidate ? { candidate } : {}),
|
|
recipe: parseValidationWindows(windows),
|
|
});
|
|
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
|
if (
|
|
alive.current &&
|
|
revision === generation.current &&
|
|
captured === currentIdentity.current
|
|
) {
|
|
setPrepared({ identity: captured, preview: value });
|
|
}
|
|
} catch (cause) {
|
|
if (
|
|
alive.current &&
|
|
revision === generation.current &&
|
|
captured === currentIdentity.current
|
|
) {
|
|
setError(message(cause));
|
|
}
|
|
} finally {
|
|
if (
|
|
alive.current &&
|
|
revision === generation.current &&
|
|
captured === currentIdentity.current
|
|
) {
|
|
pending.current = false;
|
|
setLoading(false);
|
|
}
|
|
}
|
|
};
|
|
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"
|
|
className="border-t border-border pt-4 space-y-3 text-sm"
|
|
>
|
|
<h3 className="font-semibold text-text-primary">Chronological validation preflight</h3>
|
|
<p>
|
|
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
|
|
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>
|
|
<ValidationWindowFields
|
|
windows={windows}
|
|
disabled={disabled || hasTrainingIntent}
|
|
onChange={edit}
|
|
/>
|
|
{disabled && (
|
|
<p>
|
|
Resolve or explicitly release the other submission before preparing chronological inputs.
|
|
</p>
|
|
)}
|
|
<Button
|
|
variant="outline"
|
|
disabled={disabled || hasTrainingIntent || !eligible || !name.trim() || loading}
|
|
onClick={() => void prepare()}
|
|
>
|
|
Preview chronological validation
|
|
</Button>
|
|
{loading && <p role="status">Preparing chronological validation preview...</p>}
|
|
{error && (
|
|
<p role="alert" className="text-error">
|
|
{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.
|
|
</p>
|
|
)}
|
|
{preview && (
|
|
<section aria-label="Prepared chronological inputs" className="space-y-3">
|
|
<p>
|
|
{preview.source.candidates.length} parameter candidates checked for input requirements.
|
|
No candidate has been selected or evaluated.
|
|
</p>
|
|
<dl className="grid gap-2 sm:grid-cols-2 break-all text-xs">
|
|
<div>
|
|
<dt>Source dataset</dt>
|
|
<dd>{preview.source.request.datasetHash}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Strategy version</dt>
|
|
<dd>{preview.source.request.strategy.versionId}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Initial capital / owner budget (USD)</dt>
|
|
<dd>
|
|
{preview.source.request.policy.matching.risk.ledger.initialCapital} /{' '}
|
|
{preview.source.request.strategy.selection.ownerBudget}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Seed</dt>
|
|
<dd>{preview.source.request.strategy.selection.seed}</dd>
|
|
</div>
|
|
</dl>
|
|
<p>
|
|
Planned selection: maximize train total return; ties use ascending candidate index.
|
|
Every train candidate must complete with a comparable, finite score before selection.
|
|
Validation is diagnostic only; test is holdout only. Neither may retune the selected
|
|
parameters.
|
|
</p>
|
|
<p>
|
|
Each phase resets to the same initial capital and empty positions, with warmed
|
|
indicators. Capital, costs, risk rules and seed stay unchanged. These are independent
|
|
reset segments, not a continuous portfolio equity curve.
|
|
</p>
|
|
<p>
|
|
Input checks only. Warmup sufficiency is not evidence of profitability or statistical
|
|
adequacy. Built-in strategies use the declared unfitted model. Candidate warmup is
|
|
author-declared and candidate behavior is unverified; fitting and nonzero label horizons
|
|
have no supported validation contract.
|
|
</p>
|
|
<div className="grid gap-3 lg:grid-cols-3">
|
|
{preview.partitions.map(part => (
|
|
<article
|
|
key={part.phase}
|
|
aria-label={`${phaseLabels[part.phase]} partition`}
|
|
className="border border-border rounded p-3 space-y-2 text-xs break-all"
|
|
>
|
|
<h4 className="font-semibold text-sm">{phaseLabels[part.phase]} partition</h4>
|
|
<dl className="space-y-1">
|
|
<div>
|
|
<dt>Prepared dataset hash</dt>
|
|
<dd>{part.dataset.hash}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Warmup start (UTC)</dt>
|
|
<dd>{new Date(part.dataset.bounds.warmupStart).toISOString()}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Trading start (UTC)</dt>
|
|
<dd>{new Date(part.dataset.bounds.tradeStart).toISOString()}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Trading end (UTC, exclusive)</dt>
|
|
<dd>{new Date(part.dataset.bounds.tradeEnd).toISOString()}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Total retained bars</dt>
|
|
<dd>{part.counts.totalBars}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Available before trading</dt>
|
|
<dd>{part.counts.availableWarmup}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Admitted warmup / required warmup</dt>
|
|
<dd>
|
|
{part.counts.admittedWarmup} / {part.requiredWarmup}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Ignored late warmup observations</dt>
|
|
<dd>{part.counts.ignoredLateWarmup}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Available during evaluation</dt>
|
|
<dd>{part.counts.availableEvaluation}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Available exactly at end (terminal mark only)</dt>
|
|
<dd>{part.counts.terminalAtEnd}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Completed observations unavailable at end</dt>
|
|
<dd>{part.counts.unavailableAtEnd}</dd>
|
|
</div>
|
|
</dl>
|
|
{part.warnings.map((warning, index) => (
|
|
<p key={index}>{warning}</p>
|
|
))}
|
|
</article>
|
|
))}
|
|
</div>
|
|
<details>
|
|
<summary className="cursor-pointer text-primary-500">
|
|
Exact chronological preview inputs and policies
|
|
</summary>
|
|
<pre className="mt-2 max-h-80 overflow-auto whitespace-pre-wrap text-xs">
|
|
{JSON.stringify(
|
|
{
|
|
previewHash: preview.previewHash,
|
|
input: preview.input,
|
|
policy: preview.policy,
|
|
sourcePreviewHash: preview.source.previewHash,
|
|
sourceDataset: preview.source.dataset,
|
|
strategyVersion: preview.source.request.strategy.versionId,
|
|
reviewId: preview.source.request.strategy.reviewId,
|
|
artifactHash: preview.source.request.strategy.package.artifact.sha256,
|
|
dependencyLockHash: preview.source.request.strategy.package.dependencyLock.sha256,
|
|
parameters: preview.source.candidates,
|
|
analyticsPolicy: preview.source.request.analyticsPolicy,
|
|
financialPolicy: preview.source.request.policy,
|
|
build: preview.source.request.build,
|
|
partitions: preview.partitions.map(part => ({
|
|
phase: part.phase,
|
|
dataset: part.dataset,
|
|
counts: part.counts,
|
|
requiredWarmup: part.requiredWarmup,
|
|
initialRiskSession: part.request.policy.matching.risk.ledger.riskSession,
|
|
riskBoundaries: part.request.policy.risk_boundaries,
|
|
})),
|
|
},
|
|
null,
|
|
2
|
|
)}
|
|
</pre>
|
|
</details>
|
|
</section>
|
|
)}
|
|
</section>
|
|
);
|
|
}
|