532 lines
18 KiB
TypeScript
532 lines
18 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import { z } from 'zod';
|
|
import {
|
|
parseInstrumentId,
|
|
type HistoricalBarV2,
|
|
type HistoricalDatasetInputV2,
|
|
type HistoricalDatasetMetadataV2,
|
|
type HistoricalDatasetV2,
|
|
} from '@stock-bot/types';
|
|
import {
|
|
day,
|
|
hash,
|
|
instant,
|
|
manifestSchema,
|
|
metadataSchema,
|
|
price,
|
|
sequence,
|
|
text,
|
|
} from './dataset-contracts';
|
|
|
|
const prices = {
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: z.number().finite().nonnegative(),
|
|
};
|
|
const sourceBarSchema = z
|
|
.object({
|
|
seriesId: text,
|
|
timestamp: z.union([day, instant]),
|
|
availableAt: instant.optional(),
|
|
sourceSequence: sequence,
|
|
...prices,
|
|
vwap: price.nullable().optional(),
|
|
})
|
|
.strict();
|
|
const barSchema = z
|
|
.object({
|
|
seriesId: text,
|
|
instrumentId: text,
|
|
intervalStart: instant,
|
|
intervalEnd: instant,
|
|
eventTime: instant,
|
|
availableAt: instant,
|
|
sourceSequence: sequence,
|
|
...prices,
|
|
vwap: price.nullable(),
|
|
})
|
|
.strict();
|
|
const durations = { '1m': 60_000, '5m': 300_000, '15m': 900_000, '1h': 3_600_000 };
|
|
const prepared = new WeakSet<object>();
|
|
const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
|
|
|
function unique(values: readonly string[], label: string): void {
|
|
if (new Set(values).size !== values.length) {
|
|
throw new Error(`Duplicate ${label}`);
|
|
}
|
|
}
|
|
|
|
function parseMetadata(input: unknown) {
|
|
const metadata = metadataSchema.parse(input);
|
|
const { bounds, universe } = metadata;
|
|
if (bounds.warmupStart > bounds.tradeStart || bounds.tradeStart >= bounds.tradeEnd) {
|
|
throw new Error('Invalid warmup/trade bounds');
|
|
}
|
|
unique(
|
|
metadata.calendars.map(c => c.id),
|
|
'calendar'
|
|
);
|
|
metadata.calendars.sort((a, b) => compare(a.id, b.id));
|
|
for (const calendar of metadata.calendars) {
|
|
if (calendar.startDate >= calendar.endDate) {
|
|
throw new Error('Invalid calendar coverage');
|
|
}
|
|
const formatter = new Intl.DateTimeFormat('en-CA', {
|
|
timeZone: calendar.timeZone,
|
|
year: 'numeric',
|
|
month: '2-digit',
|
|
day: '2-digit',
|
|
});
|
|
const localDate = (time: number) => {
|
|
const parts = formatter.formatToParts(time);
|
|
return ['year', 'month', 'day']
|
|
.map(key => parts.find(part => part.type === key)?.value ?? '')
|
|
.join('-');
|
|
};
|
|
if (
|
|
localDate(bounds.warmupStart) < calendar.startDate ||
|
|
localDate(bounds.tradeEnd - 1) >= calendar.endDate
|
|
) {
|
|
throw new Error('Calendar coverage must include warmup and trade bounds');
|
|
}
|
|
unique(
|
|
calendar.sessions.map(s => s.date),
|
|
'calendar session'
|
|
);
|
|
calendar.sessions.sort((a, b) => compare(a.date, b.date));
|
|
let previousClose = -1;
|
|
for (const session of calendar.sessions) {
|
|
if (
|
|
session.date < calendar.startDate ||
|
|
session.date >= calendar.endDate ||
|
|
session.open >= session.close ||
|
|
session.open < previousClose ||
|
|
localDate(session.open) !== session.date ||
|
|
localDate(session.close) !== session.date
|
|
) {
|
|
throw new Error('Invalid retained calendar session');
|
|
}
|
|
previousClose = session.close;
|
|
}
|
|
}
|
|
unique(
|
|
metadata.series.map(s => s.id),
|
|
'series'
|
|
);
|
|
metadata.series.sort((a, b) => compare(a.id, b.id));
|
|
for (const series of metadata.series) {
|
|
parseInstrumentId(series.instrumentId);
|
|
const calendar = metadata.calendars.find(c => c.id === series.calendarId);
|
|
if (
|
|
!calendar ||
|
|
calendar.venue !== series.venue ||
|
|
(series.interval === '1d') !== (series.timestamp === 'session-date')
|
|
) {
|
|
throw new Error('Unknown calendar/venue or incompatible timestamp mapping');
|
|
}
|
|
}
|
|
const instruments = [...new Set(metadata.series.map(s => s.instrumentId))].sort(compare);
|
|
unique(
|
|
metadata.executionSeries.map(s => s.instrumentId),
|
|
'execution instrument'
|
|
);
|
|
unique(
|
|
metadata.executionSeries.map(s => s.seriesId),
|
|
'execution series'
|
|
);
|
|
metadata.executionSeries.sort((a, b) => compare(a.instrumentId, b.instrumentId));
|
|
if (
|
|
JSON.stringify(metadata.executionSeries.map(s => s.instrumentId)) !==
|
|
JSON.stringify(instruments) ||
|
|
metadata.executionSeries.some(
|
|
e => !metadata.series.some(s => s.id === e.seriesId && s.instrumentId === e.instrumentId)
|
|
)
|
|
) {
|
|
throw new Error('Choose exactly one execution series per instrument');
|
|
}
|
|
unique(universe.instrumentIds, 'universe instrument');
|
|
universe.instrumentIds.sort(compare);
|
|
if (
|
|
JSON.stringify(universe.instrumentIds) !== JSON.stringify(instruments) ||
|
|
(universe.selection === 'point-in-time' &&
|
|
(universe.asOf === null || universe.asOf > bounds.tradeStart))
|
|
) {
|
|
throw new Error('Invalid universe/as-of selection');
|
|
}
|
|
unique(
|
|
metadata.corporateActions.map(c => c.instrumentId),
|
|
'action coverage'
|
|
);
|
|
metadata.corporateActions.sort((a, b) => compare(a.instrumentId, b.instrumentId));
|
|
if (
|
|
JSON.stringify(metadata.corporateActions.map(c => c.instrumentId)) !==
|
|
JSON.stringify(instruments)
|
|
) {
|
|
throw new Error('Corporate-action coverage required for every instrument');
|
|
}
|
|
for (const coverage of metadata.corporateActions) {
|
|
if (
|
|
coverage.start > bounds.warmupStart ||
|
|
coverage.end < bounds.tradeEnd ||
|
|
coverage.start >= coverage.end ||
|
|
(coverage.status === 'known-actions') !== coverage.actions.length > 0 ||
|
|
coverage.actions.some(a => a.effectiveAt < coverage.start || a.effectiveAt >= coverage.end)
|
|
) {
|
|
throw new Error('Invalid corporate-action coverage');
|
|
}
|
|
unique(
|
|
coverage.actions.map(a => a.reference),
|
|
'corporate-action reference'
|
|
);
|
|
coverage.actions.sort(
|
|
(a, b) => a.effectiveAt - b.effectiveAt || compare(a.reference, b.reference)
|
|
);
|
|
}
|
|
return metadata;
|
|
}
|
|
|
|
/** Validate and detach complete operator declarations before a stored-source read. */
|
|
export function parseHistoricalDatasetMetadataV2(input: unknown): HistoricalDatasetMetadataV2 {
|
|
return parseMetadata(input);
|
|
}
|
|
|
|
function assess(metadata: HistoricalDatasetMetadataV2, parentDatasetHash: string | null) {
|
|
const limitations = [
|
|
'Open liquidity must use previously available volume; intraday partial bars are unsupported',
|
|
];
|
|
let eligibility: 'eligible' | 'exploratory' | 'ineligible' = 'eligible';
|
|
if (parentDatasetHash) {
|
|
limitations.push('Legacy v1 VWAP provenance is unavailable; converted VWAP is null');
|
|
}
|
|
if (metadata.universe.selection !== 'point-in-time') {
|
|
eligibility = 'exploratory';
|
|
limitations.push('Universe selection is not verified point-in-time');
|
|
}
|
|
for (const coverage of metadata.corporateActions) {
|
|
if (coverage.status === 'unknown') {
|
|
if (eligibility !== 'ineligible') {
|
|
eligibility = 'exploratory';
|
|
}
|
|
limitations.push(`Unknown corporate-action coverage: ${coverage.instrumentId}`);
|
|
}
|
|
if (
|
|
coverage.actions.some(
|
|
a =>
|
|
a.effectiveAt >= metadata.bounds.warmupStart && a.effectiveAt < metadata.bounds.tradeEnd
|
|
)
|
|
) {
|
|
eligibility = 'ineligible';
|
|
limitations.push(`Unsupported corporate actions in dataset range: ${coverage.instrumentId}`);
|
|
}
|
|
}
|
|
for (const selection of metadata.executionSeries) {
|
|
if (metadata.series.find(s => s.id === selection.seriesId)?.adjustment !== 'raw') {
|
|
eligibility = 'ineligible';
|
|
limitations.push(`Adjusted prices cannot execute: ${selection.seriesId}`);
|
|
}
|
|
}
|
|
for (const series of metadata.series) {
|
|
if (series.availability === 'interval-end-assumption') {
|
|
limitations.push(`Availability assumes zero data delay at interval end: ${series.id}`);
|
|
}
|
|
}
|
|
return { eligibility, limitations };
|
|
}
|
|
|
|
/** Per-preparation indexes, not a cross-dataset cache. Session lookup is logarithmic. */
|
|
function indexMetadata(metadata: HistoricalDatasetMetadataV2) {
|
|
return {
|
|
series: new Map(metadata.series.map(series => [series.id, series])),
|
|
calendars: new Map(
|
|
metadata.calendars.map(calendar => [
|
|
calendar.id,
|
|
{
|
|
...calendar,
|
|
byDate: new Map(calendar.sessions.map(session => [session.date, session])),
|
|
},
|
|
])
|
|
),
|
|
};
|
|
}
|
|
|
|
function containingSession(
|
|
sessions: HistoricalDatasetMetadataV2['calendars'][number]['sessions'],
|
|
start: number,
|
|
end: number
|
|
) {
|
|
let low = 0,
|
|
high = sessions.length;
|
|
while (low < high) {
|
|
const middle = Math.floor((low + high) / 2);
|
|
if ((sessions[middle]?.open ?? Infinity) <= start) {
|
|
low = middle + 1;
|
|
} else {
|
|
high = middle;
|
|
}
|
|
}
|
|
const session = sessions[low - 1];
|
|
return session && end <= session.close ? session : undefined;
|
|
}
|
|
|
|
function validateBars(
|
|
metadata: HistoricalDatasetMetadataV2,
|
|
input: readonly unknown[]
|
|
): HistoricalBarV2[] {
|
|
if (!input.length) {
|
|
throw new Error('Dataset requires bars');
|
|
}
|
|
const index = indexMetadata(metadata);
|
|
const intervals = new Set<string>(),
|
|
sequences = new Set<string>(),
|
|
seen = new Set<string>();
|
|
const bars = input.map(value => {
|
|
const bar = barSchema.parse(value);
|
|
const series = index.series.get(bar.seriesId);
|
|
const calendar = series && index.calendars.get(series.calendarId);
|
|
const session =
|
|
calendar && containingSession(calendar.sessions, bar.intervalStart, bar.intervalEnd);
|
|
const duration = series?.interval === '1d' ? null : series ? durations[series.interval] : null;
|
|
if (
|
|
!series ||
|
|
bar.instrumentId !== series.instrumentId ||
|
|
!session ||
|
|
bar.intervalStart >= bar.intervalEnd ||
|
|
(duration === null
|
|
? bar.intervalStart !== session.open || bar.intervalEnd !== session.close
|
|
: bar.intervalEnd - bar.intervalStart !== duration) ||
|
|
bar.eventTime !== bar.intervalEnd ||
|
|
bar.availableAt < bar.eventTime ||
|
|
(series.availability === 'interval-end-assumption' && bar.availableAt !== bar.intervalEnd) ||
|
|
bar.intervalStart < metadata.bounds.warmupStart ||
|
|
bar.intervalStart >= metadata.bounds.tradeEnd ||
|
|
bar.intervalEnd > metadata.bounds.tradeEnd ||
|
|
bar.high < Math.max(bar.open, bar.close) ||
|
|
bar.low > Math.min(bar.open, bar.close)
|
|
) {
|
|
throw new Error('Invalid bar values, session interval or availability');
|
|
}
|
|
const intervalKey = JSON.stringify([bar.seriesId, bar.intervalStart, bar.intervalEnd]);
|
|
const sequenceKey = JSON.stringify([bar.seriesId, bar.sourceSequence]);
|
|
if (intervals.has(intervalKey) || sequences.has(sequenceKey)) {
|
|
throw new Error('Duplicate or conflicting bar interval/source sequence');
|
|
}
|
|
intervals.add(intervalKey);
|
|
sequences.add(sequenceKey);
|
|
seen.add(bar.seriesId);
|
|
return bar;
|
|
});
|
|
if (seen.size !== metadata.series.length) {
|
|
throw new Error('Every declared series requires observations');
|
|
}
|
|
let previous: HistoricalBarV2 | undefined;
|
|
for (const bar of [...bars].sort(
|
|
(a, b) => compare(a.seriesId, b.seriesId) || a.intervalStart - b.intervalStart
|
|
)) {
|
|
if (previous?.seriesId === bar.seriesId && bar.intervalStart < previous.intervalEnd) {
|
|
throw new Error('Overlapping intervals within one series');
|
|
}
|
|
previous = bar;
|
|
}
|
|
bars.sort(
|
|
(a, b) =>
|
|
a.availableAt - b.availableAt ||
|
|
compare(a.instrumentId, b.instrumentId) ||
|
|
compare(a.seriesId, b.seriesId) ||
|
|
a.sourceSequence - b.sourceSequence
|
|
);
|
|
return bars;
|
|
}
|
|
|
|
function freeze<T>(value: T): T {
|
|
if (value && typeof value === 'object') {
|
|
for (const child of Object.values(value)) {
|
|
freeze(child);
|
|
}
|
|
Object.freeze(value);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function finish(
|
|
metadata: ReturnType<typeof parseMetadata>,
|
|
bars: HistoricalBarV2[],
|
|
parentDatasetHash: string | null
|
|
): HistoricalDatasetV2 {
|
|
const manifest = {
|
|
...metadata,
|
|
version: 2 as const,
|
|
normalizationRevision: 'historical-normalization-v2' as const,
|
|
parentDatasetHash,
|
|
volumePolicy: 'reported' as const,
|
|
qualityPolicy: 'reject-invalid-no-interpolation' as const,
|
|
intradayPolicy: 'full-duration-session-contained' as const,
|
|
...assess(metadata, parentDatasetHash),
|
|
barCount: bars.length,
|
|
};
|
|
const digest = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`);
|
|
bars.forEach((bar, index) => digest.update((index ? ',' : '') + JSON.stringify(bar)));
|
|
const dataset = freeze({
|
|
manifest: { ...manifest, hash: digest.update(']}').digest('hex') },
|
|
bars,
|
|
});
|
|
prepared.add(dataset);
|
|
return dataset;
|
|
}
|
|
|
|
function create(input: unknown, parentDatasetHash: string | null): HistoricalDatasetV2 {
|
|
const parsed = z
|
|
.object({ metadata: metadataSchema, bars: z.array(sourceBarSchema).min(1) })
|
|
.strict()
|
|
.parse(input);
|
|
const metadata = parseMetadata(parsed.metadata);
|
|
const index = indexMetadata(metadata);
|
|
const bars = parsed.bars.map(row => {
|
|
const series = index.series.get(row.seriesId);
|
|
const calendar = series && index.calendars.get(series.calendarId);
|
|
if (!series || !calendar) {
|
|
throw new Error('Unknown series/calendar mapping');
|
|
}
|
|
if (series.availability === 'explicit' && row.availableAt === undefined) {
|
|
throw new Error('Explicit availability policy requires availableAt on every bar');
|
|
}
|
|
let intervalStart: number, intervalEnd: number;
|
|
if (series.interval === '1d') {
|
|
const session = typeof row.timestamp === 'string' && calendar.byDate.get(row.timestamp);
|
|
if (!session) {
|
|
throw new Error('Unknown daily session mapping');
|
|
}
|
|
intervalStart = session.open;
|
|
intervalEnd = session.close;
|
|
} else {
|
|
if (typeof row.timestamp !== 'number') {
|
|
throw new Error('Intraday timestamp requires an explicit instant');
|
|
}
|
|
const duration = durations[series.interval];
|
|
intervalStart =
|
|
series.timestamp === 'interval-start' ? row.timestamp : row.timestamp - duration;
|
|
intervalEnd = intervalStart + duration;
|
|
}
|
|
return {
|
|
seriesId: series.id,
|
|
instrumentId: series.instrumentId,
|
|
intervalStart,
|
|
intervalEnd,
|
|
eventTime: intervalEnd,
|
|
availableAt: row.availableAt ?? intervalEnd,
|
|
sourceSequence: row.sourceSequence,
|
|
open: row.open,
|
|
high: row.high,
|
|
low: row.low,
|
|
close: row.close,
|
|
volume: row.volume,
|
|
vwap: row.vwap ?? null,
|
|
};
|
|
});
|
|
return finish(metadata, validateBars(metadata, bars), parentDatasetHash);
|
|
}
|
|
|
|
/** No storage/provider access or implicit v1 cutover. Tables and timestamp semantics are mandatory. */
|
|
export function createDatasetV2(input: HistoricalDatasetInputV2): HistoricalDatasetV2 {
|
|
return create(input, null);
|
|
}
|
|
|
|
/** Recompute constraints, eligibility and hash; untrusted values are detached before freezing. */
|
|
export function validateDatasetV2(input: unknown): HistoricalDatasetV2 {
|
|
if (input && typeof input === 'object' && prepared.has(input)) {
|
|
return input as HistoricalDatasetV2;
|
|
}
|
|
const parsed = z
|
|
.object({ manifest: manifestSchema, bars: z.array(barSchema).min(1) })
|
|
.strict()
|
|
.parse(input);
|
|
const {
|
|
version: _version,
|
|
hash: expectedHash,
|
|
normalizationRevision: _revision,
|
|
parentDatasetHash,
|
|
volumePolicy: _volume,
|
|
qualityPolicy: _quality,
|
|
intradayPolicy: _intraday,
|
|
eligibility,
|
|
limitations,
|
|
barCount,
|
|
...rawMetadata
|
|
} = parsed.manifest;
|
|
const metadata = parseMetadata(rawMetadata);
|
|
const dataset = finish(metadata, validateBars(metadata, parsed.bars), parentDatasetHash);
|
|
if (
|
|
dataset.manifest.hash !== expectedHash ||
|
|
barCount !== dataset.bars.length ||
|
|
eligibility !== dataset.manifest.eligibility ||
|
|
JSON.stringify(limitations) !== JSON.stringify(dataset.manifest.limitations) ||
|
|
(parentDatasetHash !== null && dataset.bars.some(bar => bar.vwap !== null))
|
|
) {
|
|
throw new Error('Dataset v2 hash/content or derived policy mismatch');
|
|
}
|
|
return dataset;
|
|
}
|
|
|
|
/** Exact retained v2 interval slice. V2 lineage belongs to the caller's manifest;
|
|
* parentDatasetHash continues to describe only the original legacy-v1 conversion. */
|
|
export function sliceDatasetV2(
|
|
input: unknown,
|
|
boundsInput: HistoricalDatasetMetadataV2['bounds']
|
|
): HistoricalDatasetV2 {
|
|
const source = validateDatasetV2(input);
|
|
const bounds = metadataSchema.shape.bounds.parse(boundsInput);
|
|
if (
|
|
bounds.warmupStart < source.manifest.bounds.warmupStart ||
|
|
bounds.tradeStart < source.manifest.bounds.tradeStart ||
|
|
bounds.tradeEnd > source.manifest.bounds.tradeEnd
|
|
) {
|
|
throw new Error('Slice bounds must remain within the source warmup and evaluation bounds');
|
|
}
|
|
for (const boundary of [bounds.warmupStart, bounds.tradeStart, bounds.tradeEnd]) {
|
|
if (source.bars.some(bar => bar.intervalStart < boundary && boundary < bar.intervalEnd)) {
|
|
throw new Error('Slice boundaries cannot cut through a retained bar interval');
|
|
}
|
|
}
|
|
const {
|
|
version: _version,
|
|
hash: _hash,
|
|
normalizationRevision: _revision,
|
|
parentDatasetHash,
|
|
volumePolicy: _volume,
|
|
qualityPolicy: _quality,
|
|
intradayPolicy: _intraday,
|
|
eligibility: _eligibility,
|
|
limitations: _limitations,
|
|
barCount: _count,
|
|
...rawMetadata
|
|
} = source.manifest;
|
|
const metadata = parseMetadata({ ...rawMetadata, bounds });
|
|
const bars = source.bars.filter(
|
|
bar => bar.intervalStart >= bounds.warmupStart && bar.intervalEnd <= bounds.tradeEnd
|
|
);
|
|
return finish(metadata, validateBars(metadata, bars), parentDatasetHash);
|
|
}
|
|
|
|
/** Unknown coverage remains exploratory; this assertion does not certify economic correctness. */
|
|
export function assertDatasetV2Executable(input: unknown): HistoricalDatasetV2 {
|
|
const dataset = validateDatasetV2(input);
|
|
if (dataset.manifest.eligibility === 'ineligible') {
|
|
throw new Error(`Dataset is not executable: ${dataset.manifest.limitations.join('; ')}`);
|
|
}
|
|
return dataset;
|
|
}
|
|
|
|
/** Explicit legacy adapter only: retain the validated original-v1 hash. */
|
|
export function createDatasetV2FromLegacy(
|
|
input: HistoricalDatasetInputV2,
|
|
parentHash: string
|
|
): HistoricalDatasetV2 {
|
|
const dataset = create(input, hash.parse(parentHash));
|
|
// The old application adapter guaranteed this before calling private create().
|
|
// Preserve that invariant at the new exported boundary, including prepared objects.
|
|
if (dataset.bars.some(bar => bar.vwap !== null)) {
|
|
throw new Error('Legacy v1 conversion requires unknown VWAP');
|
|
}
|
|
return dataset;
|
|
}
|