feat(research): compare immutable fee and slippage scenarios
This commit is contained in:
parent
3ed7b98f7c
commit
397cd0e160
41 changed files with 3234 additions and 144 deletions
|
|
@ -11,6 +11,11 @@ import type {
|
|||
ChronologicalValidationPreview,
|
||||
ChronologicalValidationReport,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
|
|
@ -49,6 +54,158 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
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());
|
||||
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 native cost sensitivity fixture',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Fixed cost study 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,
|
||||
});
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page
|
||||
.getByLabel('Experiment name', { exact: true })
|
||||
.fill('Fixed fee and slippage study');
|
||||
await f.page.getByLabel('Experiment type').selectOption({ label: 'Cost sensitivity' });
|
||||
expect(await f.page.getByLabel('Parameter grid').isVisible()).toBe(false);
|
||||
await f.page.getByLabel('Scenario 1 fee rate', { exact: true }).fill('0.02');
|
||||
await f.page.getByLabel('Scenario 1 slippage rate', { exact: true }).fill('0');
|
||||
await f.page.getByRole('button', { name: 'Add cost scenario', exact: true }).click();
|
||||
await f.page.getByLabel('Scenario 2 fee rate', { exact: true }).fill('0.01');
|
||||
await f.page.getByLabel('Scenario 2 slippage rate', { exact: true }).fill('0.02');
|
||||
const preparing = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/experiments/cost-sensitivity/preview')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
const prepared = await preparing;
|
||||
expect(prepared.status()).toBe(200);
|
||||
const { preview } = (await prepared.json()) as { preview: CostSensitivityPreview };
|
||||
expect(preview.version).toBe('cost-sensitivity-preview/v1');
|
||||
expect(preview.source.input.grid).toEqual({});
|
||||
expect(preview.candidates.map(candidate => candidate.costs)).toEqual([
|
||||
{ feeRate: '0.01000000', slippageRate: '0.00000000' },
|
||||
{ feeRate: '0.02000000', slippageRate: '0.00000000' },
|
||||
{ feeRate: '0.01000000', slippageRate: '0.02000000' },
|
||||
]);
|
||||
expect(
|
||||
preview.candidates.every(
|
||||
candidate =>
|
||||
JSON.stringify(candidate.parameters) === JSON.stringify(definition.strategyParameters)
|
||||
)
|
||||
).toBe(true);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
const submitting = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith('/api/v2/experiments/cost-sensitivity')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const submitted = await submitting;
|
||||
expect(submitted.status()).toBe(202);
|
||||
const { experiment } = (await submitted.json()) as { experiment: CostSensitivityDetail };
|
||||
expect(submitted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
|
||||
expect(experiment.preview).toEqual(preview);
|
||||
expect(experiment.kind).toBe('cost-sensitivity');
|
||||
expect(experiment.trialCount).toBe(3);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(3);
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Edited after cost admission',
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
initialCapital: 20000,
|
||||
config: {
|
||||
...definition.config,
|
||||
canonical: { ...canonicalSettings, feeRate: '0.3', slippageRate: '0.4' },
|
||||
},
|
||||
});
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
|
||||
.n === 3,
|
||||
'all three fixed-input cost scenarios complete through the native runner'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
|
||||
await visible(f.page, /completed: 3/);
|
||||
expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(3);
|
||||
const outcomes = f.page.locator('section[aria-label="Experiment trial outcomes"] tbody tr');
|
||||
expect(await outcomes.count()).toBe(3);
|
||||
for (const [index, trial] of experiment.trials.entries()) {
|
||||
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
|
||||
const expected = structuredClone(preview.request);
|
||||
expected.runId = trial.runId!;
|
||||
expected.policy.matching.risk.ledger.sessionId = trial.runId!;
|
||||
expected.policy.matching.risk.ledger.accountId = `research:${trial.runId}`;
|
||||
const costs = costScenarioSchema.parse(trial.costs);
|
||||
expected.policy.matching.risk.feeRate = costs.feeRate;
|
||||
expected.policy.matching.slippageRate = costs.slippageRate;
|
||||
expect(result.request).toEqual(expected);
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(result.financial.policy).toEqual(expected.policy);
|
||||
expect(result.financial.identity).toEqual({
|
||||
version: 1,
|
||||
sessionId: trial.runId!,
|
||||
datasetHash: expected.datasetHash,
|
||||
});
|
||||
const text = await outcomes.nth(index).innerText();
|
||||
expect(text).toContain(index === 0 ? 'Baseline' : `Scenario ${index}`);
|
||||
expect(text).toContain(trial.costs.feeRate);
|
||||
expect(text).toContain(trial.costs.slippageRate);
|
||||
expect(text).toContain(String(result.analytics.metrics.totalReturn));
|
||||
}
|
||||
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
|
||||
const replay = (await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity',
|
||||
'POST',
|
||||
submitted.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': submitted.request().headers()['idempotency-key']! }
|
||||
)) as { experiment: CostSensitivityDetail };
|
||||
expect(replay.experiment.id).toBe(experiment.id);
|
||||
expect(replay.experiment.preview).toEqual(preview);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3);
|
||||
await f.page.reload();
|
||||
await visible(f.page, /completed: 3/);
|
||||
await f.page.getByRole('link', { name: 'All experiments', exact: true }).click();
|
||||
await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click();
|
||||
await visible(f.page, /completed: 3/);
|
||||
await f.page
|
||||
.locator(`a[href="/backtests/${backtest.id}/run/${experiment.trials[2]!.runId}"]`)
|
||||
.click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_report_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