stock-bot/apps/stock/orchestrator/src/data/historical-dataset.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

254 lines
8.1 KiB
TypeScript

import { createHash } from 'node:crypto';
import {
assertDatasetMatchesRequest,
validateDatasetManifestMetadata,
} from '@stock-bot/stock-config/backtest';
import {
parseInstrumentId,
validateHistoricalDataRequest,
type HistoricalDataPolicy,
type HistoricalDataset,
} from '@stock-bot/types';
import { datasetBarSchema } from '../contracts/historical';
import type { StorageService } from '@stock-bot/trading-runtime/historical-storage';
import type { BacktestConfig } from '../types';
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '@stock-bot/trading-runtime/preparation';
export type DatasetResolver = (
load: () => Promise<HistoricalDataset>,
signal?: AbortSignal
) => Promise<HistoricalDataset>;
// Only detached, deeply frozen values enter this cache. Mutable caller objects never do.
const prepared = new WeakSet<HistoricalDataset>();
export function dataPolicy(
config: Pick<BacktestConfig, 'dataFrequency' | 'dataPolicy'>
): HistoricalDataPolicy {
const policy = config.dataPolicy ?? {
adjustment: 'raw',
timestamp: config.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
};
if ((config.dataFrequency === '1d') !== (policy.timestamp === 'utc-session-date')) {
throw new Error('Daily bars require utc-session-date; intraday bars require utc-instant');
}
return policy;
}
function matchRequest(dataset: HistoricalDataset, config?: BacktestConfig): void {
if (config) {
assertDatasetMatchesRequest(dataset.manifest, config);
}
}
/** One canonical parse/order/hash boundary, driven synchronously or in cancellable batches. */
function* canonicalize(
input: unknown,
config: BacktestConfig | undefined,
signal?: AbortSignal,
assignHash = false
): Generator<void, HistoricalDataset> {
signal?.throwIfAborted();
if (input && typeof input === 'object' && prepared.has(input as HistoricalDataset)) {
const dataset = input as HistoricalDataset;
matchRequest(dataset, config);
return dataset;
}
if (
!input ||
typeof input !== 'object' ||
Array.isArray(input) ||
Object.keys(input).length !== 2 ||
!('manifest' in input) ||
!('bars' in input) ||
!Array.isArray(input.bars) ||
!input.bars.length
) {
throw new Error('Invalid historical dataset');
}
const m = validateDatasetManifestMetadata(input.manifest);
const ids = m.instruments.map(i => i.id);
const idSet = new Set(ids);
const start = Date.parse(m.startDate),
end = Date.parse(m.endDate);
if (m.barCount !== input.bars.length) {
throw new Error('Invalid dataset manifest');
}
const dataset: HistoricalDataset = { manifest: m, bars: [] };
matchRequest(dataset, assignHash ? undefined : config);
const { hash: _hash, ...manifest } = m;
// Identical bytes to v1 JSON.stringify({ manifest, bars }), without one giant string.
const hash = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`);
let chunk = '';
const seen = new Set<string>();
let previous: HistoricalDataset['bars'][number] | undefined;
for (let i = 0; i < input.bars.length; i++) {
signal?.throwIfAborted();
const bar = datasetBarSchema.parse(input.bars[i]);
if (
!idSet.has(bar.symbol) ||
bar.timestamp < start ||
bar.timestamp >= end ||
bar.high < Math.max(bar.open, bar.close) ||
bar.low > Math.min(bar.open, bar.close) ||
(m.policy.timestamp === 'utc-session-date' && bar.timestamp % 86400000 !== 0) ||
(previous &&
(bar.timestamp < previous.timestamp ||
(bar.timestamp === previous.timestamp && bar.symbol <= previous.symbol)))
) {
throw new Error('Invalid or unordered dataset bars');
}
const json = (i ? ',' : '') + JSON.stringify(bar);
chunk += json;
if (chunk.length >= 64 * 1024) {
hash.update(chunk);
chunk = '';
}
dataset.bars.push(Object.freeze(bar));
seen.add(bar.symbol);
previous = bar;
if ((i + 1) % PREPARATION_BATCH_SIZE === 0) {
yield;
}
}
const digest = hash.update(chunk).update(']}').digest('hex');
if (seen.size !== ids.length || (!assignHash && digest !== m.hash)) {
throw new Error('Dataset hash/content mismatch');
}
m.hash = digest;
matchRequest(dataset, config);
for (const identity of m.instruments) {
Object.freeze(identity);
}
for (const source of m.sources) {
Object.freeze(source);
}
Object.freeze(m.instruments);
Object.freeze(m.sources);
Object.freeze(m.policy);
Object.freeze(m);
Object.freeze(dataset.bars);
Object.freeze(dataset);
prepared.add(dataset);
return dataset;
}
/** Untrusted values are detached and fully checked; only prepared immutable values are reused. */
export function validateDataset(
input: unknown,
config?: BacktestConfig,
signal?: AbortSignal
): HistoricalDataset {
const work = canonicalize(input, config, signal);
let step = work.next();
while (!step.done) {
step = work.next();
}
return step.value;
}
async function finishPreparation(work: Generator<void, HistoricalDataset>, signal?: AbortSignal) {
let step = work.next();
while (!step.done) {
await preparationCheckpoint(signal);
step = work.next();
}
signal?.throwIfAborted();
return step.value;
}
export function prepareDataset(
input: unknown,
config?: BacktestConfig,
signal?: AbortSignal
): Promise<HistoricalDataset> {
return finishPreparation(canonicalize(input, config, signal), signal);
}
export async function loadDataset(
storage: Pick<StorageService, 'getHistoricalBars'>,
config: BacktestConfig,
signal?: AbortSignal
): Promise<HistoricalDataset> {
signal?.throwIfAborted();
validateHistoricalDataRequest(config);
const instruments = [...config.symbols].sort().map(parseInstrumentId);
const policy = dataPolicy(config);
const bars: HistoricalDataset['bars'] = [];
const sources: HistoricalDataset['manifest']['sources'] = [];
for (const instrument of instruments) {
signal?.throwIfAborted();
const rows = await storage.getHistoricalBars(
instrument.id,
new Date(config.startDate),
new Date(config.endDate),
config.dataFrequency,
policy,
signal,
config.dataSource ?? 'auto'
);
signal?.throwIfAborted();
const source = rows[0]?.source;
if (!source) {
throw new Error('Historical source provenance is missing or mixed');
}
sources.push({
instrumentId: instrument.id,
provider: source,
revision: 'historical-normalization-v1',
});
for (const bar of rows) {
if (bar.source !== source) {
throw new Error('Historical source provenance is missing or mixed');
}
const value = {
symbol: instrument.id,
timestamp: bar.timestamp.getTime(),
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
};
bars.push(value);
if (bars.length % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
}
signal?.throwIfAborted();
bars.sort(
(a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : a.symbol > b.symbol ? 1 : 0)
);
const dataset: HistoricalDataset = {
manifest: {
version: 1,
hash: '0'.repeat(64),
instruments,
startDate: new Date(config.startDate).toISOString(),
endDate: new Date(config.endDate).toISOString(),
interval: config.dataFrequency,
policy,
volumePolicy: 'reported',
qualityPolicy: 'reject-invalid-no-interpolation',
sources,
barCount: bars.length,
},
bars,
};
return finishPreparation(canonicalize(dataset, config, signal, true), signal);
}
export async function resolveDataset(
storage: Pick<StorageService, 'getHistoricalBars'>,
config: BacktestConfig,
resolver?: DatasetResolver,
signal?: AbortSignal
) {
signal?.throwIfAborted();
if (config.datasetHash && !resolver) {
throw new Error('Dataset replay requires the durable backtest runner');
}
const load = () => loadDataset(storage, config, signal);
return prepareDataset(await (resolver ? resolver(load, signal) : load()), config, signal);
}