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>;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue