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
|
|
@ -606,7 +606,7 @@ export class ChronologicalValidationService {
|
|||
phase: ValidationPhase,
|
||||
sourceIndex?: number
|
||||
): Promise<ValidationResultEvidence[]> {
|
||||
const detail = await this.experiments.readDetail(client, id);
|
||||
const detail = await this.experiments.readParameterDetail(client, id);
|
||||
if (
|
||||
detail.cancelRequested ||
|
||||
detail.trials.some(
|
||||
|
|
@ -698,7 +698,7 @@ export class ChronologicalValidationService {
|
|||
phase,
|
||||
status: exists ? 'admitted' : 'missing',
|
||||
experimentId: expected,
|
||||
experiment: exists ? await this.experiments.readDetail(client, expected) : null,
|
||||
experiment: exists ? await this.experiments.readParameterDetail(client, expected) : null,
|
||||
});
|
||||
}
|
||||
const ready = (phase: ValidationPhaseState) =>
|
||||
|
|
|
|||
119
apps/stock/web-api/src/services/cost-sensitivity-input.ts
Normal file
119
apps/stock/web-api/src/services/cost-sensitivity-input.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
costSensitivitySubmissionSchema,
|
||||
type CostSensitivityCandidate,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type WorkbenchExperimentPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type { ExperimentCandidate, ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
|
||||
function parse<T extends z.ZodTypeAny>(schema: T, raw: unknown): z.infer<T> {
|
||||
try {
|
||||
assertStrategyJsonText(raw);
|
||||
return schema.parse(raw);
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid cost-sensitivity input');
|
||||
}
|
||||
}
|
||||
export const parseCostSensitivityInput = (raw: unknown) => parse(costSensitivityInputSchema, raw);
|
||||
export const parseCostSensitivitySubmission = (raw: unknown) =>
|
||||
parse(costSensitivitySubmissionSchema, raw);
|
||||
const equal = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
export function buildCostSensitivityPreview(
|
||||
raw: CostSensitivityInput,
|
||||
baseline: ExperimentPreview
|
||||
): CostSensitivityPreview {
|
||||
const input = parseCostSensitivityInput(raw),
|
||||
source = retainedExperimentPreview(baseline);
|
||||
if (
|
||||
!equal(source.input, { backtestId: input.backtestId, name: input.name, grid: {} }) ||
|
||||
source.candidates.length !== 1
|
||||
) {
|
||||
throw new Error('Cost sensitivity requires the unchanged empty-grid source');
|
||||
}
|
||||
const parameters = source.request.strategy.selection.parameters;
|
||||
const costs = [
|
||||
costScenarioSchema.parse({
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
}),
|
||||
...input.scenarios,
|
||||
];
|
||||
const keys = new Set<string>();
|
||||
const candidates = costs.map((costs, index) => {
|
||||
const trialKey = experimentHash({ version: 1, kind: 'cost-sensitivity', parameters, costs });
|
||||
if (keys.has(trialKey)) {
|
||||
throw new ExperimentError(400, 'Duplicate normalized cost scenario, including baseline');
|
||||
}
|
||||
keys.add(trialKey);
|
||||
return { index, trialKey, parameters, costs };
|
||||
});
|
||||
const manifest = {
|
||||
version: 'cost-sensitivity-preview/v1' as const,
|
||||
input,
|
||||
source,
|
||||
request: source.request,
|
||||
dataset: source.dataset,
|
||||
candidates,
|
||||
};
|
||||
return { ...manifest, previewHash: experimentHash(manifest) };
|
||||
}
|
||||
export function retainedCostSensitivityPreview(raw: unknown): CostSensitivityPreview {
|
||||
const value = raw as CostSensitivityPreview;
|
||||
let expected: CostSensitivityPreview;
|
||||
try {
|
||||
expected = buildCostSensitivityPreview(value.input, value.source);
|
||||
} catch {
|
||||
throw new Error('Retained cost-sensitivity source or scenarios failed integrity validation');
|
||||
}
|
||||
if (!equal(value, expected)) {
|
||||
throw new Error('Retained cost-sensitivity preview integrity failure');
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
export function retainedWorkbenchPreview(value: unknown): WorkbenchExperimentPreview {
|
||||
if (
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'version' in value &&
|
||||
value.version === 'cost-sensitivity-preview/v1'
|
||||
) {
|
||||
return retainedCostSensitivityPreview(value);
|
||||
}
|
||||
return retainedExperimentPreview(value);
|
||||
}
|
||||
/** One immutable request recipe per trial; Rust remains the financial authority. */
|
||||
export function workbenchTrialRequest(
|
||||
preview: WorkbenchExperimentPreview,
|
||||
candidate: ExperimentCandidate | CostSensitivityCandidate,
|
||||
runId: string
|
||||
): CanonicalRunRequest {
|
||||
if (preview.version === 'research-experiment-preview/v1') {
|
||||
return experimentTrialRequest(preview, candidate, runId);
|
||||
}
|
||||
if (
|
||||
!('costs' in candidate) ||
|
||||
!equal(candidate.parameters, preview.source.request.strategy.selection.parameters)
|
||||
) {
|
||||
throw new Error('Cost candidate must preserve fixed source parameters and explicit costs');
|
||||
}
|
||||
const costs = costScenarioSchema.parse(candidate.costs),
|
||||
request = experimentTrialRequest(preview.source, candidate, runId);
|
||||
request.policy.matching.risk.feeRate = costs.feeRate;
|
||||
request.policy.matching.slippageRate = costs.slippageRate;
|
||||
return canonicalRunRequestSchema.parse(request);
|
||||
}
|
||||
|
|
@ -2,12 +2,17 @@ import { randomUUID } from 'node:crypto';
|
|||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type {
|
||||
CostSensitivityInput,
|
||||
WorkbenchExperimentDetail,
|
||||
WorkbenchExperimentPreview,
|
||||
WorkbenchExperimentRetryResult,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type {
|
||||
ExperimentCounts,
|
||||
ExperimentDetail,
|
||||
ExperimentInput,
|
||||
ExperimentPreview,
|
||||
ExperimentRetryResult,
|
||||
ExperimentSummary,
|
||||
ExperimentTrial,
|
||||
ExperimentTrialRetry,
|
||||
|
|
@ -15,17 +20,22 @@ import type {
|
|||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
import { admitCanonicalRequest, readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
buildCostSensitivityPreview,
|
||||
parseCostSensitivityInput,
|
||||
parseCostSensitivitySubmission,
|
||||
retainedWorkbenchPreview,
|
||||
workbenchTrialRequest,
|
||||
} from './cost-sensitivity-input';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
parseExperimentInput,
|
||||
parseExperimentSubmission,
|
||||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
|
|
@ -76,13 +86,14 @@ const reasons = z.enum([
|
|||
'unsupported-round-trips',
|
||||
]);
|
||||
const unavailableSchema = z.record(metricsSchema.keyof(), reasons);
|
||||
const summaryColumns = `e.id,e.name,e.backtest_id,e.created_at,e.cancel_requested,e.preview_hash,
|
||||
const summaryColumns = `CASE WHEN e.preview->>'version'='cost-sensitivity-preview/v1' THEN 'cost-sensitivity' ELSE 'parameters' END AS kind,e.id,e.name,e.backtest_id,e.created_at,e.cancel_requested,e.preview_hash,
|
||||
jsonb_array_length(e.preview->'candidates') AS trial_count,
|
||||
e.preview#>>'{request,datasetHash}' AS dataset_hash,
|
||||
e.preview#>>'{request,strategy,versionId}' AS strategy_version_id,
|
||||
(SELECT jsonb_object_agg(status, n) FROM (SELECT status,count(*) AS n FROM runs WHERE experiment_id=e.id GROUP BY status) counts) AS counts`;
|
||||
const summary = (row: QueryResultRow): ExperimentSummary => ({
|
||||
id: row.id,
|
||||
kind: row.kind ?? 'parameters',
|
||||
name: row.name,
|
||||
backtestId: row.backtest_id,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
|
|
@ -109,6 +120,18 @@ export class ExperimentsService {
|
|||
const input = parseExperimentInput(raw);
|
||||
return this.database.transaction(client => this.lockedPreview(client, input));
|
||||
}
|
||||
async previewCosts(raw: unknown) {
|
||||
const input = parseCostSensitivityInput(raw);
|
||||
return this.database.transaction(client => this.lockedCostPreview(client, input));
|
||||
}
|
||||
private async lockedCostPreview(client: PoolClient, input: CostSensitivityInput) {
|
||||
const source = await this.lockedPreview(client, {
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
});
|
||||
return buildCostSensitivityPreview(input, source);
|
||||
}
|
||||
async previewValidation(raw: unknown) {
|
||||
const input = parseChronologicalValidation(raw);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
|
|
@ -174,10 +197,29 @@ export class ExperimentsService {
|
|||
);
|
||||
}
|
||||
async submit(raw: unknown, actor: { principal: string; key: string }): Promise<ExperimentDetail> {
|
||||
const submission = parseExperimentSubmission(raw);
|
||||
const detail = await this.submitWorkbench(raw, actor, 'parameters');
|
||||
return this.parameterDetail(detail);
|
||||
}
|
||||
async submitCosts(
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string }
|
||||
): Promise<WorkbenchExperimentDetail> {
|
||||
return this.submitWorkbench(raw, actor, 'cost-sensitivity');
|
||||
}
|
||||
private async submitWorkbench(
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string },
|
||||
kind: 'parameters' | 'cost-sensitivity'
|
||||
): Promise<WorkbenchExperimentDetail> {
|
||||
const submission =
|
||||
kind === 'parameters' ? parseExperimentSubmission(raw) : parseCostSensitivitySubmission(raw);
|
||||
const receipt = experimentReceipt(actor);
|
||||
const { previewHash, ...input } = submission;
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: kind === 'parameters' ? 'create-experiment' : 'create-cost-sensitivity',
|
||||
submission,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
|
|
@ -204,7 +246,10 @@ export class ExperimentsService {
|
|||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const preview = await this.lockedPreview(client, input);
|
||||
const preview: WorkbenchExperimentPreview =
|
||||
'scenarios' in input
|
||||
? await this.lockedCostPreview(client, input)
|
||||
: await this.lockedPreview(client, input);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
|
|
@ -243,7 +288,7 @@ export class ExperimentsService {
|
|||
);
|
||||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID();
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
const request = workbenchTrialRequest(preview, candidate, runId);
|
||||
await client.query(
|
||||
`INSERT INTO runs (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
|
|
@ -274,11 +319,11 @@ export class ExperimentsService {
|
|||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
async get(id: string): Promise<ExperimentDetail> {
|
||||
async get(id: string): Promise<WorkbenchExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.readDetail(this.database, id);
|
||||
}
|
||||
async cancel(id: string): Promise<ExperimentDetail> {
|
||||
async cancel(id: string): Promise<WorkbenchExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
const row = (
|
||||
|
|
@ -329,7 +374,7 @@ export class ExperimentsService {
|
|||
runId: string,
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string }
|
||||
): Promise<ExperimentRetryResult> {
|
||||
): Promise<WorkbenchExperimentRetryResult> {
|
||||
experimentId(id);
|
||||
experimentId(runId);
|
||||
const input = parseExperimentRetry(raw);
|
||||
|
|
@ -342,7 +387,7 @@ export class ExperimentsService {
|
|||
...input,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async (): Promise<ExperimentRetryResult | null> => {
|
||||
const replay = async (): Promise<WorkbenchExperimentRetryResult | null> => {
|
||||
const saved = (
|
||||
await client.query(
|
||||
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.principal=$1 AND h.submission_key=$2`,
|
||||
|
|
@ -425,12 +470,12 @@ export class ExperimentsService {
|
|||
) {
|
||||
throw new ExperimentError(409, 'A run with a retained result cannot be retried');
|
||||
}
|
||||
const preview = retainedExperimentPreview(experiment.preview);
|
||||
const preview = retainedWorkbenchPreview(experiment.preview);
|
||||
const candidate = preview.candidates[run.trial_index];
|
||||
if (!candidate || candidate.trialKey !== run.trial_key || run.backtest_id !== parent.id) {
|
||||
throw new ExperimentError(409, 'Trial does not match its retained experiment candidate');
|
||||
}
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
const request = workbenchTrialRequest(preview, candidate, runId);
|
||||
if (!equal(request, run.request_snapshot) || request.datasetHash !== run.dataset_hash) {
|
||||
throw new ExperimentError(409, 'Trial frozen request does not match its experiment');
|
||||
}
|
||||
|
|
@ -479,7 +524,16 @@ export class ExperimentsService {
|
|||
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
private parameterDetail(detail: WorkbenchExperimentDetail): ExperimentDetail {
|
||||
if (detail.preview.version !== 'research-experiment-preview/v1') {
|
||||
throw new Error('Chronological validation requires a parameter experiment');
|
||||
}
|
||||
return detail as ExperimentDetail;
|
||||
}
|
||||
async readParameterDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
return this.parameterDetail(await this.readDetail(database, id));
|
||||
}
|
||||
async readDetail(database: Query, id: string): Promise<WorkbenchExperimentDetail> {
|
||||
const row = (
|
||||
await database.query(
|
||||
`SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`,
|
||||
|
|
@ -489,7 +543,7 @@ export class ExperimentsService {
|
|||
if (!row) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
const preview = retainedExperimentPreview(row.preview);
|
||||
const preview = retainedWorkbenchPreview(row.preview);
|
||||
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
|
||||
const runs = (
|
||||
await database.query(
|
||||
|
|
@ -508,7 +562,7 @@ export class ExperimentsService {
|
|||
).rows;
|
||||
const trials = preview.candidates.map(candidate => {
|
||||
const run = runs.find(item => item.trial_index === candidate.index);
|
||||
const trial: ExperimentTrial = {
|
||||
const trial: ExperimentTrial & { costs?: unknown } = {
|
||||
...candidate,
|
||||
runId: run?.id ?? null,
|
||||
attemptNumber: run ? Number(run.attempt_number) : 0,
|
||||
|
|
@ -527,7 +581,7 @@ export class ExperimentsService {
|
|||
trial.diagnostic = 'Expected trial run is missing';
|
||||
return trial;
|
||||
}
|
||||
const expected = experimentTrialRequest(preview, candidate, run.id);
|
||||
const expected = workbenchTrialRequest(preview, candidate, run.id);
|
||||
if (
|
||||
run.trial_key !== candidate.trialKey ||
|
||||
run.backtest_id !== preview.input.backtestId ||
|
||||
|
|
@ -607,6 +661,6 @@ export class ExperimentsService {
|
|||
counts[run.status as keyof ExperimentCounts]++;
|
||||
}
|
||||
}
|
||||
return { ...summary(row), counts, preview, trials };
|
||||
return { ...summary(row), counts, preview, trials } as WorkbenchExperimentDetail;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue