feat(research): select and reuse frozen datasets in workbench

This commit is contained in:
Boki 2026-10-23 18:13:37 -04:00
parent 6a67ae8683
commit b106c1ca85
29 changed files with 2295 additions and 426 deletions

View file

@ -1,9 +1,9 @@
import { useEffect, useState } from 'react';
import { parseInstrumentId } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import { HistoricalDataSelection } from './HistoricalDataSelection';
interface BacktestConfigurationProps {
onSubmit: (config: BacktestConfig) => void;
onSubmit: (config: BacktestConfig) => void | Promise<void>;
disabled?: boolean;
initialConfig?: BacktestConfig;
}
@ -16,8 +16,12 @@ export function BacktestConfiguration({
const [formData, setFormData] = useState<BacktestConfig>(
initialConfig || {
name: '',
startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago
endDate: new Date(),
startDate: new Date(new Date().setMonth(new Date().getMonth() - 6))
.toISOString()
.slice(0, 10), // 6 months ago
endDate: new Date().toISOString().slice(0, 10),
dataFrequency: '1d',
dataSource: 'auto',
initialCapital: 100000,
symbols: [],
strategy: 'sma-crossover',
@ -27,7 +31,10 @@ export function BacktestConfiguration({
}
);
const [symbolInput, setSymbolInput] = useState('');
const [historicalValid, setHistoricalValid] = useState(false);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const locked = disabled || saving;
useEffect(() => {
if (initialConfig) {
@ -35,53 +42,32 @@ export function BacktestConfiguration({
}
}, [initialConfig]);
const handleSubmit = (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (formData.symbols.length === 0) {
alert('Please add at least one symbol');
if (!historicalValid || locked) {
return;
}
onSubmit(formData);
setSaving(true);
setSaveError(null);
try {
await onSubmit(formData);
} catch (error) {
setSaveError(error instanceof Error ? error.message : 'Could not save configuration');
} finally {
setSaving(false);
}
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value, type } = e.target;
setFormData(prev => ({
...prev,
[name]: type === 'number' ? parseFloat(value) : type === 'date' ? new Date(value) : value,
[name]: type === 'number' ? parseFloat(value) : value,
}));
};
const handleAddSymbol = () => {
const symbol = symbolInput.trim().toUpperCase();
try {
parseInstrumentId(symbol);
} catch {
alert('Enter an exchange-qualified ID, for example AAPL.US');
return;
}
if (symbol && !formData.symbols.includes(symbol)) {
setFormData(prev => ({
...prev,
symbols: [...prev.symbols, symbol],
}));
setSymbolInput('');
}
};
const handleRemoveSymbol = (symbol: string) => {
setFormData(prev => ({
...prev,
symbols: prev.symbols.filter(s => s !== symbol),
}));
};
const formatDate = (date: Date) => {
return date.toISOString().split('T')[0];
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<form onSubmit={event => void handleSubmit(event)} className="space-y-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">Backtest Name</label>
<input
@ -91,60 +77,22 @@ export function BacktestConfiguration({
onChange={handleChange}
placeholder="My Strategy Backtest"
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
disabled={locked}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
Historical prices
</label>
<select
value={formData.priceAdjustment ?? 'raw'}
disabled={disabled}
onChange={e =>
setFormData(prev => ({
...prev,
priceAdjustment: e.target.value === 'provider-adjusted' ? 'provider-adjusted' : 'raw',
}))
}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary"
>
<option value="raw">Raw prices (no corporate-action adjustment)</option>
<option value="provider-adjusted">
Provider adjusted (splits/dividends; reported volume)
</option>
</select>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">Start Date</label>
<input
type="date"
name="startDate"
value={formatDate(formData.startDate)}
onChange={handleChange}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">End Date</label>
<input
type="date"
name="endDate"
value={formatDate(formData.endDate)}
onChange={handleChange}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
required
/>
</div>
</div>
<HistoricalDataSelection
value={formData}
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
onValidityChange={setHistoricalValid}
disabled={locked}
/>
{saveError && (
<p role="alert" className="text-sm text-error">
{saveError}
</p>
)}
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
@ -158,52 +106,11 @@ export function BacktestConfiguration({
min="1000"
step="1000"
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
disabled={locked}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">Symbols</label>
<div className="flex gap-2 mb-2">
<input
type="text"
value={symbolInput}
onChange={e => setSymbolInput(e.target.value)}
onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), handleAddSymbol())}
placeholder="AAPL.US"
className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
/>
<button
type="button"
onClick={handleAddSymbol}
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"
disabled={disabled}
>
Add
</button>
</div>
<div className="flex flex-wrap gap-2">
{formData.symbols.map(symbol => (
<span
key={symbol}
className="inline-flex items-center gap-1 px-2 py-1 bg-primary-500/10 text-primary-400 rounded-md text-sm"
>
{symbol}
<button
type="button"
onClick={() => handleRemoveSymbol(symbol)}
className="text-primary-400 hover:text-primary-300"
disabled={disabled}
>
×
</button>
</span>
))}
</div>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">Strategy</label>
<select
@ -211,7 +118,7 @@ export function BacktestConfiguration({
value={formData.strategy}
onChange={handleChange}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
disabled={locked}
>
<option value="sma-crossover">SMA Crossover</option>
<option value="mean-reversion">Mean Reversion</option>
@ -244,7 +151,7 @@ export function BacktestConfiguration({
min="0"
step="0.01"
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
disabled={locked}
/>
</div>
@ -260,7 +167,7 @@ export function BacktestConfiguration({
min="0"
step="0.01"
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
disabled={locked}
/>
</div>
</div>
@ -278,7 +185,7 @@ export function BacktestConfiguration({
max="1000"
step="0.1"
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
disabled={disabled}
disabled={locked}
/>
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
</div>
@ -286,7 +193,7 @@ export function BacktestConfiguration({
<button
type="submit"
className="w-full px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
disabled={disabled}
disabled={locked || !historicalValid}
>
Save
</button>

View file

@ -1,7 +1,8 @@
import { XMarkIcon } from '@heroicons/react/24/solid';
import { useEffect, useRef, useState } from 'react';
import { parseInstrumentId } from '@stock-bot/types';
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
import type { HistoricalSelection } from '../services/historical-selection';
import { HistoricalDataSelection } from './HistoricalDataSelection';
interface CreateBacktestDialogProps {
onClose: () => void;
@ -9,7 +10,15 @@ interface CreateBacktestDialogProps {
}
export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialogProps) {
const [formData, setFormData] = useState({
const [formData, setFormData] = useState<
HistoricalSelection & {
name: string;
strategy: string;
initialCapital: number;
commission: number;
slippage: number;
}
>({
name: '',
strategy: 'moving-average',
symbols: ['AAPL.US'],
@ -18,10 +27,12 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
initialCapital: 100000,
commission: 0,
slippage: 0,
priceAdjustment: 'raw' as 'raw' | 'provider-adjusted',
priceAdjustment: 'raw',
dataFrequency: '1d',
dataSource: 'auto',
});
const [symbolInput, setSymbolInput] = useState('');
const [historicalValid, setHistoricalValid] = useState(true);
const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle');
const isSubmitting = phase !== 'idle';
const [error, setError] = useState<string | null>(null);
@ -47,7 +58,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
};
const handleSubmit = async (runAfterSave: boolean) => {
if (pending.current || !active.current) {
if (pending.current || !active.current || (!saved.current && !historicalValid)) {
return;
}
@ -71,7 +82,13 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
config: {
commission: formData.commission,
slippage: formData.slippage,
dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' },
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) {
@ -109,27 +126,6 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
}
};
const addSymbol = () => {
const symbol = symbolInput.trim().toUpperCase();
try {
parseInstrumentId(symbol);
} catch {
alert('Enter an exchange-qualified ID, for example AAPL.US');
return;
}
if (symbol && !formData.symbols.includes(symbol)) {
setFormData({ ...formData, symbols: [...formData.symbols, symbol] });
setSymbolInput('');
}
};
const removeSymbol = (symbol: string) => {
setFormData({
...formData,
symbols: formData.symbols.filter(s => s !== symbol),
});
};
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-surface-secondary rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
@ -187,92 +183,12 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
</select>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">Symbols</label>
<div className="flex gap-2 mb-2">
<input
type="text"
value={symbolInput}
onChange={e => setSymbolInput(e.target.value)}
onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSymbol())}
className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
placeholder="Instrument ID (e.g., AAPL.US)"
/>
<button
type="button"
onClick={addSymbol}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Add
</button>
</div>
<div className="flex flex-wrap gap-2">
{formData.symbols.map(symbol => (
<span
key={symbol}
className="inline-flex items-center gap-1 px-3 py-1 bg-background border border-border rounded-full text-sm text-text-primary"
>
{symbol}
<button
type="button"
onClick={() => removeSymbol(symbol)}
className="hover:text-error transition-colors"
>
<XMarkIcon className="w-4 h-4" />
</button>
</span>
))}
</div>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Historical prices
</label>
<select
value={formData.priceAdjustment}
onChange={e =>
setFormData({
...formData,
priceAdjustment:
e.target.value === 'provider-adjusted' ? 'provider-adjusted' : 'raw',
})
}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary"
>
<option value="raw">Raw prices (no corporate-action adjustment)</option>
<option value="provider-adjusted">
Provider adjusted (splits/dividends; reported volume)
</option>
</select>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Start Date
</label>
<input
type="date"
value={formData.startDate}
onChange={e => setFormData({ ...formData, startDate: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
End Date
</label>
<input
type="date"
value={formData.endDate}
onChange={e => setFormData({ ...formData, endDate: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
required
/>
</div>
</div>
<HistoricalDataSelection
value={formData}
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
onValidityChange={setHistoricalValid}
disabled={isSubmitting || saved.current !== null}
/>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
@ -335,7 +251,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
</button>
<button
type="submit"
disabled={isSubmitting}
disabled={isSubmitting || (!saved.current && !historicalValid)}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
{isSubmitting
@ -347,7 +263,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
{!saved.current && (
<button
type="button"
disabled={isSubmitting}
disabled={isSubmitting || (!saved.current && !historicalValid)}
onClick={e => {
if (e.currentTarget.form?.reportValidity()) {
void handleSubmit(true);

View file

@ -0,0 +1,397 @@
import { useEffect, useState } from 'react';
import { parseInstrumentId, type HistoricalDatasetCatalogEntry } from '@stock-bot/types';
import { backtestApiV2 } from '../services/backtestApiV2';
import {
historicalDateInput,
historicalIntervals,
historicalSelectionError,
retainedDatasetSelection,
type HistoricalSelection,
} from '../services/historical-selection';
const inputClass =
'w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary disabled:opacity-60';
const buttonClass = 'text-sm text-primary-500 disabled:opacity-50';
export function HistoricalDataSelection({
value,
onChange,
onValidityChange,
disabled = false,
}: {
value: HistoricalSelection;
onChange: (value: HistoricalSelection) => void;
onValidityChange: (valid: boolean) => void;
disabled?: boolean;
}) {
const [entries, setEntries] = useState<HistoricalDatasetCatalogEntry[]>([]);
const [page, setPage] = useState(0);
const [retry, setRetry] = useState(0);
const [loading, setLoading] = useState(true);
const [more, setMore] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [detail, setDetail] = useState<HistoricalDatasetCatalogEntry | null>(null);
const [detailError, setDetailError] = useState<string | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [symbol, setSymbol] = useState('');
const [symbolError, setSymbolError] = useState<string | null>(null);
const frozen = value.datasetHash !== undefined;
const selected =
entries.find(entry => entry.hash === value.datasetHash) ??
(detail?.hash === value.datasetHash ? detail : null);
const frequency = value.dataFrequency ?? '1d';
const validation =
frozen && !value.datasetHash
? 'Choose a frozen dataset'
: historicalSelectionError(value, selected);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setCatalogError(null);
backtestApiV2
.listDatasets(50, page * 50, controller.signal)
.then(rows => {
if (controller.signal.aborted) {
return;
}
setEntries(previous => [
...new Map(
(page === 0 ? rows : [...previous, ...rows]).map(row => [row.hash, row])
).values(),
]);
setMore(rows.length === 50);
})
.catch(error => {
if (!controller.signal.aborted) {
setCatalogError(
error instanceof Error ? error.message : 'Could not load frozen datasets'
);
}
})
.finally(() => {
if (!controller.signal.aborted) {
setLoading(false);
}
});
return () => controller.abort();
}, [page, retry]);
useEffect(() => {
const controller = new AbortController();
setDetailError(null);
if (!value.datasetHash || entries.some(entry => entry.hash === value.datasetHash)) {
setDetailLoading(false);
return () => controller.abort();
}
setDetailLoading(true);
backtestApiV2
.getDataset(value.datasetHash, controller.signal)
.then(entry => {
if (!controller.signal.aborted) {
setDetail(entry);
}
})
.catch(error => {
if (!controller.signal.aborted) {
setDetailError(
error instanceof Error ? error.message : 'Selected dataset is unavailable'
);
}
})
.finally(() => {
if (!controller.signal.aborted) {
setDetailLoading(false);
}
});
return () => controller.abort();
}, [value.datasetHash, entries, retry]);
useEffect(
() => onValidityChange(validation === null && !detailError),
[validation, detailError, onValidityChange]
);
const choose = (hash: string) => {
const entry =
entries.find(item => item.hash === hash) ?? (detail?.hash === hash ? detail : null);
if (!entry) {
return;
}
onChange(retainedDatasetSelection(entry));
};
const addSymbol = () => {
const id = symbol.trim().toUpperCase();
try {
parseInstrumentId(id);
} catch {
setSymbolError('Enter an exchange-qualified instrument, for example AAPL.US');
return;
}
setSymbolError(null);
if (!value.symbols.includes(id)) {
onChange({ ...value, symbols: [...value.symbols, id] });
}
setSymbol('');
};
const choices =
detail && !entries.some(entry => entry.hash === detail.hash) ? [detail, ...entries] : entries;
return (
<section aria-label="Historical data" className="space-y-4 border border-border rounded-lg p-4">
<label className="block text-sm text-text-secondary">
Historical data input
<select
aria-label="Historical data input"
className={inputClass}
disabled={disabled}
value={frozen ? 'frozen' : 'source'}
onChange={event =>
onChange({ ...value, datasetHash: event.target.value === 'frozen' ? '' : undefined })
}
>
<option value="source">Source request</option>
<option value="frozen">Frozen dataset</option>
</select>
</label>
{frozen ? (
<div className="space-y-2">
<label className="block text-sm text-text-secondary">
Frozen dataset
<select
aria-label="Frozen dataset"
className={inputClass}
disabled={disabled}
value={value.datasetHash ?? ''}
onChange={event => choose(event.target.value)}
>
<option value="">Choose a frozen dataset</option>
{value.datasetHash && !choices.some(entry => entry.hash === value.datasetHash) && (
<option value={value.datasetHash}>
{value.datasetHash} — metadata unavailable
</option>
)}
{choices.map(entry => (
<option key={entry.hash} value={entry.hash} disabled={entry.status !== 'available'}>
{entry.hash} —{' '}
{entry.manifest?.instruments.map(instrument => instrument.id).join(', ') ??
`Version ${entry.version ?? 'unknown'}`}{' '}
· {entry.manifest?.interval ?? entry.status}
{entry.status !== 'available' ? ` · ${entry.reason ?? entry.status}` : ''}
</option>
))}
</select>
</label>
{(loading || detailLoading) && (
<p role="status" className="text-sm text-text-secondary">
Loading frozen dataset metadata...
</p>
)}
{!loading && !entries.length && !catalogError && (
<p className="text-sm text-text-secondary">
No frozen datasets yet. Run a source request to prepare one.
</p>
)}
{(catalogError || detailError) && (
<p role="alert" className="text-sm text-error">
{detailError ?? catalogError}
</p>
)}
{(catalogError || detailError) && (
<button
type="button"
className={buttonClass}
disabled={disabled || loading || detailLoading}
onClick={() => setRetry(value => value + 1)}
>
Retry datasets
</button>
)}
{more && (
<button
type="button"
className={buttonClass}
disabled={disabled || loading}
onClick={() => setPage(value => value + 1)}
>
Load more datasets
</button>
)}
{selected && (
<div className="text-sm text-text-secondary space-y-1 break-words">
<p>Dataset hash: {selected.hash}</p>
{selected.reason && <p>{selected.reason}</p>}
{selected.manifest && (
<>
<p>
Requested range: {selected.manifest.startDate} to {selected.manifest.endDate}{' '}
(end exclusive).
</p>
<p>
Sources:{' '}
{selected.manifest.sources
.map(
source => `${source.instrumentId}: ${source.provider} (${source.revision})`
)
.join('; ')}
</p>
<p>
Bars: {selected.manifest.barCount}. Coverage: unknown. Content integrity: not
verified by this catalog; the runner validates retained content before
execution.
</p>
</>
)}
{selected.status === 'available' && validation && (
<button
type="button"
className={buttonClass}
disabled={disabled}
onClick={() => choose(selected.hash)}
>
Apply dataset settings
</button>
)}
</div>
)}
</div>
) : (
<>
<p className="text-sm text-text-secondary">
Source request — unpinned. Historical data will be prepared asynchronously and frozen
before execution; this request is not yet a reproducible dataset.
</p>
<label className="block text-sm text-text-secondary">
Historical source
<select
aria-label="Historical source"
className={inputClass}
disabled={disabled}
value={value.dataSource ?? 'auto'}
onChange={event =>
onChange({
...value,
dataSource: event.target.value as HistoricalSelection['dataSource'],
})
}
>
<option value="auto">Automatic configured source</option>
<option value="questdb">QuestDB</option>
<option value="eod">EOD historical storage</option>
</select>
</label>
</>
)}
<fieldset disabled={disabled || frozen} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<label className="block text-sm text-text-secondary">
Timeframe
<select
aria-label="Timeframe"
className={inputClass}
value={frequency}
onChange={event =>
onChange({
...value,
dataFrequency: event.target.value as HistoricalSelection['dataFrequency'],
})
}
>
{historicalIntervals.map(interval => (
<option key={interval}>{interval}</option>
))}
</select>
</label>
<label className="block text-sm text-text-secondary">
Historical prices
<select
aria-label="Historical prices"
className={inputClass}
value={value.priceAdjustment ?? 'raw'}
onChange={event =>
onChange({
...value,
priceAdjustment:
event.target.value === 'provider-adjusted' ? 'provider-adjusted' : 'raw',
})
}
>
<option value="raw">Raw prices (no corporate-action adjustment)</option>
<option value="provider-adjusted">Provider adjusted (reported volume)</option>
</select>
</label>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{(['startDate', 'endDate'] as const).map(key => {
const label = `${key === 'startDate' ? 'Start' : 'End'} ${frequency === '1d' ? 'date' : 'instant'} (UTC)`;
return (
<label key={key} className="block text-sm text-text-secondary">
{label}
<input
aria-label={label}
className={inputClass}
type={frequency === '1d' ? 'date' : 'text'}
value={historicalDateInput(value[key], frequency)}
placeholder="2024-01-01T09:30:00.000Z"
required
onChange={event => onChange({ ...value, [key]: event.target.value })}
/>
</label>
);
})}
</div>
<p className="text-xs text-text-secondary">
End is exclusive. Intraday instants require an explicit UTC offset; milliseconds are
preserved.
</p>
<div>
<label className="block text-sm text-text-secondary">
Instrument ID
<input
aria-label="Instrument ID"
className={inputClass}
value={symbol}
placeholder="AAPL.US"
onChange={event => setSymbol(event.target.value)}
onKeyDown={event => {
if (event.key === 'Enter') {
event.preventDefault();
addSymbol();
}
}}
/>
</label>
<button type="button" className={buttonClass} onClick={addSymbol}>
Add instrument
</button>
{symbolError && (
<p role="alert" className="text-sm text-error">
{symbolError}
</p>
)}
<div className="flex flex-wrap gap-2 mt-2">
{value.symbols.map(id => (
<span key={id} className="px-2 py-1 rounded bg-background text-sm text-text-primary">
{id}{' '}
<button
type="button"
aria-label={`Remove ${id}`}
onClick={() =>
onChange({ ...value, symbols: value.symbols.filter(item => item !== id) })
}
>
×
</button>
</span>
))}
</div>
</div>
</fieldset>
{validation && !(frozen && (loading || detailLoading || detailError)) && (
<p role="alert" className="text-sm text-error">
{validation}
</p>
)}
</section>
);
}

View file

@ -0,0 +1,39 @@
import type { BacktestRunDatasetSelection } from '@stock-bot/types';
/** This binding belongs to the accepted run, never the editable backtest form. */
export function RunDataset({ dataset }: { dataset?: BacktestRunDatasetSelection }) {
return (
<section
aria-label="Run dataset"
className="mb-4 rounded-lg border border-border p-3 text-sm text-text-secondary break-words"
>
{dataset?.pinnedHash ? (
<p>
Pinned dataset hash: <code>{dataset.pinnedHash}</code>
</p>
) : dataset?.requestedHash ? (
<>
<p>
Requested frozen dataset hash: <code>{dataset.requestedHash}</code>
</p>
<p>
{dataset.state === 'unavailable'
? 'Dataset preparation is unavailable for this run.'
: 'Waiting for dataset preparation and binding.'}
</p>
</>
) : dataset?.state === 'requested' ? (
<p>
Source request ({dataset.source ?? 'auto'}) — unpinned. Historical data will be prepared
asynchronously.
</p>
) : dataset?.state === 'preparing' ? (
<p>Source request ({dataset.source ?? 'auto'}) — unpinned. Historical data is preparing.</p>
) : dataset?.state === 'unavailable' ? (
<p>No dataset was pinned. Historical data preparation is unavailable for this run.</p>
) : (
<p>Dataset provenance is unavailable for this run.</p>
)}
</section>
);
}