feat(research): prepare and retain explicit source datasets in the web workbench
This commit is contained in:
parent
06039d17ba
commit
366bee810b
21 changed files with 2677 additions and 76 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
type CanonicalDatasetCatalogEntry,
|
||||
|
|
@ -19,6 +19,7 @@ import {
|
|||
type Backtest,
|
||||
type CreateBacktestRequest,
|
||||
} from '../services/backtestApiV2';
|
||||
import { DatasetPreparation, type DatasetPreparationState } from './DatasetPreparation';
|
||||
|
||||
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
|
||||
const policyFields: {
|
||||
|
|
@ -280,6 +281,17 @@ export function CanonicalSetup({
|
|||
const [error, setError] = useState<string | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const authoritative = useRef(backtest);
|
||||
const currentBacktest = useRef(backtest);
|
||||
currentBacktest.current = backtest;
|
||||
const preparationRef = useRef<DatasetPreparationState>({ busy: false, blocking: false });
|
||||
const [preparation, setPreparation] = useState(preparationRef.current);
|
||||
const preparationChanged = useCallback((value: DatasetPreparationState) => {
|
||||
preparationRef.current = value;
|
||||
setPreparation(value);
|
||||
if (value.blocking) {
|
||||
setDirty(true);
|
||||
}
|
||||
}, []);
|
||||
const pending = useRef(false);
|
||||
const active = useRef(true);
|
||||
useUnsavedWarning(dirty);
|
||||
|
|
@ -309,6 +321,8 @@ export function CanonicalSetup({
|
|||
});
|
||||
setStrategyValid(false);
|
||||
setEpoch(value => value + 1);
|
||||
preparationRef.current = { busy: false, blocking: false };
|
||||
setPreparation(preparationRef.current);
|
||||
setDirty(false);
|
||||
setError(null);
|
||||
}, [backtest]);
|
||||
|
|
@ -387,7 +401,15 @@ export function CanonicalSetup({
|
|||
);
|
||||
const save = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (locked || pending.current || !valid || !selectedFields || !parsed.settings) {
|
||||
if (
|
||||
locked ||
|
||||
pending.current ||
|
||||
preparationRef.current.busy ||
|
||||
preparationRef.current.blocking ||
|
||||
!valid ||
|
||||
!selectedFields ||
|
||||
!parsed.settings
|
||||
) {
|
||||
return;
|
||||
}
|
||||
pending.current = true;
|
||||
|
|
@ -543,6 +565,32 @@ export function CanonicalSetup({
|
|||
</div>
|
||||
</dl>
|
||||
)}
|
||||
<details className="space-y-3 rounded-md border border-border p-3">
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Prepare dataset from source export
|
||||
</summary>
|
||||
<DatasetPreparation
|
||||
key={`${backtest.id}:${epoch}`}
|
||||
disabled={locked}
|
||||
begin={() =>
|
||||
!disabled &&
|
||||
!pending.current &&
|
||||
active.current &&
|
||||
currentBacktest.current === backtest
|
||||
}
|
||||
onStateChange={preparationChanged}
|
||||
onRetained={(retainedHash, available) => {
|
||||
if (!active.current || currentBacktest.current !== backtest) {
|
||||
return;
|
||||
}
|
||||
if (available) {
|
||||
setHash(retainedHash);
|
||||
}
|
||||
setRetry(value => value + 1);
|
||||
setDirty(true);
|
||||
}}
|
||||
/>
|
||||
</details>
|
||||
<StrategySelection
|
||||
key={epoch}
|
||||
allowArchivedSelection
|
||||
|
|
@ -588,16 +636,28 @@ export function CanonicalSetup({
|
|||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" className={actionClass} disabled={locked || !valid}>
|
||||
{preparation.blocking && (
|
||||
<p role="status">
|
||||
Retain an available dataset or clear source preparation before saving this setup.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={locked || preparation.busy || preparation.blocking || !valid}
|
||||
>
|
||||
{saving ? 'Saving canonical setup...' : 'Save canonical setup'}
|
||||
</button>{' '}
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
disabled={saving || preparation.busy}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
if (pending.current || preparationRef.current.busy) {
|
||||
return;
|
||||
}
|
||||
if (confirmDiscard(dirty || preparationRef.current.blocking)) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,373 @@
|
|||
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';
|
||||
|
||||
export interface DatasetPreparationState {
|
||||
busy: boolean;
|
||||
blocking: boolean;
|
||||
}
|
||||
interface Props {
|
||||
disabled: boolean;
|
||||
begin: () => boolean;
|
||||
onStateChange: (state: DatasetPreparationState) => void;
|
||||
onRetained: (hash: string, available: boolean) => void;
|
||||
}
|
||||
interface Retention {
|
||||
input: unknown;
|
||||
preview: CanonicalDatasetPreparation;
|
||||
}
|
||||
const instant = (value: number) => new Date(value).toISOString();
|
||||
export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) {
|
||||
const [input, setInput] = useState<{ value: unknown; filename: string } | null>(null);
|
||||
const [preview, setPreview] = useState<CanonicalDatasetPreparation | null>(null);
|
||||
const [retained, setRetained] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[phase, setPhase] = useState<'reading' | 'previewing' | 'retaining' | null>(null);
|
||||
const [intent, setIntent] = useState<Retention | null>(null);
|
||||
const source = useRef<{ value: unknown; filename: string } | null>(null);
|
||||
const prepared = useRef<Retention | null>(null);
|
||||
const generation = useRef(0),
|
||||
active = useRef(false),
|
||||
pending = useRef(false),
|
||||
captured = useRef<Retention | null>(null),
|
||||
controller = useRef<AbortController | null>(null),
|
||||
fileInput = useRef<HTMLInputElement>(null);
|
||||
const callbacks = useRef({ begin, onStateChange, onRetained });
|
||||
callbacks.current = { begin, onStateChange, onRetained };
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
generation.current++;
|
||||
controller.current?.abort();
|
||||
callbacks.current.onStateChange({ busy: false, blocking: false });
|
||||
};
|
||||
}, []);
|
||||
const state = (busy: boolean, blocking: boolean) =>
|
||||
callbacks.current.onStateChange({ busy, blocking });
|
||||
const reset = () => {
|
||||
generation.current++;
|
||||
controller.current?.abort();
|
||||
pending.current = false;
|
||||
captured.current = null;
|
||||
source.current = null;
|
||||
prepared.current = null;
|
||||
setIntent(null);
|
||||
setInput(null);
|
||||
setPreview(null);
|
||||
setRetained(false);
|
||||
setPhase(null);
|
||||
setError('');
|
||||
if (fileInput.current) {
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
state(false, false);
|
||||
};
|
||||
const loadFile = async (file: File | undefined) => {
|
||||
if (disabled || captured.current || !callbacks.current.begin()) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
const revision = generation.current;
|
||||
controller.current?.abort();
|
||||
pending.current = true;
|
||||
prepared.current = null;
|
||||
source.current = null;
|
||||
setPreview(null);
|
||||
setRetained(false);
|
||||
setInput(null);
|
||||
setError('');
|
||||
if (!file) {
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
setPhase('reading');
|
||||
state(true, true);
|
||||
try {
|
||||
const value: unknown = JSON.parse(await file.text());
|
||||
if (active.current && revision === generation.current) {
|
||||
source.current = { value, filename: file.name };
|
||||
setInput(source.current);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current && revision === generation.current) {
|
||||
setError(
|
||||
`Could not read source JSON: ${cause instanceof Error ? cause.message : 'Invalid file'}`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (active.current && revision === generation.current) {
|
||||
pending.current = false;
|
||||
setPhase(null);
|
||||
state(false, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
const inspect = async () => {
|
||||
const selectedSource = source.current;
|
||||
if (
|
||||
disabled ||
|
||||
pending.current ||
|
||||
captured.current ||
|
||||
!selectedSource ||
|
||||
!callbacks.current.begin()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
pending.current = true;
|
||||
const revision = ++generation.current;
|
||||
const abort = new AbortController();
|
||||
controller.current = abort;
|
||||
prepared.current = null;
|
||||
setPhase('previewing');
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setRetained(false);
|
||||
state(true, true);
|
||||
try {
|
||||
const result = await backtestApiV2.previewDataset(selectedSource.value, abort.signal);
|
||||
if (active.current && revision === generation.current) {
|
||||
prepared.current = { input: selectedSource.value, preview: result };
|
||||
setPreview(result);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current && revision === generation.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Could not preview dataset');
|
||||
}
|
||||
} finally {
|
||||
if (active.current && revision === generation.current) {
|
||||
pending.current = false;
|
||||
setPhase(null);
|
||||
state(false, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
const retain = async () => {
|
||||
if (
|
||||
disabled ||
|
||||
pending.current ||
|
||||
(!captured.current && !prepared.current) ||
|
||||
!callbacks.current.begin()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const target =
|
||||
captured.current ?? (prepared.current ? structuredClone(prepared.current) : null);
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
captured.current = target;
|
||||
setIntent(target);
|
||||
pending.current = true;
|
||||
const revision = ++generation.current,
|
||||
abort = new AbortController();
|
||||
controller.current = abort;
|
||||
setPhase('retaining');
|
||||
setError('');
|
||||
state(true, true);
|
||||
const reportRetained = callbacks.current.onRetained;
|
||||
let accepted = false;
|
||||
try {
|
||||
const result = await backtestApiV2.retainDataset(
|
||||
target.input,
|
||||
target.preview.hash,
|
||||
abort.signal
|
||||
);
|
||||
if (canonicalStrategyJson(result) !== canonicalStrategyJson(target.preview)) {
|
||||
throw new Error('Retained dataset descriptor differs from its captured preview.');
|
||||
}
|
||||
if (active.current && revision === generation.current) {
|
||||
accepted = result.available;
|
||||
prepared.current = null;
|
||||
setRetained(true);
|
||||
setPreview(result);
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
reportRetained(result.hash, result.available);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current && revision === generation.current) {
|
||||
if (
|
||||
cause instanceof DatasetPreparationRequestError &&
|
||||
(cause.status === 400 || cause.status === 409)
|
||||
) {
|
||||
captured.current = null;
|
||||
prepared.current = null;
|
||||
setIntent(null);
|
||||
setPreview(null);
|
||||
setError(`${cause.message} Preview again or choose a corrected source export.`);
|
||||
} else {
|
||||
setError(
|
||||
`${cause instanceof Error ? cause.message : 'Dataset retention response was lost'} Retry the exact same input and hash; retention may already have succeeded.`
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (active.current && revision === generation.current) {
|
||||
pending.current = false;
|
||||
setPhase(null);
|
||||
state(false, !accepted);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<section aria-label="Source dataset preparation" className="space-y-3 text-sm">
|
||||
<p>
|
||||
Supply a complete source export with metadata and bars. Sessions, source revisions,
|
||||
universe, corporate actions and publication availability must be explicit. Declared
|
||||
provenance is not independent provider certification. Preview writes nothing; retention does
|
||||
not save settings or start a run.
|
||||
</p>
|
||||
<label className="block">
|
||||
Source dataset JSON
|
||||
<input
|
||||
ref={fileInput}
|
||||
className={fieldClass}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
aria-label="Source dataset JSON"
|
||||
disabled={disabled || Boolean(intent)}
|
||||
onChange={event => void loadFile(event.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
{!input && !phase && !error && <p>No source export selected.</p>}
|
||||
{input && <p>Selected export: {input.filename}</p>}
|
||||
{phase && (
|
||||
<p role="status">
|
||||
{phase === 'reading'
|
||||
? 'Reading source JSON...'
|
||||
: phase === 'previewing'
|
||||
? 'Previewing dataset...'
|
||||
: 'Retaining dataset...'}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || Boolean(phase) || Boolean(intent) || !input}
|
||||
onClick={() => void inspect()}
|
||||
>
|
||||
Preview dataset
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || Boolean(phase) || retained || (!preview && !intent)}
|
||||
onClick={() => void retain()}
|
||||
>
|
||||
{intent ? 'Retry retaining same dataset' : 'Retain dataset'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || phase === 'retaining'}
|
||||
onClick={() => {
|
||||
if (disabled || (pending.current && captured.current) || !callbacks.current.begin()) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!captured.current ||
|
||||
window.confirm(
|
||||
'This dataset may already be retained. Clear this preparation and discard its exact retry input and hash?'
|
||||
)
|
||||
) {
|
||||
reset();
|
||||
}
|
||||
}}
|
||||
>
|
||||
Clear source preparation
|
||||
</button>
|
||||
</div>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{intent && !phase && (
|
||||
<p>Retention is unconfirmed. The exact original input and hash are preserved for retry.</p>
|
||||
)}
|
||||
{retained && (
|
||||
<p role="status">
|
||||
Dataset retained.{' '}
|
||||
{preview?.available
|
||||
? 'The canonical selection will be verified before settings can be saved.'
|
||||
: 'This data cannot be chosen for canonical execution. The existing selection is unchanged; clear preparation to continue editing.'}
|
||||
</p>
|
||||
)}
|
||||
{preview && (
|
||||
<section aria-label="Prepared dataset metadata" className="space-y-2 break-words">
|
||||
<p className="break-all">Dataset hash: {preview.hash}</p>
|
||||
<p>
|
||||
{preview.manifest.barCount} bars · Eligibility: {preview.manifest.eligibility} ·{' '}
|
||||
{preview.available
|
||||
? 'Available for single-asset canonical setup'
|
||||
: 'Unavailable for canonical setup'}
|
||||
</p>
|
||||
{preview.reason && <p>{preview.reason}</p>}
|
||||
<p>Warmup start (UTC): {instant(preview.manifest.bounds.warmupStart)}</p>
|
||||
<p>
|
||||
Trading bounds (UTC, end exclusive): {instant(preview.manifest.bounds.tradeStart)} —{' '}
|
||||
{instant(preview.manifest.bounds.tradeEnd)}
|
||||
</p>
|
||||
{preview.manifest.series.map(series => (
|
||||
<div key={series.id} className="space-y-1">
|
||||
<p>
|
||||
{series.instrumentId} / {series.interval} · Series: {series.id} · Adjustment:{' '}
|
||||
{series.adjustment}
|
||||
</p>
|
||||
<p>
|
||||
Timestamp: {series.timestamp} · Availability: {series.availability}
|
||||
</p>
|
||||
<p>
|
||||
Source: {series.source.provider} · Revision: {series.source.revision}
|
||||
</p>
|
||||
{series.availability === 'interval-end-assumption' && (
|
||||
<p>
|
||||
Availability is explicitly assumed at interval end; actual publication delay is
|
||||
not verified.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{preview.manifest.calendars.map(calendar => (
|
||||
<p key={calendar.id}>
|
||||
Calendar: {calendar.id} · Source: {calendar.source} · Revision: {calendar.revision} ·
|
||||
Time zone: {calendar.timeZone} · Sessions: {calendar.sessions.length} · Coverage:{' '}
|
||||
{calendar.startDate} — {calendar.endDate}
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
Universe: {preview.manifest.universe.selection} · As of:{' '}
|
||||
{preview.manifest.universe.asOf === null
|
||||
? 'Unknown'
|
||||
: instant(preview.manifest.universe.asOf)}{' '}
|
||||
· Revision: {preview.manifest.universe.revision} · Instruments:{' '}
|
||||
{preview.manifest.universe.instrumentIds.join(', ')}
|
||||
</p>
|
||||
{preview.manifest.corporateActions.map(coverage => (
|
||||
<div key={coverage.instrumentId}>
|
||||
<p>
|
||||
Corporate actions: {coverage.instrumentId} · {coverage.status} · Revision:{' '}
|
||||
{coverage.revision} · Coverage: {instant(coverage.start)} — {instant(coverage.end)}{' '}
|
||||
· Actions: {coverage.actions.length}
|
||||
</p>
|
||||
{coverage.actions.map((action, index) => (
|
||||
<p key={index}>
|
||||
{action.kind} · {instant(action.effectiveAt)} · {action.reference}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
{preview.manifest.limitations.map((limitation, index) => (
|
||||
<p key={index}>{limitation}</p>
|
||||
))}
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact prepared manifest</summary>
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(preview.manifest, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CanonicalDatasetCatalogEntry,
|
||||
CanonicalDatasetPreparation,
|
||||
CanonicalReproductionComparison,
|
||||
CanonicalReproductionPreview,
|
||||
CanonicalRunCapability,
|
||||
|
|
@ -105,7 +107,204 @@ const nullableText = (value: unknown) => value === null || typeof value === 'str
|
|||
const hashOrNull = (value: unknown) =>
|
||||
value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value));
|
||||
|
||||
const preparationText = z.string().min(1);
|
||||
const preparationHash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const preparationInstant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
const preparationDay = z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.refine(
|
||||
value =>
|
||||
Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value
|
||||
);
|
||||
const preparationManifest = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash: preparationHash,
|
||||
normalizationRevision: z.literal('historical-normalization-v2'),
|
||||
parentDatasetHash: z.null(),
|
||||
volumePolicy: z.literal('reported'),
|
||||
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
|
||||
intradayPolicy: z.literal('full-duration-session-contained'),
|
||||
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
|
||||
limitations: z.array(preparationText),
|
||||
barCount: z.number().int().positive().safe(),
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: preparationText,
|
||||
venue: preparationText,
|
||||
timeZone: preparationText,
|
||||
source: preparationText,
|
||||
revision: preparationText,
|
||||
startDate: preparationDay,
|
||||
endDate: preparationDay,
|
||||
sessions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
date: preparationDay,
|
||||
open: preparationInstant,
|
||||
close: preparationInstant,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.open < value.close)
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
series: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: preparationText,
|
||||
instrumentId: preparationText,
|
||||
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
calendarId: preparationText,
|
||||
venue: preparationText,
|
||||
source: z.object({ provider: preparationText, revision: preparationText }).strict(),
|
||||
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
|
||||
availability: z.enum(['explicit', 'interval-end-assumption']),
|
||||
adjustment: z.enum(['raw', 'provider-adjusted']),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
executionSeries: z
|
||||
.array(z.object({ instrumentId: preparationText, seriesId: preparationText }).strict())
|
||||
.min(1),
|
||||
bounds: z
|
||||
.object({
|
||||
warmupStart: preparationInstant,
|
||||
tradeStart: preparationInstant,
|
||||
tradeEnd: preparationInstant,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd),
|
||||
universe: z
|
||||
.object({
|
||||
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
|
||||
asOf: preparationInstant.nullable(),
|
||||
revision: preparationText,
|
||||
instrumentIds: z.array(preparationText).min(1),
|
||||
})
|
||||
.strict(),
|
||||
corporateActions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: preparationText,
|
||||
status: z.enum(['unknown', 'action-free', 'known-actions']),
|
||||
start: preparationInstant,
|
||||
end: preparationInstant,
|
||||
revision: preparationText,
|
||||
actions: z.array(
|
||||
z
|
||||
.object({
|
||||
effectiveAt: preparationInstant,
|
||||
kind: z.enum(['split', 'dividend', 'other']),
|
||||
reference: preparationText,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict();
|
||||
const datasetPreparationSchema = z
|
||||
.object({
|
||||
version: z.literal('canonical-dataset-preparation/v1'),
|
||||
hash: preparationHash,
|
||||
manifest: preparationManifest,
|
||||
available: z.boolean(),
|
||||
reason: preparationText.nullable(),
|
||||
})
|
||||
.strict();
|
||||
export function parseDatasetPreparation(
|
||||
raw: unknown,
|
||||
expectedHash?: string
|
||||
): CanonicalDatasetPreparation {
|
||||
const value = datasetPreparationSchema.parse(raw),
|
||||
manifest = value.manifest;
|
||||
const available =
|
||||
manifest.eligibility === 'eligible' &&
|
||||
manifest.executionSeries.length === 1 &&
|
||||
manifest.series.length === 1 &&
|
||||
manifest.universe.instrumentIds.length === 1;
|
||||
if (
|
||||
value.hash !== manifest.hash ||
|
||||
(expectedHash !== undefined && value.hash !== expectedHash) ||
|
||||
value.available !== available ||
|
||||
(value.available ? value.reason !== null : value.reason === null) ||
|
||||
new Set(manifest.series.map(item => item.id)).size !== manifest.series.length ||
|
||||
new Set(manifest.calendars.map(item => item.id)).size !== manifest.calendars.length ||
|
||||
manifest.series.some(
|
||||
item =>
|
||||
!manifest.calendars.some(
|
||||
calendar => calendar.id === item.calendarId && calendar.venue === item.venue
|
||||
)
|
||||
) ||
|
||||
manifest.executionSeries.some(
|
||||
item =>
|
||||
!manifest.series.some(
|
||||
series => series.id === item.seriesId && series.instrumentId === item.instrumentId
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new Error('The dataset preparation response could not be verified.');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export class DatasetPreparationRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'DatasetPreparationRequestError';
|
||||
}
|
||||
}
|
||||
async function prepareDatasetRequest(
|
||||
body: { input: unknown; expectedHash?: string },
|
||||
signal?: AbortSignal
|
||||
): Promise<CanonicalDatasetPreparation> {
|
||||
const operation = body.expectedHash === undefined ? 'preview' : 'retain';
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/${operation}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new DatasetPreparationRequestError(
|
||||
(await requestError(response, `Could not ${operation} dataset`)).message,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== 200) {
|
||||
throw new Error('Unexpected dataset preparation status');
|
||||
}
|
||||
const envelope = z
|
||||
.object({ preparation: z.unknown() })
|
||||
.strict()
|
||||
.parse(await response.json());
|
||||
return parseDatasetPreparation(envelope.preparation, body.expectedHash);
|
||||
} catch {
|
||||
throw new Error('The dataset preparation response could not be verified.');
|
||||
}
|
||||
}
|
||||
|
||||
export const backtestApiV2 = {
|
||||
previewDataset: (input: unknown, signal?: AbortSignal) =>
|
||||
prepareDatasetRequest({ input }, signal),
|
||||
retainDataset: (input: unknown, expectedHash: string, signal?: AbortSignal) =>
|
||||
prepareDatasetRequest({ input, expectedHash }, signal),
|
||||
async reproductionPreview(
|
||||
id: string,
|
||||
signal?: AbortSignal
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue