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
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue