feat(research): compare saved experiments against explicit trials
This commit is contained in:
parent
397cd0e160
commit
46a4f13acd
22 changed files with 3045 additions and 35 deletions
|
|
@ -16,6 +16,7 @@ import {
|
|||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type { ExperimentComparison } from '@stock-bot/stock-config/experiment-comparison';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
|
|
@ -54,6 +55,190 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const { dataset } = canonicalSmaFixture();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed saved comparison fixture',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Saved comparison template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const backtest = await f.request('/api/v2/backtests', 'POST', {
|
||||
...definition,
|
||||
autoStart: false,
|
||||
});
|
||||
const costInput = {
|
||||
backtestId: backtest.id,
|
||||
name: 'Older cost experiment',
|
||||
scenarios: [
|
||||
{ feeRate: '0.02', slippageRate: '0' },
|
||||
{ feeRate: '0.01', slippageRate: '0.02' },
|
||||
],
|
||||
};
|
||||
const { preview: costPreview } = (await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity/preview',
|
||||
'POST',
|
||||
costInput
|
||||
)) as { preview: CostSensitivityPreview };
|
||||
const { experiment: costs } = (await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity',
|
||||
'POST',
|
||||
{ ...costInput, previewHash: costPreview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as { experiment: CostSensitivityDetail };
|
||||
const parameterInput = {
|
||||
backtestId: backtest.id,
|
||||
name: 'Newer parameter experiment',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
};
|
||||
const { preview } = (await f.request(
|
||||
'/api/v2/experiments/preview',
|
||||
'POST',
|
||||
parameterInput
|
||||
)) as { preview: ExperimentPreview };
|
||||
const { experiment: parameters } = (await f.request(
|
||||
'/api/v2/experiments',
|
||||
'POST',
|
||||
{ ...parameterInput, previewHash: preview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as { experiment: ExperimentDetail };
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
|
||||
.n === 5,
|
||||
'five native cost and parameter trials complete'
|
||||
);
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Mutable template changed after execution',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'revoke',
|
||||
reason: 'Historical reads must not require current admission approval',
|
||||
});
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
|
||||
const durableCounts = async () =>
|
||||
(
|
||||
await f.pool.query(`SELECT
|
||||
(SELECT count(*)::int FROM runs) AS runs,
|
||||
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
|
||||
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT sum(manual_retry_count)::int FROM runs) AS retries`)
|
||||
).rows[0];
|
||||
const before = await durableCounts();
|
||||
const query = new URLSearchParams({ leftId: costs.id, rightId: parameters.id });
|
||||
const endpoint = `/api/v2/experiments/compare?${query}`;
|
||||
const { comparison } = (await f.request(endpoint)) as { comparison: ExperimentComparison };
|
||||
expect(comparison.selection.referenceTrialKey).toBe(costs.trials[0]!.trialKey);
|
||||
expect(comparison.rows.map(row => row.differences)).toEqual([[], ['costs'], ['costs'], [], []]);
|
||||
expect(comparison.rows.map(row => row.ready)).toEqual([true, false, false, true, true]);
|
||||
for (const experiment of comparison.experiments) {
|
||||
for (const trial of experiment.trials) {
|
||||
const result = (await f.request(
|
||||
`/api/v2/runs/${trial.runId}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(trial.metrics).toEqual(result.analytics.metrics);
|
||||
expect(trial.unavailable).toEqual(result.analytics.unavailable);
|
||||
}
|
||||
}
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/experiments`);
|
||||
// Click order, rather than the newest-first list, chooses the explicit left reference.
|
||||
await f.page.getByLabel(`Select ${costs.name} for comparison`, { exact: true }).check();
|
||||
await f.page.getByLabel(`Select ${parameters.name} for comparison`, { exact: true }).check();
|
||||
await f.page.getByRole('link', { name: 'Compare selected experiments', exact: true }).click();
|
||||
await f.page.getByRole('heading', { name: 'Compare experiments', exact: true }).waitFor();
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
|
||||
expect(new URL(f.page.url()).searchParams.get('leftId')).toBe(costs.id);
|
||||
expect(new URL(f.page.url()).searchParams.get('rightId')).toBe(parameters.id);
|
||||
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
|
||||
costs.trials[0]!.trialKey
|
||||
);
|
||||
expect(await f.page.getByText('Matching settings', { exact: true }).count()).toBe(3);
|
||||
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(2);
|
||||
expect(await f.page.getByText('Saved summary available', { exact: true }).count()).toBe(5);
|
||||
for (const experiment of comparison.experiments) {
|
||||
for (const trial of experiment.trials) {
|
||||
const row = f.page.locator(
|
||||
`tr:has(a[href="/backtests/${backtest.id}/run/${trial.runId}"])`
|
||||
);
|
||||
expect(await row.count()).toBe(1);
|
||||
expect(await row.innerText()).toContain(String(trial.metrics!.totalReturn));
|
||||
}
|
||||
}
|
||||
const referenceKey = costs.trials[1]!.trialKey;
|
||||
const changedRead = f.page.waitForResponse(response => {
|
||||
const url = new URL(response.url());
|
||||
return (
|
||||
url.pathname === '/api/v2/experiments/compare' &&
|
||||
url.searchParams.get('referenceTrialKey') === referenceKey
|
||||
);
|
||||
});
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).selectOption(referenceKey);
|
||||
const response = await changedRead;
|
||||
expect(response.status()).toBe(200);
|
||||
const changed = (await response.json()) as { comparison: ExperimentComparison };
|
||||
expect(changed.comparison.rows.map(row => row.differences)).toEqual([
|
||||
['costs'],
|
||||
[],
|
||||
['costs'],
|
||||
['costs'],
|
||||
['costs'],
|
||||
]);
|
||||
await until(
|
||||
async () => (await f.page.getByText('Matching settings', { exact: true }).count()) === 1,
|
||||
'explicit cost reference replaces comparison'
|
||||
);
|
||||
expect(new URL(f.page.url()).searchParams.get('referenceTrialKey')).toBe(referenceKey);
|
||||
const savedUrl = f.page.url();
|
||||
await f.page.reload();
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
|
||||
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
|
||||
referenceKey
|
||||
);
|
||||
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(4);
|
||||
await f.page
|
||||
.locator(`a[href="/backtests/${backtest.id}/run/${costs.trials[1]!.runId}"]`)
|
||||
.click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await f.page.goto(savedUrl);
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
|
||||
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
|
||||
referenceKey
|
||||
);
|
||||
expect(await durableCounts()).toEqual(before);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing_experiment_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue