Bound backtest dataset preparation and preserve replay identity

This commit is contained in:
Boki 2026-10-21 23:18:23 -04:00
parent cca5d71e6e
commit 6bd671d92a
20 changed files with 1420 additions and 155 deletions

View file

@ -5,8 +5,19 @@ import type {
QuestDBClient,
} from '@stock-bot/services';
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
import {
assertDatasetLimit,
datasetLimits,
PREPARATION_BATCH_SIZE,
preparationCheckpoint,
} from '../data/dataset-limits';
import type { MarketData, ModeConfig, PerformanceMetrics } from '../types';
export interface HistoricalReadOptions {
maxBars?: number;
signal?: AbortSignal;
}
export interface HistoricalBar {
symbol: string;
timestamp: Date;
@ -174,8 +185,11 @@ export class StorageService {
policy: HistoricalDataPolicy = {
adjustment: 'raw',
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
}
},
options: HistoricalReadOptions = {}
): Promise<HistoricalBar[]> {
const limits = datasetLimits({ maxBars: options.maxBars ?? datasetLimits().maxBars });
options.signal?.throwIfAborted();
parseInstrumentId(symbol);
if (
!Number.isFinite(startTime.getTime()) ||
@ -196,63 +210,77 @@ export class StorageService {
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
);
}
const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval);
const bars = rows
.map(row => {
if (row.symbol !== symbol) {
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
const rows = await this.readHistoricalBars(
symbol,
startTime,
endTime,
interval,
limits.maxBars
);
options.signal?.throwIfAborted();
assertDatasetLimit(limits, 'maxBars', rows.length);
const bars: HistoricalBar[] = [];
let processed = 0;
for (const row of rows) {
if (row.symbol !== symbol) {
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
}
if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) {
throw new Error('Historical instants require an explicit UTC offset');
}
const timestamp = new Date(row.timestamp);
const numeric = (value: unknown) =>
typeof value === 'number'
? value
: typeof value === 'string' && value.trim()
? Number(value)
: NaN;
let open = numeric(row.open),
high = numeric(row.high),
low = numeric(row.low),
close = numeric(row.close);
const volume = numeric(row.volume);
if (
!Number.isFinite(timestamp.getTime()) ||
![open, high, low, close, volume].every(Number.isFinite) ||
low <= 0 ||
high < Math.max(open, close) ||
low > Math.min(open, close) ||
volume < 0 ||
(interval === '1d' && timestamp.getTime() % 86400000 !== 0)
) {
throw new Error(`Invalid historical OHLCV data for ${symbol}`);
}
let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap);
if (policy.adjustment === 'provider-adjusted') {
const adjustedClose = numeric(row.adjustedClose);
if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) {
throw new Error(`Provider-adjusted prices unavailable for ${symbol}`);
}
if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) {
throw new Error('Historical instants require an explicit UTC offset');
const factor = adjustedClose / close;
open *= factor;
high *= factor;
low *= factor;
close = adjustedClose;
if (vwap !== undefined) {
vwap *= factor;
}
const timestamp = new Date(row.timestamp);
const numeric = (value: unknown) =>
typeof value === 'number'
? value
: typeof value === 'string' && value.trim()
? Number(value)
: NaN;
let open = numeric(row.open),
high = numeric(row.high),
low = numeric(row.low),
close = numeric(row.close);
const volume = numeric(row.volume);
if (
!Number.isFinite(timestamp.getTime()) ||
![open, high, low, close, volume].every(Number.isFinite) ||
low <= 0 ||
high < Math.max(open, close) ||
low > Math.min(open, close) ||
volume < 0 ||
(interval === '1d' && timestamp.getTime() % 86400000 !== 0)
) {
throw new Error(`Invalid historical OHLCV data for ${symbol}`);
}
let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap);
if (policy.adjustment === 'provider-adjusted') {
const adjustedClose = numeric(row.adjustedClose);
if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) {
throw new Error(`Provider-adjusted prices unavailable for ${symbol}`);
}
const factor = adjustedClose / close;
open *= factor;
high *= factor;
low *= factor;
close = adjustedClose;
if (vwap !== undefined) {
vwap *= factor;
}
}
if (
![open, high, low, close].every(value => Number.isFinite(value) && value > 0) ||
(vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0))
) {
throw new Error(`Invalid adjusted historical data for ${symbol}`);
}
return { ...row, symbol, timestamp, open, high, low, close, volume, vwap };
})
.filter(bar => bar.timestamp >= startTime && bar.timestamp < endTime)
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
}
if (
![open, high, low, close].every(value => Number.isFinite(value) && value > 0) ||
(vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0))
) {
throw new Error(`Invalid adjusted historical data for ${symbol}`);
}
if (timestamp >= startTime && timestamp < endTime) {
bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap });
}
if (++processed % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(options.signal);
}
}
options.signal?.throwIfAborted();
bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
if (!bars.length) {
throw new Error(`No historical data for ${symbol}`);
}
@ -271,7 +299,8 @@ export class StorageService {
symbol: string,
startTime: Date,
endTime: Date,
interval: string = '1m'
interval: string,
maxBars: number
): Promise<HistoricalBar[]> {
// If QuestDB is available, use real data
if (this.questdb) {
@ -279,9 +308,10 @@ export class StorageService {
throw new Error('Unsupported historical interval');
}
const result = await this.questdb.query<HistoricalBar>(
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`,
[symbol, startTime, endTime]
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp LIMIT $4`,
[symbol, startTime, endTime, maxBars + 1]
);
assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', result.rows.length);
return result.rows.map(row => ({ ...row, source: 'questdb' }));
}
@ -311,8 +341,25 @@ export class StorageService {
$lt: endTime.toISOString().slice(0, 10),
},
},
{ sort: { date: 1 } }
{
sort: { date: 1 },
limit: maxBars + 1,
projection: {
symbol: 1,
exchange: 1,
eodSearchCode: 1,
providerExchange: 1,
date: 1,
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
adjustedClose: 1,
},
}
);
assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', prices.length);
return prices.map(price => {
if (
price.eodSearchCode !== identity.id ||
@ -346,6 +393,11 @@ export class StorageService {
'No historical data store configured; synthetic data requires explicit opt-in'
);
}
assertDatasetLimit(
datasetLimits({ maxBars }),
'maxBars',
Math.ceil((endTime.getTime() - startTime.getTime()) / this.getIntervalMilliseconds(interval))
);
return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({
...bar,
source: 'synthetic',