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
|
|
@ -3,6 +3,7 @@ import { defined } from '@stock-bot/invariants';
|
|||
import { at } from '@stock-bot/utils';
|
||||
import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
|
||||
import { DataManager } from '../data/DataManager';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import type { Signal } from '../strategies/BaseStrategy';
|
||||
import { StrategyManager } from '../strategies/StrategyManager';
|
||||
|
|
@ -62,7 +63,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
// this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital);
|
||||
}
|
||||
|
||||
async runBacktest(config: unknown): Promise<BacktestResult> {
|
||||
async runBacktest(config: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
||||
// Validate config
|
||||
const validatedConfig = BacktestConfigSchema.parse(config);
|
||||
|
||||
|
|
@ -126,24 +127,20 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
}
|
||||
|
||||
try {
|
||||
// Load historical data with multi-resolution support
|
||||
const dataMap = await this.dataManager.loadHistoricalData(
|
||||
validatedConfig.symbols,
|
||||
new Date(validatedConfig.startDate),
|
||||
new Date(validatedConfig.endDate),
|
||||
validatedConfig.dataFrequency,
|
||||
true // Include extended hours
|
||||
);
|
||||
// Both engines execute exactly these frozen, already-normalized bars.
|
||||
const dataset = await resolveDataset(this.storageService, validatedConfig, resolver);
|
||||
this.dataManager.inspectDataset(dataset);
|
||||
this.marketSimulator.resetWithSeed(Number.parseInt(dataset.manifest.hash.slice(0, 8), 16));
|
||||
|
||||
// Load market microstructure for each symbol
|
||||
await this.loadMarketMicrostructure(validatedConfig.symbols);
|
||||
|
||||
// Convert to flat array and sort by time
|
||||
const marketData: MarketData[] = [];
|
||||
dataMap.forEach((data, _symbol) => {
|
||||
marketData.push(...data);
|
||||
});
|
||||
marketData.sort((a, b) => a.data.timestamp - b.data.timestamp);
|
||||
const marketData: MarketData[] = dataset.bars.map(bar => ({
|
||||
type: 'bar',
|
||||
data: bar,
|
||||
eventId: `${dataset.manifest.hash}:${bar.symbol}:${bar.timestamp}`,
|
||||
}));
|
||||
|
||||
this.container.logger.info(`Loaded ${marketData.length} market data points`);
|
||||
|
||||
|
|
@ -157,12 +154,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
allocation: 1 / (validatedConfig.strategies?.length ?? 1),
|
||||
})) || [
|
||||
{
|
||||
id: `${validatedConfig.strategy}-${Date.now()}`,
|
||||
id: `${validatedConfig.strategy}-0`,
|
||||
name: validatedConfig.strategy,
|
||||
enabled: true,
|
||||
parameters: {
|
||||
symbols: validatedConfig.symbols,
|
||||
initialCapital: validatedConfig.initialCapital,
|
||||
...validatedConfig.config,
|
||||
// Add any default strategy parameters here
|
||||
},
|
||||
symbols: validatedConfig.symbols,
|
||||
|
|
@ -784,10 +782,10 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
for (const symbol of symbols) {
|
||||
const microstructure: MarketMicrostructure = {
|
||||
symbol,
|
||||
avgSpreadBps: 2 + Math.random() * 3, // 2-5 bps
|
||||
dailyVolume: 10_000_000 * (1 + Math.random() * 9), // 10-100M shares
|
||||
avgTradeSize: 100 + Math.random() * 400, // 100-500 shares
|
||||
volatility: 0.15 + Math.random() * 0.25, // 15-40% annual vol
|
||||
avgSpreadBps: 3,
|
||||
dailyVolume: 10_000_000,
|
||||
avgTradeSize: 100,
|
||||
volatility: 0.2,
|
||||
tickSize: 0.01,
|
||||
lotSize: 1,
|
||||
intradayVolumeProfile: this.generateIntradayProfile(),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { z } from 'zod';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { validateHistoricalDataRequest } from '@stock-bot/types';
|
||||
import { dataPolicy, validateDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
||||
import { normalizeBacktestResult } from './result';
|
||||
|
|
@ -14,6 +16,8 @@ import {
|
|||
|
||||
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
||||
const config = BacktestConfigSchema.parse(input);
|
||||
validateHistoricalDataRequest(config);
|
||||
dataPolicy(config);
|
||||
if (new Date(config.endDate) <= new Date(config.startDate)) {
|
||||
throw new z.ZodError([
|
||||
{ code: 'custom', path: ['endDate'], message: 'Backtest endDate must be after startDate' },
|
||||
|
|
@ -193,7 +197,24 @@ export class BacktestRunner extends EventEmitter {
|
|||
throw new BacktestCancelledError();
|
||||
}
|
||||
this.phase = 'executing';
|
||||
const raw = await this.dependencies.engine.runBacktest(executionConfig);
|
||||
let manifest: HistoricalDatasetManifest | undefined;
|
||||
const claim = this.active;
|
||||
const raw = await this.dependencies.engine.runBacktest(executionConfig, async load => {
|
||||
const saved = await this.dependencies.repository.loadDataset(
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
executionConfig.datasetHash
|
||||
);
|
||||
const dataset = validateDataset(saved ?? (await load()), executionConfig);
|
||||
const frozen =
|
||||
saved ??
|
||||
(await this.dependencies.repository.freezeDataset(claim.runId, claim.attemptId, dataset));
|
||||
manifest = frozen.manifest;
|
||||
return frozen;
|
||||
});
|
||||
if (!manifest) {
|
||||
throw new Error('Backtest engine did not resolve frozen execution inputs');
|
||||
}
|
||||
if (this.leaseFailure) {
|
||||
throw this.leaseFailure;
|
||||
}
|
||||
|
|
@ -206,7 +227,8 @@ export class BacktestRunner extends EventEmitter {
|
|||
executionConfig,
|
||||
this.active,
|
||||
performance.now() - started,
|
||||
this.cancelled
|
||||
this.cancelled,
|
||||
manifest
|
||||
);
|
||||
} catch (error) {
|
||||
throw new Error('Backtest engine returned an invalid result', { cause: error });
|
||||
|
|
|
|||
|
|
@ -34,6 +34,20 @@ export class MarketSimulator {
|
|||
private liquidityProfiles: Map<string, LiquidityProfile> = new Map();
|
||||
private lastTrades: Map<string, Trade> = new Map();
|
||||
private config: SimulationConfig;
|
||||
private randomState = 1;
|
||||
|
||||
resetWithSeed(seed: number): void {
|
||||
this.randomState = seed >>> 0;
|
||||
this.orderBooks.clear();
|
||||
this.microstructures.clear();
|
||||
this.liquidityProfiles.clear();
|
||||
this.lastTrades.clear();
|
||||
}
|
||||
|
||||
private random(): number {
|
||||
this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0;
|
||||
return this.randomState / 4294967296;
|
||||
}
|
||||
|
||||
constructor(config: Partial<SimulationConfig> = {}) {
|
||||
this.config = {
|
||||
|
|
@ -158,12 +172,12 @@ export class MarketSimulator {
|
|||
|
||||
// Hidden liquidity modeling
|
||||
const hiddenRatio = this.config.modelHiddenLiquidity
|
||||
? 1 + Math.random() * 2 // 1-3x visible size hidden
|
||||
? 1 + this.random() * 2 // 1-3x visible size hidden
|
||||
: 1;
|
||||
|
||||
// Bid levels
|
||||
const bidPrice = topQuote.bid - i * micro.tickSize;
|
||||
const bidSize = topQuote.bidSize * depthFactor * (0.8 + Math.random() * 0.4);
|
||||
const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
bids.push({
|
||||
price: bidPrice,
|
||||
size: Math.round(bidSize / micro.lotSize) * micro.lotSize,
|
||||
|
|
@ -173,7 +187,7 @@ export class MarketSimulator {
|
|||
|
||||
// Ask levels
|
||||
const askPrice = topQuote.ask + i * micro.tickSize;
|
||||
const askSize = topQuote.askSize * depthFactor * (0.8 + Math.random() * 0.4);
|
||||
const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
asks.push({
|
||||
price: askPrice,
|
||||
size: Math.round(askSize / micro.lotSize) * micro.lotSize,
|
||||
|
|
@ -218,7 +232,7 @@ export class MarketSimulator {
|
|||
for (let i = 1; i < current.bids.length; i++) {
|
||||
// Adjust sizes based on top of book changes
|
||||
const sizeRatio = quote.bidSize / (at(current.bids, 0).size || quote.bidSize);
|
||||
at(current.bids, i).size *= sizeRatio * (0.9 + Math.random() * 0.2);
|
||||
at(current.bids, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
// Adjust prices to maintain relative spacing
|
||||
const spacing = (at(current.bids, i - 1).price - at(current.bids, i).price) * spreadRatio;
|
||||
|
|
@ -227,7 +241,7 @@ export class MarketSimulator {
|
|||
|
||||
for (let i = 1; i < current.asks.length; i++) {
|
||||
const sizeRatio = quote.askSize / (at(current.asks, 0).size || quote.askSize);
|
||||
at(current.asks, i).size *= sizeRatio * (0.9 + Math.random() * 0.2);
|
||||
at(current.asks, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
const spacing = (at(current.asks, i).price - at(current.asks, i - 1).price) * spreadRatio;
|
||||
at(current.asks, i).price = at(current.asks, i - 1).price + spacing;
|
||||
|
|
@ -285,7 +299,7 @@ export class MarketSimulator {
|
|||
// Calculate available liquidity including hidden
|
||||
let availableSize = level.size;
|
||||
if (level.hiddenSize && this.config.modelHiddenLiquidity) {
|
||||
availableSize += level.hiddenSize * Math.random(); // Hidden liquidity probabilistic
|
||||
availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity
|
||||
}
|
||||
|
||||
const fillSize = Math.min(remainingSize, availableSize);
|
||||
|
|
@ -293,7 +307,7 @@ export class MarketSimulator {
|
|||
// Simulate latency - price might move
|
||||
if (this.config.latencyMs > 0 && orderType === 'market') {
|
||||
const priceMovement = microstructure
|
||||
? (((Math.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
|
||||
? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
|
||||
: 0;
|
||||
level.price += priceMovement * multiplier;
|
||||
}
|
||||
|
|
@ -319,7 +333,7 @@ export class MarketSimulator {
|
|||
// Dark pool execution for remaining size
|
||||
if (remainingSize > 0 && this.config.includeDarkPools && liquidityProfile) {
|
||||
const darkPoolPct = liquidityProfile.darkPoolLiquidity / liquidityProfile.totalLiquidity;
|
||||
const darkPoolSize = remainingSize * darkPoolPct * Math.random();
|
||||
const darkPoolSize = remainingSize * darkPoolPct * this.random();
|
||||
|
||||
if (darkPoolSize > 0) {
|
||||
const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { validateDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError } from './execution-engine';
|
||||
import {
|
||||
|
|
@ -126,6 +127,93 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
async loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
requestedHash?: string
|
||||
): Promise<HistoricalDataset | null> {
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`,
|
||||
[runId, attemptId]
|
||||
);
|
||||
if (!owned.rows[0]) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
const hash = owned.rows[0].dataset_hash ?? requestedHash;
|
||||
if (!hash) {
|
||||
return null;
|
||||
}
|
||||
if (requestedHash && requestedHash !== hash) {
|
||||
throw new BacktestConflictError('Run dataset is already frozen');
|
||||
}
|
||||
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
if (!saved.rows[0]) {
|
||||
throw new Error('Frozen dataset not found');
|
||||
}
|
||||
const dataset = validateDataset(saved.rows[0].payload);
|
||||
if (dataset.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
const pinned = await client.query(
|
||||
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
|
||||
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
|
||||
[runId, hash, attemptId]
|
||||
);
|
||||
if (!pinned.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
|
||||
}
|
||||
return dataset;
|
||||
});
|
||||
}
|
||||
|
||||
async freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
input: HistoricalDataset
|
||||
): Promise<HistoricalDataset> {
|
||||
const dataset = validateDataset(input);
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`,
|
||||
[runId, attemptId]
|
||||
);
|
||||
if (!owned.rows[0]) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
const hash = dataset.manifest.hash;
|
||||
if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) {
|
||||
throw new BacktestConflictError('Run dataset is already frozen');
|
||||
}
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING',
|
||||
[hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
const frozen = validateDataset(saved.rows[0]?.payload);
|
||||
if (frozen.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
const pinned = await client.query(
|
||||
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
|
||||
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
|
||||
[runId, hash, attemptId]
|
||||
);
|
||||
if (!pinned.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
|
||||
}
|
||||
return frozen;
|
||||
});
|
||||
}
|
||||
|
||||
/** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its
|
||||
* predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */
|
||||
private ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
|
||||
|
|
@ -156,7 +244,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
|
||||
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
|
||||
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
|
||||
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id`,
|
||||
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id, dataset_hash`,
|
||||
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
|
||||
);
|
||||
if (!updated.rows.length) {
|
||||
|
|
@ -171,6 +259,9 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
}
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
if (!result.config.dataset || result.config.dataset.hash !== updated.rows[0]?.dataset_hash) {
|
||||
throw new BacktestConflictError('Result does not reference the run frozen dataset');
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO backtest_results
|
||||
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
||||
import {
|
||||
|
|
@ -47,7 +48,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
);
|
||||
}
|
||||
|
||||
async runBacktest(input: BacktestConfig): Promise<NativeBacktestResult> {
|
||||
async runBacktest(
|
||||
input: BacktestConfig,
|
||||
dataset?: DatasetResolver
|
||||
): Promise<NativeBacktestResult> {
|
||||
if (this.closing || this.active) {
|
||||
throw new Error(
|
||||
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
||||
|
|
@ -79,7 +83,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
resolveNativeStrategies(config);
|
||||
// Race the read too: a slow database must not prevent cancellation. A late read
|
||||
// cannot spawn a worker after the run has been stopped.
|
||||
const data = await Promise.race([this.loadData(config, signal), aborted]);
|
||||
const data = await Promise.race([this.loadData(config, signal, dataset), aborted]);
|
||||
signal.throwIfAborted();
|
||||
const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => {
|
||||
this.progress = progress.progress;
|
||||
|
|
@ -108,36 +112,13 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
|
||||
private async loadData(
|
||||
config: BacktestConfig,
|
||||
signal: AbortSignal
|
||||
signal: AbortSignal,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<NativeWorkerRequest['data']> {
|
||||
const data: NativeWorkerRequest['data'] = [];
|
||||
for (const symbol of config.symbols) {
|
||||
signal.throwIfAborted();
|
||||
const bars = await this.storageService.getHistoricalBars(
|
||||
symbol,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
if (!bars.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
}
|
||||
for (const bar of bars) {
|
||||
data.push({
|
||||
symbol,
|
||||
timestamp: bar.timestamp.getTime(),
|
||||
type: 'bar',
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
return data;
|
||||
signal.throwIfAborted();
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver);
|
||||
signal.throwIfAborted();
|
||||
return dataset.bars.map(bar => ({ ...bar, type: 'bar' }));
|
||||
}
|
||||
|
||||
private publish(event: string, data: unknown): void {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
|
||||
import { resolveDataset } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { RustStrategy } from '../strategies/RustStrategy';
|
||||
import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types';
|
||||
|
|
@ -34,11 +35,13 @@ export interface RustBacktestResult {
|
|||
finalPositions: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** @deprecated Diagnostic wrapper only. Use BacktestRunner for durable, isolated execution. */
|
||||
export class RustBacktestEngine {
|
||||
private engine: RustEngine;
|
||||
private container: IServiceContainer;
|
||||
private storageService: StorageService;
|
||||
private config: RustBacktestConfig;
|
||||
private readonly request: BacktestConfig;
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
|
|
@ -47,6 +50,7 @@ export class RustBacktestEngine {
|
|||
) {
|
||||
this.container = container;
|
||||
this.storageService = storageService;
|
||||
this.request = config;
|
||||
|
||||
// Convert config for Rust
|
||||
const rustConfig: RustBacktestConfig = {
|
||||
|
|
@ -75,38 +79,8 @@ export class RustBacktestEngine {
|
|||
* Load historical data for the backtest
|
||||
*/
|
||||
async loadData(): Promise<void> {
|
||||
// Get config from engine
|
||||
const config = this.getConfig();
|
||||
|
||||
const startDate = new Date(config.startDate);
|
||||
const endDate = new Date(config.endDate);
|
||||
|
||||
// Load data for each symbol
|
||||
for (const symbol of config.symbols) {
|
||||
const bars = await this.storageService.getHistoricalBars(
|
||||
symbol,
|
||||
startDate,
|
||||
endDate,
|
||||
config.dataFrequency
|
||||
);
|
||||
|
||||
// Convert to Rust format
|
||||
const marketData = bars.map(bar => ({
|
||||
symbol,
|
||||
timestamp: bar.timestamp.getTime(), // Convert to milliseconds
|
||||
type: 'bar',
|
||||
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,
|
||||
}));
|
||||
|
||||
// Load into Rust engine
|
||||
this.container.logger.info(`Loading ${marketData.length} bars for ${symbol}`);
|
||||
this.engine.loadMarketData(marketData);
|
||||
}
|
||||
const dataset = await resolveDataset(this.storageService, this.request);
|
||||
this.engine.loadMarketData(dataset.bars.map(bar => ({ ...bar, type: 'bar' })));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
import type { EventEmitter } from 'node:events';
|
||||
import type { DatasetResolver } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { BacktestResult } from './typescript-result';
|
||||
|
||||
/** The runner depends on execution capabilities, not backend implementations. */
|
||||
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
|
||||
runBacktest(config: BacktestConfig): Promise<BacktestResult | NativeBacktestResult>;
|
||||
runBacktest(
|
||||
config: BacktestConfig,
|
||||
dataset?: DatasetResolver
|
||||
): Promise<BacktestResult | NativeBacktestResult>;
|
||||
stopBacktest(): Promise<void>;
|
||||
pauseBacktest(): Promise<void>;
|
||||
resumeBacktest(): Promise<void>;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { datasetManifestSchema } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { RunIdentity } from './run-repository';
|
||||
|
|
@ -31,6 +32,7 @@ export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
|||
slippage: finite,
|
||||
dataFrequency: z.string(),
|
||||
parameters: z.record(z.unknown()),
|
||||
dataset: datasetManifestSchema.optional(),
|
||||
riskLimits: z
|
||||
.object({
|
||||
maxPositionSize: finite,
|
||||
|
|
@ -115,7 +117,8 @@ export function normalizeBacktestResult(
|
|||
config: BacktestConfig,
|
||||
identity: RunIdentity,
|
||||
executionTime: number,
|
||||
cancelled: boolean
|
||||
cancelled: boolean,
|
||||
dataset?: HistoricalDatasetManifest
|
||||
): BacktestRunResult {
|
||||
if (raw.status !== 'completed' && raw.status !== 'cancelled') {
|
||||
throw new Error(
|
||||
|
|
@ -186,6 +189,7 @@ export function normalizeBacktestResult(
|
|||
slippage: config.slippage ?? 0.0001,
|
||||
dataFrequency: config.dataFrequency,
|
||||
parameters: config.config ?? {},
|
||||
dataset,
|
||||
riskLimits: config.riskLimits,
|
||||
strategies: config.strategies,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
export interface RunIdentity {
|
||||
|
|
@ -16,6 +16,16 @@ export interface BacktestRunRepository {
|
|||
load(runId: string): Promise<{ status: string; config: unknown } | null>;
|
||||
rejectPending(runId: string, error: string): Promise<void>;
|
||||
heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>;
|
||||
loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
requestedHash?: string
|
||||
): Promise<HistoricalDataset | null>;
|
||||
freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
dataset: HistoricalDataset
|
||||
): Promise<HistoricalDataset>;
|
||||
complete(result: BacktestRunResult, attemptId: string): Promise<void>;
|
||||
updateProgress(
|
||||
runId: string,
|
||||
|
|
@ -51,6 +61,12 @@ export class UnavailableBacktestRunRepository implements BacktestRunRepository {
|
|||
async heartbeat(_runId: string, _attemptId: string): Promise<{ cancelRequested: boolean }> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async loadDataset(): Promise<null> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async freezeDataset(): Promise<HistoricalDataset> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async complete(_result: BacktestRunResult, _attemptId: string): Promise<void> {
|
||||
this.unavailable();
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue