feat(research): select and reuse frozen datasets in workbench

This commit is contained in:
Boki 2026-10-23 18:13:37 -04:00
parent 6a67ae8683
commit b106c1ca85
29 changed files with 2295 additions and 426 deletions

View file

@ -1,6 +1,9 @@
import type { BacktestRunResult } from '@stock-bot/types';
import type {
BacktestRunDatasetSelection,
BacktestRunResult,
HistoricalDatasetCatalogEntry,
} from '@stock-bot/types';
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import { browserLog } from '@/utils/browserLog';
export interface Backtest {
id: string;
@ -31,6 +34,7 @@ export interface Run {
currentSimulationDate?: string;
createdAt: string;
updatedAt: string;
dataset?: BacktestRunDatasetSelection;
}
export interface CreateBacktestRequest {
@ -56,7 +60,43 @@ export class RunResultsUnavailableError extends Error {
}
}
async function requestError(response: Response, fallback: string): Promise<Error> {
const payload: unknown = await response.json().catch(() => null);
const message =
payload &&
typeof payload === 'object' &&
'error' in payload &&
typeof payload.error === 'string'
? payload.error
: `${fallback}: ${response.status} ${response.statusText}`;
return new Error(message);
}
export const backtestApiV2 = {
async listDatasets(
limit = 50,
offset = 0,
signal?: AbortSignal
): Promise<HistoricalDatasetCatalogEntry[]> {
const response = await fetch(
`${API_BASE_URL}/api/v2/datasets?limit=${limit}&offset=${offset}`,
{ signal }
);
if (!response.ok) {
throw await requestError(response, 'Failed to load frozen datasets');
}
return (await response.json()).datasets;
},
async getDataset(hash: string, signal?: AbortSignal): Promise<HistoricalDatasetCatalogEntry> {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/${encodeURIComponent(hash)}`, {
signal,
});
if (!response.ok) {
throw await requestError(response, 'Failed to load frozen dataset');
}
return (await response.json()).dataset;
},
// Backtest operations
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
@ -69,7 +109,7 @@ export const backtestApiV2 = {
});
if (!response.ok) {
throw new Error(`Failed to create backtest: ${response.statusText}`);
throw await requestError(response, 'Failed to create backtest');
}
return response.json();
@ -107,7 +147,7 @@ export const backtestApiV2 = {
});
if (!response.ok) {
throw new Error(`Failed to update backtest: ${response.statusText}`);
throw await requestError(response, 'Failed to update backtest');
}
return response.json();
@ -139,9 +179,7 @@ export const backtestApiV2 = {
});
if (!response.ok) {
const errorText = await response.text();
browserLog.error(`Failed to create run:`, response.status, errorText);
throw new Error(`Failed to create run: ${response.statusText}`);
throw await requestError(response, 'Failed to create run');
}
return response.json();

View file

@ -0,0 +1,86 @@
import {
validateHistoricalDataRequest,
type HistoricalDatasetCatalogEntry,
} from '@stock-bot/types';
export const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const;
export interface HistoricalSelection {
symbols: string[];
startDate: string;
endDate: string;
dataFrequency?: (typeof historicalIntervals)[number];
dataSource?: 'auto' | 'questdb' | 'eod';
priceAdjustment?: 'raw' | 'provider-adjusted';
datasetHash?: string;
}
/** Selecting a retained snapshot adopts its exact request, never a cropped range. */
export function retainedDatasetSelection(
entry: HistoricalDatasetCatalogEntry
): HistoricalSelection {
const manifest = entry.manifest;
if (entry.status !== 'available' || manifest?.version !== 1 || manifest.hash !== entry.hash) {
throw new Error(entry.reason ?? 'This dataset is unavailable in the current workbench');
}
const interval = historicalIntervals.find(value => value === manifest.interval);
if (!interval) {
throw new Error('This dataset timeframe is unsupported');
}
return {
symbols: manifest.instruments.map(instrument => instrument.id),
startDate: manifest.startDate,
endDate: manifest.endDate,
dataFrequency: interval,
dataSource: 'auto',
priceAdjustment: manifest.policy.adjustment,
datasetHash: entry.hash,
};
}
export function historicalSelectionError(
value: HistoricalSelection,
retained?: HistoricalDatasetCatalogEntry | null
): string | null {
try {
const frequency = value.dataFrequency ?? '1d';
if (!['auto', 'questdb', 'eod'].includes(value.dataSource ?? 'auto')) {
return 'Choose a supported historical source';
}
validateHistoricalDataRequest({
symbols: value.symbols,
startDate: value.startDate,
endDate: value.endDate,
dataFrequency: frequency,
dataPolicy: {
adjustment: value.priceAdjustment ?? 'raw',
timestamp: frequency === '1d' ? 'utc-session-date' : 'utc-instant',
},
datasetHash: value.datasetHash,
});
if (value.datasetHash !== undefined) {
if (!retained || retained.hash !== value.datasetHash) {
return 'Select an available frozen dataset and wait for its metadata';
}
const exact = retainedDatasetSelection(retained);
if (
JSON.stringify([...value.symbols].sort()) !== JSON.stringify([...exact.symbols].sort()) ||
new Date(value.startDate).toISOString() !== exact.startDate ||
new Date(value.endDate).toISOString() !== exact.endDate ||
frequency !== exact.dataFrequency ||
(value.priceAdjustment ?? 'raw') !== exact.priceAdjustment ||
(value.dataSource ?? 'auto') !== 'auto'
) {
return 'These settings do not match the frozen dataset. Apply its exact settings or switch to a source request.';
}
}
return null;
} catch (error) {
return error instanceof Error ? error.message : 'Invalid historical data settings';
}
}
/** A daily control displays the UTC session date; intraday controls retain the
* complete explicit-offset string, including milliseconds. */
export function historicalDateInput(value: string, frequency: string): string {
return frequency === '1d' ? value.slice(0, 10) : value;
}