67 lines
2.4 KiB
TypeScript
67 lines
2.4 KiB
TypeScript
import {
|
|
createDatasetV2FromLegacy,
|
|
parseHistoricalDatasetMetadataV2,
|
|
} from '@stock-bot/research/datasets';
|
|
import type { HistoricalDatasetMetadataV2, HistoricalDatasetV2 } from '@stock-bot/types';
|
|
import { validateDataset } from './historical-dataset';
|
|
|
|
/** Compatibility entrypoint; legacy conversion remains application-owned. */
|
|
export * from '@stock-bot/research/datasets';
|
|
|
|
/** 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 = parseHistoricalDatasetMetadataV2(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 createDatasetV2FromLegacy({ metadata: normalized, bars }, legacy.manifest.hash);
|
|
}
|