Freeze historical datasets and qualify backtest instrument identities
This commit is contained in:
parent
63c3856797
commit
d6b09eb635
43 changed files with 2249 additions and 1230 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { HistoricalDataset } from '@stock-bot/types';
|
||||
import { at } from '@stock-bot/utils';
|
||||
import { StorageService, type HistoricalBar } from '../services/StorageService';
|
||||
import { type Bar, type MarketData } from '../types';
|
||||
|
|
@ -12,15 +13,6 @@ export interface DataResolution {
|
|||
milliseconds: number;
|
||||
}
|
||||
|
||||
export interface CorporateAction {
|
||||
symbol: string;
|
||||
date: Date;
|
||||
type: 'split' | 'dividend' | 'spinoff';
|
||||
factor?: number;
|
||||
amount?: number;
|
||||
newSymbol?: string;
|
||||
}
|
||||
|
||||
export interface DataQualityIssue {
|
||||
timestamp: Date;
|
||||
symbol: string;
|
||||
|
|
@ -47,7 +39,6 @@ export class DataManager extends EventEmitter {
|
|||
|
||||
private dataCache: Map<string, MarketData[]> = new Map();
|
||||
private aggregatedCache: Map<string, Map<string, Bar[]>> = new Map();
|
||||
private corporateActions: Map<string, CorporateAction[]> = new Map();
|
||||
private dataQualityIssues: DataQualityIssue[] = [];
|
||||
|
||||
constructor(private storageService: StorageService) {
|
||||
|
|
@ -76,18 +67,10 @@ export class DataManager extends EventEmitter {
|
|||
if (!data.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
}
|
||||
this.recordQualityWarnings(symbol, data);
|
||||
|
||||
// Apply corporate actions
|
||||
const adjustedData = await this.applyCorporateActions(symbol, data, startDate, endDate);
|
||||
|
||||
// Quality checks
|
||||
const cleanedData = this.performQualityChecks(symbol, adjustedData);
|
||||
if (!cleanedData.length) {
|
||||
throw new Error(`No valid historical data for ${symbol}`);
|
||||
}
|
||||
|
||||
// Convert to MarketData format
|
||||
const marketData = this.convertToMarketData(symbol, cleanedData);
|
||||
// Storage owns validation and adjustment. Never interpolate or adjust a second time.
|
||||
const marketData = this.convertToMarketData(symbol, data);
|
||||
|
||||
result.set(symbol, marketData);
|
||||
this.dataCache.set(`${symbol}:${resolution}`, marketData);
|
||||
|
|
@ -104,140 +87,31 @@ export class DataManager extends EventEmitter {
|
|||
return result;
|
||||
}
|
||||
|
||||
async applyCorporateActions(
|
||||
symbol: string,
|
||||
data: HistoricalBar[],
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<HistoricalBar[]> {
|
||||
// Load corporate actions for the period
|
||||
const actions = await this.loadCorporateActions(symbol, startDate, endDate);
|
||||
if (actions.length === 0) {
|
||||
return data;
|
||||
/** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */
|
||||
inspectDataset(dataset: HistoricalDataset): void {
|
||||
this.clearCache();
|
||||
for (const instrument of dataset.manifest.instruments) {
|
||||
this.recordQualityWarnings(
|
||||
instrument.id,
|
||||
dataset.bars
|
||||
.filter(bar => bar.symbol === instrument.id)
|
||||
.map(bar => ({ ...bar, timestamp: new Date(bar.timestamp) }))
|
||||
);
|
||||
}
|
||||
|
||||
// Sort actions by date (newest first)
|
||||
actions.sort((a, b) => b.date.getTime() - a.date.getTime());
|
||||
|
||||
// Apply adjustments
|
||||
return data.map(bar => {
|
||||
const barDate = new Date(bar.timestamp);
|
||||
const adjustedBar = { ...bar };
|
||||
|
||||
for (const action of actions) {
|
||||
if (barDate < action.date) {
|
||||
switch (action.type) {
|
||||
case 'split':
|
||||
if (action.factor) {
|
||||
adjustedBar.open /= action.factor;
|
||||
adjustedBar.high /= action.factor;
|
||||
adjustedBar.low /= action.factor;
|
||||
adjustedBar.close /= action.factor;
|
||||
adjustedBar.volume *= action.factor;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'dividend':
|
||||
if (action.amount) {
|
||||
// Adjust for dividends (simplified)
|
||||
const adjustment = 1 - action.amount / adjustedBar.close;
|
||||
adjustedBar.open *= adjustment;
|
||||
adjustedBar.high *= adjustment;
|
||||
adjustedBar.low *= adjustment;
|
||||
adjustedBar.close *= adjustment;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return adjustedBar;
|
||||
});
|
||||
}
|
||||
|
||||
performQualityChecks(symbol: string, data: HistoricalBar[]): HistoricalBar[] {
|
||||
const cleaned: HistoricalBar[] = [];
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const bar = at(data, i);
|
||||
const prevBar = i > 0 ? data[i - 1] : null;
|
||||
const issues: string[] = [];
|
||||
|
||||
// Check for missing data
|
||||
if (!bar.open || !bar.high || !bar.low || !bar.close || bar.volume === undefined) {
|
||||
issues.push('Missing OHLCV data');
|
||||
}
|
||||
|
||||
// Check for invalid prices
|
||||
if (bar.low > bar.high) {
|
||||
issues.push('Low > High');
|
||||
}
|
||||
if (bar.open > bar.high || bar.open < bar.low) {
|
||||
issues.push('Open outside High/Low range');
|
||||
}
|
||||
if (bar.close > bar.high || bar.close < bar.low) {
|
||||
issues.push('Close outside High/Low range');
|
||||
}
|
||||
|
||||
// Check for zero or negative prices
|
||||
if (bar.open <= 0 || bar.high <= 0 || bar.low <= 0 || bar.close <= 0) {
|
||||
issues.push('Zero or negative prices');
|
||||
}
|
||||
|
||||
// Check for extreme price movements (>20% in one bar)
|
||||
if (prevBar) {
|
||||
const priceChange = Math.abs((bar.close - prevBar.close) / prevBar.close);
|
||||
if (priceChange > 0.2) {
|
||||
issues.push(`Extreme price movement: ${(priceChange * 100).toFixed(1)}%`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for volume spikes (>10x average)
|
||||
if (i >= 20) {
|
||||
const avgVolume = data.slice(i - 20, i).reduce((sum, b) => sum + b.volume, 0) / 20;
|
||||
if (bar.volume > avgVolume * 10) {
|
||||
issues.push('Volume spike detected');
|
||||
}
|
||||
}
|
||||
|
||||
// Handle issues
|
||||
if (issues.length > 0) {
|
||||
const severity = issues.some(issue => issue.includes('Missing') || issue.includes('Zero'))
|
||||
? 'error'
|
||||
: 'warning';
|
||||
|
||||
private recordQualityWarnings(symbol: string, bars: HistoricalBar[]): void {
|
||||
bars.forEach((bar, index) => {
|
||||
const previous = bars[index - 1];
|
||||
if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) {
|
||||
this.dataQualityIssues.push({
|
||||
timestamp: new Date(bar.timestamp),
|
||||
symbol,
|
||||
issue: issues.join(', '),
|
||||
severity,
|
||||
details: bar,
|
||||
issue: 'Price movement exceeds 20%; prices retained unchanged',
|
||||
severity: 'warning',
|
||||
});
|
||||
|
||||
// For errors, try to interpolate or skip
|
||||
if (severity === 'error') {
|
||||
if (prevBar && i < data.length - 1) {
|
||||
// Interpolate from surrounding bars
|
||||
const nextBar = at(data, i + 1);
|
||||
cleaned.push({
|
||||
...bar,
|
||||
open: (prevBar.close + nextBar.open) / 2,
|
||||
high: Math.max(prevBar.high, nextBar.high) * 0.9,
|
||||
low: Math.min(prevBar.low, nextBar.low) * 1.1,
|
||||
close: (prevBar.close + nextBar.close) / 2,
|
||||
volume: (prevBar.volume + nextBar.volume) / 2,
|
||||
interpolated: true,
|
||||
});
|
||||
}
|
||||
// Skip if we can't interpolate
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
cleaned.push(bar);
|
||||
}
|
||||
|
||||
return cleaned;
|
||||
});
|
||||
}
|
||||
|
||||
aggregateData(data: MarketData[], fromResolution: string, toResolution: string): Bar[] {
|
||||
|
|
@ -397,22 +271,6 @@ export class DataManager extends EventEmitter {
|
|||
}));
|
||||
}
|
||||
|
||||
private async loadCorporateActions(
|
||||
symbol: string,
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<CorporateAction[]> {
|
||||
// Check cache first
|
||||
const cached = this.corporateActions.get(symbol);
|
||||
if (cached) {
|
||||
return cached.filter(action => action.date >= startDate && action.date <= endDate);
|
||||
}
|
||||
|
||||
// In real implementation, load from database
|
||||
// For now, return empty array
|
||||
return [];
|
||||
}
|
||||
|
||||
getDataQualityReport(): {
|
||||
totalIssues: number;
|
||||
bySymbol: Record<string, number>;
|
||||
|
|
|
|||
231
apps/stock/orchestrator/src/data/historical-dataset.ts
Normal file
231
apps/stock/orchestrator/src/data/historical-dataset.ts
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
parseInstrumentId,
|
||||
validateHistoricalDataRequest,
|
||||
type HistoricalDataPolicy,
|
||||
type HistoricalDataset,
|
||||
} from '@stock-bot/types';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
export const instrumentIdSchema = z.string().refine(id => {
|
||||
try {
|
||||
parseInstrumentId(id);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, 'Use an exchange-qualified instrument ID, for example AAPL.US');
|
||||
export const historicalDataPolicySchema = z
|
||||
.object({
|
||||
adjustment: z.enum(['raw', 'provider-adjusted']),
|
||||
timestamp: z.enum(['utc-session-date', 'utc-instant']),
|
||||
})
|
||||
.strict();
|
||||
export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const positive = z.number().finite().positive();
|
||||
export const datasetBarSchema = z
|
||||
.object({
|
||||
symbol: instrumentIdSchema,
|
||||
timestamp: z.number().int().nonnegative(),
|
||||
open: positive,
|
||||
high: positive,
|
||||
low: positive,
|
||||
close: positive,
|
||||
volume: z.number().finite().nonnegative(),
|
||||
vwap: positive,
|
||||
})
|
||||
.strict();
|
||||
export const datasetManifestSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
hash: datasetHashSchema,
|
||||
instruments: z
|
||||
.array(
|
||||
z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict()
|
||||
)
|
||||
.min(1),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
policy: historicalDataPolicySchema,
|
||||
volumePolicy: z.literal('reported'),
|
||||
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
|
||||
sources: z.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: instrumentIdSchema,
|
||||
provider: z.enum(['eod', 'questdb', 'synthetic']),
|
||||
revision: z.string().min(1),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
barCount: z.number().int().positive(),
|
||||
})
|
||||
.strict();
|
||||
const datasetSchema = z
|
||||
.object({ manifest: datasetManifestSchema, bars: z.array(datasetBarSchema).min(1) })
|
||||
.strict();
|
||||
|
||||
export type DatasetResolver = (
|
||||
load: () => Promise<HistoricalDataset>
|
||||
) => Promise<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 hashDataset(dataset: HistoricalDataset): string {
|
||||
const { hash: _hash, ...manifest } = dataset.manifest;
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify({ manifest, bars: dataset.bars }))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
/** Parsing reconstructs a fixed property order before hashing, independent of JSONB key order. */
|
||||
export function validateDataset(input: unknown, config?: BacktestConfig): HistoricalDataset {
|
||||
const dataset = datasetSchema.parse(input);
|
||||
const m = dataset.manifest;
|
||||
const ids = m.instruments.map(i => i.id);
|
||||
const idSet = new Set(ids);
|
||||
const sortedIds = [...ids].sort();
|
||||
const start = Date.parse(m.startDate),
|
||||
end = Date.parse(m.endDate);
|
||||
validateHistoricalDataRequest({
|
||||
symbols: ids,
|
||||
startDate: m.startDate,
|
||||
endDate: m.endDate,
|
||||
dataFrequency: m.interval,
|
||||
dataPolicy: m.policy,
|
||||
datasetHash: m.hash,
|
||||
});
|
||||
if (
|
||||
ids.some((id, i) => id !== sortedIds[i]) ||
|
||||
m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) ||
|
||||
m.sources.length !== ids.length ||
|
||||
m.sources.some((s, i) => s.instrumentId !== ids[i]) ||
|
||||
m.barCount !== dataset.bars.length
|
||||
) {
|
||||
throw new Error('Invalid dataset manifest');
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
let previous: HistoricalDataset['bars'][number] | undefined;
|
||||
for (const bar of dataset.bars) {
|
||||
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');
|
||||
}
|
||||
seen.add(bar.symbol);
|
||||
previous = bar;
|
||||
}
|
||||
if (seen.size !== ids.length || hashDataset(dataset) !== m.hash) {
|
||||
throw new Error('Dataset hash/content mismatch');
|
||||
}
|
||||
if (
|
||||
config &&
|
||||
(JSON.stringify([...config.symbols].sort()) !== JSON.stringify(ids) ||
|
||||
new Date(config.startDate).toISOString() !== m.startDate ||
|
||||
new Date(config.endDate).toISOString() !== m.endDate ||
|
||||
config.dataFrequency !== m.interval ||
|
||||
JSON.stringify(dataPolicy(config)) !== JSON.stringify(m.policy) ||
|
||||
(config.datasetHash && config.datasetHash !== m.hash))
|
||||
) {
|
||||
throw new Error('Frozen dataset does not match the backtest request');
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
||||
export async function loadDataset(
|
||||
storage: StorageService,
|
||||
config: BacktestConfig
|
||||
): Promise<HistoricalDataset> {
|
||||
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) {
|
||||
const rows = await storage.getHistoricalBars(
|
||||
instrument.id,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency,
|
||||
policy
|
||||
);
|
||||
const source = rows[0]?.source;
|
||||
if (!source || rows.some(row => row.source !== 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) {
|
||||
bars.push({
|
||||
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.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,
|
||||
};
|
||||
// Canonicalize before hashing, including metadata key order.
|
||||
const canonical = datasetSchema.parse(dataset);
|
||||
canonical.manifest.hash = hashDataset(canonical);
|
||||
return validateDataset(canonical, config);
|
||||
}
|
||||
|
||||
export async function resolveDataset(
|
||||
storage: StorageService,
|
||||
config: BacktestConfig,
|
||||
resolver?: DatasetResolver
|
||||
) {
|
||||
if (config.datasetHash && !resolver) {
|
||||
throw new Error('Dataset replay requires the durable backtest runner');
|
||||
}
|
||||
return validateDataset(
|
||||
await (resolver ? resolver(() => loadDataset(storage, config)) : loadDataset(storage, config)),
|
||||
config
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue