feat(research): preview chronological validation inputs and windows
This commit is contained in:
parent
b373410320
commit
67ab30cb7a
25 changed files with 2917 additions and 54 deletions
|
|
@ -0,0 +1,373 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import {
|
||||
chronologicalValidationApi,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '../services/chronologicalValidationApi';
|
||||
|
||||
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('; ')
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: 'Could not prepare chronological validation inputs';
|
||||
|
||||
export function ChronologicalValidationPreflight({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
}) {
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
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, 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] !== ''));
|
||||
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: (typeof fields)[number], value: string) => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
request.current?.abort();
|
||||
setWindows(previous => ({ ...previous, [phase]: { ...previous[phase], [field]: value } }));
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !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 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,
|
||||
},
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
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>
|
||||
Preview only. No datasets, experiments or runs are saved. Staged execution and immutable
|
||||
reports are not available yet.
|
||||
</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>
|
||||
<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">{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>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the ordinary sweep submission before preparing chronological
|
||||
inputs.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || !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>
|
||||
)}
|
||||
{!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. Only deterministic, unfitted strategies with zero label horizon are supported.
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ import {
|
|||
ExperimentApiError,
|
||||
type ExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
|
||||
const fieldClass =
|
||||
|
|
@ -63,7 +64,11 @@ export function ExperimentEditor({
|
|||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const dirty = hasIntent || Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
const [validationDirty, setValidationDirty] = useState(false);
|
||||
const dirty =
|
||||
hasIntent ||
|
||||
validationDirty ||
|
||||
Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
|
|
@ -286,6 +291,11 @@ export function ExperimentEditor({
|
|||
the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per experiment; this
|
||||
does not promise concurrent execution.
|
||||
</p>
|
||||
<h3 className="font-semibold text-text-primary">Ordinary parameter sweep</h3>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Ordinary submission uses the template's retained window. Chronological preflight below does
|
||||
not change or execute this sweep.
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
|
|
@ -328,6 +338,14 @@ export function ExperimentEditor({
|
|||
)}
|
||||
</div>
|
||||
)}
|
||||
<ChronologicalValidationPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={hasIntent}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue