feat(research): prepare stored data by declared sessions (RP03)

This commit is contained in:
Boki 2026-10-27 01:07:45 -04:00
parent 302ba60e53
commit d2b78eacdf
10 changed files with 805 additions and 72 deletions

View file

@ -2,7 +2,11 @@ import { useEffect, useRef, useState } from 'react';
import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import { backtestApiV2, DatasetPreparationRequestError } from '../services/backtestApiV2';
import {
backtestApiV2,
DatasetPreparationRequestError,
storedSourceSessionScope,
} from '../services/backtestApiV2';
import { StoredSourceInspector } from './StoredSourceInspector';
export interface DatasetPreparationState {
@ -19,7 +23,7 @@ interface Retention {
input: unknown;
preview: CanonicalDatasetPreparation;
}
type InputMode = 'export' | 'stored-eod';
type InputMode = 'export' | 'stored-eod' | 'stored-eod-sessions';
const instant = (value: number) => new Date(value).toISOString();
export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) {
const [mode, setMode] = useState<InputMode>('export');
@ -71,7 +75,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
};
const changeMode = (next: string) => {
if (
(next !== 'export' && next !== 'stored-eod') ||
(next !== 'export' && next !== 'stored-eod' && next !== 'stored-eod-sessions') ||
next === modeRef.current ||
disabled ||
captured.current ||
@ -147,8 +151,12 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
state(true, true);
try {
const result =
selectedMode === 'stored-eod'
? await backtestApiV2.previewStoredDataset(selectedSource.value, abort.signal)
selectedMode !== 'export'
? await backtestApiV2.previewStoredDataset(
selectedSource.value,
abort.signal,
selectedMode === 'stored-eod-sessions' ? 'declared-sessions' : undefined
)
: {
input: selectedSource.value,
preparation: await backtestApiV2.previewDataset(selectedSource.value, abort.signal),
@ -239,6 +247,8 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
}
}
};
const sessionWindows =
mode === 'stored-eod-sessions' && input ? storedSourceSessionScope(input.value) : null;
return (
<section aria-label="Source dataset preparation" className="space-y-3 text-sm">
<p>
@ -258,9 +268,10 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
>
<option value="export">Source export</option>
<option value="stored-eod">Stored EOD intraday bars</option>
<option value="stored-eod-sessions">Stored EOD — declared sessions only</option>
</select>
</label>
{mode === 'stored-eod' && (
{mode !== 'export' && (
<p>
Load one EOD instrument from existing storage using raw 1m, 5m or 1h interval-start bars.
Supply complete metadata with interval-end-assumption availability. Source sequence is a
@ -269,7 +280,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
uses that captured snapshot without querying storage again.
</p>
)}
{mode === 'stored-eod' && (
{mode !== 'export' && (
<StoredSourceInspector disabled={disabled || Boolean(intent) || Boolean(phase)} />
)}
<label className="block">
@ -292,6 +303,29 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
Selected {mode === 'export' ? 'export' : 'metadata'}: {input.filename}
</p>
)}
{mode === 'stored-eod-sessions' && (
<section aria-label="Declared session selection" className="space-y-2">
<p>
Reads only the declared calendar sessions intersecting warmup start through trading end.
Rows outside those explicit windows are not requested. Invalid or empty selected
sessions fail preparation; bars are never shortened to fit. This does not verify the
calendar or establish gap-free coverage.
</p>
{sessionWindows === null ? (
<p>Supply complete single-series metadata to view the declared UTC query windows.</p>
) : sessionWindows.length === 0 ? (
<p>No declared sessions intersect the requested bounds.</p>
) : (
<ul aria-label="Declared UTC query windows">
{sessionWindows.map(window => (
<li key={window.date}>
{window.date}: {instant(window.start)} — {instant(window.end)} (end exclusive)
</li>
))}
</ul>
)}
</section>
)}
{phase && (
<p role="status">
{phase === 'reading'
@ -353,10 +387,11 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
)}
{preview && (
<section aria-label="Prepared dataset metadata" className="space-y-2 break-words">
{mode === 'stored-eod' && (
{mode !== 'export' && (
<p>
Stored source: EOD · Query bounds (UTC, end exclusive):{' '}
{instant(preview.manifest.bounds.warmupStart)} —{' '}
Stored source: EOD ·{' '}
{mode === 'stored-eod-sessions' ? 'Declared sessions within bounds' : 'Query bounds'}{' '}
(UTC, end exclusive): {instant(preview.manifest.bounds.warmupStart)} —{' '}
{instant(preview.manifest.bounds.tradeEnd)}
</p>
)}

View file

@ -4,7 +4,10 @@ import {
preparationManifestSchema,
} from '@stock-bot/research/dataset-contracts';
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import {
canonicalRunRequestSchema,
declaredStoredSourceWindows,
} from '@stock-bot/stock-config/canonical-research';
import type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
@ -218,14 +221,29 @@ function metadataIdentity(value: PreparationMetadata) {
.sort((a, b) => compareText(a.instrumentId, b.instrumentId)),
});
}
/** Preview caller declarations only; the server still validates the complete metadata and bars. */
export function storedSourceSessionScope(raw: unknown) {
const parsed = preparationMetadata.safeParse(raw);
return parsed.success && parsed.data.series.length === 1
? declaredStoredSourceWindows(parsed.data)
: null;
}
export function parseStoredDatasetPreparation(
raw: unknown,
suppliedMetadata: unknown
suppliedMetadata: unknown,
selection?: CanonicalStoredSourcePreparation['selection']
): CanonicalStoredSourcePreparation {
const envelope = z
.object({ input: storedSourceInput, preparation: z.unknown() })
.object({
input: storedSourceInput,
preparation: z.unknown(),
selection: z.literal('declared-sessions').optional(),
})
.strict()
.parse(raw);
if (envelope.selection !== selection) {
throw new Error('The stored source response does not match the requested selection.');
}
const preparation = parseDatasetPreparation(envelope.preparation);
const expected = preparationMetadata.parse(suppliedMetadata);
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
@ -268,7 +286,7 @@ export function parseStoredDatasetPreparation(
) {
throw new Error('The stored source response does not match its metadata and prepared dataset.');
}
return { input, preparation };
return { input, preparation, ...(selection ? { selection } : {}) };
}
export class DatasetPreparationRequestError extends Error {
constructor(
@ -317,12 +335,13 @@ export const backtestApiV2 = {
prepareDatasetRequest({ input, expectedHash }, signal),
async previewStoredDataset(
metadata: unknown,
signal?: AbortSignal
signal?: AbortSignal,
selection?: CanonicalStoredSourcePreparation['selection']
): Promise<CanonicalStoredSourcePreparation> {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/stored-source`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ metadata }),
body: JSON.stringify({ metadata, ...(selection ? { selection } : {}) }),
signal,
});
if (!response.ok) {
@ -332,7 +351,7 @@ export const backtestApiV2 = {
if (response.status !== 200) {
throw new Error('Unexpected stored source status');
}
return parseStoredDatasetPreparation(await response.json(), metadata);
return parseStoredDatasetPreparation(await response.json(), metadata, selection);
} catch {
throw new Error('The stored source response could not be verified.');
}