feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
|
|
@ -3,10 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import { SaveFindingDialog } from '@/features/research/components/SaveFindingDialog';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog';
|
||||
import { BacktestConfiguration } from './components/BacktestConfiguration';
|
||||
|
|
@ -77,9 +74,7 @@ export function BacktestDetailPageV2() {
|
|||
? runResults
|
||||
: null;
|
||||
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
|
||||
const unsupportedLegacy = Boolean(
|
||||
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
|
||||
);
|
||||
const unsupportedLegacy = Boolean(backtest && !catalog);
|
||||
const executionUnavailable = catalog ? !canonicalCapability?.available : unsupportedLegacy;
|
||||
const canSubmit = (!archived && !executionUnavailable) || hasPendingSubmission;
|
||||
|
||||
|
|
@ -572,8 +567,8 @@ export function BacktestDetailPageV2() {
|
|||
)}
|
||||
{unsupportedLegacy && (
|
||||
<p role="status" className="mb-4 text-sm text-text-secondary">
|
||||
This legacy strategy is not supported for new submissions by this form. Its existing
|
||||
history remains readable.
|
||||
Legacy execution is retired. Create a catalog backtest to run with retained canonical
|
||||
inputs. Its existing history remains readable.
|
||||
</p>
|
||||
)}
|
||||
{archived && (
|
||||
|
|
|
|||
|
|
@ -199,9 +199,9 @@ export function BacktestListPageV2() {
|
|||
}
|
||||
void loadBacktests();
|
||||
}}
|
||||
onCreated={(created, run) => {
|
||||
onCreated={created => {
|
||||
setShowCreateDialog(false);
|
||||
navigate(`/backtests/${created.id}${run ? `/run/${run.id}` : ''}`);
|
||||
navigate(`/backtests/${created.id}`);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { XMarkIcon } from '@heroicons/react/24/solid';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
LegacyStrategySelect,
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
|
|
@ -9,14 +8,14 @@ import {
|
|||
confirmDiscard,
|
||||
useUnsavedWarning,
|
||||
} from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
|
||||
import { backtestApiV2, type Backtest } from '../services/backtestApiV2';
|
||||
import type { HistoricalSelection } from '../services/historical-selection';
|
||||
import { HistoricalDataSelection } from './HistoricalDataSelection';
|
||||
|
||||
interface CreateBacktestDialogProps {
|
||||
initialSelection?: CatalogSelection;
|
||||
onClose: () => void;
|
||||
onCreated: (backtest: Backtest, run?: Run) => void;
|
||||
onCreated: (backtest: Backtest) => void;
|
||||
}
|
||||
|
||||
export function CreateBacktestDialog({
|
||||
|
|
@ -27,14 +26,12 @@ export function CreateBacktestDialog({
|
|||
const [formData, setFormData] = useState<
|
||||
HistoricalSelection & {
|
||||
name: string;
|
||||
strategy: string;
|
||||
initialCapital: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
}
|
||||
>({
|
||||
name: '',
|
||||
strategy: 'moving-average',
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
|
||||
endDate: new Date().toISOString().slice(0, 10),
|
||||
|
|
@ -46,17 +43,14 @@ export function CreateBacktestDialog({
|
|||
dataSource: 'auto',
|
||||
});
|
||||
|
||||
const [catalogMode, setCatalogMode] = useState(Boolean(initialSelection?.strategyVersionId));
|
||||
const [selection, setSelection] = useState<CatalogSelection>(initialSelection ?? {});
|
||||
const [strategyValid, setStrategyValid] = useState(false);
|
||||
const [edited, setEdited] = useState(false);
|
||||
useUnsavedWarning(edited);
|
||||
const [historicalValid, setHistoricalValid] = useState(true);
|
||||
const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle');
|
||||
const [phase, setPhase] = useState<'idle' | 'saving'>('idle');
|
||||
const isSubmitting = phase !== 'idle';
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const saved = useRef<Backtest | null>(null);
|
||||
const submission = useRef<{ key: string; body: { speedMultiplier: null } } | null>(null);
|
||||
const pending = useRef(false);
|
||||
const active = useRef(true);
|
||||
|
||||
|
|
@ -69,23 +63,18 @@ export function CreateBacktestDialog({
|
|||
|
||||
const close = () => {
|
||||
// A list refresh before this write settles could miss the newly saved row.
|
||||
if (pending.current && !saved.current) {
|
||||
if (pending.current) {
|
||||
return;
|
||||
}
|
||||
if (!saved.current && !confirmDiscard(edited)) {
|
||||
if (!confirmDiscard(edited)) {
|
||||
return;
|
||||
}
|
||||
active.current = false;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSubmit = async (runAfterSave: boolean) => {
|
||||
if (
|
||||
pending.current ||
|
||||
!active.current ||
|
||||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid))) ||
|
||||
(runAfterSave && catalogMode)
|
||||
) {
|
||||
const handleSubmit = async () => {
|
||||
if (pending.current || !active.current || !historicalValid || !strategyValid) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -95,56 +84,36 @@ export function CreateBacktestDialog({
|
|||
}
|
||||
|
||||
pending.current = true;
|
||||
setPhase(saved.current ? 'submitting' : 'saving');
|
||||
setPhase('saving');
|
||||
setError(null);
|
||||
try {
|
||||
if (!saved.current) {
|
||||
const created = await backtestApiV2.createBacktest({
|
||||
name: formData.name,
|
||||
strategy: catalogMode ? 'catalog' : formData.strategy,
|
||||
...(catalogMode ? selection : {}),
|
||||
symbols: formData.symbols,
|
||||
startDate: formData.startDate,
|
||||
endDate: formData.endDate,
|
||||
initialCapital: formData.initialCapital,
|
||||
config: {
|
||||
commission: formData.commission,
|
||||
slippage: formData.slippage,
|
||||
dataFrequency: formData.dataFrequency,
|
||||
dataSource: formData.dataSource,
|
||||
datasetHash: formData.datasetHash,
|
||||
dataPolicy: {
|
||||
adjustment: formData.priceAdjustment ?? 'raw',
|
||||
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||
},
|
||||
const created = await backtestApiV2.createBacktest({
|
||||
name: formData.name,
|
||||
strategy: 'catalog',
|
||||
...selection,
|
||||
symbols: formData.symbols,
|
||||
startDate: formData.startDate,
|
||||
endDate: formData.endDate,
|
||||
initialCapital: formData.initialCapital,
|
||||
config: {
|
||||
commission: formData.commission,
|
||||
slippage: formData.slippage,
|
||||
dataFrequency: formData.dataFrequency,
|
||||
dataSource: formData.dataSource,
|
||||
datasetHash: formData.datasetHash,
|
||||
dataPolicy: {
|
||||
adjustment: formData.priceAdjustment ?? 'raw',
|
||||
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||
},
|
||||
});
|
||||
if (!active.current) {
|
||||
return;
|
||||
}
|
||||
saved.current = created;
|
||||
}
|
||||
let run: Run | undefined;
|
||||
if (runAfterSave) {
|
||||
setPhase('submitting');
|
||||
submission.current ??= { key: crypto.randomUUID(), body: { speedMultiplier: null } };
|
||||
run = await backtestApiV2.createRun(
|
||||
saved.current.id,
|
||||
submission.current.body,
|
||||
submission.current.key
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
if (active.current) {
|
||||
onCreated(saved.current, run);
|
||||
onCreated(created);
|
||||
}
|
||||
} catch (err) {
|
||||
if (active.current) {
|
||||
const detail = err instanceof Error ? err.message : 'Please try again.';
|
||||
setError(
|
||||
saved.current
|
||||
? `Backtest saved, but run submission failed. Retry submission to recover the same run. ${detail}`
|
||||
: `Failed to save backtest. ${detail}`
|
||||
);
|
||||
setError(`Failed to save backtest. ${detail}`);
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
|
|
@ -177,12 +146,12 @@ export function CreateBacktestDialog({
|
|||
<form
|
||||
onSubmit={e => {
|
||||
e.preventDefault();
|
||||
void handleSubmit(saved.current !== null);
|
||||
void handleSubmit();
|
||||
}}
|
||||
className="space-y-6"
|
||||
onChange={() => setEdited(true)}
|
||||
>
|
||||
<fieldset disabled={isSubmitting || saved.current !== null} className="space-y-6">
|
||||
<fieldset disabled={isSubmitting} className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Backtest Name
|
||||
|
|
@ -197,41 +166,22 @@ export function CreateBacktestDialog({
|
|||
/>
|
||||
</div>
|
||||
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Strategy mode
|
||||
<select
|
||||
aria-label="Strategy mode"
|
||||
value={catalogMode ? 'catalog' : 'legacy'}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(Boolean(selection.strategyVersionId))) {
|
||||
setCatalogMode(event.target.value === 'catalog');
|
||||
}
|
||||
}}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md"
|
||||
>
|
||||
<option value="legacy">Legacy strategy</option>
|
||||
<option value="catalog">Catalog version (save only)</option>
|
||||
</select>
|
||||
</label>
|
||||
{catalogMode ? (
|
||||
<StrategySelection
|
||||
value={selection}
|
||||
onChange={setSelection}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={isSubmitting || saved.current !== null}
|
||||
/>
|
||||
) : (
|
||||
<LegacyStrategySelect
|
||||
value={formData.strategy}
|
||||
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
|
||||
/>
|
||||
)}
|
||||
<p className="text-sm text-text-secondary">
|
||||
Select an immutable strategy version. After saving, configure a retained dataset and
|
||||
financial policies before running a canonical backtest.
|
||||
</p>
|
||||
<StrategySelection
|
||||
value={selection}
|
||||
onChange={setSelection}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
|
||||
<HistoricalDataSelection
|
||||
value={formData}
|
||||
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
|
||||
onValidityChange={setHistoricalValid}
|
||||
disabled={isSubmitting || saved.current !== null}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
|
||||
<div>
|
||||
|
|
@ -295,32 +245,19 @@ export function CreateBacktestDialog({
|
|||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={
|
||||
isSubmitting ||
|
||||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid)))
|
||||
}
|
||||
disabled={isSubmitting || !historicalValid || !strategyValid}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
{isSubmitting
|
||||
? 'Saving / submitting...'
|
||||
: saved.current
|
||||
? 'Retry submission'
|
||||
: 'Save'}
|
||||
{isSubmitting ? 'Saving...' : 'Save'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
title="Save first, then configure the retained dataset and financial policies."
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium opacity-50"
|
||||
>
|
||||
Save and run
|
||||
</button>
|
||||
{!saved.current && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isSubmitting || catalogMode || (!saved.current && !historicalValid)}
|
||||
onClick={e => {
|
||||
if (e.currentTarget.form?.reportValidity()) {
|
||||
void handleSubmit(true);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Save and run
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
|
||||
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
|
||||
import type {
|
||||
Backtest,
|
||||
|
|
@ -423,30 +420,30 @@ export function useBacktestV2() {
|
|||
}, []);
|
||||
|
||||
const createRun = useCallback(
|
||||
async (speedMultiplier: number | null = null) => {
|
||||
async (_speedMultiplier: number | null = null) => {
|
||||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
}
|
||||
if (catalog && !canonicalCapability?.available && !submission.current) {
|
||||
setSubmissionError(
|
||||
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (!catalog && !supportedLegacyStrategy(backtest.strategy) && !submission.current) {
|
||||
if (!catalog && !submission.current) {
|
||||
setSubmissionError(
|
||||
'This legacy strategy is not supported for new submissions by this form.'
|
||||
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
}
|
||||
const intent = (submission.current ??= {
|
||||
backtestId: backtest.id,
|
||||
key: crypto.randomUUID(),
|
||||
body: { speedMultiplier: catalog ? null : speedMultiplier },
|
||||
body: { speedMultiplier: null },
|
||||
pending: false,
|
||||
});
|
||||
intent.pending = true;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue