feat(research): prepare stored EOD datasets before canonical admission
This commit is contained in:
parent
366bee810b
commit
0c6aec4dc6
16 changed files with 1897 additions and 61 deletions
|
|
@ -6,8 +6,10 @@ import type {
|
|||
CanonicalReproductionComparison,
|
||||
CanonicalReproductionPreview,
|
||||
CanonicalRunCapability,
|
||||
CanonicalStoredSourcePreparation,
|
||||
ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
|
|
@ -260,6 +262,118 @@ export function parseDatasetPreparation(
|
|||
}
|
||||
return value;
|
||||
}
|
||||
const preparationMetadata = preparationManifest.pick({
|
||||
calendars: true,
|
||||
series: true,
|
||||
executionSeries: true,
|
||||
bounds: true,
|
||||
universe: true,
|
||||
corporateActions: true,
|
||||
});
|
||||
const storedSourceInput = z
|
||||
.object({
|
||||
metadata: preparationMetadata,
|
||||
bars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
seriesId: preparationText,
|
||||
timestamp: preparationInstant,
|
||||
sourceSequence: z.number().int().nonnegative().safe(),
|
||||
open: z.number().finite().positive(),
|
||||
high: z.number().finite().positive(),
|
||||
low: z.number().finite().positive(),
|
||||
close: z.number().finite().positive(),
|
||||
volume: z.number().finite().nonnegative(),
|
||||
vwap: z.number().finite().positive().nullable().optional(),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict();
|
||||
type PreparationMetadata = z.infer<typeof preparationMetadata>;
|
||||
const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0);
|
||||
/** Compare declarations across server-normalized collection order; never normalize bars or calculate hashes. */
|
||||
function metadataIdentity(value: PreparationMetadata) {
|
||||
return canonicalStrategyJson({
|
||||
...value,
|
||||
calendars: value.calendars
|
||||
.map(calendar => ({
|
||||
...calendar,
|
||||
sessions: [...calendar.sessions].sort((a, b) => compareText(a.date, b.date)),
|
||||
}))
|
||||
.sort((a, b) => compareText(a.id, b.id)),
|
||||
series: [...value.series].sort((a, b) => compareText(a.id, b.id)),
|
||||
executionSeries: [...value.executionSeries].sort((a, b) =>
|
||||
compareText(a.instrumentId, b.instrumentId)
|
||||
),
|
||||
universe: {
|
||||
...value.universe,
|
||||
instrumentIds: [...value.universe.instrumentIds].sort(compareText),
|
||||
},
|
||||
corporateActions: value.corporateActions
|
||||
.map(coverage => ({
|
||||
...coverage,
|
||||
actions: [...coverage.actions].sort(
|
||||
(a, b) => a.effectiveAt - b.effectiveAt || compareText(a.reference, b.reference)
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => compareText(a.instrumentId, b.instrumentId)),
|
||||
});
|
||||
}
|
||||
export function parseStoredDatasetPreparation(
|
||||
raw: unknown,
|
||||
suppliedMetadata: unknown
|
||||
): CanonicalStoredSourcePreparation {
|
||||
const envelope = z
|
||||
.object({ input: storedSourceInput, preparation: z.unknown() })
|
||||
.strict()
|
||||
.parse(raw);
|
||||
const preparation = parseDatasetPreparation(envelope.preparation);
|
||||
const expected = preparationMetadata.parse(suppliedMetadata);
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
preparation.manifest;
|
||||
const retainedMetadata = {
|
||||
calendars,
|
||||
series,
|
||||
executionSeries,
|
||||
bounds,
|
||||
universe,
|
||||
corporateActions,
|
||||
};
|
||||
const input = envelope.input,
|
||||
metadata = input.metadata,
|
||||
selected = metadata.series[0];
|
||||
if (
|
||||
!selected ||
|
||||
metadata.series.length !== 1 ||
|
||||
metadata.executionSeries.length !== 1 ||
|
||||
metadata.universe.instrumentIds.length !== 1 ||
|
||||
selected.source.provider !== 'eod' ||
|
||||
!['1m', '5m', '1h'].includes(selected.interval) ||
|
||||
selected.adjustment !== 'raw' ||
|
||||
selected.timestamp !== 'interval-start' ||
|
||||
selected.availability !== 'interval-end-assumption' ||
|
||||
metadata.executionSeries[0]?.seriesId !== selected.id ||
|
||||
metadata.executionSeries[0]?.instrumentId !== selected.instrumentId ||
|
||||
metadata.universe.instrumentIds[0] !== selected.instrumentId ||
|
||||
metadataIdentity(metadata) !== metadataIdentity(expected) ||
|
||||
metadataIdentity(metadata) !== metadataIdentity(preparationMetadata.parse(retainedMetadata)) ||
|
||||
input.bars.length !== preparation.manifest.barCount ||
|
||||
input.bars.some(
|
||||
(bar, index) =>
|
||||
bar.seriesId !== selected.id ||
|
||||
bar.sourceSequence !== index ||
|
||||
bar.timestamp < metadata.bounds.warmupStart ||
|
||||
bar.timestamp >= metadata.bounds.tradeEnd ||
|
||||
(index > 0 && bar.timestamp <= (input.bars[index - 1]?.timestamp ?? Infinity))
|
||||
)
|
||||
) {
|
||||
throw new Error('The stored source response does not match its metadata and prepared dataset.');
|
||||
}
|
||||
return { input, preparation };
|
||||
}
|
||||
export class DatasetPreparationRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
|
|
@ -305,6 +419,28 @@ export const backtestApiV2 = {
|
|||
prepareDatasetRequest({ input }, signal),
|
||||
retainDataset: (input: unknown, expectedHash: string, signal?: AbortSignal) =>
|
||||
prepareDatasetRequest({ input, expectedHash }, signal),
|
||||
async previewStoredDataset(
|
||||
metadata: unknown,
|
||||
signal?: AbortSignal
|
||||
): 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 }),
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not load stored EOD bars');
|
||||
}
|
||||
try {
|
||||
if (response.status !== 200) {
|
||||
throw new Error('Unexpected stored source status');
|
||||
}
|
||||
return parseStoredDatasetPreparation(await response.json(), metadata);
|
||||
} catch {
|
||||
throw new Error('The stored source response could not be verified.');
|
||||
}
|
||||
},
|
||||
async reproductionPreview(
|
||||
id: string,
|
||||
signal?: AbortSignal
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue