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