feat(research): add financial contracts and availability-aware datasets
Implement reviewed F01/D01 foundations without changing active trading runtimes. Validate strict Rust/TypeScript financial wire contracts, decimal postings, versioned datasets, explicit calendars, provenance, and v1 compatibility.
This commit is contained in:
parent
243e9ab43f
commit
b4af840d4e
25 changed files with 4071 additions and 43 deletions
622
apps/stock/orchestrator/src/data/historical-dataset-v2.ts
Normal file
622
apps/stock/orchestrator/src/data/historical-dataset-v2.ts
Normal file
|
|
@ -0,0 +1,622 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
parseInstrumentId,
|
||||
type HistoricalBarV2,
|
||||
type HistoricalDatasetInputV2,
|
||||
type HistoricalDatasetMetadataV2,
|
||||
type HistoricalDatasetV2,
|
||||
} from '@stock-bot/types';
|
||||
import { validateDataset } from './historical-dataset';
|
||||
|
||||
const text = z.string().min(1);
|
||||
const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const price = z.number().finite().positive();
|
||||
const day = z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.refine(value => {
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value;
|
||||
}, 'Invalid session date');
|
||||
const hash = z
|
||||
.string()
|
||||
.length(64)
|
||||
.regex(/^[a-f0-9]{64}$/);
|
||||
const prices = {
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: z.number().finite().nonnegative(),
|
||||
};
|
||||
const metadataSchema = z
|
||||
.object({
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: text,
|
||||
venue: text,
|
||||
timeZone: text,
|
||||
revision: text,
|
||||
source: text,
|
||||
startDate: day,
|
||||
endDate: day,
|
||||
sessions: z
|
||||
.array(z.object({ date: day, open: instant, close: instant }).strict())
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
series: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: text,
|
||||
instrumentId: text,
|
||||
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
calendarId: text,
|
||||
venue: text,
|
||||
source: z.object({ provider: text, revision: text }).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: text, seriesId: text }).strict()).min(1),
|
||||
bounds: z.object({ warmupStart: instant, tradeStart: instant, tradeEnd: instant }).strict(),
|
||||
universe: z
|
||||
.object({
|
||||
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
|
||||
asOf: instant.nullable(),
|
||||
revision: text,
|
||||
instrumentIds: z.array(text).min(1),
|
||||
})
|
||||
.strict(),
|
||||
corporateActions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: text,
|
||||
status: z.enum(['unknown', 'action-free', 'known-actions']),
|
||||
start: instant,
|
||||
end: instant,
|
||||
revision: text,
|
||||
actions: z.array(
|
||||
z
|
||||
.object({
|
||||
effectiveAt: instant,
|
||||
kind: z.enum(['split', 'dividend', 'other']),
|
||||
reference: text,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict();
|
||||
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 manifestSchema = metadataSchema
|
||||
.extend({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
normalizationRevision: z.literal('historical-normalization-v2'),
|
||||
parentDatasetHash: hash.nullable(),
|
||||
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(text),
|
||||
barCount: z.number().int().positive(),
|
||||
})
|
||||
.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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** 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 conversion keeps the original v1 hash and treats all legacy VWAP as unknown. */
|
||||
export function convertDatasetV1ToV2(
|
||||
input: unknown,
|
||||
metadata: HistoricalDatasetMetadataV2
|
||||
): HistoricalDatasetV2 {
|
||||
const legacy = validateDataset(input);
|
||||
const normalized = parseMetadata(metadata);
|
||||
if (
|
||||
normalized.series.length !== legacy.manifest.instruments.length ||
|
||||
normalized.series.some(
|
||||
series =>
|
||||
series.interval !== legacy.manifest.interval ||
|
||||
series.adjustment !== legacy.manifest.policy.adjustment ||
|
||||
series.availability !== 'interval-end-assumption' ||
|
||||
!legacy.manifest.sources.some(
|
||||
source =>
|
||||
source.instrumentId === series.instrumentId &&
|
||||
source.provider === series.source.provider &&
|
||||
source.revision === series.source.revision
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'V1 conversion requires one matching source/interval/adjustment series per instrument'
|
||||
);
|
||||
}
|
||||
if (
|
||||
JSON.stringify(normalized.executionSeries.map(s => s.instrumentId)) !==
|
||||
JSON.stringify(legacy.manifest.instruments.map(i => i.id))
|
||||
) {
|
||||
throw new Error('V1 conversion must retain every instrument');
|
||||
}
|
||||
const sequences = new Map<string, number>();
|
||||
const bars = legacy.bars.map(bar => {
|
||||
const series = normalized.series.find(s => s.instrumentId === bar.symbol);
|
||||
if (!series) {
|
||||
throw new Error('V1 conversion is missing an instrument mapping');
|
||||
}
|
||||
const sourceSequence = sequences.get(series.id) ?? 0;
|
||||
sequences.set(series.id, sourceSequence + 1);
|
||||
return {
|
||||
seriesId: series.id,
|
||||
timestamp:
|
||||
series.interval === '1d'
|
||||
? new Date(bar.timestamp).toISOString().slice(0, 10)
|
||||
: bar.timestamp,
|
||||
sourceSequence,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: null,
|
||||
};
|
||||
});
|
||||
return create({ metadata: normalized, bars }, legacy.manifest.hash);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue