feat(research): select and reuse frozen datasets in workbench
This commit is contained in:
parent
6a67ae8683
commit
b106c1ca85
29 changed files with 2295 additions and 426 deletions
|
|
@ -1,11 +1,12 @@
|
|||
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import { BacktestConfiguration } from './components/BacktestConfiguration';
|
||||
import { BacktestPlayback } from './components/BacktestPlayback';
|
||||
import { BacktestTrades } from './components/BacktestTrades';
|
||||
import { RunControlsCompact } from './components/RunControlsCompact';
|
||||
import { RunDataset } from './components/RunDataset';
|
||||
import { RunsListWithMetrics } from './components/RunsListWithMetrics';
|
||||
import { useBacktestV2 } from './hooks/useBacktestV2';
|
||||
import type { BacktestConfig } from './types/backtest.types';
|
||||
|
|
@ -90,18 +91,21 @@ export function BacktestDetailPageV2() {
|
|||
name: config.name,
|
||||
strategy: config.strategy,
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate.toISOString().split('T')[0],
|
||||
endDate: config.endDate.toISOString().split('T')[0],
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
config: {
|
||||
...backtest?.config,
|
||||
commission: config.commission,
|
||||
slippage: config.slippage,
|
||||
speedMultiplier: config.speedMultiplier,
|
||||
dataFrequency: config.dataFrequency,
|
||||
dataSource: config.dataSource,
|
||||
datasetHash: config.datasetHash,
|
||||
dataPolicy: {
|
||||
adjustment: config.priceAdjustment ?? 'raw',
|
||||
timestamp:
|
||||
!backtest?.config?.dataFrequency || backtest.config.dataFrequency === '1d'
|
||||
!config.dataFrequency || config.dataFrequency === '1d'
|
||||
? 'utc-session-date'
|
||||
: 'utc-instant',
|
||||
},
|
||||
|
|
@ -134,26 +138,37 @@ export function BacktestDetailPageV2() {
|
|||
);
|
||||
|
||||
// Convert backtest to config format for the form
|
||||
const backtestConfig: BacktestConfig | undefined = backtest
|
||||
? {
|
||||
name: backtest.name,
|
||||
startDate: new Date(backtest.startDate),
|
||||
endDate: new Date(backtest.endDate),
|
||||
initialCapital: backtest.initialCapital,
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
speedMultiplier: 1,
|
||||
commission: Number(backtest.config?.commission ?? 0.001),
|
||||
slippage: Number(backtest.config?.slippage ?? 0.0001),
|
||||
priceAdjustment:
|
||||
backtest.config?.dataPolicy &&
|
||||
typeof backtest.config.dataPolicy === 'object' &&
|
||||
'adjustment' in backtest.config.dataPolicy &&
|
||||
backtest.config.dataPolicy.adjustment === 'provider-adjusted'
|
||||
? 'provider-adjusted'
|
||||
: 'raw',
|
||||
}
|
||||
: undefined;
|
||||
const backtestConfig = useMemo<BacktestConfig | undefined>(
|
||||
() =>
|
||||
backtest
|
||||
? {
|
||||
name: backtest.name,
|
||||
startDate: backtest.startDate,
|
||||
endDate: backtest.endDate,
|
||||
initialCapital: backtest.initialCapital,
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
speedMultiplier: 1,
|
||||
dataFrequency: (backtest.config?.dataFrequency ??
|
||||
'1d') as BacktestConfig['dataFrequency'],
|
||||
dataSource: (backtest.config?.dataSource ?? 'auto') as BacktestConfig['dataSource'],
|
||||
datasetHash:
|
||||
typeof backtest.config?.datasetHash === 'string'
|
||||
? backtest.config.datasetHash
|
||||
: undefined,
|
||||
commission: Number(backtest.config?.commission ?? 0.001),
|
||||
slippage: Number(backtest.config?.slippage ?? 0.0001),
|
||||
priceAdjustment:
|
||||
backtest.config?.dataPolicy &&
|
||||
typeof backtest.config.dataPolicy === 'object' &&
|
||||
'adjustment' in backtest.config.dataPolicy &&
|
||||
backtest.config.dataPolicy.adjustment === 'provider-adjusted'
|
||||
? 'provider-adjusted'
|
||||
: 'raw',
|
||||
}
|
||||
: undefined,
|
||||
[backtest]
|
||||
);
|
||||
|
||||
const renderTabContent = () => {
|
||||
if (['details', 'trades'].includes(activeTab)) {
|
||||
|
|
@ -393,7 +408,7 @@ export function BacktestDetailPageV2() {
|
|||
</div>
|
||||
|
||||
{/* Tab Content */}
|
||||
<div className="flex-1 overflow-hidden py-4">
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden py-4">
|
||||
{submissionError && (
|
||||
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
|
||||
<p role="alert" className="text-sm text-error">
|
||||
|
|
@ -422,7 +437,8 @@ export function BacktestDetailPageV2() {
|
|||
)}
|
||||
</div>
|
||||
)}
|
||||
{renderTabContent()}
|
||||
{currentRun && <RunDataset dataset={currentRun.dataset} />}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{renderTabContent()}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
HistoricalDatasetCatalogEntry,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
|
||||
import { browserLog } from '@/utils/browserLog';
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
|
|
@ -31,6 +34,7 @@ export interface Run {
|
|||
currentSimulationDate?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
dataset?: BacktestRunDatasetSelection;
|
||||
}
|
||||
|
||||
export interface CreateBacktestRequest {
|
||||
|
|
@ -56,7 +60,43 @@ export class RunResultsUnavailableError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
async function requestError(response: Response, fallback: string): Promise<Error> {
|
||||
const payload: unknown = await response.json().catch(() => null);
|
||||
const message =
|
||||
payload &&
|
||||
typeof payload === 'object' &&
|
||||
'error' in payload &&
|
||||
typeof payload.error === 'string'
|
||||
? payload.error
|
||||
: `${fallback}: ${response.status} ${response.statusText}`;
|
||||
return new Error(message);
|
||||
}
|
||||
|
||||
export const backtestApiV2 = {
|
||||
async listDatasets(
|
||||
limit = 50,
|
||||
offset = 0,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDatasetCatalogEntry[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/datasets?limit=${limit}&offset=${offset}`,
|
||||
{ signal }
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to load frozen datasets');
|
||||
}
|
||||
return (await response.json()).datasets;
|
||||
},
|
||||
|
||||
async getDataset(hash: string, signal?: AbortSignal): Promise<HistoricalDatasetCatalogEntry> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/${encodeURIComponent(hash)}`, {
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to load frozen dataset');
|
||||
}
|
||||
return (await response.json()).dataset;
|
||||
},
|
||||
// Backtest operations
|
||||
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
|
||||
|
|
@ -69,7 +109,7 @@ export const backtestApiV2 = {
|
|||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to create backtest: ${response.statusText}`);
|
||||
throw await requestError(response, 'Failed to create backtest');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
|
|
@ -107,7 +147,7 @@ export const backtestApiV2 = {
|
|||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to update backtest: ${response.statusText}`);
|
||||
throw await requestError(response, 'Failed to update backtest');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
|
|
@ -139,9 +179,7 @@ export const backtestApiV2 = {
|
|||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
browserLog.error(`Failed to create run:`, response.status, errorText);
|
||||
throw new Error(`Failed to create run: ${response.statusText}`);
|
||||
throw await requestError(response, 'Failed to create run');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,86 @@
|
|||
import {
|
||||
validateHistoricalDataRequest,
|
||||
type HistoricalDatasetCatalogEntry,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
export const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const;
|
||||
export interface HistoricalSelection {
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
dataFrequency?: (typeof historicalIntervals)[number];
|
||||
dataSource?: 'auto' | 'questdb' | 'eod';
|
||||
priceAdjustment?: 'raw' | 'provider-adjusted';
|
||||
datasetHash?: string;
|
||||
}
|
||||
|
||||
/** Selecting a retained snapshot adopts its exact request, never a cropped range. */
|
||||
export function retainedDatasetSelection(
|
||||
entry: HistoricalDatasetCatalogEntry
|
||||
): HistoricalSelection {
|
||||
const manifest = entry.manifest;
|
||||
if (entry.status !== 'available' || manifest?.version !== 1 || manifest.hash !== entry.hash) {
|
||||
throw new Error(entry.reason ?? 'This dataset is unavailable in the current workbench');
|
||||
}
|
||||
const interval = historicalIntervals.find(value => value === manifest.interval);
|
||||
if (!interval) {
|
||||
throw new Error('This dataset timeframe is unsupported');
|
||||
}
|
||||
return {
|
||||
symbols: manifest.instruments.map(instrument => instrument.id),
|
||||
startDate: manifest.startDate,
|
||||
endDate: manifest.endDate,
|
||||
dataFrequency: interval,
|
||||
dataSource: 'auto',
|
||||
priceAdjustment: manifest.policy.adjustment,
|
||||
datasetHash: entry.hash,
|
||||
};
|
||||
}
|
||||
|
||||
export function historicalSelectionError(
|
||||
value: HistoricalSelection,
|
||||
retained?: HistoricalDatasetCatalogEntry | null
|
||||
): string | null {
|
||||
try {
|
||||
const frequency = value.dataFrequency ?? '1d';
|
||||
if (!['auto', 'questdb', 'eod'].includes(value.dataSource ?? 'auto')) {
|
||||
return 'Choose a supported historical source';
|
||||
}
|
||||
validateHistoricalDataRequest({
|
||||
symbols: value.symbols,
|
||||
startDate: value.startDate,
|
||||
endDate: value.endDate,
|
||||
dataFrequency: frequency,
|
||||
dataPolicy: {
|
||||
adjustment: value.priceAdjustment ?? 'raw',
|
||||
timestamp: frequency === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||
},
|
||||
datasetHash: value.datasetHash,
|
||||
});
|
||||
if (value.datasetHash !== undefined) {
|
||||
if (!retained || retained.hash !== value.datasetHash) {
|
||||
return 'Select an available frozen dataset and wait for its metadata';
|
||||
}
|
||||
const exact = retainedDatasetSelection(retained);
|
||||
if (
|
||||
JSON.stringify([...value.symbols].sort()) !== JSON.stringify([...exact.symbols].sort()) ||
|
||||
new Date(value.startDate).toISOString() !== exact.startDate ||
|
||||
new Date(value.endDate).toISOString() !== exact.endDate ||
|
||||
frequency !== exact.dataFrequency ||
|
||||
(value.priceAdjustment ?? 'raw') !== exact.priceAdjustment ||
|
||||
(value.dataSource ?? 'auto') !== 'auto'
|
||||
) {
|
||||
return 'These settings do not match the frozen dataset. Apply its exact settings or switch to a source request.';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
return error instanceof Error ? error.message : 'Invalid historical data settings';
|
||||
}
|
||||
}
|
||||
|
||||
/** A daily control displays the UTC session date; intraday controls retain the
|
||||
* complete explicit-offset string, including milliseconds. */
|
||||
export function historicalDateInput(value: string, frequency: string): string {
|
||||
return frequency === '1d' ? value.slice(0, 10) : value;
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import type { HistoricalSelection } from '../services/historical-selection';
|
||||
|
||||
export type BacktestStatus =
|
||||
| 'idle'
|
||||
| 'configured'
|
||||
|
|
@ -7,17 +9,13 @@ export type BacktestStatus =
|
|||
| 'completed'
|
||||
| 'error';
|
||||
|
||||
export interface BacktestConfig {
|
||||
export interface BacktestConfig extends HistoricalSelection {
|
||||
name: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
symbols: string[];
|
||||
strategy: string;
|
||||
speedMultiplier: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
priceAdjustment?: 'raw' | 'provider-adjusted';
|
||||
}
|
||||
|
||||
export interface BacktestMetrics {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue