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
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,307 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { at, defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { HistoricalDataset } from '@stock-bot/types';
|
||||
import type { HistoricalBar, StorageService } from '../services/StorageService';
|
||||
import { type Bar, type MarketData } from '../types';
|
||||
|
||||
const logger = getLogger('DataManager');
|
||||
|
||||
export interface DataResolution {
|
||||
interval: string;
|
||||
milliseconds: number;
|
||||
}
|
||||
|
||||
export interface DataQualityIssue {
|
||||
timestamp: Date;
|
||||
symbol: string;
|
||||
issue: string;
|
||||
severity: 'warning' | 'error';
|
||||
details?: unknown;
|
||||
}
|
||||
|
||||
export class DataManager extends EventEmitter {
|
||||
private static RESOLUTIONS: Record<string, DataResolution> = {
|
||||
tick: { interval: 'tick', milliseconds: 0 },
|
||||
'1s': { interval: '1s', milliseconds: 1000 },
|
||||
'5s': { interval: '5s', milliseconds: 5000 },
|
||||
'10s': { interval: '10s', milliseconds: 10000 },
|
||||
'30s': { interval: '30s', milliseconds: 30000 },
|
||||
'1m': { interval: '1m', milliseconds: 60000 },
|
||||
'5m': { interval: '5m', milliseconds: 300000 },
|
||||
'15m': { interval: '15m', milliseconds: 900000 },
|
||||
'30m': { interval: '30m', milliseconds: 1800000 },
|
||||
'1h': { interval: '1h', milliseconds: 3600000 },
|
||||
'4h': { interval: '4h', milliseconds: 14400000 },
|
||||
'1d': { interval: '1d', milliseconds: 86400000 },
|
||||
};
|
||||
|
||||
private dataCache: Map<string, MarketData[]> = new Map();
|
||||
private aggregatedCache: Map<string, Map<string, Bar[]>> = new Map();
|
||||
private dataQualityIssues: DataQualityIssue[] = [];
|
||||
|
||||
constructor(private storageService: Pick<StorageService, 'getHistoricalBars'>) {
|
||||
super();
|
||||
}
|
||||
|
||||
async loadHistoricalData(
|
||||
symbols: string[],
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
resolution: string = '1m',
|
||||
_includeExtendedHours: boolean = false
|
||||
): Promise<Map<string, MarketData[]>> {
|
||||
const result = new Map<string, MarketData[]>();
|
||||
|
||||
for (const symbol of symbols) {
|
||||
try {
|
||||
// Load raw data
|
||||
const data = await this.storageService.getHistoricalBars(
|
||||
symbol,
|
||||
startDate,
|
||||
endDate,
|
||||
resolution
|
||||
);
|
||||
|
||||
if (!data.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
}
|
||||
this.recordQualityWarnings(symbol, data);
|
||||
|
||||
// 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);
|
||||
|
||||
logger.info(`Loaded ${marketData.length} bars for ${symbol} at ${resolution} resolution`);
|
||||
} catch (error) {
|
||||
logger.error(`Failed to load data for ${symbol}:`, error);
|
||||
this.emit('dataError', { symbol, error });
|
||||
this.dataCache.clear();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */
|
||||
inspectDataset(dataset: HistoricalDataset): void {
|
||||
this.clearCache();
|
||||
const grouped = new Map<string, HistoricalDataset['bars']>();
|
||||
for (const bar of dataset.bars) {
|
||||
let bars = grouped.get(bar.symbol);
|
||||
if (!bars) {
|
||||
bars = [];
|
||||
grouped.set(bar.symbol, bars);
|
||||
}
|
||||
bars.push(bar);
|
||||
}
|
||||
for (const instrument of dataset.manifest.instruments) {
|
||||
this.recordQualityWarnings(instrument.id, grouped.get(instrument.id) ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
private recordQualityWarnings(
|
||||
symbol: string,
|
||||
bars: readonly { timestamp: Date | number; close: number }[]
|
||||
): 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: 'Price movement exceeds 20%; prices retained unchanged',
|
||||
severity: 'warning',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
aggregateData(data: MarketData[], fromResolution: string, toResolution: string): Bar[] {
|
||||
const fromMs = DataManager.RESOLUTIONS[fromResolution]?.milliseconds;
|
||||
const toMs = DataManager.RESOLUTIONS[toResolution]?.milliseconds;
|
||||
|
||||
if (!fromMs || !toMs || fromMs >= toMs) {
|
||||
throw new Error(`Cannot aggregate from ${fromResolution} to ${toResolution}`);
|
||||
}
|
||||
|
||||
const bars: Bar[] = [];
|
||||
let currentBar: Partial<Bar> | null = null;
|
||||
let barStartTime = 0;
|
||||
|
||||
for (const item of data) {
|
||||
if (item.type !== 'bar') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const bar = item.data;
|
||||
const timestamp = bar.timestamp;
|
||||
const alignedTime = Math.floor(timestamp / toMs) * toMs;
|
||||
|
||||
if (!currentBar || alignedTime > barStartTime) {
|
||||
// Finalize previous bar
|
||||
if (currentBar && currentBar.open !== undefined) {
|
||||
bars.push(currentBar as Bar);
|
||||
}
|
||||
|
||||
// Start new bar
|
||||
currentBar = {
|
||||
timestamp: alignedTime,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap,
|
||||
};
|
||||
barStartTime = alignedTime;
|
||||
} else {
|
||||
// Update current bar
|
||||
currentBar.high = Math.max(defined(currentBar.high), bar.high);
|
||||
currentBar.low = Math.min(defined(currentBar.low), bar.low);
|
||||
currentBar.close = bar.close;
|
||||
currentBar.volume = (currentBar.volume ?? 0) + bar.volume;
|
||||
|
||||
// Recalculate VWAP if available
|
||||
if (bar.vwap && currentBar.vwap) {
|
||||
const totalValue =
|
||||
currentBar.vwap * (defined(currentBar.volume) - bar.volume) + bar.vwap * bar.volume;
|
||||
currentBar.vwap = totalValue / defined(currentBar.volume);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add final bar
|
||||
if (currentBar && currentBar.open !== undefined) {
|
||||
bars.push(currentBar as Bar);
|
||||
}
|
||||
|
||||
return bars;
|
||||
}
|
||||
|
||||
downsampleData(data: MarketData[], targetPoints: number): MarketData[] {
|
||||
if (data.length <= targetPoints) {
|
||||
return data;
|
||||
}
|
||||
|
||||
// Use LTTB (Largest Triangle Three Buckets) algorithm
|
||||
const downsampled: MarketData[] = [];
|
||||
const bucketSize = (data.length - 2) / (targetPoints - 2);
|
||||
|
||||
// Always include first point
|
||||
downsampled.push(at(data, 0));
|
||||
|
||||
for (let i = 0; i < targetPoints - 2; i++) {
|
||||
const bucketStart = Math.floor(i * bucketSize) + 1;
|
||||
const bucketEnd = Math.floor((i + 1) * bucketSize) + 1;
|
||||
|
||||
// Find point with maximum area in bucket
|
||||
let maxArea = -1;
|
||||
let maxAreaPoint = 0;
|
||||
|
||||
const prevPoint = at(downsampled, downsampled.length - 1);
|
||||
const prevTime = prevPoint.data.timestamp;
|
||||
const prevPrice = this.getPrice(prevPoint);
|
||||
|
||||
// Calculate average of next bucket for area calculation
|
||||
const nextBucketStart = Math.floor((i + 1) * bucketSize) + 1;
|
||||
let nextBucketEnd = Math.floor((i + 2) * bucketSize) + 1;
|
||||
if (nextBucketEnd >= data.length) {
|
||||
nextBucketEnd = data.length - 1;
|
||||
}
|
||||
|
||||
let avgTime = 0;
|
||||
let avgPrice = 0;
|
||||
for (let j = nextBucketStart; j < nextBucketEnd; j++) {
|
||||
avgTime += at(data, j).data.timestamp;
|
||||
avgPrice += this.getPrice(at(data, j));
|
||||
}
|
||||
avgTime /= nextBucketEnd - nextBucketStart;
|
||||
avgPrice /= nextBucketEnd - nextBucketStart;
|
||||
|
||||
// Find point with max area
|
||||
for (let j = bucketStart; j < bucketEnd && j < data.length; j++) {
|
||||
const time = at(data, j).data.timestamp;
|
||||
const price = this.getPrice(at(data, j));
|
||||
|
||||
// Calculate triangle area
|
||||
const area = Math.abs(
|
||||
(prevTime - avgTime) * (price - prevPrice) - (prevTime - time) * (avgPrice - prevPrice)
|
||||
);
|
||||
|
||||
if (area > maxArea) {
|
||||
maxArea = area;
|
||||
maxAreaPoint = j;
|
||||
}
|
||||
}
|
||||
|
||||
downsampled.push(at(data, maxAreaPoint));
|
||||
}
|
||||
|
||||
// Always include last point
|
||||
downsampled.push(at(data, data.length - 1));
|
||||
|
||||
return downsampled;
|
||||
}
|
||||
|
||||
private getPrice(data: MarketData): number {
|
||||
switch (data.type) {
|
||||
case 'bar':
|
||||
return data.data.close;
|
||||
case 'trade':
|
||||
return data.data.price;
|
||||
case 'quote':
|
||||
return (data.data.bid + data.data.ask) / 2;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private convertToMarketData(symbol: string, bars: HistoricalBar[]): MarketData[] {
|
||||
return bars.map(bar => ({
|
||||
type: 'bar' as const,
|
||||
data: {
|
||||
symbol,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap,
|
||||
timestamp: new Date(bar.timestamp).getTime(),
|
||||
interpolated: bar.interpolated,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
getDataQualityReport(): {
|
||||
totalIssues: number;
|
||||
bySymbol: Record<string, number>;
|
||||
bySeverity: Record<string, number>;
|
||||
issues: DataQualityIssue[];
|
||||
} {
|
||||
const bySymbol: Record<string, number> = {};
|
||||
const bySeverity: Record<string, number> = { warning: 0, error: 0 };
|
||||
|
||||
for (const issue of this.dataQualityIssues) {
|
||||
bySymbol[issue.symbol] = (bySymbol[issue.symbol] || 0) + 1;
|
||||
bySeverity[issue.severity] = (bySeverity[issue.severity] ?? 0) + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
totalIssues: this.dataQualityIssues.length,
|
||||
bySymbol,
|
||||
bySeverity,
|
||||
issues: this.dataQualityIssues,
|
||||
};
|
||||
}
|
||||
|
||||
clearCache(): void {
|
||||
this.dataCache.clear();
|
||||
this.aggregatedCache.clear();
|
||||
this.dataQualityIssues = [];
|
||||
}
|
||||
}
|
||||
|
|
@ -10,9 +10,9 @@ import {
|
|||
type HistoricalDataset,
|
||||
} from '@stock-bot/types';
|
||||
import { datasetBarSchema } from '../contracts/historical';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { StorageService } from '@stock-bot/trading-runtime/historical-storage';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '@stock-bot/trading-runtime/preparation';
|
||||
|
||||
export type DatasetResolver = (
|
||||
load: () => Promise<HistoricalDataset>,
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/preparation';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/retained-dataset';
|
||||
Loading…
Add table
Add a link
Reference in a new issue