feat(research): select and reuse frozen datasets in workbench
This commit is contained in:
parent
6a67ae8683
commit
b106c1ca85
29 changed files with 2295 additions and 426 deletions
|
|
@ -4,12 +4,17 @@ 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 { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
datasetHashSchema,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunDatasetSelection, BacktestRunResult } from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
||||
|
|
@ -42,6 +47,7 @@ export interface Backtest {
|
|||
}
|
||||
|
||||
export interface Run {
|
||||
dataset: BacktestRunDatasetSelection;
|
||||
id: string;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
|
|
@ -93,7 +99,10 @@ export class BacktestServiceV2 {
|
|||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
backtestRequestFromDefinition(request);
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
this.container.postgres,
|
||||
backtestRequestFromDefinition(request)
|
||||
);
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
|
|
@ -146,63 +155,66 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
async updateBacktest(id: string, request: Partial<BacktestRequest>): Promise<Backtest | null> {
|
||||
const existing = await this.getBacktest(id);
|
||||
if (!existing) {
|
||||
return null;
|
||||
}
|
||||
const next = { ...existing, ...request };
|
||||
backtestRequestFromDefinition(next);
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
return this.container.postgres.transaction(async client => {
|
||||
const locked = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [id]);
|
||||
if (!locked.rows[0]) {
|
||||
return null;
|
||||
}
|
||||
const existing = this.mapBacktest(locked.rows[0]);
|
||||
const next = { ...existing, ...request };
|
||||
await assertSelectedDatasetMatchesRequest(client, backtestRequestFromDefinition(next));
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
||||
if (request.name !== undefined) {
|
||||
updates.push(`name = $${paramCount++}`);
|
||||
values.push(request.name);
|
||||
}
|
||||
if (request.strategy !== undefined) {
|
||||
updates.push(`strategy = $${paramCount++}`);
|
||||
values.push(request.strategy);
|
||||
}
|
||||
if (request.symbols !== undefined) {
|
||||
updates.push(`symbols = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.symbols));
|
||||
}
|
||||
if (request.startDate !== undefined) {
|
||||
updates.push(`start_date = $${paramCount++}`);
|
||||
values.push(request.startDate);
|
||||
}
|
||||
if (request.endDate !== undefined) {
|
||||
updates.push(`end_date = $${paramCount++}`);
|
||||
values.push(request.endDate);
|
||||
}
|
||||
if (request.initialCapital !== undefined) {
|
||||
updates.push(`initial_capital = $${paramCount++}`);
|
||||
values.push(request.initialCapital);
|
||||
}
|
||||
if (request.config !== undefined) {
|
||||
updates.push(`config = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.config));
|
||||
}
|
||||
if (request.name !== undefined) {
|
||||
updates.push(`name = $${paramCount++}`);
|
||||
values.push(request.name);
|
||||
}
|
||||
if (request.strategy !== undefined) {
|
||||
updates.push(`strategy = $${paramCount++}`);
|
||||
values.push(request.strategy);
|
||||
}
|
||||
if (request.symbols !== undefined) {
|
||||
updates.push(`symbols = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.symbols));
|
||||
}
|
||||
if (request.startDate !== undefined) {
|
||||
updates.push(`start_date = $${paramCount++}`);
|
||||
values.push(request.startDate);
|
||||
}
|
||||
if (request.endDate !== undefined) {
|
||||
updates.push(`end_date = $${paramCount++}`);
|
||||
values.push(request.endDate);
|
||||
}
|
||||
if (request.initialCapital !== undefined) {
|
||||
updates.push(`initial_capital = $${paramCount++}`);
|
||||
values.push(request.initialCapital);
|
||||
}
|
||||
if (request.config !== undefined) {
|
||||
updates.push(`config = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.config));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return this.getBacktest(id);
|
||||
}
|
||||
if (updates.length === 0) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
values.push(id);
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE backtests
|
||||
values.push(id);
|
||||
const result = await client.query(
|
||||
`UPDATE backtests
|
||||
SET ${updates.join(', ')}, updated_at = NOW()
|
||||
WHERE id = $${paramCount}
|
||||
RETURNING *`,
|
||||
values
|
||||
);
|
||||
values
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.mapBacktest(at(result.rows, 0));
|
||||
return this.mapBacktest(at(result.rows, 0));
|
||||
});
|
||||
}
|
||||
|
||||
async listBacktests(params: { limit: number; offset: number }): Promise<Backtest[]> {
|
||||
|
|
@ -275,6 +287,7 @@ export class BacktestServiceV2 {
|
|||
backtestId: definition.id,
|
||||
speedMultiplier: multiplier,
|
||||
});
|
||||
await assertSelectedDatasetMatchesRequest(client, snapshot);
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot,
|
||||
|
|
@ -441,6 +454,7 @@ export class BacktestServiceV2 {
|
|||
|
||||
private mapRun(row: QueryResultRow): Run {
|
||||
return {
|
||||
dataset: datasetSelectionForRun(row),
|
||||
id: row.id,
|
||||
backtestId: row.backtest_id,
|
||||
runNumber: row.run_number,
|
||||
|
|
@ -459,3 +473,27 @@ export class BacktestServiceV2 {
|
|||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Provenance comes from the immutable request and bound dataset, never its template. */
|
||||
export function datasetSelectionForRun(row: QueryResultRow): BacktestRunDatasetSelection {
|
||||
const hash = datasetHashSchema.safeParse(row.dataset_hash);
|
||||
const pinnedHash = hash.success ? hash.data : null;
|
||||
let snapshot;
|
||||
try {
|
||||
snapshot = parseBacktestRequest(row.request_snapshot);
|
||||
} catch {
|
||||
return { requestedHash: null, pinnedHash, source: null, state: 'unknown' };
|
||||
}
|
||||
return {
|
||||
requestedHash: snapshot.datasetHash ?? null,
|
||||
pinnedHash,
|
||||
source: snapshot.dataSource ?? 'auto',
|
||||
state: pinnedHash
|
||||
? 'pinned'
|
||||
: ['completed', 'failed', 'cancelled'].includes(row.status)
|
||||
? 'unavailable'
|
||||
: ['running', 'paused'].includes(row.status)
|
||||
? 'preparing'
|
||||
: 'requested',
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue