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
|
|
@ -37,6 +37,10 @@
|
|||
"types": "./dist/contracts/chronological-validation.d.ts",
|
||||
"default": "./dist/contracts/chronological-validation.js"
|
||||
},
|
||||
"./cost-sensitivity": {
|
||||
"types": "./dist/contracts/cost-sensitivity.d.ts",
|
||||
"default": "./dist/contracts/cost-sensitivity.js"
|
||||
},
|
||||
"./walk-forward": {
|
||||
"types": "./dist/contracts/walk-forward.d.ts",
|
||||
"default": "./dist/contracts/walk-forward.js"
|
||||
|
|
|
|||
64
apps/stock/config/src/contracts/cost-sensitivity.ts
Normal file
64
apps/stock/config/src/contracts/cost-sensitivity.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
/** Cost diagnostics reuse ordinary experiments and the authoritative Rust matcher. */
|
||||
import { z } from 'zod';
|
||||
import type { financialDecimal } from '@stock-bot/types';
|
||||
import { canonicalResearchSettingsSchema, type CanonicalRunRequest } from './canonical-research';
|
||||
import {
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentCandidate,
|
||||
type ExperimentDetail,
|
||||
type ExperimentPreview,
|
||||
type ExperimentRetryResult,
|
||||
type ExperimentTrial,
|
||||
} from './experiments';
|
||||
|
||||
export type { financialDecimal };
|
||||
|
||||
/** Exact decimal fractions: 0.001 is 10 basis points, not 0.001 percent. */
|
||||
export const costScenarioSchema = canonicalResearchSettingsSchema
|
||||
.pick({ feeRate: true, slippageRate: true })
|
||||
.strict();
|
||||
export const costSensitivityInputSchema = z
|
||||
.object({
|
||||
backtestId: z.string().uuid(),
|
||||
name: z.string().trim().min(1),
|
||||
/** Baseline is automatic and consumes one of the existing 100 trial slots. */
|
||||
scenarios: z
|
||||
.array(costScenarioSchema)
|
||||
.min(1)
|
||||
.max(MAX_EXPERIMENT_TRIALS - 1),
|
||||
})
|
||||
.strict();
|
||||
export const costSensitivitySubmissionSchema = costSensitivityInputSchema.extend({
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type CostScenario = z.input<typeof costScenarioSchema>;
|
||||
export type CostSensitivityInput = z.input<typeof costSensitivityInputSchema>;
|
||||
export type CostSensitivitySubmission = z.input<typeof costSensitivitySubmissionSchema>;
|
||||
export interface CostSensitivityCandidate extends ExperimentCandidate {
|
||||
/** Index zero is the unchanged-cost baseline; later indexes follow input order. */
|
||||
costs: CostScenario;
|
||||
}
|
||||
export interface CostSensitivityPreview {
|
||||
version: 'cost-sensitivity-preview/v1';
|
||||
previewHash: string;
|
||||
input: CostSensitivityInput;
|
||||
/** Original approved template and empty parameter grid, before cost overrides. */
|
||||
source: ExperimentPreview;
|
||||
/** Exact mirrors of the source, for existing experiment provenance consumers. */
|
||||
request: CanonicalRunRequest;
|
||||
dataset: ExperimentPreview['dataset'];
|
||||
candidates: CostSensitivityCandidate[];
|
||||
}
|
||||
export interface CostSensitivityTrial extends ExperimentTrial {
|
||||
costs: CostScenario;
|
||||
}
|
||||
export interface CostSensitivityDetail extends Omit<ExperimentDetail, 'preview' | 'trials'> {
|
||||
preview: CostSensitivityPreview;
|
||||
trials: CostSensitivityTrial[];
|
||||
}
|
||||
/** Only the ordinary workbench accepts both kinds. Validation sources stay v1. */
|
||||
export type WorkbenchExperimentPreview = ExperimentPreview | CostSensitivityPreview;
|
||||
export type WorkbenchExperimentDetail = ExperimentDetail | CostSensitivityDetail;
|
||||
export type WorkbenchExperimentRetryResult = Omit<ExperimentRetryResult, 'experiment'> & {
|
||||
experiment: WorkbenchExperimentDetail;
|
||||
};
|
||||
|
|
@ -99,6 +99,8 @@ export type ExperimentRunStatus =
|
|||
| 'cancelled';
|
||||
export type ExperimentCounts = Record<ExperimentRunStatus, number>;
|
||||
export interface ExperimentSummary {
|
||||
/** Optional for older clients/fixtures; absent means a parameter experiment. */
|
||||
kind?: 'parameters' | 'cost-sensitivity';
|
||||
id: string;
|
||||
name: string;
|
||||
backtestId: string;
|
||||
|
|
|
|||
|
|
@ -65,7 +65,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '22-experiments.sql' ||
|
||||
f === '23-experiment-retries.sql' ||
|
||||
f === '24-chronological-validation.sql' ||
|
||||
f === '25-walk-forward.sql')
|
||||
f === '25-walk-forward.sql' ||
|
||||
f === '26-cost-sensitivity.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@ import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { ChronologicalValidationService } from '../services/chronological-validation.service';
|
||||
import {
|
||||
parseCostSensitivityInput,
|
||||
parseCostSensitivitySubmission,
|
||||
} from '../services/cost-sensitivity-input';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentId,
|
||||
|
|
@ -57,6 +61,23 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
throw new ExperimentError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.post('/api/v2/experiments/cost-sensitivity/preview', async c =>
|
||||
c.json({
|
||||
preview: await service.previewCosts(parseCostSensitivityInput(await body(c.req.raw))),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/experiments/cost-sensitivity', async c => {
|
||||
const input = parseCostSensitivitySubmission(await body(c.req.raw));
|
||||
const experiment = await service.submitCosts(
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
);
|
||||
c.header('Location', `/api/v2/experiments/${experiment.id}`);
|
||||
return c.json({ experiment }, 202);
|
||||
});
|
||||
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
||||
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,10 @@ import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWa
|
|||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentInputs } from './components/ExperimentInputs';
|
||||
import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery';
|
||||
import { experimentApi, type ExperimentDetailView as Detail } from './services/experimentApi';
|
||||
import {
|
||||
experimentApi,
|
||||
type WorkbenchExperimentDetailView as Detail,
|
||||
} from './services/experimentApi';
|
||||
|
||||
export function ExperimentDetailPage() {
|
||||
const { experimentId = '' } = useParams<{ experimentId: string }>();
|
||||
|
|
@ -21,6 +24,7 @@ function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTri
|
|||
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
||||
const alive = useRef(false);
|
||||
const pending = useRef(false);
|
||||
const reading = useRef(true);
|
||||
const generation = useRef(0);
|
||||
const readRequest = useRef<AbortController | null>(null);
|
||||
const [experiment, setExperiment] = useState<Detail | null>(null);
|
||||
|
|
@ -58,6 +62,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
const revision = ++generation.current;
|
||||
const controller = new AbortController();
|
||||
readRequest.current = controller;
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void experimentApi
|
||||
|
|
@ -74,6 +79,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
})
|
||||
.finally(() => {
|
||||
if (current && revision === generation.current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
|
@ -83,7 +89,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
};
|
||||
}, [experimentId, reload]);
|
||||
const beginMutation = () => {
|
||||
if (pending.current) {
|
||||
if (pending.current || reading.current) {
|
||||
return false;
|
||||
}
|
||||
pending.current = true;
|
||||
|
|
@ -159,7 +165,8 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
size="sm"
|
||||
disabled={loading || mutating}
|
||||
onClick={() => {
|
||||
if (!pending.current) {
|
||||
if (!pending.current && !reading.current) {
|
||||
reading.current = true;
|
||||
generation.current++;
|
||||
readRequest.current?.abort();
|
||||
setReload(value => value + 1);
|
||||
|
|
@ -201,16 +208,22 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
<section aria-label="Experiment trial outcomes" className="space-y-2">
|
||||
<h2 className="font-semibold">Every trial outcome</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Rows retain grid order. Metrics come from saved results; unavailable, failed and
|
||||
incomparable outcomes remain visible. Returns and drawdowns are fractions. No
|
||||
cross-experiment ranking is applied.
|
||||
Rows retain{' '}
|
||||
{experiment.preview.version === 'cost-sensitivity-preview/v1'
|
||||
? 'baseline/scenario'
|
||||
: 'grid'}{' '}
|
||||
order. Metrics come from saved results; unavailable, failed and incomparable outcomes
|
||||
remain visible. Returns and drawdowns are fractions. No cross-experiment ranking is
|
||||
applied.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Trial / parameters',
|
||||
experiment.preview.version === 'cost-sensitivity-preview/v1'
|
||||
? 'Scenario / costs / fixed parameters'
|
||||
: 'Trial / parameters',
|
||||
'Status',
|
||||
'Comparability',
|
||||
'Total return',
|
||||
|
|
@ -228,7 +241,19 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
{experiment.trials.map(trial => (
|
||||
<tr key={trial.trialKey} className="align-top">
|
||||
<td className="p-2 border-b border-border">
|
||||
<span>Trial {trial.index + 1}</span>
|
||||
<span>
|
||||
{'costs' in trial
|
||||
? trial.index === 0
|
||||
? 'Baseline'
|
||||
: `Scenario ${trial.index}`
|
||||
: `Trial ${trial.index + 1}`}
|
||||
</span>
|
||||
{'costs' in trial && (
|
||||
<p className="text-xs">
|
||||
Fee rate: {trial.costs.feeRate} · Slippage rate:{' '}
|
||||
{trial.costs.slippageRate} (fractions)
|
||||
</p>
|
||||
)}
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(trial.parameters, null, 2)}
|
||||
</pre>
|
||||
|
|
|
|||
|
|
@ -110,6 +110,9 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
{item.kind === 'cost-sensitivity' && (
|
||||
<p className="text-sm">Cost sensitivity · template diagnostics</p>
|
||||
)}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
<ExperimentCounts experiment={item} />
|
||||
</article>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostScenario,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
|
|
@ -12,7 +17,7 @@ import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWa
|
|||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type ExperimentPreviewView,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
|
|
@ -47,15 +52,25 @@ export function ExperimentEditor({
|
|||
const navigate = useNavigate();
|
||||
const alive = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const previewRevision = useRef<number | null>(null);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
type Intent =
|
||||
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
|
||||
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
|
||||
const intent = useRef<Intent | null>(null);
|
||||
const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters');
|
||||
const modeRef = useRef(mode);
|
||||
const [scenarios, setScenarios] = useState<CostScenario[]>([{ feeRate: '', slippageRate: '' }]);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
if (
|
||||
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
|
||||
(submissionOwner.current && submissionOwner.current !== owner)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
|
|
@ -63,6 +78,7 @@ export function ExperimentEditor({
|
|||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
|
|
@ -84,7 +100,7 @@ export function ExperimentEditor({
|
|||
const [templateReload, setTemplateReload] = useState(0);
|
||||
const [limit, setLimit] = useState(50);
|
||||
const [moreTemplates, setMoreTemplates] = useState(false);
|
||||
const [preview, setPreview] = useState<ExperimentPreviewView | null>(null);
|
||||
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
|
@ -95,7 +111,14 @@ export function ExperimentEditor({
|
|||
hasIntent ||
|
||||
validationDirty ||
|
||||
walkForwardDirty ||
|
||||
Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
Boolean(
|
||||
name ||
|
||||
grid !== '{}' ||
|
||||
backtestId !== initialBacktestId ||
|
||||
mode !== 'parameters' ||
|
||||
scenarios.length !== 1 ||
|
||||
scenarios.some(item => item.feeRate || item.slippageRate)
|
||||
);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
|
|
@ -149,6 +172,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
setError('');
|
||||
|
|
@ -162,13 +186,23 @@ export function ExperimentEditor({
|
|||
previewRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
previewRequest.current = controller;
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setPreviewLoading(true);
|
||||
try {
|
||||
const input = experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) });
|
||||
const value = await experimentApi.preview(input, controller.signal);
|
||||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({ backtestId, name, scenarios }),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
previewRevision.current = current;
|
||||
setPreview(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
|
|
@ -182,17 +216,29 @@ export function ExperimentEditor({
|
|||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !preview) || !claimSubmission('ordinary')) {
|
||||
if (
|
||||
pending.current ||
|
||||
(!intent.current && (!preview || previewRevision.current !== generation.current)) ||
|
||||
!claimSubmission('ordinary')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
intent.current = {
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
intent.current =
|
||||
preview.version === 'cost-sensitivity-preview/v1'
|
||||
? {
|
||||
kind: 'cost-sensitivity',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
}
|
||||
: {
|
||||
kind: 'parameters',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
}
|
||||
const captured = intent.current;
|
||||
pending.current = true;
|
||||
|
|
@ -200,7 +246,10 @@ export function ExperimentEditor({
|
|||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const accepted = await experimentApi.create(captured.body, captured.key);
|
||||
const accepted =
|
||||
captured.kind === 'cost-sensitivity'
|
||||
? await experimentApi.costSubmit(captured.body, captured.key)
|
||||
: await experimentApi.create(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
|
|
@ -232,6 +281,7 @@ export function ExperimentEditor({
|
|||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
};
|
||||
|
|
@ -240,10 +290,13 @@ export function ExperimentEditor({
|
|||
aria-label="Create experiment"
|
||||
className="rounded-lg border border-border bg-surface p-4 space-y-4"
|
||||
>
|
||||
<h2 className="font-semibold text-text-primary">New parameter sweep</h2>
|
||||
<h2 className="font-semibold text-text-primary">
|
||||
{mode === 'parameters' ? 'New parameter sweep' : 'New cost sensitivity experiment'}
|
||||
</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Choose a saved canonical backtest and vary its strategy parameters. Preview validates every
|
||||
combination before any trials are submitted.
|
||||
{mode === 'parameters'
|
||||
? 'Choose a saved canonical backtest and vary its strategy parameters. Preview validates every combination before any trials are submitted.'
|
||||
: 'Compare explicit execution costs using fixed saved strategy parameters and dataset. Every scenario reruns the authoritative financial engine.'}
|
||||
</p>
|
||||
{templateLoading && <p role="status">Loading saved backtests...</p>}
|
||||
{templateError && (
|
||||
|
|
@ -304,27 +357,113 @@ export function ExperimentEditor({
|
|||
</Button>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Parameter grid (JSON)
|
||||
<textarea
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
Experiment type
|
||||
<select
|
||||
className={fieldClass}
|
||||
value={mode}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
onChange={event =>
|
||||
invalidate(() => {
|
||||
const next =
|
||||
event.target.value === 'cost-sensitivity' ? 'cost-sensitivity' : 'parameters';
|
||||
modeRef.current = next;
|
||||
setMode(next);
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="parameters">Parameter sweep</option>
|
||||
<option value="cost-sensitivity">Cost sensitivity</option>
|
||||
</select>
|
||||
</label>
|
||||
<p id="experiment-grid-help" className="text-xs text-text-secondary">
|
||||
Use parameter names from the selected strategy with arrays of values, e.g.{' '}
|
||||
{'{"fastPeriod":[5,10],"slowPeriod":[20,30]}'}. All combinations must be valid. {'{}'} runs
|
||||
the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per experiment; this
|
||||
does not promise concurrent execution.
|
||||
</p>
|
||||
<h3 className="font-semibold text-text-primary">Ordinary parameter sweep</h3>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Ordinary submission uses the template's retained window. Chronological preflight below does
|
||||
not change or execute this sweep.
|
||||
</p>
|
||||
{mode === 'parameters' ? (
|
||||
<>
|
||||
<label className="block text-sm">
|
||||
Parameter grid (JSON)
|
||||
<textarea
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
</label>
|
||||
<p id="experiment-grid-help" className="text-xs text-text-secondary">
|
||||
Use parameter names from the selected strategy with arrays of values, e.g.{' '}
|
||||
{'{"fastPeriod":[5,10],"slowPeriod":[20,30]}'}. All combinations must be valid. {'{}'}{' '}
|
||||
runs the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per
|
||||
experiment; this does not promise concurrent execution.
|
||||
</p>
|
||||
<h3 className="font-semibold text-text-primary">Ordinary parameter sweep</h3>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Ordinary submission uses the template's retained window. Chronological preflight below
|
||||
does not change or execute this sweep.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<section aria-label="Cost scenarios" className="space-y-3">
|
||||
<h3 className="font-semibold">Cost sensitivity · template diagnostics</h3>
|
||||
<p className="text-sm">
|
||||
Baseline is automatic and uses the saved template's original costs. Add up to{' '}
|
||||
{MAX_EXPERIMENT_TRIALS - 1} explicit fee/slippage pairs; no parameter grid or held-out
|
||||
selection is performed.
|
||||
</p>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Rates are decimal fractions: 0.001 is 10 basis points (0.1%). Fees are charged once per
|
||||
fill; slippage is an adverse price fraction. Strategy parameters, half-spread, capital
|
||||
and risk limits stay fixed. Duplicate cost pairs, including baseline, are rejected.
|
||||
</p>
|
||||
{scenarios.map((scenario, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
disabled={Boolean(lockedBy)}
|
||||
className="grid gap-2 sm:grid-cols-3 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1">Scenario {index + 1}</legend>
|
||||
{(['feeRate', 'slippageRate'] as const).map(key => (
|
||||
<label className="text-sm" key={key}>
|
||||
Scenario {index + 1} {key === 'feeRate' ? 'fee rate' : 'slippage rate'}
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className={fieldClass}
|
||||
value={scenario[key]}
|
||||
onChange={event =>
|
||||
invalidate(() =>
|
||||
setScenarios(current =>
|
||||
current.map((item, i) =>
|
||||
i === index ? { ...item, [key]: event.target.value } : item
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={Boolean(lockedBy) || scenarios.length === 1}
|
||||
onClick={() =>
|
||||
invalidate(() => setScenarios(current => current.filter((_, i) => i !== index)))
|
||||
}
|
||||
>
|
||||
Remove scenario {index + 1}
|
||||
</Button>
|
||||
</fieldset>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={Boolean(lockedBy) || scenarios.length >= MAX_EXPERIMENT_TRIALS - 1}
|
||||
onClick={() =>
|
||||
invalidate(() =>
|
||||
setScenarios(current => [...current, { feeRate: '', slippageRate: '' }])
|
||||
)
|
||||
}
|
||||
>
|
||||
Add cost scenario
|
||||
</Button>
|
||||
</section>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
|
|
@ -370,26 +509,28 @@ export function ExperimentEditor({
|
|||
)}
|
||||
</div>
|
||||
)}
|
||||
<ChronologicalValidationPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'chronological'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'walk-forward'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<div hidden={mode !== 'parameters'}>
|
||||
<ChronologicalValidationPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'chronological')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'walk-forward')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import type { ExperimentPreviewView } from '../services/experimentApi';
|
||||
import type { WorkbenchExperimentPreviewView } from '../services/experimentApi';
|
||||
|
||||
export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }) {
|
||||
export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPreviewView }) {
|
||||
const { request, dataset } = preview;
|
||||
const costs = preview.version === 'cost-sensitivity-preview/v1';
|
||||
const series = dataset.series.find(item => item.id === request.strategy.selection.seriesId);
|
||||
return (
|
||||
<section
|
||||
|
|
@ -50,9 +51,36 @@ export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }
|
|||
</div>
|
||||
</dl>
|
||||
<p>
|
||||
Only strategy parameters vary. Every trial retains this dataset, strategy version, capital,
|
||||
costs and risk policy.
|
||||
{costs
|
||||
? 'Template cost diagnostics only. Strategy parameters, dataset, seed, capital, half-spread and risk limits remain fixed; each fee/slippage scenario executes independently. No strategy selection or ranking is performed.'
|
||||
: 'Only strategy parameters vary. Every trial retains this dataset, strategy version, capital, costs and risk policy.'}
|
||||
</p>
|
||||
{preview.version === 'cost-sensitivity-preview/v1' && (
|
||||
<section aria-label="Prepared cost scenarios" className="space-y-2">
|
||||
<h3 className="font-semibold">Baseline and explicit cost scenarios</h3>
|
||||
<p>Fixed parameters: {JSON.stringify(request.strategy.selection.parameters)}</p>
|
||||
<p>Fixed half-spread rate: {request.policy.matching.halfSpreadRate}</p>
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Scenario</th>
|
||||
<th>Fee rate (fraction)</th>
|
||||
<th>Slippage rate (fraction)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.candidates.map(candidate => (
|
||||
<tr key={candidate.trialKey}>
|
||||
<td>{candidate.index === 0 ? 'Baseline' : `Scenario ${candidate.index}`}</td>
|
||||
<td>{candidate.costs.feeRate}</td>
|
||||
<td>{candidate.costs.slippageRate}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="break-all">Source preview {preview.source.previewHash}</p>
|
||||
</section>
|
||||
)}
|
||||
<details>
|
||||
<summary className="cursor-pointer text-primary-500">
|
||||
Exact parameters, policies and provenance
|
||||
|
|
@ -62,6 +90,9 @@ export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }
|
|||
{
|
||||
previewHash: preview.previewHash,
|
||||
input: preview.input,
|
||||
...(preview.version === 'cost-sensitivity-preview/v1'
|
||||
? { source: preview.source }
|
||||
: {}),
|
||||
candidates: preview.candidates,
|
||||
strategy: {
|
||||
versionId: request.strategy.versionId,
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import { Button } from '@/components/ui/Button';
|
|||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type ExperimentDetailView,
|
||||
type ExperimentRetryTarget,
|
||||
type WorkbenchExperimentDetailView,
|
||||
} from '../services/experimentApi';
|
||||
|
||||
interface Props {
|
||||
|
|
@ -20,7 +20,7 @@ interface Props {
|
|||
trial: ExperimentTrial;
|
||||
disabled: boolean;
|
||||
beginMutation: () => boolean;
|
||||
acceptMutation: (experiment: ExperimentDetailView) => void;
|
||||
acceptMutation: (experiment: WorkbenchExperimentDetailView) => void;
|
||||
endMutation: () => void;
|
||||
onIntentChange: (trialKey: string, active: boolean) => void;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentRetrySchema,
|
||||
|
|
@ -30,11 +38,13 @@ const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
|||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const counter = z.number().int().nonnegative().max(2147483647);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
});
|
||||
const candidate = z
|
||||
.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
})
|
||||
.strict();
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
|
|
@ -45,6 +55,7 @@ const counts = z.object({
|
|||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
kind: z.enum(['parameters', 'cost-sensitivity']).optional(),
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
|
|
@ -78,14 +89,25 @@ export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
|
|||
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
|
||||
preview: ExperimentPreviewView;
|
||||
};
|
||||
const preview = z.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export type CostSensitivityPreviewView = Omit<CostSensitivityPreview, 'dataset' | 'source'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
source: ExperimentPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView;
|
||||
export type CostSensitivityDetailView = Omit<CostSensitivityDetail, 'preview'> & {
|
||||
preview: CostSensitivityPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView;
|
||||
const preview = z
|
||||
.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const metric = z.number().finite().nullable();
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
|
|
@ -185,10 +207,60 @@ export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
|||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
const costCandidate = candidate.extend({ costs: costScenarioSchema });
|
||||
const costPreview = preview
|
||||
.omit({ version: true, input: true, candidates: true })
|
||||
.extend({
|
||||
version: z.literal('cost-sensitivity-preview/v1'),
|
||||
input: costSensitivityInputSchema,
|
||||
source: z.unknown(),
|
||||
candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView {
|
||||
const parsed = costPreview.parse(raw),
|
||||
source = parseExperimentPreview(parsed.source);
|
||||
const costs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...parsed.input.scenarios,
|
||||
];
|
||||
if (
|
||||
!same(source.input, {
|
||||
backtestId: parsed.input.backtestId,
|
||||
name: parsed.input.name,
|
||||
grid: {},
|
||||
}) ||
|
||||
source.candidates.length !== 1 ||
|
||||
!same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(parsed.request, source.request) ||
|
||||
!same(parsed.dataset, source.dataset) ||
|
||||
parsed.candidates.length !== costs.length ||
|
||||
new Set(costs.map(canonicalStrategyJson)).size !== costs.length ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length ||
|
||||
parsed.candidates.some(
|
||||
(item, index) =>
|
||||
item.index !== index ||
|
||||
!same(item.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(item.costs, costs[index])
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, source } as CostSensitivityPreviewView;
|
||||
}
|
||||
function checkDetail(
|
||||
parsed: z.infer<typeof detail> | z.infer<typeof costDetail>,
|
||||
retained: WorkbenchExperimentPreviewView
|
||||
) {
|
||||
parseSummary(parsed);
|
||||
const retained = parseExperimentPreview(parsed.preview);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
|
|
@ -200,6 +272,13 @@ export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
|||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const costKind = retained.version === 'cost-sensitivity-preview/v1';
|
||||
if (
|
||||
(costKind && parsed.kind !== 'cost-sensitivity') ||
|
||||
(!costKind && parsed.kind === 'cost-sensitivity')
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
|
|
@ -208,6 +287,8 @@ export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
|||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(costKind &&
|
||||
(!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
|
|
@ -227,7 +308,27 @@ export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
|||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, preview: retained } as ExperimentDetailView;
|
||||
|
||||
return { ...parsed, preview: retained };
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView;
|
||||
}
|
||||
export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView {
|
||||
const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value)
|
||||
.preview.version;
|
||||
if (version === 'research-experiment-preview/v1') {
|
||||
return parseExperimentDetail(value);
|
||||
}
|
||||
if (version !== 'cost-sensitivity-preview/v1') {
|
||||
throw invalid();
|
||||
}
|
||||
const parsed = costDetail.parse(value);
|
||||
return checkDetail(
|
||||
parsed,
|
||||
parseCostSensitivityPreview(parsed.preview)
|
||||
) as CostSensitivityDetailView;
|
||||
}
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
@ -272,6 +373,37 @@ const json = (body: unknown): RequestInit => ({
|
|||
body: JSON.stringify(body),
|
||||
});
|
||||
export const experimentApi = {
|
||||
costPreview: (input: CostSensitivityInput, signal?: AbortSignal) =>
|
||||
request(
|
||||
'/cost-sensitivity/preview',
|
||||
{ ...json(costSensitivityInputSchema.parse(input)), signal },
|
||||
200,
|
||||
body => {
|
||||
const value = parseCostSensitivityPreview(envelope(body, 'preview'));
|
||||
if (!same(value.input, costSensitivityInputSchema.parse(input))) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
),
|
||||
costSubmit: (input: CostSensitivitySubmission, key: string) =>
|
||||
request(
|
||||
'/cost-sensitivity',
|
||||
{ ...json(input), headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key } },
|
||||
202,
|
||||
body => {
|
||||
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (
|
||||
value.preview.version !== 'cost-sensitivity-preview/v1' ||
|
||||
value.previewHash !== previewHash ||
|
||||
!same(value.preview.input, costSensitivityInputSchema.parse(original))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
),
|
||||
retryTrial: (target: ExperimentRetryTarget, input: ExperimentRetryInput, key: string) =>
|
||||
request(
|
||||
`/${encodeURIComponent(target.experimentId)}/trials/${encodeURIComponent(target.runId)}/retry`,
|
||||
|
|
@ -282,7 +414,7 @@ export const experimentApi = {
|
|||
202,
|
||||
body => {
|
||||
const receipt = retryReceipt.parse(envelope(body, 'retry'));
|
||||
const experiment = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const experiment = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
const current = experiment.trials.find(
|
||||
item => item.trialKey === target.trialKey && item.runId === target.runId
|
||||
);
|
||||
|
|
@ -370,7 +502,7 @@ export const experimentApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -378,7 +510,7 @@ export const experimentApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue