refactor: share research domain and simplify application workflows
This commit is contained in:
parent
805a9f8fd4
commit
8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions
|
|
@ -1,51 +1,21 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { 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,
|
||||
type ExperimentSubmission,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { type CostScenario } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import { MAX_EXPERIMENT_TRIALS } from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import {
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
import { useExperimentSubmission } from '../hooks/useExperimentSubmission';
|
||||
import { useExperimentTemplates } from '../hooks/useExperimentTemplates';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import { WalkForwardPreflight } from './WalkForwardPreflight';
|
||||
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: 'Could not prepare the experiment';
|
||||
const canonical = (value: Backtest) =>
|
||||
value &&
|
||||
typeof value.id === 'string' &&
|
||||
typeof value.name === 'string' &&
|
||||
!value.archivedAt &&
|
||||
value.strategyVersionId &&
|
||||
value.config &&
|
||||
typeof value.config.canonical === 'object' &&
|
||||
value.config.canonical !== null &&
|
||||
typeof value.config.datasetHash === 'string';
|
||||
|
||||
export function ExperimentEditor({
|
||||
initialBacktestId,
|
||||
onDirty,
|
||||
|
|
@ -54,47 +24,9 @@ export function ExperimentEditor({
|
|||
onDirty: (dirty: boolean) => void;
|
||||
}) {
|
||||
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);
|
||||
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 (
|
||||
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
|
||||
(submissionOwner.current && submissionOwner.current !== owner)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
}
|
||||
}, []);
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
const [grid, setGrid] = useState('{}');
|
||||
|
|
@ -111,19 +43,38 @@ export function ExperimentEditor({
|
|||
parameters: candidateSelection.strategyParameters ?? {},
|
||||
}
|
||||
: undefined;
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [templateLoading, setTemplateLoading] = useState(true);
|
||||
const [templateError, setTemplateError] = useState('');
|
||||
const [templateReload, setTemplateReload] = useState(0);
|
||||
const [limit, setLimit] = useState(50);
|
||||
const [moreTemplates, setMoreTemplates] = useState(false);
|
||||
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [validationDirty, setValidationDirty] = useState(false);
|
||||
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
|
||||
const { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit } =
|
||||
useExperimentTemplates(initialBacktestId);
|
||||
const {
|
||||
submissionOwner,
|
||||
lockedBy,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
preview,
|
||||
previewLoading,
|
||||
error,
|
||||
hasIntent,
|
||||
submitting,
|
||||
ambiguous,
|
||||
invalidate,
|
||||
prepare,
|
||||
submit,
|
||||
newIntent,
|
||||
} = useExperimentSubmission({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
modeRef,
|
||||
scenarios,
|
||||
candidate,
|
||||
candidateRevision,
|
||||
renderedCandidateRevision,
|
||||
useCandidate,
|
||||
candidateValid,
|
||||
onAccepted: id => navigate(`/experiments/${encodeURIComponent(id)}`),
|
||||
});
|
||||
const dirty =
|
||||
hasIntent ||
|
||||
validationDirty ||
|
||||
|
|
@ -141,183 +92,7 @@ export function ExperimentEditor({
|
|||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setTemplateLoading(true);
|
||||
setTemplateError('');
|
||||
void (async () => {
|
||||
const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal);
|
||||
if (!Array.isArray(rows)) {
|
||||
throw new Error('The saved backtest list could not be read');
|
||||
}
|
||||
const selected =
|
||||
initialBacktestId && !rows.some(item => item?.id === initialBacktestId)
|
||||
? await backtestApiV2.getBacktest(initialBacktestId)
|
||||
: null;
|
||||
if (current) {
|
||||
setMoreTemplates(rows.length === limit);
|
||||
setBacktests((selected ? [...rows, selected] : rows).filter(canonical));
|
||||
}
|
||||
})()
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setTemplateError(message(cause));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setTemplateLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [initialBacktestId, templateReload, limit]);
|
||||
|
||||
const invalidate = (change: () => void) => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
setError('');
|
||||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (
|
||||
submissionOwner.current ||
|
||||
previewLoading ||
|
||||
candidateRevision.current !== renderedCandidateRevision ||
|
||||
(useCandidate && !candidateValid)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
previewRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
previewRequest.current = controller;
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setPreviewLoading(true);
|
||||
try {
|
||||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
scenarios,
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
previewRevision.current = current;
|
||||
setPreview(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current && current === generation.current) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
if (alive.current && current === generation.current) {
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (
|
||||
pending.current ||
|
||||
(!intent.current && (!preview || previewRevision.current !== generation.current)) ||
|
||||
!claimSubmission('ordinary')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
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);
|
||||
releaseSubmission('ordinary');
|
||||
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const newIntent = () => {
|
||||
if (
|
||||
pending.current ||
|
||||
!window.confirm(
|
||||
'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Create experiment"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue