Share backtest request contracts and isolate stored result mapping
This commit is contained in:
parent
007e35c747
commit
420c47704e
21 changed files with 777 additions and 244 deletions
|
|
@ -1,7 +1,7 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { isBacktestRequestError } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestService } from '../services/backtest.service';
|
||||
|
||||
const logger = getLogger('backtest-routes');
|
||||
|
|
@ -33,7 +33,7 @@ export function createBacktestRoutes(container: IServiceContainer) {
|
|||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', { error });
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { isBacktestRequestError } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
|
@ -44,7 +44,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
|
|
@ -61,7 +61,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to update backtest' }, 500);
|
||||
|
|
@ -100,7 +100,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to create run' }, 500);
|
||||
|
|
|
|||
108
apps/stock/web-api/src/services/backtest-result.ts
Normal file
108
apps/stock/web-api/src/services/backtest-result.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { BACKTEST_DEFAULTS } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
|
||||
|
||||
type StoredTrade = Omit<BacktestRunTrade, 'kind' | 'timestamp' | 'price'> &
|
||||
Partial<Pick<BacktestRunTrade, 'kind' | 'timestamp' | 'price'>>;
|
||||
|
||||
/** Projection returned by the saved-result query, including pre-contract history. */
|
||||
export interface StoredBacktestResult {
|
||||
run_id: string;
|
||||
backtest_id: string;
|
||||
run_status?: BacktestRunResult['status'];
|
||||
completed_at: Date;
|
||||
engine?: BacktestRunResult['engine'] | null;
|
||||
configuration?: BacktestRunResult['config'] | null;
|
||||
metrics: BacktestRunResult['metrics'];
|
||||
analytics?: Partial<BacktestRunResult['analytics']> | null;
|
||||
trades: StoredTrade[];
|
||||
equity_curve: BacktestRunResult['equity'];
|
||||
ohlc_data: BacktestRunResult['ohlcData'];
|
||||
positions: BacktestRunResult['positions'];
|
||||
execution_time: number;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
start_date: Date;
|
||||
end_date: Date;
|
||||
initial_capital: string | number;
|
||||
backtest_config?: Record<string, unknown> & {
|
||||
name?: string;
|
||||
commission?: number;
|
||||
slippage?: number;
|
||||
dataFrequency?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** Read-only compatibility conversion. Stored rows and metric units are never rewritten. */
|
||||
export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunResult {
|
||||
const legacy = !row.configuration;
|
||||
const metrics = { ...row.metrics };
|
||||
const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? 0 };
|
||||
const trades = row.trades.map(trade => {
|
||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||
const price = trade.price ?? trade.entryPrice;
|
||||
if (!timestamp || price === undefined) {
|
||||
throw new Error('Malformed stored backtest trade');
|
||||
}
|
||||
return {
|
||||
...trade,
|
||||
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
|
||||
timestamp,
|
||||
price,
|
||||
};
|
||||
});
|
||||
if (legacy) {
|
||||
// Pre-contract backends reported return/win rate in percentage points.
|
||||
metrics.totalReturn /= 100;
|
||||
metrics.winRate /= 100;
|
||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
}
|
||||
if (trades.some(trade => trade.kind === 'closed')) {
|
||||
metrics.totalTrades = trades.length;
|
||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
analytics.exposureTime /= 100;
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
}));
|
||||
// Legacy native finalValue marks daily returns already expressed as fractions.
|
||||
if (typeof row.metrics.finalValue !== 'number') {
|
||||
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
|
||||
}
|
||||
if (analytics.monthlyReturns) {
|
||||
analytics.monthlyReturns = Object.fromEntries(
|
||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
runId: row.run_id,
|
||||
backtestId: row.backtest_id,
|
||||
status: row.run_status ?? 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
engine: row.engine ?? 'legacy',
|
||||
...(legacy ? { legacy: true } : {}),
|
||||
config: row.configuration ?? {
|
||||
parameters: row.backtest_config ?? {},
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date.toISOString(),
|
||||
endDate: row.end_date.toISOString(),
|
||||
initialCapital: parseFloat(String(row.initial_capital)),
|
||||
commission: row.backtest_config?.commission ?? BACKTEST_DEFAULTS.commission,
|
||||
slippage: row.backtest_config?.slippage ?? BACKTEST_DEFAULTS.slippage,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || BACKTEST_DEFAULTS.dataFrequency,
|
||||
},
|
||||
metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades,
|
||||
positions: row.positions,
|
||||
analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
|
@ -4,9 +4,11 @@ import { authenticatedServiceFetch } from '@stock-bot/di';
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { validateHistoricalDataRequest, type BacktestRunResult } from '@stock-bot/types';
|
||||
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
||||
|
|
@ -78,12 +80,7 @@ export class BacktestServiceV2 {
|
|||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
validateHistoricalDataRequest({
|
||||
...request,
|
||||
dataFrequency: request.config?.dataFrequency,
|
||||
dataPolicy: request.config?.dataPolicy,
|
||||
datasetHash: request.config?.datasetHash,
|
||||
});
|
||||
backtestRequestFromDefinition(request);
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
|
|
@ -141,14 +138,7 @@ export class BacktestServiceV2 {
|
|||
return null;
|
||||
}
|
||||
const next = { ...existing, ...request };
|
||||
validateHistoricalDataRequest({
|
||||
symbols: next.symbols,
|
||||
startDate: new Date(next.startDate).toISOString(),
|
||||
endDate: new Date(next.endDate).toISOString(),
|
||||
dataFrequency: next.config?.dataFrequency,
|
||||
dataPolicy: next.config?.dataPolicy,
|
||||
datasetHash: next.config?.datasetHash,
|
||||
});
|
||||
backtestRequestFromDefinition(next);
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
|
@ -228,62 +218,12 @@ export class BacktestServiceV2 {
|
|||
throw new Error('Backtest not found');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
validateHistoricalDataRequest({
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
dataFrequency: definition.config.dataFrequency,
|
||||
dataPolicy: definition.config.dataPolicy,
|
||||
datasetHash: definition.config.datasetHash,
|
||||
});
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new Error('Speed multiplier must be positive or null');
|
||||
}
|
||||
const snapshot = {
|
||||
const snapshot = backtestRequestFromDefinition(definition, {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
name: definition.name,
|
||||
mode: 'backtest',
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
riskLimits: definition.config.riskLimits,
|
||||
dataPolicy: definition.config.dataPolicy,
|
||||
datasetHash: definition.config.datasetHash,
|
||||
dataFrequency: definition.config.dataFrequency ?? '1d',
|
||||
commission: definition.config.commission ?? 0.001,
|
||||
slippage: definition.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
multiplier === null
|
||||
? 'max'
|
||||
: multiplier >= 10
|
||||
? '10x'
|
||||
: multiplier >= 5
|
||||
? '5x'
|
||||
: multiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
};
|
||||
if (
|
||||
!snapshot.strategy ||
|
||||
!Array.isArray(snapshot.symbols) ||
|
||||
!snapshot.symbols.length ||
|
||||
snapshot.symbols.some(symbol => typeof symbol !== 'string' || !symbol.length) ||
|
||||
!Number.isFinite(snapshot.initialCapital) ||
|
||||
snapshot.initialCapital <= 0 ||
|
||||
Date.parse(snapshot.endDate) <= Date.parse(snapshot.startDate) ||
|
||||
!['1m', '5m', '15m', '1h', '1d'].includes(String(snapshot.dataFrequency)) ||
|
||||
typeof snapshot.commission !== 'number' ||
|
||||
!Number.isFinite(snapshot.commission) ||
|
||||
typeof snapshot.slippage !== 'number' ||
|
||||
!Number.isFinite(snapshot.slippage)
|
||||
) {
|
||||
throw new Error('Invalid backtest execution configuration');
|
||||
}
|
||||
speedMultiplier: multiplier,
|
||||
});
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||
|
|
@ -381,7 +321,7 @@ export class BacktestServiceV2 {
|
|||
|
||||
// Get run results
|
||||
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
||||
const result = await this.container.postgres.query(
|
||||
const result = await this.container.postgres.query<StoredBacktestResult>(
|
||||
`SELECT
|
||||
br.*,
|
||||
r.backtest_id,
|
||||
|
|
@ -403,83 +343,7 @@ export class BacktestServiceV2 {
|
|||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
const legacy = !row.configuration;
|
||||
const metrics: BacktestRunResult['metrics'] = { ...row.metrics };
|
||||
const analytics: BacktestRunResult['analytics'] = {
|
||||
...row.analytics,
|
||||
exposureTime: row.analytics?.exposureTime ?? 0,
|
||||
};
|
||||
const storedTrades: BacktestRunResult['trades'] = row.trades;
|
||||
const trades = storedTrades.map(trade => {
|
||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||
const price = trade.price ?? trade.entryPrice;
|
||||
if (!timestamp || price === undefined) {
|
||||
throw new Error('Malformed stored backtest trade');
|
||||
}
|
||||
return {
|
||||
...trade,
|
||||
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
|
||||
timestamp,
|
||||
price,
|
||||
};
|
||||
});
|
||||
if (legacy) {
|
||||
// Pre-contract backends both reported return/win rate in percentage points.
|
||||
metrics.totalReturn /= 100;
|
||||
metrics.winRate /= 100;
|
||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
}
|
||||
if (trades.some(trade => trade.kind === 'closed')) {
|
||||
metrics.totalTrades = trades.length;
|
||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
analytics.exposureTime /= 100;
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
}));
|
||||
// Older native results identify themselves by finalValue and already use daily fractions.
|
||||
if (typeof row.metrics.finalValue !== 'number') {
|
||||
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
|
||||
}
|
||||
if (analytics.monthlyReturns) {
|
||||
analytics.monthlyReturns = Object.fromEntries(
|
||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
runId: row.run_id,
|
||||
backtestId: row.backtest_id,
|
||||
status: row.run_status ?? 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
engine: row.engine ?? 'legacy',
|
||||
...(legacy ? { legacy: true } : {}),
|
||||
config: row.configuration ?? {
|
||||
parameters: row.backtest_config ?? {},
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date.toISOString(),
|
||||
endDate: row.end_date.toISOString(),
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
commission: row.backtest_config?.commission ?? 0.001,
|
||||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
},
|
||||
metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades,
|
||||
positions: row.positions,
|
||||
analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
return mapStoredBacktestResult(at(result.rows, 0));
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue