Freeze historical datasets and qualify backtest instrument identities
This commit is contained in:
parent
63c3856797
commit
d6b09eb635
43 changed files with 2249 additions and 1230 deletions
47
README.md
47
README.md
|
|
@ -81,6 +81,53 @@ is contacted. Native SMA and MACD regressions are covered by the repository chec
|
|||
Coverage reports contain measured LCOV data only. Missing coverage or an empty package
|
||||
selection fails the coverage command instead of producing an estimated score.
|
||||
|
||||
## Historical input identity and reproducibility
|
||||
|
||||
Backtest `symbols` are exchange-qualified IDs such as `AAPL.US` or `BRK.B.US`, using
|
||||
the existing EOD provider exchange namespace (not a guessed venue MIC). Ticker-only
|
||||
definitions remain readable but must be explicitly updated before a new run. MongoDB
|
||||
history reads match the qualified `eodSearchCode` and verify each returned identity;
|
||||
QuestDB `bars_<interval>.symbol` must contain the same qualified ID. No ticker fallback,
|
||||
automatic legacy-history rewrite, or cross-provider fallback is performed.
|
||||
Provider namespace (`providerExchange`, also encoded in the ID) is distinct from the
|
||||
source's `exchange` venue metadata. Older rows with a valid qualified key remain readable
|
||||
without rewriting that metadata.
|
||||
|
||||
`dataPolicy` explicitly describes prices and timestamps:
|
||||
|
||||
- `adjustment: 'raw'` is the default; no corporate-action accounting is implied.
|
||||
- `adjustment: 'provider-adjusted'` scales **all OHLC/VWAP prices** by
|
||||
`adjustedClose / close`. Missing/nonpositive provider factors fail the run. This is
|
||||
the provider's combined split/dividend adjustment, not a split-only or point-in-time
|
||||
total-return model. Reported volume is unchanged; no extra dividend cash is credited.
|
||||
- Daily bars use `timestamp: 'utc-session-date'`: UTC-midnight session labels, not
|
||||
exchange close instants. Daily range boundaries must be UTC midnight. Intraday bars
|
||||
use `timestamp: 'utc-instant'` with an explicit timezone. Ranges are `[start, end)`.
|
||||
- Invalid prices, duplicate timestamps, mixed identities, or missing requested listings
|
||||
fail; prices are never interpolated or silently repaired. Market holidays are not
|
||||
synthesized, and exchange-calendar/session completeness is not yet verified.
|
||||
|
||||
Apply additive migration `database/postgres/init/12-historical-datasets.sql` via the
|
||||
web API migration runner before starting a new backtest. The first execution attempt
|
||||
validates and content-hashes the actual input bars and provenance, then atomically stores
|
||||
them in `backtest_datasets` and pins `runs.dataset_hash` **before executing any bar**.
|
||||
Recovered attempts reuse that snapshot, never revised provider data. Both execution
|
||||
backends consume the same normalized, deterministically ordered bars with no second
|
||||
corporate-action transformation. The TypeScript simulator's pseudo-random sequence is
|
||||
seeded from the dataset hash; native same-timestamp seeks retain every listing.
|
||||
|
||||
The canonical result records the manifest in `config.dataset`: SHA-256 hash, listing
|
||||
identities, range, interval, adjustment/timestamp/volume policies, source normalization
|
||||
revision, and bar count. Replay through the runner by supplying `datasetHash` (or put it
|
||||
in a V2 definition's `config`); the range, listings, interval and policy must match.
|
||||
Missing, corrupted or incompatible snapshots fail instead of falling back to provider
|
||||
history. Runs capture data at execution preparation, **not HTTP acceptance time**.
|
||||
Reproducibility assumes the same engine/strategy code and configuration; the snapshot
|
||||
is not an engine binary archive or a point-in-time constituent universe. Direct backend
|
||||
calls can load data for diagnostics, but durable replay/persistence requires the runner.
|
||||
Snapshots are currently JSONB and load in memory; large tick datasets need chunked storage
|
||||
and an explicit retention policy before scaling.
|
||||
|
||||
## Simulation order execution
|
||||
|
||||
`ExecutionService` is the runtime order gateway for REST, Socket.IO (when enabled), and
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { MongoDBClient } from '@stock-bot/services';
|
||||
import { parseInstrumentId } from '@stock-bot/types';
|
||||
|
||||
export interface EodPrice {
|
||||
date: string;
|
||||
|
|
@ -16,6 +17,10 @@ export async function persistEodPrices(
|
|||
identity: { symbol: string; exchange: string; eodSearchCode: string },
|
||||
prices: readonly EodPrice[]
|
||||
) {
|
||||
const parsed = parseInstrumentId(identity.eodSearchCode);
|
||||
if (parsed.symbol !== identity.symbol) {
|
||||
throw new Error('EOD instrument identity mismatch');
|
||||
}
|
||||
const documents = prices.map(price => {
|
||||
if (
|
||||
typeof price.date !== 'string' ||
|
||||
|
|
@ -23,7 +28,8 @@ export async function persistEodPrices(
|
|||
!Number.isFinite(Date.parse(price.date)) ||
|
||||
new Date(price.date).toISOString().slice(0, 10) !== price.date ||
|
||||
![price.open, price.high, price.low, price.close, price.volume].every(Number.isFinite) ||
|
||||
(price.adjusted_close !== undefined && !Number.isFinite(price.adjusted_close)) ||
|
||||
(price.adjusted_close !== undefined &&
|
||||
(!Number.isFinite(price.adjusted_close) || price.adjusted_close <= 0)) ||
|
||||
price.low <= 0 ||
|
||||
price.high < Math.max(price.open, price.close) ||
|
||||
price.low > Math.min(price.open, price.close) ||
|
||||
|
|
@ -33,13 +39,16 @@ export async function persistEodPrices(
|
|||
}
|
||||
return {
|
||||
...identity,
|
||||
// Exchange can name the venue; the provider routing namespace is distinct.
|
||||
providerExchange: parsed.exchange,
|
||||
source: 'eod',
|
||||
date: price.date,
|
||||
open: price.open,
|
||||
high: price.high,
|
||||
low: price.low,
|
||||
close: price.close,
|
||||
adjustedClose: price.adjusted_close ?? price.close,
|
||||
// Missing adjustment data must not masquerade as an unadjusted factor of one.
|
||||
...(price.adjusted_close === undefined ? {} : { adjustedClose: price.adjusted_close }),
|
||||
volume: price.volume,
|
||||
};
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,370 +1,400 @@
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::*;
|
||||
use crate::{
|
||||
Bar, MarketDataType, MarketUpdate, TradingMode,
|
||||
core::{
|
||||
time_providers::SimulatedTime,
|
||||
market_data_sources::HistoricalDataSource,
|
||||
execution_handlers::{SimulatedExecution, BacktestFillSimulator},
|
||||
},
|
||||
};
|
||||
use chrono::{DateTime, Utc, TimeZone};
|
||||
use std::collections::HashMap;
|
||||
|
||||
// Test strategy that tracks prices and places orders
|
||||
struct PriceTrackingStrategy {
|
||||
name: String,
|
||||
price_history: Vec<(DateTime<Utc>, String, f64)>,
|
||||
should_buy_at: Vec<(String, usize)>, // (symbol, bar_index)
|
||||
should_sell_at: Vec<(String, usize)>,
|
||||
bar_count: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl PriceTrackingStrategy {
|
||||
fn new(name: &str) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
price_history: Vec::new(),
|
||||
should_buy_at: Vec::new(),
|
||||
should_sell_at: Vec::new(),
|
||||
bar_count: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_trades(mut self, buys: Vec<(String, usize)>, sells: Vec<(String, usize)>) -> Self {
|
||||
self.should_buy_at = buys;
|
||||
self.should_sell_at = sells;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Strategy for PriceTrackingStrategy {
|
||||
fn get_name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn get_parameters(&self) -> serde_json::Value {
|
||||
serde_json::json!({})
|
||||
}
|
||||
|
||||
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
|
||||
let mut signals = Vec::new();
|
||||
|
||||
// Track the price
|
||||
if let MarketDataType::Bar(bar) = &data.data {
|
||||
self.price_history.push((data.timestamp, data.symbol.clone(), bar.close));
|
||||
|
||||
let count = self.bar_count.entry(data.symbol.clone()).or_insert(0);
|
||||
*count += 1;
|
||||
|
||||
// Check if we should trade at this bar
|
||||
for (symbol, bar_index) in &self.should_buy_at {
|
||||
if &data.symbol == symbol && *count == *bar_index {
|
||||
signals.push(Signal {
|
||||
symbol: symbol.clone(),
|
||||
signal_type: SignalType::Buy,
|
||||
strength: 1.0,
|
||||
quantity: Some(100.0),
|
||||
reason: Some("Test buy signal".to_string()),
|
||||
metadata: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (symbol, bar_index) in &self.should_sell_at {
|
||||
if &data.symbol == symbol && *count == *bar_index {
|
||||
signals.push(Signal {
|
||||
symbol: symbol.clone(),
|
||||
signal_type: SignalType::Sell,
|
||||
strength: 1.0,
|
||||
quantity: Some(100.0),
|
||||
reason: Some("Test sell signal".to_string()),
|
||||
metadata: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
signals
|
||||
}
|
||||
|
||||
fn on_fill(&mut self, _symbol: &str, _quantity: f64, _price: f64, _side: &str) {
|
||||
// Track fills if needed
|
||||
}
|
||||
}
|
||||
|
||||
fn create_test_bars(symbol: &str, start_time: DateTime<Utc>, prices: Vec<f64>) -> Vec<MarketUpdate> {
|
||||
prices.into_iter().enumerate().map(|(i, close)| {
|
||||
let timestamp = start_time + chrono::Duration::days(i as i64);
|
||||
let high = close * 1.01;
|
||||
let low = close * 0.99;
|
||||
let open = if i == 0 { close } else { close * 0.995 };
|
||||
|
||||
MarketUpdate {
|
||||
symbol: symbol.to_string(),
|
||||
timestamp,
|
||||
data: MarketDataType::Bar(Bar {
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume: 1000000.0,
|
||||
vwap: Some(close),
|
||||
}),
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_price_tracking_single_symbol() {
|
||||
// Create test data with known prices
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = Utc.with_ymd_and_hms(2024, 1, 10, 0, 0, 0).unwrap();
|
||||
|
||||
// Prices: index 0=100, 1=101, 2=102, 3=103, 4=104, 5=105, 6=104, 7=103, 8=102, 9=101
|
||||
let prices = vec![100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 104.0, 103.0, 102.0, 101.0];
|
||||
let bars = create_test_bars("AAPL", start_time, prices.clone());
|
||||
|
||||
// Setup backtest engine
|
||||
let config = BacktestConfig {
|
||||
name: "PriceTrackingTest".to_string(),
|
||||
strategy: None,
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 100000.0,
|
||||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
symbols: vec!["AAPL".to_string()],
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
|
||||
let time_provider = Box::new(SimulatedTime::new(start_time));
|
||||
let mut data_source = Box::new(HistoricalDataSource::new());
|
||||
data_source.load_data(bars.clone());
|
||||
|
||||
let fill_simulator = Box::new(BacktestFillSimulator::new());
|
||||
let execution_handler = Box::new(SimulatedExecution::new(fill_simulator));
|
||||
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
};
|
||||
|
||||
let mut engine = BacktestEngine::new(
|
||||
config,
|
||||
mode,
|
||||
time_provider,
|
||||
data_source,
|
||||
execution_handler,
|
||||
);
|
||||
|
||||
// Add strategy that tracks prices and trades at specific bars
|
||||
// Note: bar_count starts at 1, so bar 3 is the 3rd bar (index 2, price 102.0)
|
||||
let strategy = PriceTrackingStrategy::new("PriceTracker")
|
||||
.with_trades(
|
||||
vec![("AAPL".to_string(), 3)], // Buy at bar 3 (3rd bar, price 102)
|
||||
vec![("AAPL".to_string(), 7)], // Sell at bar 7 (7th bar, price 103)
|
||||
);
|
||||
|
||||
let strategy_ref = Box::new(strategy);
|
||||
engine.add_strategy(strategy_ref);
|
||||
|
||||
// Run backtest
|
||||
let result = engine.run().await.unwrap();
|
||||
|
||||
// Verify trades executed at correct prices
|
||||
assert_eq!(result.trades.len(), 2, "Should have exactly 2 trades");
|
||||
|
||||
let buy_trade = &result.trades[0];
|
||||
assert_eq!(buy_trade.side, "buy");
|
||||
assert_eq!(buy_trade.symbol, "AAPL");
|
||||
// Buy signal at bar 3 (index 2, price 102) executes at that bar's close price
|
||||
// In backtesting, we execute at the close price of the bar that generated the signal
|
||||
let expected_buy_price = 102.0 * (1.0 + 0.0001);
|
||||
assert!(
|
||||
(buy_trade.price - expected_buy_price).abs() < 0.01,
|
||||
"Buy price {} should be close to {}", buy_trade.price, expected_buy_price
|
||||
);
|
||||
|
||||
let sell_trade = &result.trades[1];
|
||||
assert_eq!(sell_trade.side, "sell");
|
||||
assert_eq!(sell_trade.symbol, "AAPL");
|
||||
// Sell signal at bar 7 (7th bar, index 6, price 104) executes at that bar's close price
|
||||
let expected_sell_price = 104.0 * (1.0 - 0.0001);
|
||||
assert!(
|
||||
(sell_trade.price - expected_sell_price).abs() < 0.01,
|
||||
"Sell price {} should be close to {}", sell_trade.price, expected_sell_price
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_price_tracking_multiple_symbols() {
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap();
|
||||
|
||||
// Create different price series for each symbol
|
||||
// AAPL: index 0=100, 1=101, 2=102, 3=103, 4=104
|
||||
let aapl_prices = vec![100.0, 101.0, 102.0, 103.0, 104.0];
|
||||
// GOOGL: index 0=150, 1=149, 2=148, 3=147, 4=146
|
||||
let googl_prices = vec![150.0, 149.0, 148.0, 147.0, 146.0];
|
||||
// MSFT: index 0=200, 1=202, 2=204, 3=206, 4=208
|
||||
let msft_prices = vec![200.0, 202.0, 204.0, 206.0, 208.0];
|
||||
|
||||
let mut all_bars = Vec::new();
|
||||
all_bars.extend(create_test_bars("AAPL", start_time, aapl_prices));
|
||||
all_bars.extend(create_test_bars("GOOGL", start_time, googl_prices));
|
||||
all_bars.extend(create_test_bars("MSFT", start_time, msft_prices));
|
||||
|
||||
// Sort by timestamp to simulate realistic data flow
|
||||
all_bars.sort_by_key(|bar| bar.timestamp);
|
||||
|
||||
// Setup backtest
|
||||
let config = BacktestConfig {
|
||||
name: "MultiSymbolTest".to_string(),
|
||||
strategy: None,
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 100000.0,
|
||||
commission: 0.001,
|
||||
slippage: 0.0,
|
||||
symbols: vec!["AAPL".to_string(), "GOOGL".to_string(), "MSFT".to_string()],
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
|
||||
let time_provider = Box::new(SimulatedTime::new(start_time));
|
||||
let mut data_source = Box::new(HistoricalDataSource::new());
|
||||
data_source.load_data(all_bars);
|
||||
|
||||
let fill_simulator = Box::new(BacktestFillSimulator::new());
|
||||
let execution_handler = Box::new(SimulatedExecution::new(fill_simulator));
|
||||
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
};
|
||||
|
||||
let mut engine = BacktestEngine::new(
|
||||
config,
|
||||
mode,
|
||||
time_provider,
|
||||
data_source,
|
||||
execution_handler,
|
||||
);
|
||||
|
||||
// Strategy that trades each symbol at different times
|
||||
let strategy = PriceTrackingStrategy::new("MultiSymbolTracker")
|
||||
.with_trades(
|
||||
vec![
|
||||
("AAPL".to_string(), 2), // Buy AAPL at bar 2 (price 102)
|
||||
("GOOGL".to_string(), 3), // Buy GOOGL at bar 3 (price 147)
|
||||
("MSFT".to_string(), 4), // Buy MSFT at bar 4 (price 208)
|
||||
],
|
||||
vec![
|
||||
("AAPL".to_string(), 4), // Sell AAPL at bar 4 (price 104)
|
||||
("GOOGL".to_string(), 5), // Sell GOOGL at bar 5 (price 146)
|
||||
("MSFT".to_string(), 5), // Sell MSFT at bar 5 (price 208)
|
||||
],
|
||||
);
|
||||
|
||||
engine.add_strategy(Box::new(strategy));
|
||||
|
||||
// Run backtest
|
||||
let result = engine.run().await.unwrap();
|
||||
|
||||
// Verify each symbol traded at its own correct price
|
||||
// Note: Trades execute at the close price of the bar when the signal is generated
|
||||
let aapl_trades: Vec<_> = result.trades.iter().filter(|t| t.symbol == "AAPL").collect();
|
||||
assert_eq!(aapl_trades.len(), 2);
|
||||
// Buy at bar 2 (when bar_count=2) = Jan 3 = index 2 = price 102
|
||||
assert!((aapl_trades[0].price - 102.0).abs() < 0.1, "AAPL buy price should be ~102 (bar 2)");
|
||||
// Sell at bar 4 (when bar_count=4) = Jan 5 = index 4 = price 104
|
||||
assert!((aapl_trades[1].price - 104.0).abs() < 0.1, "AAPL sell price should be ~104 (bar 4)");
|
||||
|
||||
let googl_trades: Vec<_> = result.trades.iter().filter(|t| t.symbol == "GOOGL").collect();
|
||||
assert_eq!(googl_trades.len(), 2);
|
||||
// Buy at bar 3 = Jan 4 = index 3 = price 147
|
||||
assert!((googl_trades[0].price - 147.0).abs() < 0.1, "GOOGL buy price should be ~147 (bar 3)");
|
||||
// Sell at bar 5 or closing = price 146
|
||||
assert!((googl_trades[1].price - 146.0).abs() < 0.1, "GOOGL sell price should be ~146 (closing)");
|
||||
|
||||
let msft_trades: Vec<_> = result.trades.iter().filter(|t| t.symbol == "MSFT").collect();
|
||||
assert_eq!(msft_trades.len(), 2);
|
||||
// Buy at bar 4 = Jan 5 = index 4 = price 208 (but on Jan 4 it's 206)
|
||||
assert!((msft_trades[0].price - 206.0).abs() < 0.1, "MSFT buy price should be ~206 (bar 4)");
|
||||
// Sell at bar 5 = end of data = price 208
|
||||
assert!((msft_trades[1].price - 208.0).abs() < 0.1, "MSFT sell price should be ~208 (bar 5)");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_closing_position_prices() {
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap();
|
||||
|
||||
// Prices that change significantly
|
||||
let prices = vec![100.0, 110.0, 120.0, 130.0, 140.0];
|
||||
let bars = create_test_bars("TEST", start_time, prices);
|
||||
|
||||
let config = BacktestConfig {
|
||||
name: "ClosePositionTest".to_string(),
|
||||
strategy: None,
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 100000.0,
|
||||
commission: 0.0,
|
||||
slippage: 0.0,
|
||||
symbols: vec!["TEST".to_string()],
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
|
||||
let time_provider = Box::new(SimulatedTime::new(start_time));
|
||||
let mut data_source = Box::new(HistoricalDataSource::new());
|
||||
data_source.load_data(bars);
|
||||
|
||||
let fill_simulator = Box::new(BacktestFillSimulator::new());
|
||||
let execution_handler = Box::new(SimulatedExecution::new(fill_simulator));
|
||||
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
};
|
||||
|
||||
let mut engine = BacktestEngine::new(
|
||||
config,
|
||||
mode,
|
||||
time_provider,
|
||||
data_source,
|
||||
execution_handler,
|
||||
);
|
||||
|
||||
// Buy early, never sell (position will be closed at end)
|
||||
let strategy = PriceTrackingStrategy::new("ClosePositionTest")
|
||||
.with_trades(
|
||||
vec![("TEST".to_string(), 1)], // Buy at bar 1 (price 110)
|
||||
vec![], // Never sell
|
||||
);
|
||||
|
||||
engine.add_strategy(Box::new(strategy));
|
||||
|
||||
let result = engine.run().await.unwrap();
|
||||
|
||||
// Should have 2 trades: the buy and the closing trade
|
||||
assert_eq!(result.trades.len(), 2, "Should have buy and closing trade");
|
||||
|
||||
let buy_trade = &result.trades[0];
|
||||
assert_eq!(buy_trade.side, "buy");
|
||||
// Buy at bar 1 executes at the first bar's price (100.0)
|
||||
assert!((buy_trade.price - 100.0).abs() < 0.1, "Buy price should be ~100 (bar 1)");
|
||||
|
||||
let close_trade = &result.trades[1];
|
||||
assert_eq!(close_trade.side, "sell");
|
||||
// Position should be closed at the last available price (140)
|
||||
assert!(
|
||||
(close_trade.price - 140.0).abs() < 0.1,
|
||||
"Close price {} should be ~140 (last bar price)", close_trade.price
|
||||
);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::*;
|
||||
use crate::{
|
||||
core::{
|
||||
execution_handlers::{BacktestFillSimulator, SimulatedExecution},
|
||||
market_data_sources::HistoricalDataSource,
|
||||
time_providers::SimulatedTime,
|
||||
},
|
||||
Bar, MarketDataType, MarketUpdate, TradingMode,
|
||||
};
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use std::collections::HashMap;
|
||||
|
||||
// Test strategy that tracks prices and places orders
|
||||
struct PriceTrackingStrategy {
|
||||
name: String,
|
||||
price_history: Vec<(DateTime<Utc>, String, f64)>,
|
||||
should_buy_at: Vec<(String, usize)>, // (symbol, bar_index)
|
||||
should_sell_at: Vec<(String, usize)>,
|
||||
bar_count: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl PriceTrackingStrategy {
|
||||
fn new(name: &str) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
price_history: Vec::new(),
|
||||
should_buy_at: Vec::new(),
|
||||
should_sell_at: Vec::new(),
|
||||
bar_count: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_trades(mut self, buys: Vec<(String, usize)>, sells: Vec<(String, usize)>) -> Self {
|
||||
self.should_buy_at = buys;
|
||||
self.should_sell_at = sells;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Strategy for PriceTrackingStrategy {
|
||||
fn get_name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn get_parameters(&self) -> serde_json::Value {
|
||||
serde_json::json!({})
|
||||
}
|
||||
|
||||
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
|
||||
let mut signals = Vec::new();
|
||||
|
||||
// Track the price
|
||||
if let MarketDataType::Bar(bar) = &data.data {
|
||||
self.price_history
|
||||
.push((data.timestamp, data.symbol.clone(), bar.close));
|
||||
|
||||
let count = self.bar_count.entry(data.symbol.clone()).or_insert(0);
|
||||
*count += 1;
|
||||
|
||||
// Check if we should trade at this bar
|
||||
for (symbol, bar_index) in &self.should_buy_at {
|
||||
if &data.symbol == symbol && *count == *bar_index {
|
||||
signals.push(Signal {
|
||||
symbol: symbol.clone(),
|
||||
signal_type: SignalType::Buy,
|
||||
strength: 1.0,
|
||||
quantity: Some(100.0),
|
||||
reason: Some("Test buy signal".to_string()),
|
||||
metadata: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (symbol, bar_index) in &self.should_sell_at {
|
||||
if &data.symbol == symbol && *count == *bar_index {
|
||||
signals.push(Signal {
|
||||
symbol: symbol.clone(),
|
||||
signal_type: SignalType::Sell,
|
||||
strength: 1.0,
|
||||
quantity: Some(100.0),
|
||||
reason: Some("Test sell signal".to_string()),
|
||||
metadata: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
signals
|
||||
}
|
||||
|
||||
fn on_fill(&mut self, _symbol: &str, _quantity: f64, _price: f64, _side: &str) {
|
||||
// Track fills if needed
|
||||
}
|
||||
}
|
||||
|
||||
fn create_test_bars(
|
||||
symbol: &str,
|
||||
start_time: DateTime<Utc>,
|
||||
prices: Vec<f64>,
|
||||
) -> Vec<MarketUpdate> {
|
||||
prices
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, close)| {
|
||||
let timestamp = start_time + chrono::Duration::days(i as i64);
|
||||
let high = close * 1.01;
|
||||
let low = close * 0.99;
|
||||
let open = if i == 0 { close } else { close * 0.995 };
|
||||
|
||||
MarketUpdate {
|
||||
symbol: symbol.to_string(),
|
||||
timestamp,
|
||||
data: MarketDataType::Bar(Bar {
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume: 1000000.0,
|
||||
vwap: Some(close),
|
||||
}),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_price_tracking_single_symbol() {
|
||||
// Create test data with known prices
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = Utc.with_ymd_and_hms(2024, 1, 10, 0, 0, 0).unwrap();
|
||||
|
||||
// Prices: index 0=100, 1=101, 2=102, 3=103, 4=104, 5=105, 6=104, 7=103, 8=102, 9=101
|
||||
let prices = vec![
|
||||
100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 104.0, 103.0, 102.0, 101.0,
|
||||
];
|
||||
let bars = create_test_bars("AAPL", start_time, prices.clone());
|
||||
|
||||
// Setup backtest engine
|
||||
let config = BacktestConfig {
|
||||
name: "PriceTrackingTest".to_string(),
|
||||
strategy: None,
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 100000.0,
|
||||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
symbols: vec!["AAPL".to_string()],
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
|
||||
let time_provider = Box::new(SimulatedTime::new(start_time));
|
||||
let mut data_source = Box::new(HistoricalDataSource::new());
|
||||
data_source.load_data(bars.clone());
|
||||
|
||||
let fill_simulator = Box::new(BacktestFillSimulator::new());
|
||||
let execution_handler = Box::new(SimulatedExecution::new(fill_simulator));
|
||||
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
};
|
||||
|
||||
let mut engine =
|
||||
BacktestEngine::new(config, mode, time_provider, data_source, execution_handler);
|
||||
|
||||
// Add strategy that tracks prices and trades at specific bars
|
||||
// Note: bar_count starts at 1, so bar 3 is the 3rd bar (index 2, price 102.0)
|
||||
let strategy = PriceTrackingStrategy::new("PriceTracker").with_trades(
|
||||
vec![("AAPL".to_string(), 3)], // Buy at bar 3 (3rd bar, price 102)
|
||||
vec![("AAPL".to_string(), 7)], // Sell at bar 7 (7th bar, price 103)
|
||||
);
|
||||
|
||||
let strategy_ref = Box::new(strategy);
|
||||
engine.add_strategy(strategy_ref);
|
||||
|
||||
// Run backtest
|
||||
let result = engine.run().await.unwrap();
|
||||
|
||||
// Verify trades executed at correct prices
|
||||
assert_eq!(result.trades.len(), 2, "Should have exactly 2 trades");
|
||||
|
||||
let buy_trade = &result.trades[0];
|
||||
assert_eq!(buy_trade.side, "buy");
|
||||
assert_eq!(buy_trade.symbol, "AAPL");
|
||||
// Buy signal at bar 3 (index 2, price 102) executes at that bar's close price
|
||||
// In backtesting, we execute at the close price of the bar that generated the signal
|
||||
let expected_buy_price = 102.0 * (1.0 + 0.0001);
|
||||
assert!(
|
||||
(buy_trade.price - expected_buy_price).abs() < 0.01,
|
||||
"Buy price {} should be close to {}",
|
||||
buy_trade.price,
|
||||
expected_buy_price
|
||||
);
|
||||
|
||||
let sell_trade = &result.trades[1];
|
||||
assert_eq!(sell_trade.side, "sell");
|
||||
assert_eq!(sell_trade.symbol, "AAPL");
|
||||
// Sell signal at bar 7 (7th bar, index 6, price 104) executes at that bar's close price
|
||||
let expected_sell_price = 104.0 * (1.0 - 0.0001);
|
||||
assert!(
|
||||
(sell_trade.price - expected_sell_price).abs() < 0.01,
|
||||
"Sell price {} should be close to {}",
|
||||
sell_trade.price,
|
||||
expected_sell_price
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_price_tracking_multiple_symbols() {
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap();
|
||||
|
||||
// Create different price series for each symbol
|
||||
// AAPL: index 0=100, 1=101, 2=102, 3=103, 4=104
|
||||
let aapl_prices = vec![100.0, 101.0, 102.0, 103.0, 104.0];
|
||||
// GOOGL: index 0=150, 1=149, 2=148, 3=147, 4=146
|
||||
let googl_prices = vec![150.0, 149.0, 148.0, 147.0, 146.0];
|
||||
// MSFT: index 0=200, 1=202, 2=204, 3=206, 4=208
|
||||
let msft_prices = vec![200.0, 202.0, 204.0, 206.0, 208.0];
|
||||
|
||||
let mut all_bars = Vec::new();
|
||||
all_bars.extend(create_test_bars("AAPL", start_time, aapl_prices));
|
||||
all_bars.extend(create_test_bars("GOOGL", start_time, googl_prices));
|
||||
all_bars.extend(create_test_bars("MSFT", start_time, msft_prices));
|
||||
|
||||
// Sort by timestamp to simulate realistic data flow
|
||||
all_bars.sort_by_key(|bar| bar.timestamp);
|
||||
|
||||
// Setup backtest
|
||||
let config = BacktestConfig {
|
||||
name: "MultiSymbolTest".to_string(),
|
||||
strategy: None,
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 100000.0,
|
||||
commission: 0.001,
|
||||
slippage: 0.0,
|
||||
symbols: vec!["AAPL".to_string(), "GOOGL".to_string(), "MSFT".to_string()],
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
|
||||
let time_provider = Box::new(SimulatedTime::new(start_time));
|
||||
let mut data_source = Box::new(HistoricalDataSource::new());
|
||||
data_source.load_data(all_bars);
|
||||
|
||||
let fill_simulator = Box::new(BacktestFillSimulator::new());
|
||||
let execution_handler = Box::new(SimulatedExecution::new(fill_simulator));
|
||||
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
};
|
||||
|
||||
let mut engine =
|
||||
BacktestEngine::new(config, mode, time_provider, data_source, execution_handler);
|
||||
|
||||
// Strategy that trades each symbol at different times
|
||||
let strategy = PriceTrackingStrategy::new("MultiSymbolTracker").with_trades(
|
||||
vec![
|
||||
("AAPL".to_string(), 2), // Second bar: Jan 2, price 101
|
||||
("GOOGL".to_string(), 3), // Third bar: Jan 3, price 148
|
||||
("MSFT".to_string(), 4), // Fourth bar: Jan 4, price 206
|
||||
],
|
||||
vec![
|
||||
("AAPL".to_string(), 4), // Fourth bar: Jan 4, price 103
|
||||
("GOOGL".to_string(), 5), // Sell GOOGL at bar 5 (price 146)
|
||||
("MSFT".to_string(), 5), // Sell MSFT at bar 5 (price 208)
|
||||
],
|
||||
);
|
||||
|
||||
engine.add_strategy(Box::new(strategy));
|
||||
|
||||
// Run backtest
|
||||
let result = engine.run().await.unwrap();
|
||||
|
||||
// Verify each symbol traded at its own correct price
|
||||
// Note: Trades execute at the close price of the bar when the signal is generated
|
||||
let aapl_trades: Vec<_> = result
|
||||
.trades
|
||||
.iter()
|
||||
.filter(|t| t.symbol == "AAPL")
|
||||
.collect();
|
||||
assert_eq!(aapl_trades.len(), 2);
|
||||
// Every listing retains its opening bar; strategy bar counts are one-based.
|
||||
assert!(
|
||||
(aapl_trades[0].price - 101.0).abs() < 0.1,
|
||||
"AAPL buy price should be ~101 (bar 2)"
|
||||
);
|
||||
assert!(
|
||||
(aapl_trades[1].price - 103.0).abs() < 0.1,
|
||||
"AAPL sell price should be ~103 (bar 4)"
|
||||
);
|
||||
|
||||
let googl_trades: Vec<_> = result
|
||||
.trades
|
||||
.iter()
|
||||
.filter(|t| t.symbol == "GOOGL")
|
||||
.collect();
|
||||
assert_eq!(googl_trades.len(), 2);
|
||||
// Third bar = Jan 3 = index 2 = price 148.
|
||||
assert!(
|
||||
(googl_trades[0].price - 148.0).abs() < 0.1,
|
||||
"GOOGL buy price should be ~148 (bar 3)"
|
||||
);
|
||||
// Sell at bar 5 or closing = price 146
|
||||
assert!(
|
||||
(googl_trades[1].price - 146.0).abs() < 0.1,
|
||||
"GOOGL sell price should be ~146 (closing)"
|
||||
);
|
||||
|
||||
let msft_trades: Vec<_> = result
|
||||
.trades
|
||||
.iter()
|
||||
.filter(|t| t.symbol == "MSFT")
|
||||
.collect();
|
||||
assert_eq!(msft_trades.len(), 2);
|
||||
// Fourth bar = Jan 4 = index 3 = price 206.
|
||||
assert!(
|
||||
(msft_trades[0].price - 206.0).abs() < 0.1,
|
||||
"MSFT buy price should be ~206 (bar 4)"
|
||||
);
|
||||
// Sell at bar 5 = end of data = price 208
|
||||
assert!(
|
||||
(msft_trades[1].price - 208.0).abs() < 0.1,
|
||||
"MSFT sell price should be ~208 (bar 5)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_closing_position_prices() {
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap();
|
||||
|
||||
// Prices that change significantly
|
||||
let prices = vec![100.0, 110.0, 120.0, 130.0, 140.0];
|
||||
let bars = create_test_bars("TEST", start_time, prices);
|
||||
|
||||
let config = BacktestConfig {
|
||||
name: "ClosePositionTest".to_string(),
|
||||
strategy: None,
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 100000.0,
|
||||
commission: 0.0,
|
||||
slippage: 0.0,
|
||||
symbols: vec!["TEST".to_string()],
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
|
||||
let time_provider = Box::new(SimulatedTime::new(start_time));
|
||||
let mut data_source = Box::new(HistoricalDataSource::new());
|
||||
data_source.load_data(bars);
|
||||
|
||||
let fill_simulator = Box::new(BacktestFillSimulator::new());
|
||||
let execution_handler = Box::new(SimulatedExecution::new(fill_simulator));
|
||||
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
};
|
||||
|
||||
let mut engine =
|
||||
BacktestEngine::new(config, mode, time_provider, data_source, execution_handler);
|
||||
|
||||
// Buy early, never sell (position will be closed at end)
|
||||
let strategy = PriceTrackingStrategy::new("ClosePositionTest").with_trades(
|
||||
vec![("TEST".to_string(), 1)], // Buy at bar 1 (price 110)
|
||||
vec![], // Never sell
|
||||
);
|
||||
|
||||
engine.add_strategy(Box::new(strategy));
|
||||
|
||||
let result = engine.run().await.unwrap();
|
||||
|
||||
// Should have 2 trades: the buy and the closing trade
|
||||
assert_eq!(result.trades.len(), 2, "Should have buy and closing trade");
|
||||
|
||||
let buy_trade = &result.trades[0];
|
||||
assert_eq!(buy_trade.side, "buy");
|
||||
// Buy at bar 1 executes at the first bar's price (100.0)
|
||||
assert!(
|
||||
(buy_trade.price - 100.0).abs() < 0.1,
|
||||
"Buy price should be ~100 (bar 1)"
|
||||
);
|
||||
|
||||
let close_trade = &result.trades[1];
|
||||
assert_eq!(close_trade.side, "sell");
|
||||
// Position should be closed at the last available price (140)
|
||||
assert!(
|
||||
(close_trade.price - 140.0).abs() < 0.1,
|
||||
"Close price {} should be ~140 (last bar price)",
|
||||
close_trade.price
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,152 +1,160 @@
|
|||
use crate::{MarketDataSource, MarketUpdate};
|
||||
use chrono::{DateTime, Utc};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::VecDeque;
|
||||
use super::mock_data_generator::MockDataGenerator;
|
||||
|
||||
// Historical data source for backtesting
|
||||
pub struct HistoricalDataSource {
|
||||
data_queue: Mutex<VecDeque<MarketUpdate>>,
|
||||
current_position: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl HistoricalDataSource {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
data_queue: Mutex::new(VecDeque::new()),
|
||||
current_position: Mutex::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
// This would be called by the orchestrator to load data
|
||||
pub fn load_data(&self, data: Vec<MarketUpdate>) {
|
||||
eprintln!("HistoricalDataSource::load_data called with {} items", data.len());
|
||||
|
||||
// Log first few items
|
||||
for (i, update) in data.iter().take(3).enumerate() {
|
||||
eprintln!(" Item {}: symbol={}, time={}", i, update.symbol, update.timestamp);
|
||||
}
|
||||
|
||||
let mut queue = self.data_queue.lock();
|
||||
queue.clear();
|
||||
queue.extend(data);
|
||||
*self.current_position.lock() = 0;
|
||||
|
||||
eprintln!("Data loaded successfully. Queue size: {}", queue.len());
|
||||
}
|
||||
|
||||
pub fn data_len(&self) -> usize {
|
||||
self.data_queue.lock().len()
|
||||
}
|
||||
|
||||
// Generate mock data for testing
|
||||
pub fn generate_mock_data(
|
||||
&self,
|
||||
symbol: String,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
seed: Option<u64>
|
||||
) {
|
||||
let mut generator = MockDataGenerator::new(seed.unwrap_or(42));
|
||||
let data = generator.generate_mixed_data(symbol, start_time, end_time);
|
||||
self.load_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MarketDataSource for HistoricalDataSource {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate> {
|
||||
let queue = self.data_queue.lock();
|
||||
let mut position = self.current_position.lock();
|
||||
|
||||
if *position < queue.len() {
|
||||
let update = queue[*position].clone();
|
||||
*position += 1;
|
||||
Some(update)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn seek_to_time(&mut self, timestamp: DateTime<Utc>) -> Result<(), String> {
|
||||
let queue = self.data_queue.lock();
|
||||
let mut position = self.current_position.lock();
|
||||
|
||||
eprintln!("HistoricalDataSource::seek_to_time called");
|
||||
eprintln!(" Target time: {}", timestamp);
|
||||
eprintln!(" Queue size: {}", queue.len());
|
||||
|
||||
if queue.is_empty() {
|
||||
eprintln!(" WARNING: Queue is empty!");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
eprintln!(" First item time: {}", queue.front().map(|u| u.timestamp.to_string()).unwrap_or("N/A".to_string()));
|
||||
eprintln!(" Last item time: {}", queue.back().map(|u| u.timestamp.to_string()).unwrap_or("N/A".to_string()));
|
||||
|
||||
// Binary search for the timestamp
|
||||
match queue.binary_search_by_key(×tamp, |update| update.timestamp) {
|
||||
Ok(pos) => {
|
||||
*position = pos;
|
||||
eprintln!(" Found exact match at position {}", pos);
|
||||
Ok(())
|
||||
}
|
||||
Err(pos) => {
|
||||
// Position where it would be inserted
|
||||
*position = pos;
|
||||
eprintln!(" No exact match, would insert at position {}", pos);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// Live data source for paper and live trading
|
||||
pub struct LiveDataSource {
|
||||
// Channel to receive data from the orchestrator
|
||||
data_receiver: tokio::sync::Mutex<Option<tokio::sync::mpsc::Receiver<MarketUpdate>>>,
|
||||
}
|
||||
|
||||
impl LiveDataSource {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
data_receiver: tokio::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn set_receiver(&self, receiver: tokio::sync::mpsc::Receiver<MarketUpdate>) {
|
||||
*self.data_receiver.lock().await = Some(receiver);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MarketDataSource for LiveDataSource {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate> {
|
||||
let mut receiver_guard = self.data_receiver.lock().await;
|
||||
if let Some(receiver) = receiver_guard.as_mut() {
|
||||
receiver.recv().await
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn seek_to_time(&mut self, _timestamp: DateTime<Utc>) -> Result<(), String> {
|
||||
Err("Cannot seek in live data source".to_string())
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
use super::mock_data_generator::MockDataGenerator;
|
||||
use crate::{MarketDataSource, MarketUpdate};
|
||||
use chrono::{DateTime, Utc};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
// Historical data source for backtesting
|
||||
pub struct HistoricalDataSource {
|
||||
data_queue: Mutex<VecDeque<MarketUpdate>>,
|
||||
current_position: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl HistoricalDataSource {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
data_queue: Mutex::new(VecDeque::new()),
|
||||
current_position: Mutex::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
// This would be called by the orchestrator to load data
|
||||
pub fn load_data(&self, data: Vec<MarketUpdate>) {
|
||||
eprintln!(
|
||||
"HistoricalDataSource::load_data called with {} items",
|
||||
data.len()
|
||||
);
|
||||
|
||||
// Log first few items
|
||||
for (i, update) in data.iter().take(3).enumerate() {
|
||||
eprintln!(
|
||||
" Item {}: symbol={}, time={}",
|
||||
i, update.symbol, update.timestamp
|
||||
);
|
||||
}
|
||||
|
||||
let mut queue = self.data_queue.lock();
|
||||
queue.clear();
|
||||
queue.extend(data);
|
||||
*self.current_position.lock() = 0;
|
||||
|
||||
eprintln!("Data loaded successfully. Queue size: {}", queue.len());
|
||||
}
|
||||
|
||||
pub fn data_len(&self) -> usize {
|
||||
self.data_queue.lock().len()
|
||||
}
|
||||
|
||||
// Generate mock data for testing
|
||||
pub fn generate_mock_data(
|
||||
&self,
|
||||
symbol: String,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
seed: Option<u64>,
|
||||
) {
|
||||
let mut generator = MockDataGenerator::new(seed.unwrap_or(42));
|
||||
let data = generator.generate_mixed_data(symbol, start_time, end_time);
|
||||
self.load_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MarketDataSource for HistoricalDataSource {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate> {
|
||||
let queue = self.data_queue.lock();
|
||||
let mut position = self.current_position.lock();
|
||||
|
||||
if *position < queue.len() {
|
||||
let update = queue[*position].clone();
|
||||
*position += 1;
|
||||
Some(update)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn seek_to_time(&mut self, timestamp: DateTime<Utc>) -> Result<(), String> {
|
||||
let queue = self.data_queue.lock();
|
||||
let mut position = self.current_position.lock();
|
||||
|
||||
eprintln!("HistoricalDataSource::seek_to_time called");
|
||||
eprintln!(" Target time: {}", timestamp);
|
||||
eprintln!(" Queue size: {}", queue.len());
|
||||
|
||||
if queue.is_empty() {
|
||||
eprintln!(" WARNING: Queue is empty!");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
" First item time: {}",
|
||||
queue
|
||||
.front()
|
||||
.map(|u| u.timestamp.to_string())
|
||||
.unwrap_or("N/A".to_string())
|
||||
);
|
||||
eprintln!(
|
||||
" Last item time: {}",
|
||||
queue
|
||||
.back()
|
||||
.map(|u| u.timestamp.to_string())
|
||||
.unwrap_or("N/A".to_string())
|
||||
);
|
||||
|
||||
// Lower bound, not an arbitrary equal match: several listings can share the
|
||||
// first timestamp, and seeking must not skip any of their opening bars.
|
||||
*position = queue.partition_point(|update| update.timestamp < timestamp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// Live data source for paper and live trading
|
||||
pub struct LiveDataSource {
|
||||
// Channel to receive data from the orchestrator
|
||||
data_receiver: tokio::sync::Mutex<Option<tokio::sync::mpsc::Receiver<MarketUpdate>>>,
|
||||
}
|
||||
|
||||
impl LiveDataSource {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
data_receiver: tokio::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn set_receiver(&self, receiver: tokio::sync::mpsc::Receiver<MarketUpdate>) {
|
||||
*self.data_receiver.lock().await = Some(receiver);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MarketDataSource for LiveDataSource {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate> {
|
||||
let mut receiver_guard = self.data_receiver.lock().await;
|
||||
if let Some(receiver) = receiver_guard.as_mut() {
|
||||
receiver.recv().await
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn seek_to_time(&mut self, _timestamp: DateTime<Utc>) -> Result<(), String> {
|
||||
Err("Cannot seek in live data source".to_string())
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -316,10 +316,13 @@ impl PositionTracker {
|
|||
}
|
||||
|
||||
pub fn get_all_positions(&self) -> Vec<Position> {
|
||||
self.positions
|
||||
let mut positions: Vec<Position> = self
|
||||
.positions
|
||||
.iter()
|
||||
.map(|entry| entry.value().clone())
|
||||
.collect()
|
||||
.collect();
|
||||
positions.sort_by(|a, b| a.symbol.cmp(&b.symbol));
|
||||
positions
|
||||
}
|
||||
|
||||
pub fn get_open_positions(&self) -> Vec<Position> {
|
||||
|
|
@ -348,7 +351,7 @@ impl PositionTracker {
|
|||
let mut realized = 0.0;
|
||||
let mut unrealized = 0.0;
|
||||
|
||||
for position in self.positions.iter() {
|
||||
for position in self.get_all_positions() {
|
||||
realized += position.realized_pnl;
|
||||
unrealized += position.unrealized_pnl;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ async function debugPositionTracking() {
|
|||
startDate: '2023-06-01T00:00:00Z',
|
||||
endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -36,7 +36,7 @@ async function debugPositionTracking() {
|
|||
mode: 'backtest' as const,
|
||||
name: 'Position Tracking Debug',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2023-06-01T00:00:00Z',
|
||||
endDate: '2023-09-01T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ async function forceBothTradeTypes() {
|
|||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -75,7 +75,7 @@ async function forceBothTradeTypes() {
|
|||
mode: 'backtest' as const,
|
||||
name: 'Force Both Trade Types',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ async function showOrderFlow() {
|
|||
startDate: '2023-07-01T00:00:00Z',
|
||||
endDate: '2023-08-01T00:00:00Z', // Just 1 month
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -31,7 +31,7 @@ async function showOrderFlow() {
|
|||
mode: 'backtest' as const,
|
||||
name: 'Order Flow Demo',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2023-07-01T00:00:00Z',
|
||||
endDate: '2023-08-01T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ async function runSimpleBacktest() {
|
|||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -34,7 +34,7 @@ async function runSimpleBacktest() {
|
|||
mode: 'backtest' as const, // Add mode field
|
||||
name: 'SMA Crossover Test',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'], // Just one symbol for simplicity
|
||||
symbols: ['AAPL.US'], // Just one symbol for simplicity
|
||||
startDate: '2023-01-01T00:00:00Z', // ISO datetime format
|
||||
endDate: '2024-01-01T00:00:00Z', // ISO datetime format
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ async function runSophisticatedBacktest() {
|
|||
mode: 'backtest' as const,
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2023-12-31T23:59:59Z',
|
||||
symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'],
|
||||
symbols: ['AAPL.US', 'GOOGL.US', 'MSFT.US', 'AMZN.US', 'TSLA.US'],
|
||||
initialCapital: 1_000_000,
|
||||
dataFrequency: '5m' as const, // 5-minute bars for detailed analysis
|
||||
|
||||
|
|
@ -76,7 +76,7 @@ async function runSophisticatedBacktest() {
|
|||
type: 'MeanReversion',
|
||||
enabled: true,
|
||||
allocation: 0.5,
|
||||
symbols: ['AAPL', 'GOOGL', 'MSFT'],
|
||||
symbols: ['AAPL.US', 'GOOGL.US', 'MSFT.US'],
|
||||
parameters: {
|
||||
lookback: 20,
|
||||
entryZScore: 2.0,
|
||||
|
|
@ -91,7 +91,7 @@ async function runSophisticatedBacktest() {
|
|||
type: 'MLEnhanced',
|
||||
enabled: true,
|
||||
allocation: 0.5,
|
||||
symbols: ['AMZN', 'TSLA'],
|
||||
symbols: ['AMZN.US', 'TSLA.US'],
|
||||
parameters: {
|
||||
modelPath: './models/ml_strategy_v1',
|
||||
updateFrequency: 1440, // Daily retraining
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ async function testShortTrades() {
|
|||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -31,7 +31,7 @@ async function testShortTrades() {
|
|||
mode: 'backtest' as const,
|
||||
name: 'Short Trade Test',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ async function traceShortPositions() {
|
|||
startDate: '2023-06-01T00:00:00Z',
|
||||
endDate: '2023-09-01T00:00:00Z', // 3 months
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -44,7 +44,7 @@ async function traceShortPositions() {
|
|||
mode: 'backtest' as const,
|
||||
name: 'Short Position Trace',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2023-06-01T00:00:00Z',
|
||||
endDate: '2023-09-01T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ async function verifyBothTradeTypes() {
|
|||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -31,7 +31,7 @@ async function verifyBothTradeTypes() {
|
|||
mode: 'backtest' as const,
|
||||
name: 'Trade Type Verification',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2024-01-01T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Hono, type Handler } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { parseBacktestRequest } from '../../backtest/BacktestRunner';
|
||||
import { BacktestCancelledError } from '../../backtest/execution-engine';
|
||||
import { BacktestConflictError } from '../../backtest/run-repository';
|
||||
|
|
@ -43,6 +44,9 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
400
|
||||
);
|
||||
}
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json(
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { defined } from '@stock-bot/invariants';
|
|||
import { at } from '@stock-bot/utils';
|
||||
import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
|
||||
import { DataManager } from '../data/DataManager';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import type { Signal } from '../strategies/BaseStrategy';
|
||||
import { StrategyManager } from '../strategies/StrategyManager';
|
||||
|
|
@ -62,7 +63,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
// this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital);
|
||||
}
|
||||
|
||||
async runBacktest(config: unknown): Promise<BacktestResult> {
|
||||
async runBacktest(config: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
||||
// Validate config
|
||||
const validatedConfig = BacktestConfigSchema.parse(config);
|
||||
|
||||
|
|
@ -126,24 +127,20 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
}
|
||||
|
||||
try {
|
||||
// Load historical data with multi-resolution support
|
||||
const dataMap = await this.dataManager.loadHistoricalData(
|
||||
validatedConfig.symbols,
|
||||
new Date(validatedConfig.startDate),
|
||||
new Date(validatedConfig.endDate),
|
||||
validatedConfig.dataFrequency,
|
||||
true // Include extended hours
|
||||
);
|
||||
// Both engines execute exactly these frozen, already-normalized bars.
|
||||
const dataset = await resolveDataset(this.storageService, validatedConfig, resolver);
|
||||
this.dataManager.inspectDataset(dataset);
|
||||
this.marketSimulator.resetWithSeed(Number.parseInt(dataset.manifest.hash.slice(0, 8), 16));
|
||||
|
||||
// Load market microstructure for each symbol
|
||||
await this.loadMarketMicrostructure(validatedConfig.symbols);
|
||||
|
||||
// Convert to flat array and sort by time
|
||||
const marketData: MarketData[] = [];
|
||||
dataMap.forEach((data, _symbol) => {
|
||||
marketData.push(...data);
|
||||
});
|
||||
marketData.sort((a, b) => a.data.timestamp - b.data.timestamp);
|
||||
const marketData: MarketData[] = dataset.bars.map(bar => ({
|
||||
type: 'bar',
|
||||
data: bar,
|
||||
eventId: `${dataset.manifest.hash}:${bar.symbol}:${bar.timestamp}`,
|
||||
}));
|
||||
|
||||
this.container.logger.info(`Loaded ${marketData.length} market data points`);
|
||||
|
||||
|
|
@ -157,12 +154,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
allocation: 1 / (validatedConfig.strategies?.length ?? 1),
|
||||
})) || [
|
||||
{
|
||||
id: `${validatedConfig.strategy}-${Date.now()}`,
|
||||
id: `${validatedConfig.strategy}-0`,
|
||||
name: validatedConfig.strategy,
|
||||
enabled: true,
|
||||
parameters: {
|
||||
symbols: validatedConfig.symbols,
|
||||
initialCapital: validatedConfig.initialCapital,
|
||||
...validatedConfig.config,
|
||||
// Add any default strategy parameters here
|
||||
},
|
||||
symbols: validatedConfig.symbols,
|
||||
|
|
@ -784,10 +782,10 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
for (const symbol of symbols) {
|
||||
const microstructure: MarketMicrostructure = {
|
||||
symbol,
|
||||
avgSpreadBps: 2 + Math.random() * 3, // 2-5 bps
|
||||
dailyVolume: 10_000_000 * (1 + Math.random() * 9), // 10-100M shares
|
||||
avgTradeSize: 100 + Math.random() * 400, // 100-500 shares
|
||||
volatility: 0.15 + Math.random() * 0.25, // 15-40% annual vol
|
||||
avgSpreadBps: 3,
|
||||
dailyVolume: 10_000_000,
|
||||
avgTradeSize: 100,
|
||||
volatility: 0.2,
|
||||
tickSize: 0.01,
|
||||
lotSize: 1,
|
||||
intradayVolumeProfile: this.generateIntradayProfile(),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { z } from 'zod';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { validateHistoricalDataRequest } from '@stock-bot/types';
|
||||
import { dataPolicy, validateDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
||||
import { normalizeBacktestResult } from './result';
|
||||
|
|
@ -14,6 +16,8 @@ import {
|
|||
|
||||
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
||||
const config = BacktestConfigSchema.parse(input);
|
||||
validateHistoricalDataRequest(config);
|
||||
dataPolicy(config);
|
||||
if (new Date(config.endDate) <= new Date(config.startDate)) {
|
||||
throw new z.ZodError([
|
||||
{ code: 'custom', path: ['endDate'], message: 'Backtest endDate must be after startDate' },
|
||||
|
|
@ -193,7 +197,24 @@ export class BacktestRunner extends EventEmitter {
|
|||
throw new BacktestCancelledError();
|
||||
}
|
||||
this.phase = 'executing';
|
||||
const raw = await this.dependencies.engine.runBacktest(executionConfig);
|
||||
let manifest: HistoricalDatasetManifest | undefined;
|
||||
const claim = this.active;
|
||||
const raw = await this.dependencies.engine.runBacktest(executionConfig, async load => {
|
||||
const saved = await this.dependencies.repository.loadDataset(
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
executionConfig.datasetHash
|
||||
);
|
||||
const dataset = validateDataset(saved ?? (await load()), executionConfig);
|
||||
const frozen =
|
||||
saved ??
|
||||
(await this.dependencies.repository.freezeDataset(claim.runId, claim.attemptId, dataset));
|
||||
manifest = frozen.manifest;
|
||||
return frozen;
|
||||
});
|
||||
if (!manifest) {
|
||||
throw new Error('Backtest engine did not resolve frozen execution inputs');
|
||||
}
|
||||
if (this.leaseFailure) {
|
||||
throw this.leaseFailure;
|
||||
}
|
||||
|
|
@ -206,7 +227,8 @@ export class BacktestRunner extends EventEmitter {
|
|||
executionConfig,
|
||||
this.active,
|
||||
performance.now() - started,
|
||||
this.cancelled
|
||||
this.cancelled,
|
||||
manifest
|
||||
);
|
||||
} catch (error) {
|
||||
throw new Error('Backtest engine returned an invalid result', { cause: error });
|
||||
|
|
|
|||
|
|
@ -34,6 +34,20 @@ export class MarketSimulator {
|
|||
private liquidityProfiles: Map<string, LiquidityProfile> = new Map();
|
||||
private lastTrades: Map<string, Trade> = new Map();
|
||||
private config: SimulationConfig;
|
||||
private randomState = 1;
|
||||
|
||||
resetWithSeed(seed: number): void {
|
||||
this.randomState = seed >>> 0;
|
||||
this.orderBooks.clear();
|
||||
this.microstructures.clear();
|
||||
this.liquidityProfiles.clear();
|
||||
this.lastTrades.clear();
|
||||
}
|
||||
|
||||
private random(): number {
|
||||
this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0;
|
||||
return this.randomState / 4294967296;
|
||||
}
|
||||
|
||||
constructor(config: Partial<SimulationConfig> = {}) {
|
||||
this.config = {
|
||||
|
|
@ -158,12 +172,12 @@ export class MarketSimulator {
|
|||
|
||||
// Hidden liquidity modeling
|
||||
const hiddenRatio = this.config.modelHiddenLiquidity
|
||||
? 1 + Math.random() * 2 // 1-3x visible size hidden
|
||||
? 1 + this.random() * 2 // 1-3x visible size hidden
|
||||
: 1;
|
||||
|
||||
// Bid levels
|
||||
const bidPrice = topQuote.bid - i * micro.tickSize;
|
||||
const bidSize = topQuote.bidSize * depthFactor * (0.8 + Math.random() * 0.4);
|
||||
const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
bids.push({
|
||||
price: bidPrice,
|
||||
size: Math.round(bidSize / micro.lotSize) * micro.lotSize,
|
||||
|
|
@ -173,7 +187,7 @@ export class MarketSimulator {
|
|||
|
||||
// Ask levels
|
||||
const askPrice = topQuote.ask + i * micro.tickSize;
|
||||
const askSize = topQuote.askSize * depthFactor * (0.8 + Math.random() * 0.4);
|
||||
const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
asks.push({
|
||||
price: askPrice,
|
||||
size: Math.round(askSize / micro.lotSize) * micro.lotSize,
|
||||
|
|
@ -218,7 +232,7 @@ export class MarketSimulator {
|
|||
for (let i = 1; i < current.bids.length; i++) {
|
||||
// Adjust sizes based on top of book changes
|
||||
const sizeRatio = quote.bidSize / (at(current.bids, 0).size || quote.bidSize);
|
||||
at(current.bids, i).size *= sizeRatio * (0.9 + Math.random() * 0.2);
|
||||
at(current.bids, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
// Adjust prices to maintain relative spacing
|
||||
const spacing = (at(current.bids, i - 1).price - at(current.bids, i).price) * spreadRatio;
|
||||
|
|
@ -227,7 +241,7 @@ export class MarketSimulator {
|
|||
|
||||
for (let i = 1; i < current.asks.length; i++) {
|
||||
const sizeRatio = quote.askSize / (at(current.asks, 0).size || quote.askSize);
|
||||
at(current.asks, i).size *= sizeRatio * (0.9 + Math.random() * 0.2);
|
||||
at(current.asks, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
const spacing = (at(current.asks, i).price - at(current.asks, i - 1).price) * spreadRatio;
|
||||
at(current.asks, i).price = at(current.asks, i - 1).price + spacing;
|
||||
|
|
@ -285,7 +299,7 @@ export class MarketSimulator {
|
|||
// Calculate available liquidity including hidden
|
||||
let availableSize = level.size;
|
||||
if (level.hiddenSize && this.config.modelHiddenLiquidity) {
|
||||
availableSize += level.hiddenSize * Math.random(); // Hidden liquidity probabilistic
|
||||
availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity
|
||||
}
|
||||
|
||||
const fillSize = Math.min(remainingSize, availableSize);
|
||||
|
|
@ -293,7 +307,7 @@ export class MarketSimulator {
|
|||
// Simulate latency - price might move
|
||||
if (this.config.latencyMs > 0 && orderType === 'market') {
|
||||
const priceMovement = microstructure
|
||||
? (((Math.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
|
||||
? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
|
||||
: 0;
|
||||
level.price += priceMovement * multiplier;
|
||||
}
|
||||
|
|
@ -319,7 +333,7 @@ export class MarketSimulator {
|
|||
// Dark pool execution for remaining size
|
||||
if (remainingSize > 0 && this.config.includeDarkPools && liquidityProfile) {
|
||||
const darkPoolPct = liquidityProfile.darkPoolLiquidity / liquidityProfile.totalLiquidity;
|
||||
const darkPoolSize = remainingSize * darkPoolPct * Math.random();
|
||||
const darkPoolSize = remainingSize * darkPoolPct * this.random();
|
||||
|
||||
if (darkPoolSize > 0) {
|
||||
const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { validateDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError } from './execution-engine';
|
||||
import {
|
||||
|
|
@ -126,6 +127,93 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
async loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
requestedHash?: string
|
||||
): Promise<HistoricalDataset | null> {
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`,
|
||||
[runId, attemptId]
|
||||
);
|
||||
if (!owned.rows[0]) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
const hash = owned.rows[0].dataset_hash ?? requestedHash;
|
||||
if (!hash) {
|
||||
return null;
|
||||
}
|
||||
if (requestedHash && requestedHash !== hash) {
|
||||
throw new BacktestConflictError('Run dataset is already frozen');
|
||||
}
|
||||
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
if (!saved.rows[0]) {
|
||||
throw new Error('Frozen dataset not found');
|
||||
}
|
||||
const dataset = validateDataset(saved.rows[0].payload);
|
||||
if (dataset.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
const pinned = await client.query(
|
||||
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
|
||||
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
|
||||
[runId, hash, attemptId]
|
||||
);
|
||||
if (!pinned.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
|
||||
}
|
||||
return dataset;
|
||||
});
|
||||
}
|
||||
|
||||
async freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
input: HistoricalDataset
|
||||
): Promise<HistoricalDataset> {
|
||||
const dataset = validateDataset(input);
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`,
|
||||
[runId, attemptId]
|
||||
);
|
||||
if (!owned.rows[0]) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
const hash = dataset.manifest.hash;
|
||||
if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) {
|
||||
throw new BacktestConflictError('Run dataset is already frozen');
|
||||
}
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING',
|
||||
[hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
const frozen = validateDataset(saved.rows[0]?.payload);
|
||||
if (frozen.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
const pinned = await client.query(
|
||||
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
|
||||
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
|
||||
[runId, hash, attemptId]
|
||||
);
|
||||
if (!pinned.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
|
||||
}
|
||||
return frozen;
|
||||
});
|
||||
}
|
||||
|
||||
/** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its
|
||||
* predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */
|
||||
private ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
|
||||
|
|
@ -156,7 +244,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
|
||||
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
|
||||
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
|
||||
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id`,
|
||||
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id, dataset_hash`,
|
||||
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
|
||||
);
|
||||
if (!updated.rows.length) {
|
||||
|
|
@ -171,6 +259,9 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
}
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
if (!result.config.dataset || result.config.dataset.hash !== updated.rows[0]?.dataset_hash) {
|
||||
throw new BacktestConflictError('Result does not reference the run frozen dataset');
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO backtest_results
|
||||
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
||||
import {
|
||||
|
|
@ -47,7 +48,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
);
|
||||
}
|
||||
|
||||
async runBacktest(input: BacktestConfig): Promise<NativeBacktestResult> {
|
||||
async runBacktest(
|
||||
input: BacktestConfig,
|
||||
dataset?: DatasetResolver
|
||||
): Promise<NativeBacktestResult> {
|
||||
if (this.closing || this.active) {
|
||||
throw new Error(
|
||||
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
||||
|
|
@ -79,7 +83,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
resolveNativeStrategies(config);
|
||||
// Race the read too: a slow database must not prevent cancellation. A late read
|
||||
// cannot spawn a worker after the run has been stopped.
|
||||
const data = await Promise.race([this.loadData(config, signal), aborted]);
|
||||
const data = await Promise.race([this.loadData(config, signal, dataset), aborted]);
|
||||
signal.throwIfAborted();
|
||||
const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => {
|
||||
this.progress = progress.progress;
|
||||
|
|
@ -108,36 +112,13 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
|
||||
private async loadData(
|
||||
config: BacktestConfig,
|
||||
signal: AbortSignal
|
||||
signal: AbortSignal,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<NativeWorkerRequest['data']> {
|
||||
const data: NativeWorkerRequest['data'] = [];
|
||||
for (const symbol of config.symbols) {
|
||||
signal.throwIfAborted();
|
||||
const bars = await this.storageService.getHistoricalBars(
|
||||
symbol,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
if (!bars.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
}
|
||||
for (const bar of bars) {
|
||||
data.push({
|
||||
symbol,
|
||||
timestamp: bar.timestamp.getTime(),
|
||||
type: 'bar',
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
|
||||
});
|
||||
}
|
||||
}
|
||||
return data;
|
||||
signal.throwIfAborted();
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver);
|
||||
signal.throwIfAborted();
|
||||
return dataset.bars.map(bar => ({ ...bar, type: 'bar' }));
|
||||
}
|
||||
|
||||
private publish(event: string, data: unknown): void {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
|
||||
import { resolveDataset } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { RustStrategy } from '../strategies/RustStrategy';
|
||||
import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types';
|
||||
|
|
@ -34,11 +35,13 @@ export interface RustBacktestResult {
|
|||
finalPositions: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** @deprecated Diagnostic wrapper only. Use BacktestRunner for durable, isolated execution. */
|
||||
export class RustBacktestEngine {
|
||||
private engine: RustEngine;
|
||||
private container: IServiceContainer;
|
||||
private storageService: StorageService;
|
||||
private config: RustBacktestConfig;
|
||||
private readonly request: BacktestConfig;
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
|
|
@ -47,6 +50,7 @@ export class RustBacktestEngine {
|
|||
) {
|
||||
this.container = container;
|
||||
this.storageService = storageService;
|
||||
this.request = config;
|
||||
|
||||
// Convert config for Rust
|
||||
const rustConfig: RustBacktestConfig = {
|
||||
|
|
@ -75,38 +79,8 @@ export class RustBacktestEngine {
|
|||
* Load historical data for the backtest
|
||||
*/
|
||||
async loadData(): Promise<void> {
|
||||
// Get config from engine
|
||||
const config = this.getConfig();
|
||||
|
||||
const startDate = new Date(config.startDate);
|
||||
const endDate = new Date(config.endDate);
|
||||
|
||||
// Load data for each symbol
|
||||
for (const symbol of config.symbols) {
|
||||
const bars = await this.storageService.getHistoricalBars(
|
||||
symbol,
|
||||
startDate,
|
||||
endDate,
|
||||
config.dataFrequency
|
||||
);
|
||||
|
||||
// Convert to Rust format
|
||||
const marketData = bars.map(bar => ({
|
||||
symbol,
|
||||
timestamp: bar.timestamp.getTime(), // Convert to milliseconds
|
||||
type: 'bar',
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3,
|
||||
}));
|
||||
|
||||
// Load into Rust engine
|
||||
this.container.logger.info(`Loading ${marketData.length} bars for ${symbol}`);
|
||||
this.engine.loadMarketData(marketData);
|
||||
}
|
||||
const dataset = await resolveDataset(this.storageService, this.request);
|
||||
this.engine.loadMarketData(dataset.bars.map(bar => ({ ...bar, type: 'bar' })));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
import type { EventEmitter } from 'node:events';
|
||||
import type { DatasetResolver } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { BacktestResult } from './typescript-result';
|
||||
|
||||
/** The runner depends on execution capabilities, not backend implementations. */
|
||||
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
|
||||
runBacktest(config: BacktestConfig): Promise<BacktestResult | NativeBacktestResult>;
|
||||
runBacktest(
|
||||
config: BacktestConfig,
|
||||
dataset?: DatasetResolver
|
||||
): Promise<BacktestResult | NativeBacktestResult>;
|
||||
stopBacktest(): Promise<void>;
|
||||
pauseBacktest(): Promise<void>;
|
||||
resumeBacktest(): Promise<void>;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { datasetManifestSchema } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { RunIdentity } from './run-repository';
|
||||
|
|
@ -31,6 +32,7 @@ export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
|||
slippage: finite,
|
||||
dataFrequency: z.string(),
|
||||
parameters: z.record(z.unknown()),
|
||||
dataset: datasetManifestSchema.optional(),
|
||||
riskLimits: z
|
||||
.object({
|
||||
maxPositionSize: finite,
|
||||
|
|
@ -115,7 +117,8 @@ export function normalizeBacktestResult(
|
|||
config: BacktestConfig,
|
||||
identity: RunIdentity,
|
||||
executionTime: number,
|
||||
cancelled: boolean
|
||||
cancelled: boolean,
|
||||
dataset?: HistoricalDatasetManifest
|
||||
): BacktestRunResult {
|
||||
if (raw.status !== 'completed' && raw.status !== 'cancelled') {
|
||||
throw new Error(
|
||||
|
|
@ -186,6 +189,7 @@ export function normalizeBacktestResult(
|
|||
slippage: config.slippage ?? 0.0001,
|
||||
dataFrequency: config.dataFrequency,
|
||||
parameters: config.config ?? {},
|
||||
dataset,
|
||||
riskLimits: config.riskLimits,
|
||||
strategies: config.strategies,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
export interface RunIdentity {
|
||||
|
|
@ -16,6 +16,16 @@ export interface BacktestRunRepository {
|
|||
load(runId: string): Promise<{ status: string; config: unknown } | null>;
|
||||
rejectPending(runId: string, error: string): Promise<void>;
|
||||
heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>;
|
||||
loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
requestedHash?: string
|
||||
): Promise<HistoricalDataset | null>;
|
||||
freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
dataset: HistoricalDataset
|
||||
): Promise<HistoricalDataset>;
|
||||
complete(result: BacktestRunResult, attemptId: string): Promise<void>;
|
||||
updateProgress(
|
||||
runId: string,
|
||||
|
|
@ -51,6 +61,12 @@ export class UnavailableBacktestRunRepository implements BacktestRunRepository {
|
|||
async heartbeat(_runId: string, _attemptId: string): Promise<{ cancelRequested: boolean }> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async loadDataset(): Promise<null> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async freezeDataset(): Promise<HistoricalDataset> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async complete(_result: BacktestRunResult, _attemptId: string): Promise<void> {
|
||||
this.unavailable();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { HistoricalDataset } from '@stock-bot/types';
|
||||
import { at } from '@stock-bot/utils';
|
||||
import { StorageService, type HistoricalBar } from '../services/StorageService';
|
||||
import { type Bar, type MarketData } from '../types';
|
||||
|
|
@ -12,15 +13,6 @@ export interface DataResolution {
|
|||
milliseconds: number;
|
||||
}
|
||||
|
||||
export interface CorporateAction {
|
||||
symbol: string;
|
||||
date: Date;
|
||||
type: 'split' | 'dividend' | 'spinoff';
|
||||
factor?: number;
|
||||
amount?: number;
|
||||
newSymbol?: string;
|
||||
}
|
||||
|
||||
export interface DataQualityIssue {
|
||||
timestamp: Date;
|
||||
symbol: string;
|
||||
|
|
@ -47,7 +39,6 @@ export class DataManager extends EventEmitter {
|
|||
|
||||
private dataCache: Map<string, MarketData[]> = new Map();
|
||||
private aggregatedCache: Map<string, Map<string, Bar[]>> = new Map();
|
||||
private corporateActions: Map<string, CorporateAction[]> = new Map();
|
||||
private dataQualityIssues: DataQualityIssue[] = [];
|
||||
|
||||
constructor(private storageService: StorageService) {
|
||||
|
|
@ -76,18 +67,10 @@ export class DataManager extends EventEmitter {
|
|||
if (!data.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
}
|
||||
this.recordQualityWarnings(symbol, data);
|
||||
|
||||
// Apply corporate actions
|
||||
const adjustedData = await this.applyCorporateActions(symbol, data, startDate, endDate);
|
||||
|
||||
// Quality checks
|
||||
const cleanedData = this.performQualityChecks(symbol, adjustedData);
|
||||
if (!cleanedData.length) {
|
||||
throw new Error(`No valid historical data for ${symbol}`);
|
||||
}
|
||||
|
||||
// Convert to MarketData format
|
||||
const marketData = this.convertToMarketData(symbol, cleanedData);
|
||||
// Storage owns validation and adjustment. Never interpolate or adjust a second time.
|
||||
const marketData = this.convertToMarketData(symbol, data);
|
||||
|
||||
result.set(symbol, marketData);
|
||||
this.dataCache.set(`${symbol}:${resolution}`, marketData);
|
||||
|
|
@ -104,140 +87,31 @@ export class DataManager extends EventEmitter {
|
|||
return result;
|
||||
}
|
||||
|
||||
async applyCorporateActions(
|
||||
symbol: string,
|
||||
data: HistoricalBar[],
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<HistoricalBar[]> {
|
||||
// Load corporate actions for the period
|
||||
const actions = await this.loadCorporateActions(symbol, startDate, endDate);
|
||||
if (actions.length === 0) {
|
||||
return data;
|
||||
/** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */
|
||||
inspectDataset(dataset: HistoricalDataset): void {
|
||||
this.clearCache();
|
||||
for (const instrument of dataset.manifest.instruments) {
|
||||
this.recordQualityWarnings(
|
||||
instrument.id,
|
||||
dataset.bars
|
||||
.filter(bar => bar.symbol === instrument.id)
|
||||
.map(bar => ({ ...bar, timestamp: new Date(bar.timestamp) }))
|
||||
);
|
||||
}
|
||||
|
||||
// Sort actions by date (newest first)
|
||||
actions.sort((a, b) => b.date.getTime() - a.date.getTime());
|
||||
|
||||
// Apply adjustments
|
||||
return data.map(bar => {
|
||||
const barDate = new Date(bar.timestamp);
|
||||
const adjustedBar = { ...bar };
|
||||
|
||||
for (const action of actions) {
|
||||
if (barDate < action.date) {
|
||||
switch (action.type) {
|
||||
case 'split':
|
||||
if (action.factor) {
|
||||
adjustedBar.open /= action.factor;
|
||||
adjustedBar.high /= action.factor;
|
||||
adjustedBar.low /= action.factor;
|
||||
adjustedBar.close /= action.factor;
|
||||
adjustedBar.volume *= action.factor;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'dividend':
|
||||
if (action.amount) {
|
||||
// Adjust for dividends (simplified)
|
||||
const adjustment = 1 - action.amount / adjustedBar.close;
|
||||
adjustedBar.open *= adjustment;
|
||||
adjustedBar.high *= adjustment;
|
||||
adjustedBar.low *= adjustment;
|
||||
adjustedBar.close *= adjustment;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return adjustedBar;
|
||||
});
|
||||
}
|
||||
|
||||
performQualityChecks(symbol: string, data: HistoricalBar[]): HistoricalBar[] {
|
||||
const cleaned: HistoricalBar[] = [];
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const bar = at(data, i);
|
||||
const prevBar = i > 0 ? data[i - 1] : null;
|
||||
const issues: string[] = [];
|
||||
|
||||
// Check for missing data
|
||||
if (!bar.open || !bar.high || !bar.low || !bar.close || bar.volume === undefined) {
|
||||
issues.push('Missing OHLCV data');
|
||||
}
|
||||
|
||||
// Check for invalid prices
|
||||
if (bar.low > bar.high) {
|
||||
issues.push('Low > High');
|
||||
}
|
||||
if (bar.open > bar.high || bar.open < bar.low) {
|
||||
issues.push('Open outside High/Low range');
|
||||
}
|
||||
if (bar.close > bar.high || bar.close < bar.low) {
|
||||
issues.push('Close outside High/Low range');
|
||||
}
|
||||
|
||||
// Check for zero or negative prices
|
||||
if (bar.open <= 0 || bar.high <= 0 || bar.low <= 0 || bar.close <= 0) {
|
||||
issues.push('Zero or negative prices');
|
||||
}
|
||||
|
||||
// Check for extreme price movements (>20% in one bar)
|
||||
if (prevBar) {
|
||||
const priceChange = Math.abs((bar.close - prevBar.close) / prevBar.close);
|
||||
if (priceChange > 0.2) {
|
||||
issues.push(`Extreme price movement: ${(priceChange * 100).toFixed(1)}%`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for volume spikes (>10x average)
|
||||
if (i >= 20) {
|
||||
const avgVolume = data.slice(i - 20, i).reduce((sum, b) => sum + b.volume, 0) / 20;
|
||||
if (bar.volume > avgVolume * 10) {
|
||||
issues.push('Volume spike detected');
|
||||
}
|
||||
}
|
||||
|
||||
// Handle issues
|
||||
if (issues.length > 0) {
|
||||
const severity = issues.some(issue => issue.includes('Missing') || issue.includes('Zero'))
|
||||
? 'error'
|
||||
: 'warning';
|
||||
|
||||
private recordQualityWarnings(symbol: string, bars: HistoricalBar[]): void {
|
||||
bars.forEach((bar, index) => {
|
||||
const previous = bars[index - 1];
|
||||
if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) {
|
||||
this.dataQualityIssues.push({
|
||||
timestamp: new Date(bar.timestamp),
|
||||
symbol,
|
||||
issue: issues.join(', '),
|
||||
severity,
|
||||
details: bar,
|
||||
issue: 'Price movement exceeds 20%; prices retained unchanged',
|
||||
severity: 'warning',
|
||||
});
|
||||
|
||||
// For errors, try to interpolate or skip
|
||||
if (severity === 'error') {
|
||||
if (prevBar && i < data.length - 1) {
|
||||
// Interpolate from surrounding bars
|
||||
const nextBar = at(data, i + 1);
|
||||
cleaned.push({
|
||||
...bar,
|
||||
open: (prevBar.close + nextBar.open) / 2,
|
||||
high: Math.max(prevBar.high, nextBar.high) * 0.9,
|
||||
low: Math.min(prevBar.low, nextBar.low) * 1.1,
|
||||
close: (prevBar.close + nextBar.close) / 2,
|
||||
volume: (prevBar.volume + nextBar.volume) / 2,
|
||||
interpolated: true,
|
||||
});
|
||||
}
|
||||
// Skip if we can't interpolate
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
cleaned.push(bar);
|
||||
}
|
||||
|
||||
return cleaned;
|
||||
});
|
||||
}
|
||||
|
||||
aggregateData(data: MarketData[], fromResolution: string, toResolution: string): Bar[] {
|
||||
|
|
@ -397,22 +271,6 @@ export class DataManager extends EventEmitter {
|
|||
}));
|
||||
}
|
||||
|
||||
private async loadCorporateActions(
|
||||
symbol: string,
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<CorporateAction[]> {
|
||||
// Check cache first
|
||||
const cached = this.corporateActions.get(symbol);
|
||||
if (cached) {
|
||||
return cached.filter(action => action.date >= startDate && action.date <= endDate);
|
||||
}
|
||||
|
||||
// In real implementation, load from database
|
||||
// For now, return empty array
|
||||
return [];
|
||||
}
|
||||
|
||||
getDataQualityReport(): {
|
||||
totalIssues: number;
|
||||
bySymbol: Record<string, number>;
|
||||
|
|
|
|||
231
apps/stock/orchestrator/src/data/historical-dataset.ts
Normal file
231
apps/stock/orchestrator/src/data/historical-dataset.ts
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
parseInstrumentId,
|
||||
validateHistoricalDataRequest,
|
||||
type HistoricalDataPolicy,
|
||||
type HistoricalDataset,
|
||||
} from '@stock-bot/types';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
export const instrumentIdSchema = z.string().refine(id => {
|
||||
try {
|
||||
parseInstrumentId(id);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, 'Use an exchange-qualified instrument ID, for example AAPL.US');
|
||||
export const historicalDataPolicySchema = z
|
||||
.object({
|
||||
adjustment: z.enum(['raw', 'provider-adjusted']),
|
||||
timestamp: z.enum(['utc-session-date', 'utc-instant']),
|
||||
})
|
||||
.strict();
|
||||
export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const positive = z.number().finite().positive();
|
||||
export const datasetBarSchema = z
|
||||
.object({
|
||||
symbol: instrumentIdSchema,
|
||||
timestamp: z.number().int().nonnegative(),
|
||||
open: positive,
|
||||
high: positive,
|
||||
low: positive,
|
||||
close: positive,
|
||||
volume: z.number().finite().nonnegative(),
|
||||
vwap: positive,
|
||||
})
|
||||
.strict();
|
||||
export const datasetManifestSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
hash: datasetHashSchema,
|
||||
instruments: z
|
||||
.array(
|
||||
z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict()
|
||||
)
|
||||
.min(1),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
policy: historicalDataPolicySchema,
|
||||
volumePolicy: z.literal('reported'),
|
||||
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
|
||||
sources: z.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: instrumentIdSchema,
|
||||
provider: z.enum(['eod', 'questdb', 'synthetic']),
|
||||
revision: z.string().min(1),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
barCount: z.number().int().positive(),
|
||||
})
|
||||
.strict();
|
||||
const datasetSchema = z
|
||||
.object({ manifest: datasetManifestSchema, bars: z.array(datasetBarSchema).min(1) })
|
||||
.strict();
|
||||
|
||||
export type DatasetResolver = (
|
||||
load: () => Promise<HistoricalDataset>
|
||||
) => Promise<HistoricalDataset>;
|
||||
export function dataPolicy(
|
||||
config: Pick<BacktestConfig, 'dataFrequency' | 'dataPolicy'>
|
||||
): HistoricalDataPolicy {
|
||||
const policy = config.dataPolicy ?? {
|
||||
adjustment: 'raw',
|
||||
timestamp: config.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||
};
|
||||
if ((config.dataFrequency === '1d') !== (policy.timestamp === 'utc-session-date')) {
|
||||
throw new Error('Daily bars require utc-session-date; intraday bars require utc-instant');
|
||||
}
|
||||
return policy;
|
||||
}
|
||||
|
||||
function hashDataset(dataset: HistoricalDataset): string {
|
||||
const { hash: _hash, ...manifest } = dataset.manifest;
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify({ manifest, bars: dataset.bars }))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
/** Parsing reconstructs a fixed property order before hashing, independent of JSONB key order. */
|
||||
export function validateDataset(input: unknown, config?: BacktestConfig): HistoricalDataset {
|
||||
const dataset = datasetSchema.parse(input);
|
||||
const m = dataset.manifest;
|
||||
const ids = m.instruments.map(i => i.id);
|
||||
const idSet = new Set(ids);
|
||||
const sortedIds = [...ids].sort();
|
||||
const start = Date.parse(m.startDate),
|
||||
end = Date.parse(m.endDate);
|
||||
validateHistoricalDataRequest({
|
||||
symbols: ids,
|
||||
startDate: m.startDate,
|
||||
endDate: m.endDate,
|
||||
dataFrequency: m.interval,
|
||||
dataPolicy: m.policy,
|
||||
datasetHash: m.hash,
|
||||
});
|
||||
if (
|
||||
ids.some((id, i) => id !== sortedIds[i]) ||
|
||||
m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) ||
|
||||
m.sources.length !== ids.length ||
|
||||
m.sources.some((s, i) => s.instrumentId !== ids[i]) ||
|
||||
m.barCount !== dataset.bars.length
|
||||
) {
|
||||
throw new Error('Invalid dataset manifest');
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
let previous: HistoricalDataset['bars'][number] | undefined;
|
||||
for (const bar of dataset.bars) {
|
||||
if (
|
||||
!idSet.has(bar.symbol) ||
|
||||
bar.timestamp < start ||
|
||||
bar.timestamp >= end ||
|
||||
bar.high < Math.max(bar.open, bar.close) ||
|
||||
bar.low > Math.min(bar.open, bar.close) ||
|
||||
(m.policy.timestamp === 'utc-session-date' && bar.timestamp % 86400000 !== 0) ||
|
||||
(previous &&
|
||||
(bar.timestamp < previous.timestamp ||
|
||||
(bar.timestamp === previous.timestamp && bar.symbol <= previous.symbol)))
|
||||
) {
|
||||
throw new Error('Invalid or unordered dataset bars');
|
||||
}
|
||||
seen.add(bar.symbol);
|
||||
previous = bar;
|
||||
}
|
||||
if (seen.size !== ids.length || hashDataset(dataset) !== m.hash) {
|
||||
throw new Error('Dataset hash/content mismatch');
|
||||
}
|
||||
if (
|
||||
config &&
|
||||
(JSON.stringify([...config.symbols].sort()) !== JSON.stringify(ids) ||
|
||||
new Date(config.startDate).toISOString() !== m.startDate ||
|
||||
new Date(config.endDate).toISOString() !== m.endDate ||
|
||||
config.dataFrequency !== m.interval ||
|
||||
JSON.stringify(dataPolicy(config)) !== JSON.stringify(m.policy) ||
|
||||
(config.datasetHash && config.datasetHash !== m.hash))
|
||||
) {
|
||||
throw new Error('Frozen dataset does not match the backtest request');
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
||||
export async function loadDataset(
|
||||
storage: StorageService,
|
||||
config: BacktestConfig
|
||||
): Promise<HistoricalDataset> {
|
||||
const instruments = [...config.symbols].sort().map(parseInstrumentId);
|
||||
const policy = dataPolicy(config);
|
||||
const bars: HistoricalDataset['bars'] = [];
|
||||
const sources: HistoricalDataset['manifest']['sources'] = [];
|
||||
for (const instrument of instruments) {
|
||||
const rows = await storage.getHistoricalBars(
|
||||
instrument.id,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency,
|
||||
policy
|
||||
);
|
||||
const source = rows[0]?.source;
|
||||
if (!source || rows.some(row => row.source !== source)) {
|
||||
throw new Error('Historical source provenance is missing or mixed');
|
||||
}
|
||||
sources.push({
|
||||
instrumentId: instrument.id,
|
||||
provider: source,
|
||||
revision: 'historical-normalization-v1',
|
||||
});
|
||||
for (const bar of rows) {
|
||||
bars.push({
|
||||
symbol: instrument.id,
|
||||
timestamp: bar.timestamp.getTime(),
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
|
||||
});
|
||||
}
|
||||
}
|
||||
bars.sort(
|
||||
(a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : a.symbol > b.symbol ? 1 : 0)
|
||||
);
|
||||
const dataset: HistoricalDataset = {
|
||||
manifest: {
|
||||
version: 1,
|
||||
hash: '0'.repeat(64),
|
||||
instruments,
|
||||
startDate: new Date(config.startDate).toISOString(),
|
||||
endDate: new Date(config.endDate).toISOString(),
|
||||
interval: config.dataFrequency,
|
||||
policy,
|
||||
volumePolicy: 'reported',
|
||||
qualityPolicy: 'reject-invalid-no-interpolation',
|
||||
sources,
|
||||
barCount: bars.length,
|
||||
},
|
||||
bars,
|
||||
};
|
||||
// Canonicalize before hashing, including metadata key order.
|
||||
const canonical = datasetSchema.parse(dataset);
|
||||
canonical.manifest.hash = hashDataset(canonical);
|
||||
return validateDataset(canonical, config);
|
||||
}
|
||||
|
||||
export async function resolveDataset(
|
||||
storage: StorageService,
|
||||
config: BacktestConfig,
|
||||
resolver?: DatasetResolver
|
||||
) {
|
||||
if (config.datasetHash && !resolver) {
|
||||
throw new Error('Dataset replay requires the durable backtest runner');
|
||||
}
|
||||
return validateDataset(
|
||||
await (resolver ? resolver(() => loadDataset(storage, config)) : loadDataset(storage, config)),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import type {
|
|||
PostgresClient,
|
||||
QuestDBClient,
|
||||
} from '@stock-bot/services';
|
||||
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
|
||||
import type { MarketData, ModeConfig, PerformanceMetrics } from '../types';
|
||||
|
||||
export interface HistoricalBar {
|
||||
|
|
@ -16,6 +17,8 @@ export interface HistoricalBar {
|
|||
volume: number;
|
||||
vwap?: number;
|
||||
interpolated?: boolean;
|
||||
source?: 'eod' | 'questdb' | 'synthetic';
|
||||
adjustedClose?: number;
|
||||
}
|
||||
export class StorageService {
|
||||
private questdb: QuestDBClient | null = null;
|
||||
|
|
@ -87,6 +90,7 @@ export class StorageService {
|
|||
|
||||
for (const item of data) {
|
||||
try {
|
||||
parseInstrumentId(item.data.symbol);
|
||||
switch (item.type) {
|
||||
case 'quote':
|
||||
await this.insertTimeSeries('quotes', {
|
||||
|
|
@ -166,8 +170,13 @@ export class StorageService {
|
|||
symbol: string,
|
||||
startTime: Date,
|
||||
endTime: Date,
|
||||
interval = '1m'
|
||||
interval = '1m',
|
||||
policy: HistoricalDataPolicy = {
|
||||
adjustment: 'raw',
|
||||
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||
}
|
||||
): Promise<HistoricalBar[]> {
|
||||
parseInstrumentId(symbol);
|
||||
if (
|
||||
!Number.isFinite(startTime.getTime()) ||
|
||||
!Number.isFinite(endTime.getTime()) ||
|
||||
|
|
@ -178,9 +187,24 @@ export class StorageService {
|
|||
if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) {
|
||||
throw new Error('Unsupported historical interval');
|
||||
}
|
||||
if (
|
||||
(interval === '1d') !== (policy.timestamp === 'utc-session-date') ||
|
||||
(interval === '1d' &&
|
||||
(startTime.getTime() % 86400000 !== 0 || endTime.getTime() % 86400000 !== 0))
|
||||
) {
|
||||
throw new Error(
|
||||
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
|
||||
);
|
||||
}
|
||||
const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval);
|
||||
const bars = rows
|
||||
.map(row => {
|
||||
if (row.symbol !== symbol) {
|
||||
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
|
||||
}
|
||||
if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) {
|
||||
throw new Error('Historical instants require an explicit UTC offset');
|
||||
}
|
||||
const timestamp = new Date(row.timestamp);
|
||||
const numeric = (value: unknown) =>
|
||||
typeof value === 'number'
|
||||
|
|
@ -188,22 +212,44 @@ export class StorageService {
|
|||
: typeof value === 'string' && value.trim()
|
||||
? Number(value)
|
||||
: NaN;
|
||||
const open = numeric(row.open),
|
||||
let open = numeric(row.open),
|
||||
high = numeric(row.high),
|
||||
low = numeric(row.low),
|
||||
close = numeric(row.close),
|
||||
volume = numeric(row.volume);
|
||||
close = numeric(row.close);
|
||||
const volume = numeric(row.volume);
|
||||
if (
|
||||
!Number.isFinite(timestamp.getTime()) ||
|
||||
![open, high, low, close, volume].every(Number.isFinite) ||
|
||||
low <= 0 ||
|
||||
high < Math.max(open, close) ||
|
||||
low > Math.min(open, close) ||
|
||||
volume < 0
|
||||
volume < 0 ||
|
||||
(interval === '1d' && timestamp.getTime() % 86400000 !== 0)
|
||||
) {
|
||||
throw new Error(`Invalid historical OHLCV data for ${symbol}`);
|
||||
}
|
||||
return { ...row, symbol, timestamp, open, high, low, close, volume };
|
||||
let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap);
|
||||
if (policy.adjustment === 'provider-adjusted') {
|
||||
const adjustedClose = numeric(row.adjustedClose);
|
||||
if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) {
|
||||
throw new Error(`Provider-adjusted prices unavailable for ${symbol}`);
|
||||
}
|
||||
const factor = adjustedClose / close;
|
||||
open *= factor;
|
||||
high *= factor;
|
||||
low *= factor;
|
||||
close = adjustedClose;
|
||||
if (vwap !== undefined) {
|
||||
vwap *= factor;
|
||||
}
|
||||
}
|
||||
if (
|
||||
![open, high, low, close].every(value => Number.isFinite(value) && value > 0) ||
|
||||
(vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0))
|
||||
) {
|
||||
throw new Error(`Invalid adjusted historical data for ${symbol}`);
|
||||
}
|
||||
return { ...row, symbol, timestamp, open, high, low, close, volume, vwap };
|
||||
})
|
||||
.filter(bar => bar.timestamp >= startTime && bar.timestamp < endTime)
|
||||
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
||||
|
|
@ -236,24 +282,30 @@ export class StorageService {
|
|||
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`,
|
||||
[symbol, startTime, endTime]
|
||||
);
|
||||
return result.rows;
|
||||
return result.rows.map(row => ({ ...row, source: 'questdb' }));
|
||||
}
|
||||
|
||||
if (this.mongodb) {
|
||||
if (interval !== '1d') {
|
||||
throw new Error('Daily provider storage cannot satisfy an intraday request');
|
||||
}
|
||||
const identity = parseInstrumentId(symbol);
|
||||
const prices = await this.mongodb.find<{
|
||||
symbol: string;
|
||||
exchange: string;
|
||||
eodSearchCode: string;
|
||||
providerExchange?: string;
|
||||
date: string;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
adjustedClose?: number;
|
||||
}>(
|
||||
'eodPrices',
|
||||
{
|
||||
symbol,
|
||||
eodSearchCode: identity.id,
|
||||
date: {
|
||||
$gte: startTime.toISOString().slice(0, 10),
|
||||
$lt: endTime.toISOString().slice(0, 10),
|
||||
|
|
@ -261,22 +313,43 @@ export class StorageService {
|
|||
},
|
||||
{ sort: { date: 1 } }
|
||||
);
|
||||
return prices.map(price => ({
|
||||
symbol,
|
||||
timestamp: new Date(price.date),
|
||||
open: price.open,
|
||||
high: price.high,
|
||||
low: price.low,
|
||||
close: price.close,
|
||||
volume: price.volume,
|
||||
}));
|
||||
return prices.map(price => {
|
||||
if (
|
||||
price.eodSearchCode !== identity.id ||
|
||||
price.symbol !== identity.symbol ||
|
||||
(price.providerExchange !== undefined && price.providerExchange !== identity.exchange)
|
||||
) {
|
||||
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
|
||||
}
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(price.date) ||
|
||||
!Number.isFinite(Date.parse(price.date)) ||
|
||||
new Date(price.date).toISOString().slice(0, 10) !== price.date
|
||||
) {
|
||||
throw new Error(`Invalid historical session date for ${symbol}`);
|
||||
}
|
||||
return {
|
||||
symbol,
|
||||
timestamp: new Date(price.date),
|
||||
open: price.open,
|
||||
high: price.high,
|
||||
low: price.low,
|
||||
close: price.close,
|
||||
volume: price.volume,
|
||||
adjustedClose: price.adjustedClose,
|
||||
source: 'eod' as const,
|
||||
};
|
||||
});
|
||||
}
|
||||
if (!this.options.allowSyntheticData) {
|
||||
throw new Error(
|
||||
'No historical data store configured; synthetic data requires explicit opt-in'
|
||||
);
|
||||
}
|
||||
return this.generateMockBars(symbol, startTime, endTime, interval);
|
||||
return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({
|
||||
...bar,
|
||||
source: 'synthetic',
|
||||
}));
|
||||
}
|
||||
|
||||
private generateMockBars(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
datasetHashSchema,
|
||||
historicalDataPolicySchema,
|
||||
instrumentIdSchema,
|
||||
} from './data/historical-dataset';
|
||||
|
||||
// Trading modes
|
||||
export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']);
|
||||
|
|
@ -20,7 +25,12 @@ export const BacktestConfigSchema = z.object({
|
|||
config: z.record(z.unknown()).optional(),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
symbols: z.array(z.string().min(1)).min(1),
|
||||
symbols: z
|
||||
.array(instrumentIdSchema)
|
||||
.min(1)
|
||||
.refine(ids => new Set(ids).size === ids.length, 'Duplicate instruments'),
|
||||
dataPolicy: historicalDataPolicySchema.optional(),
|
||||
datasetHash: datasetHashSchema.optional(),
|
||||
initialCapital: z.number().positive(),
|
||||
dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
strategy: z.string(),
|
||||
|
|
|
|||
|
|
@ -46,7 +46,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
(f.startsWith('001_') ||
|
||||
f === '09-backtest-run-contract.sql' ||
|
||||
f === '10-durable-backtest-dispatch.sql' ||
|
||||
f === '11-simulation-execution-ledger.sql')
|
||||
f === '11-simulation-execution-ledger.sql' ||
|
||||
f === '12-historical-datasets.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,97 +1,104 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { BacktestService } from '../services/backtest.service';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('backtest-routes');
|
||||
|
||||
export function createBacktestRoutes(container: IServiceContainer) {
|
||||
const backtestRoutes = new Hono();
|
||||
const backtestService = new BacktestService(container);
|
||||
|
||||
// Create a new backtest
|
||||
backtestRoutes.post('/api/backtests', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!body.strategy || !body.symbols || !body.startDate || !body.endDate) {
|
||||
return c.json({
|
||||
error: 'Missing required fields: strategy, symbols, startDate, endDate'
|
||||
}, 400);
|
||||
}
|
||||
|
||||
const backtest = await backtestService.createBacktest({
|
||||
...body,
|
||||
initialCapital: body.initialCapital || 100000,
|
||||
});
|
||||
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', { error });
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest status
|
||||
backtestRoutes.get('/api/backtests/:id', async (c) => {
|
||||
try {
|
||||
const id = c.req.param('id');
|
||||
const backtest = await backtestService.getBacktest(id);
|
||||
|
||||
if (!backtest) {
|
||||
return c.json({ error: 'Backtest not found' }, 404);
|
||||
}
|
||||
|
||||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backtest', { error });
|
||||
return c.json({ error: 'Failed to get backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest results
|
||||
backtestRoutes.get('/api/backtests/:id/results', async (c) => {
|
||||
try {
|
||||
const id = c.req.param('id');
|
||||
const results = await backtestService.getBacktestResults(id);
|
||||
|
||||
if (!results) {
|
||||
return c.json({ error: 'Results not found' }, 404);
|
||||
}
|
||||
|
||||
return c.json(results);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get results', { error });
|
||||
return c.json({ error: 'Failed to get results' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// List all backtests
|
||||
backtestRoutes.get('/api/backtests', async (c) => {
|
||||
try {
|
||||
const limit = Number(c.req.query('limit')) || 50;
|
||||
const offset = Number(c.req.query('offset')) || 0;
|
||||
|
||||
const backtests = await backtestService.listBacktests({ limit, offset });
|
||||
return c.json(backtests);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list backtests', { error });
|
||||
return c.json({ error: 'Failed to list backtests' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Cancel a backtest
|
||||
backtestRoutes.post('/api/backtests/:id/cancel', async (c) => {
|
||||
try {
|
||||
const id = c.req.param('id');
|
||||
await backtestService.cancelBacktest(id);
|
||||
return c.json({ message: 'Backtest cancelled' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel backtest', { error });
|
||||
return c.json({ error: 'Failed to cancel backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
return backtestRoutes;
|
||||
}
|
||||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { BacktestService } from '../services/backtest.service';
|
||||
|
||||
const logger = getLogger('backtest-routes');
|
||||
|
||||
export function createBacktestRoutes(container: IServiceContainer) {
|
||||
const backtestRoutes = new Hono();
|
||||
const backtestService = new BacktestService(container);
|
||||
|
||||
// Create a new backtest
|
||||
backtestRoutes.post('/api/backtests', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!body.strategy || !body.symbols || !body.startDate || !body.endDate) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Missing required fields: strategy, symbols, startDate, endDate',
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
const backtest = await backtestService.createBacktest({
|
||||
...body,
|
||||
initialCapital: body.initialCapital || 100000,
|
||||
});
|
||||
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', { error });
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest status
|
||||
backtestRoutes.get('/api/backtests/:id', async c => {
|
||||
try {
|
||||
const id = c.req.param('id');
|
||||
const backtest = await backtestService.getBacktest(id);
|
||||
|
||||
if (!backtest) {
|
||||
return c.json({ error: 'Backtest not found' }, 404);
|
||||
}
|
||||
|
||||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backtest', { error });
|
||||
return c.json({ error: 'Failed to get backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest results
|
||||
backtestRoutes.get('/api/backtests/:id/results', async c => {
|
||||
try {
|
||||
const id = c.req.param('id');
|
||||
const results = await backtestService.getBacktestResults(id);
|
||||
|
||||
if (!results) {
|
||||
return c.json({ error: 'Results not found' }, 404);
|
||||
}
|
||||
|
||||
return c.json(results);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get results', { error });
|
||||
return c.json({ error: 'Failed to get results' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// List all backtests
|
||||
backtestRoutes.get('/api/backtests', async c => {
|
||||
try {
|
||||
const limit = Number(c.req.query('limit')) || 50;
|
||||
const offset = Number(c.req.query('offset')) || 0;
|
||||
|
||||
const backtests = await backtestService.listBacktests({ limit, offset });
|
||||
return c.json(backtests);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list backtests', { error });
|
||||
return c.json({ error: 'Failed to list backtests' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Cancel a backtest
|
||||
backtestRoutes.post('/api/backtests/:id/cancel', async c => {
|
||||
try {
|
||||
const id = c.req.param('id');
|
||||
await backtestService.cancelBacktest(id);
|
||||
return c.json({ message: 'Backtest cancelled' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel backtest', { error });
|
||||
return c.json({ error: 'Failed to cancel backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
return backtestRoutes;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
|
@ -43,6 +44,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
|
@ -57,6 +61,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to update backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
|
@ -93,6 +100,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
return c.json({ error: 'Failed to create run' }, 500);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { authenticatedServiceFetch } from '@stock-bot/di';
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { validateHistoricalDataRequest, type BacktestRunResult } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
|
||||
|
|
@ -78,6 +78,12 @@ export class BacktestServiceV2 {
|
|||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
validateHistoricalDataRequest({
|
||||
...request,
|
||||
dataFrequency: request.config?.dataFrequency,
|
||||
dataPolicy: request.config?.dataPolicy,
|
||||
datasetHash: request.config?.datasetHash,
|
||||
});
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
|
|
@ -130,6 +136,19 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
async updateBacktest(id: string, request: Partial<BacktestRequest>): Promise<Backtest | null> {
|
||||
const existing = await this.getBacktest(id);
|
||||
if (!existing) {
|
||||
return null;
|
||||
}
|
||||
const next = { ...existing, ...request };
|
||||
validateHistoricalDataRequest({
|
||||
symbols: next.symbols,
|
||||
startDate: new Date(next.startDate).toISOString(),
|
||||
endDate: new Date(next.endDate).toISOString(),
|
||||
dataFrequency: next.config?.dataFrequency,
|
||||
dataPolicy: next.config?.dataPolicy,
|
||||
datasetHash: next.config?.datasetHash,
|
||||
});
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
|
@ -209,6 +228,14 @@ export class BacktestServiceV2 {
|
|||
throw new Error('Backtest not found');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
validateHistoricalDataRequest({
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
dataFrequency: definition.config.dataFrequency,
|
||||
dataPolicy: definition.config.dataPolicy,
|
||||
datasetHash: definition.config.datasetHash,
|
||||
});
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new Error('Speed multiplier must be positive or null');
|
||||
|
|
@ -225,6 +252,8 @@ export class BacktestServiceV2 {
|
|||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
riskLimits: definition.config.riskLimits,
|
||||
dataPolicy: definition.config.dataPolicy,
|
||||
datasetHash: definition.config.datasetHash,
|
||||
dataFrequency: definition.config.dataFrequency ?? '1d',
|
||||
commission: definition.config.commission ?? 0.001,
|
||||
slippage: definition.config.slippage ?? 0.0001,
|
||||
|
|
|
|||
|
|
@ -138,13 +138,21 @@ export function BacktestDetailPageV2() {
|
|||
endDate: config.endDate.toISOString().split('T')[0],
|
||||
initialCapital: config.initialCapital,
|
||||
config: {
|
||||
...backtest?.config,
|
||||
commission: config.commission,
|
||||
slippage: config.slippage,
|
||||
speedMultiplier: config.speedMultiplier,
|
||||
dataPolicy: {
|
||||
adjustment: config.priceAdjustment ?? 'raw',
|
||||
timestamp:
|
||||
!backtest?.config?.dataFrequency || backtest.config.dataFrequency === '1d'
|
||||
? 'utc-session-date'
|
||||
: 'utc-instant',
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
[id, updateBacktest]
|
||||
[id, updateBacktest, backtest]
|
||||
);
|
||||
|
||||
// Handle new run creation
|
||||
|
|
@ -186,6 +194,13 @@ export function BacktestDetailPageV2() {
|
|||
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;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,268 +1,295 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
interface BacktestConfigurationProps {
|
||||
onSubmit: (config: BacktestConfig) => void;
|
||||
disabled?: boolean;
|
||||
initialConfig?: BacktestConfig;
|
||||
}
|
||||
|
||||
export function BacktestConfiguration({ onSubmit, disabled, initialConfig }: BacktestConfigurationProps) {
|
||||
const [formData, setFormData] = useState<BacktestConfig>(initialConfig || {
|
||||
name: '',
|
||||
startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago
|
||||
endDate: new Date(),
|
||||
initialCapital: 100000,
|
||||
symbols: [],
|
||||
strategy: 'sma-crossover',
|
||||
speedMultiplier: 1,
|
||||
commission: 0.001, // 0.1%
|
||||
slippage: 0.0005, // 0.05%
|
||||
});
|
||||
|
||||
const [symbolInput, setSymbolInput] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (initialConfig) {
|
||||
setFormData(initialConfig);
|
||||
}
|
||||
}, [initialConfig]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (formData.symbols.length === 0) {
|
||||
alert('Please add at least one symbol');
|
||||
return;
|
||||
}
|
||||
onSubmit(formData);
|
||||
};
|
||||
|
||||
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
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAddSymbol = () => {
|
||||
const symbol = symbolInput.trim().toUpperCase();
|
||||
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">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Backtest Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value={formData.name}
|
||||
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}
|
||||
required
|
||||
/>
|
||||
</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>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Initial Capital ($)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="initialCapital"
|
||||
value={formData.initialCapital}
|
||||
onChange={handleChange}
|
||||
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}
|
||||
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"
|
||||
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
|
||||
name="strategy"
|
||||
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}
|
||||
>
|
||||
<option value="sma-crossover">SMA Crossover</option>
|
||||
<option value="mean-reversion">Mean Reversion</option>
|
||||
<option value="ml-enhanced">ML Enhanced (Advanced)</option>
|
||||
<option value="momentum">Momentum (Coming Soon)</option>
|
||||
<option value="pairs-trading">Pairs Trading (Coming Soon)</option>
|
||||
</select>
|
||||
<p className="text-xs text-text-muted mt-1">
|
||||
{formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'}
|
||||
{formData.strategy === 'mean-reversion' && 'Trades when price deviates from mean by 2+ std devs'}
|
||||
{formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'}
|
||||
{formData.strategy === 'momentum' && 'Follows strong price trends'}
|
||||
{formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Commission (%)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="commission"
|
||||
value={formData.commission * 100}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, commission: parseFloat(e.target.value) / 100 }))}
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Slippage (%)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="slippage"
|
||||
value={formData.slippage * 100}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, slippage: parseFloat(e.target.value) / 100 }))}
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Speed Multiplier
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="speedMultiplier"
|
||||
value={formData.speedMultiplier}
|
||||
onChange={handleChange}
|
||||
min="0.1"
|
||||
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}
|
||||
/>
|
||||
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
|
||||
</div>
|
||||
|
||||
<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}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
import { useEffect, useState } from 'react';
|
||||
import { parseInstrumentId } from '@stock-bot/types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
interface BacktestConfigurationProps {
|
||||
onSubmit: (config: BacktestConfig) => void;
|
||||
disabled?: boolean;
|
||||
initialConfig?: BacktestConfig;
|
||||
}
|
||||
|
||||
export function BacktestConfiguration({
|
||||
onSubmit,
|
||||
disabled,
|
||||
initialConfig,
|
||||
}: BacktestConfigurationProps) {
|
||||
const [formData, setFormData] = useState<BacktestConfig>(
|
||||
initialConfig || {
|
||||
name: '',
|
||||
startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago
|
||||
endDate: new Date(),
|
||||
initialCapital: 100000,
|
||||
symbols: [],
|
||||
strategy: 'sma-crossover',
|
||||
speedMultiplier: 1,
|
||||
commission: 0.001, // 0.1%
|
||||
slippage: 0.0005, // 0.05%
|
||||
}
|
||||
);
|
||||
|
||||
const [symbolInput, setSymbolInput] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (initialConfig) {
|
||||
setFormData(initialConfig);
|
||||
}
|
||||
}, [initialConfig]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (formData.symbols.length === 0) {
|
||||
alert('Please add at least one symbol');
|
||||
return;
|
||||
}
|
||||
onSubmit(formData);
|
||||
};
|
||||
|
||||
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,
|
||||
}));
|
||||
};
|
||||
|
||||
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">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">Backtest Name</label>
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value={formData.name}
|
||||
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}
|
||||
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>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Initial Capital ($)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="initialCapital"
|
||||
value={formData.initialCapital}
|
||||
onChange={handleChange}
|
||||
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}
|
||||
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
|
||||
name="strategy"
|
||||
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}
|
||||
>
|
||||
<option value="sma-crossover">SMA Crossover</option>
|
||||
<option value="mean-reversion">Mean Reversion</option>
|
||||
<option value="ml-enhanced">ML Enhanced (Advanced)</option>
|
||||
<option value="momentum">Momentum (Coming Soon)</option>
|
||||
<option value="pairs-trading">Pairs Trading (Coming Soon)</option>
|
||||
</select>
|
||||
<p className="text-xs text-text-muted mt-1">
|
||||
{formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'}
|
||||
{formData.strategy === 'mean-reversion' &&
|
||||
'Trades when price deviates from mean by 2+ std devs'}
|
||||
{formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'}
|
||||
{formData.strategy === 'momentum' && 'Follows strong price trends'}
|
||||
{formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Commission (%)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="commission"
|
||||
value={formData.commission * 100}
|
||||
onChange={e =>
|
||||
setFormData(prev => ({ ...prev, commission: parseFloat(e.target.value) / 100 }))
|
||||
}
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">Slippage (%)</label>
|
||||
<input
|
||||
type="number"
|
||||
name="slippage"
|
||||
value={formData.slippage * 100}
|
||||
onChange={e =>
|
||||
setFormData(prev => ({ ...prev, slippage: parseFloat(e.target.value) / 100 }))
|
||||
}
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Speed Multiplier
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="speedMultiplier"
|
||||
value={formData.speedMultiplier}
|
||||
onChange={handleChange}
|
||||
min="0.1"
|
||||
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}
|
||||
/>
|
||||
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
|
||||
</div>
|
||||
|
||||
<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}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { XMarkIcon } from '@heroicons/react/24/solid';
|
||||
import { useState } from 'react';
|
||||
import { parseInstrumentId } from '@stock-bot/types';
|
||||
import type { Backtest } from '../services/backtestApiV2';
|
||||
|
||||
interface CreateBacktestDialogProps {
|
||||
|
|
@ -11,12 +12,13 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog
|
|||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
strategy: 'moving-average',
|
||||
symbols: ['AAPL'],
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
|
||||
endDate: new Date().toISOString().slice(0, 10),
|
||||
initialCapital: 100000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
priceAdjustment: 'raw' as 'raw' | 'provider-adjusted',
|
||||
});
|
||||
|
||||
const [symbolInput, setSymbolInput] = useState('');
|
||||
|
|
@ -31,12 +33,22 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog
|
|||
|
||||
onCreate({
|
||||
...formData,
|
||||
config: { commission: formData.commission, slippage: formData.slippage },
|
||||
config: {
|
||||
commission: formData.commission,
|
||||
slippage: formData.slippage,
|
||||
dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
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('');
|
||||
|
|
@ -102,7 +114,7 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog
|
|||
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="Enter symbol (e.g., AAPL)"
|
||||
placeholder="Instrument ID (e.g., AAPL.US)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -131,6 +143,28 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog
|
|||
</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">
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ export interface BacktestConfig {
|
|||
speedMultiplier: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
priceAdjustment?: 'raw' | 'provider-adjusted';
|
||||
}
|
||||
|
||||
export interface BacktestMetrics {
|
||||
|
|
|
|||
7
database/postgres/init/12-historical-datasets.sql
Normal file
7
database/postgres/init/12-historical-datasets.sql
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
-- Content-addressed execution inputs. No provider history is rewritten or removed.
|
||||
CREATE TABLE IF NOT EXISTS backtest_datasets (
|
||||
hash TEXT PRIMARY KEY CHECK (hash ~ '^[a-f0-9]{64}$'),
|
||||
payload JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS dataset_hash TEXT REFERENCES backtest_datasets(hash);
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import type { HistoricalDatasetManifest } from './historical-data';
|
||||
|
||||
/** Transport-neutral contract shared by backtest entry points and result readers. */
|
||||
export interface BacktestRunConfiguration {
|
||||
name: string;
|
||||
|
|
@ -10,6 +12,8 @@ export interface BacktestRunConfiguration {
|
|||
slippage: number;
|
||||
dataFrequency: string;
|
||||
parameters: Record<string, unknown>;
|
||||
/** Missing only on historical results without frozen input provenance. */
|
||||
dataset?: HistoricalDatasetManifest;
|
||||
riskLimits?: {
|
||||
maxPositionSize: number;
|
||||
maxOrderSize: number;
|
||||
|
|
|
|||
117
libs/core/types/src/historical-data.ts
Normal file
117
libs/core/types/src/historical-data.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
/** Listing IDs use the existing EOD provider exchange namespace, not a guessed MIC. */
|
||||
export interface InstrumentIdentity {
|
||||
id: string;
|
||||
symbol: string;
|
||||
exchange: string;
|
||||
}
|
||||
|
||||
export class HistoricalDataRequestError extends Error {}
|
||||
|
||||
export function parseInstrumentId(id: string): InstrumentIdentity {
|
||||
const match = /^([A-Z0-9][A-Z0-9._^-]*)\.([A-Z0-9][A-Z0-9_-]*)$/.exec(id);
|
||||
if (!match?.[1] || !match[2] || id.length > 128) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Use an exchange-qualified instrument ID, for example AAPL.US'
|
||||
);
|
||||
}
|
||||
return { id, symbol: match[1], exchange: match[2] };
|
||||
}
|
||||
|
||||
export interface HistoricalDataPolicy {
|
||||
adjustment: 'raw' | 'provider-adjusted';
|
||||
timestamp: 'utc-session-date' | 'utc-instant';
|
||||
}
|
||||
|
||||
/** Validate transport-independent data choices before accepting a durable run. */
|
||||
export function validateHistoricalDataRequest(input: {
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
dataFrequency?: unknown;
|
||||
dataPolicy?: unknown;
|
||||
datasetHash?: unknown;
|
||||
}): void {
|
||||
if (
|
||||
!Array.isArray(input.symbols) ||
|
||||
!input.symbols.length ||
|
||||
new Set(input.symbols).size !== input.symbols.length
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Choose one or more distinct exchange-qualified instruments'
|
||||
);
|
||||
}
|
||||
input.symbols.forEach(parseInstrumentId);
|
||||
const frequency = input.dataFrequency ?? '1d';
|
||||
if (typeof frequency !== 'string' || !['1m', '5m', '15m', '1h', '1d'].includes(frequency)) {
|
||||
throw new HistoricalDataRequestError('Unsupported historical interval');
|
||||
}
|
||||
if (
|
||||
![input.startDate, input.endDate].every(
|
||||
date =>
|
||||
typeof date === 'string' &&
|
||||
(/^\d{4}-\d{2}-\d{2}$/.test(date) || /(Z|[+-]\d{2}:\d{2})$/.test(date))
|
||||
)
|
||||
) {
|
||||
throw new HistoricalDataRequestError('Historical instants require an explicit UTC offset');
|
||||
}
|
||||
const start = Date.parse(input.startDate),
|
||||
end = Date.parse(input.endDate);
|
||||
if (
|
||||
!Number.isFinite(start) ||
|
||||
!Number.isFinite(end) ||
|
||||
end <= start ||
|
||||
(frequency === '1d' && (start % 86400000 !== 0 || end % 86400000 !== 0))
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Use an increasing range; daily ranges require UTC midnight session dates'
|
||||
);
|
||||
}
|
||||
if (input.dataPolicy !== undefined) {
|
||||
const policy = input.dataPolicy;
|
||||
if (
|
||||
!policy ||
|
||||
typeof policy !== 'object' ||
|
||||
!('adjustment' in policy) ||
|
||||
!('timestamp' in policy) ||
|
||||
!['raw', 'provider-adjusted'].includes(String(policy.adjustment)) ||
|
||||
policy.timestamp !== (frequency === '1d' ? 'utc-session-date' : 'utc-instant')
|
||||
) {
|
||||
throw new HistoricalDataRequestError('Invalid historical adjustment/timestamp policy');
|
||||
}
|
||||
}
|
||||
if (
|
||||
input.datasetHash !== undefined &&
|
||||
(typeof input.datasetHash !== 'string' || !/^[a-f0-9]{64}$/.test(input.datasetHash))
|
||||
) {
|
||||
throw new HistoricalDataRequestError('Invalid dataset hash');
|
||||
}
|
||||
}
|
||||
|
||||
export interface HistoricalDatasetManifest {
|
||||
version: 1;
|
||||
hash: string;
|
||||
instruments: InstrumentIdentity[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
interval: string;
|
||||
policy: HistoricalDataPolicy;
|
||||
/** Adjusted-close ratios include splits/dividends; reported volume is never rescaled. */
|
||||
volumePolicy: 'reported';
|
||||
qualityPolicy: 'reject-invalid-no-interpolation';
|
||||
sources: { instrumentId: string; provider: 'eod' | 'questdb' | 'synthetic'; revision: string }[];
|
||||
barCount: number;
|
||||
}
|
||||
|
||||
export interface HistoricalDataset {
|
||||
manifest: HistoricalDatasetManifest;
|
||||
bars: {
|
||||
symbol: string;
|
||||
timestamp: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
vwap: number;
|
||||
}[];
|
||||
}
|
||||
|
|
@ -93,3 +93,14 @@ export {
|
|||
parseReferenceDataResetRequest,
|
||||
} from './reference-data';
|
||||
export type { ReferenceDataResetRequest, ReferenceDataResetScope } from './reference-data';
|
||||
export {
|
||||
parseInstrumentId,
|
||||
HistoricalDataRequestError,
|
||||
validateHistoricalDataRequest,
|
||||
} from './historical-data';
|
||||
export type {
|
||||
InstrumentIdentity,
|
||||
HistoricalDataPolicy,
|
||||
HistoricalDataset,
|
||||
HistoricalDatasetManifest,
|
||||
} from './historical-data';
|
||||
|
|
|
|||
2
test/fixtures/execution.ts
vendored
2
test/fixtures/execution.ts
vendored
|
|
@ -15,7 +15,7 @@ export const start = Date.parse('2024-01-01T00:00:00Z');
|
|||
export const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A', 'B'],
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: new Date(start).toISOString(),
|
||||
endDate: '2025-01-01T00:00:00Z',
|
||||
initialCapital: 10000,
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/back
|
|||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
import {
|
||||
|
|
@ -45,7 +46,7 @@ const config = BacktestConfigSchema.parse({
|
|||
mode: 'backtest',
|
||||
name: 'Workflow fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE'],
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
|
|
@ -75,11 +76,12 @@ async function fixture(
|
|||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
|
||||
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
|
||||
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0,
|
||||
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0, dataset_hash text,
|
||||
lease_expires_at timestamptz, cancel_requested boolean DEFAULT false,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id),
|
||||
next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0);
|
||||
CREATE TABLE backtest_datasets (hash text PRIMARY KEY, payload jsonb, created_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE backtest_results (run_id uuid PRIMARY KEY REFERENCES runs(id), completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
|
||||
execution_time numeric, configuration jsonb, engine text);`);
|
||||
|
|
@ -141,6 +143,49 @@ async function fixture(
|
|||
}
|
||||
|
||||
describe('one backtest execution workflow', () => {
|
||||
test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => {
|
||||
const f = await fixture();
|
||||
const api = createBacktestV2Routes(f.services);
|
||||
for (const request of [
|
||||
{ ...config, symbols: ['FIXTURE'] },
|
||||
{ ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } },
|
||||
{ ...config, config: { datasetHash: 'invalid' } },
|
||||
]) {
|
||||
const response = await api.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
}
|
||||
expect((await f.postgres.query('SELECT * FROM backtests')).rows).toHaveLength(0);
|
||||
expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
});
|
||||
test('frozen inputs replay without reading mutable provider history and are recorded in results', async () => {
|
||||
const f = await fixture();
|
||||
const first = await f.runner.runBacktest(config);
|
||||
expect(first.config.dataset?.barCount).toBe(70);
|
||||
expect(first.config.dataset?.hash).toMatch(/^[a-f0-9]{64}$/);
|
||||
const saved = await f.postgres.query('SELECT dataset_hash FROM runs WHERE id = $1', [
|
||||
first.runId,
|
||||
]);
|
||||
expect(saved.rows[0]?.dataset_hash).toBe(first.config.dataset!.hash);
|
||||
f.storage.getHistoricalBars = async () => {
|
||||
throw new Error('Provider unavailable or revised');
|
||||
};
|
||||
const replay = await f.runner.runBacktest({
|
||||
...config,
|
||||
datasetHash: first.config.dataset!.hash,
|
||||
});
|
||||
expect(replay.config.dataset).toEqual(first.config.dataset);
|
||||
expect(replay.trades).toEqual(first.trades);
|
||||
expect(replay.metrics).toEqual(first.metrics);
|
||||
expect(replay.equity).toEqual(first.equity);
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
|
||||
await expect(f.runner.runBacktest({ ...config, datasetHash: 'f'.repeat(64) })).rejects.toThrow(
|
||||
'not found'
|
||||
);
|
||||
});
|
||||
test('REST and decorated jobs execute real data and commit the same canonical result', async () => {
|
||||
const f = await fixture();
|
||||
const response = await f.routes.request('/api/backtest/run', {
|
||||
|
|
@ -208,10 +253,17 @@ describe('one backtest execution workflow', () => {
|
|||
expect(result.engine).toBe('typescript');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(result.status).toBe('completed');
|
||||
const repeated = await services.custom!.BacktestRunner!.runBacktest(config);
|
||||
services.custom!.StorageService!.getHistoricalBars = async () => {
|
||||
throw new Error('Provider unavailable');
|
||||
};
|
||||
const repeated = await services.custom!.BacktestRunner!.runBacktest({
|
||||
...config,
|
||||
datasetHash: result.config.dataset!.hash,
|
||||
});
|
||||
expect(repeated.config.dataset).toEqual(result.config.dataset);
|
||||
expect(repeated.trades).toEqual(result.trades);
|
||||
expect(repeated.metrics).toEqual(result.metrics);
|
||||
expect(result.ohlcData.FIXTURE).toHaveLength(70);
|
||||
expect(result.ohlcData['FIXTURE.TEST']).toHaveLength(70);
|
||||
expect(result.trades.every(trade => trade.kind === 'closed')).toBe(true);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
|
||||
} finally {
|
||||
|
|
@ -262,7 +314,7 @@ describe('one backtest execution workflow', () => {
|
|||
const f = await fixture(true);
|
||||
await expect(
|
||||
new DataManager(f.storage).loadHistoricalData(
|
||||
['FIXTURE'],
|
||||
['FIXTURE.TEST'],
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
'1d'
|
||||
|
|
@ -318,7 +370,10 @@ describe('one backtest execution workflow', () => {
|
|||
if (sql.includes('INSERT INTO backtest_results')) {
|
||||
throw new Error('Insert failed');
|
||||
}
|
||||
return { rows: [{ id: result.runId }], rowCount: 1 };
|
||||
return {
|
||||
rows: [{ id: result.runId, dataset_hash: result.config.dataset?.hash }],
|
||||
rowCount: 1,
|
||||
};
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import type { MongoDBClient } from '@stock-bot/services';
|
||||
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
||||
import {
|
||||
persistEodPrices,
|
||||
type EodPrice,
|
||||
} from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import {
|
||||
loadDataset,
|
||||
validateDataset,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
|
||||
|
|
@ -48,13 +52,13 @@ function memoryStore() {
|
|||
},
|
||||
async find(
|
||||
collection: string,
|
||||
filter: { symbol: string; date: { $gte: string; $lt: string } }
|
||||
filter: { eodSearchCode: string; date: { $gte: string; $lt: string } }
|
||||
) {
|
||||
expect(collection).toBe('eodPrices');
|
||||
return documents
|
||||
.filter(
|
||||
row =>
|
||||
row.symbol === filter.symbol &&
|
||||
row.eodSearchCode === filter.eodSearchCode &&
|
||||
row.date >= filter.date.$gte &&
|
||||
row.date < filter.date.$lt
|
||||
)
|
||||
|
|
@ -65,6 +69,176 @@ function memoryStore() {
|
|||
}
|
||||
|
||||
describe('deterministic ingestion → storage → native backtest', () => {
|
||||
test('intraday queries bind qualified IDs and reject timezone-less instants or wrong listings', async () => {
|
||||
let timestamp = '2024-01-01T10:00:00-05:00';
|
||||
let symbol = identity.eodSearchCode;
|
||||
const questdb = {
|
||||
async query(_sql: string, parameters: unknown[]) {
|
||||
expect(parameters[0]).toBe(identity.eodSearchCode);
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
symbol,
|
||||
timestamp,
|
||||
open: 100,
|
||||
high: 101,
|
||||
low: 99,
|
||||
close: 100,
|
||||
volume: 1000,
|
||||
vwap: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
} as unknown as QuestDBClient;
|
||||
const storage = new StorageService({ logger }, null, null, questdb);
|
||||
const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m');
|
||||
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T15:00:00.000Z');
|
||||
timestamp = '2024-01-01T10:00:00';
|
||||
await expect(
|
||||
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m')
|
||||
).rejects.toThrow('explicit UTC offset');
|
||||
timestamp = '2024-01-01T15:00:00Z';
|
||||
symbol = 'FIXTURE.OTHER';
|
||||
await expect(
|
||||
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m')
|
||||
).rejects.toThrow('identity mismatch');
|
||||
});
|
||||
test('provider routing namespaces remain distinct from venue metadata, including legacy rows', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
const listing = { symbol: 'FIXTURE', exchange: 'NASDAQ', eodSearchCode: 'FIXTURE.US' };
|
||||
await persistEodPrices(mongodb, listing, [fixture[0]!]);
|
||||
expect(documents[0]?.exchange).toBe('NASDAQ');
|
||||
expect((documents[0] as unknown as { providerExchange: string }).providerExchange).toBe('US');
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
expect(
|
||||
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.symbol
|
||||
).toBe('FIXTURE.US');
|
||||
delete (documents[0] as unknown as { providerExchange?: string }).providerExchange;
|
||||
expect(
|
||||
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.close
|
||||
).toBe(fixture[0]!.close);
|
||||
});
|
||||
test('same ticker on different exchanges never shares bars and bare tickers fail closed', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const other = { symbol: 'FIXTURE', exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' };
|
||||
await persistEodPrices(mongodb, identity, [fixture[0]!]);
|
||||
await persistEodPrices(mongodb, other, [
|
||||
{ ...fixture[0]!, open: 200, high: 201, low: 199, close: 200 },
|
||||
]);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
expect(
|
||||
(await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d'))[0]?.close
|
||||
).toBe(fixture[0]!.close);
|
||||
expect((await storage.getHistoricalBars(other.eodSearchCode, start, end, '1d'))[0]?.close).toBe(
|
||||
200
|
||||
);
|
||||
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
|
||||
'exchange-qualified'
|
||||
);
|
||||
expect(
|
||||
BacktestConfigSchema.safeParse({ ...datasetConfig(), symbols: ['FIXTURE'] }).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('split and dividend adjusted-close factors apply to every OHLC price, never to reported volume', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const prices = [
|
||||
{
|
||||
...fixture[0]!,
|
||||
open: 100,
|
||||
high: 110,
|
||||
low: 90,
|
||||
close: 100,
|
||||
adjusted_close: 50,
|
||||
volume: 1000,
|
||||
},
|
||||
{ ...fixture[1]!, open: 50, high: 55, low: 45, close: 50, adjusted_close: 49, volume: 2000 },
|
||||
];
|
||||
await persistEodPrices(mongodb, identity, prices);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const raw = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d');
|
||||
const adjusted = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
|
||||
adjustment: 'provider-adjusted',
|
||||
timestamp: 'utc-session-date',
|
||||
});
|
||||
expect(raw.map(b => b.close)).toEqual([100, 50]);
|
||||
expect(adjusted.map(b => [b.open, b.high, b.low, b.close, b.volume])).toEqual([
|
||||
[50, 55, 45, 50, 1000],
|
||||
[49, 53.9, 44.1, 49, 2000],
|
||||
]);
|
||||
const a = await loadDataset(storage, datasetConfig());
|
||||
const b = await loadDataset(storage, {
|
||||
...datasetConfig(),
|
||||
dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' },
|
||||
});
|
||||
expect(a.manifest.hash).not.toBe(b.manifest.hash);
|
||||
});
|
||||
|
||||
test('missing provider factors cannot silently turn adjusted requests into raw data', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, [fixture[0]!]);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
await expect(
|
||||
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
|
||||
adjustment: 'provider-adjusted',
|
||||
timestamp: 'utc-session-date',
|
||||
})
|
||||
).rejects.toThrow('unavailable');
|
||||
await expect(
|
||||
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, adjusted_close: 0 }])
|
||||
).rejects.toThrow('Invalid OHLCV');
|
||||
await expect(
|
||||
persistEodPrices(mongodb, { ...identity, symbol: 'WRONG' }, [fixture[0]!])
|
||||
).rejects.toThrow('identity mismatch');
|
||||
});
|
||||
|
||||
test('daily timestamps are UTC session labels with aligned, exclusive ranges', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture.slice(0, 3));
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const bars = await storage.getHistoricalBars(
|
||||
identity.eodSearchCode,
|
||||
start,
|
||||
new Date(start.getTime() + 86400000),
|
||||
'1d'
|
||||
);
|
||||
expect(bars).toHaveLength(1);
|
||||
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T00:00:00.000Z');
|
||||
await expect(
|
||||
storage.getHistoricalBars(
|
||||
identity.eodSearchCode,
|
||||
new Date(start.getTime() + 3600000),
|
||||
end,
|
||||
'1d'
|
||||
)
|
||||
).rejects.toThrow('UTC midnight');
|
||||
await expect(
|
||||
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, date: '2024-02-30' }])
|
||||
).rejects.toThrow('Invalid OHLCV');
|
||||
});
|
||||
|
||||
test('dataset hashes survive JSON key reordering and reject tampering or mismatched requests', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const first = await loadDataset(storage, datasetConfig());
|
||||
const reordered = JSON.parse(JSON.stringify(first), (_key, value) =>
|
||||
value && !Array.isArray(value) && typeof value === 'object'
|
||||
? Object.fromEntries(Object.entries(value).reverse())
|
||||
: value
|
||||
);
|
||||
expect(validateDataset(reordered, datasetConfig())).toEqual(first);
|
||||
const changed = structuredClone(first);
|
||||
changed.bars[0]!.volume++;
|
||||
expect(() => validateDataset(changed)).toThrow('hash/content');
|
||||
expect(() =>
|
||||
validateDataset(first, { ...datasetConfig(), symbols: ['FIXTURE.OTHER'] })
|
||||
).toThrow('does not match');
|
||||
expect(() =>
|
||||
validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) })
|
||||
).toThrow('does not match');
|
||||
});
|
||||
test('replays stored provider fixtures and produces identical trades and metrics', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
|
|
@ -76,7 +250,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
name: 'Fixed replay',
|
||||
symbols: ['FIXTURE'],
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
|
|
@ -98,6 +272,28 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
|
||||
test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const other = { ...identity, exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' };
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
await persistEodPrices(mongodb, other, fixture);
|
||||
const config = {
|
||||
...datasetConfig(),
|
||||
symbols: [identity.eodSearchCode, other.eodSearchCode],
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
};
|
||||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
for (const id of config.symbols) {
|
||||
expect(first.ohlcData[id]).toHaveLength(fixture.length);
|
||||
expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime());
|
||||
}
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
});
|
||||
|
||||
test('rejects malformed provider records before writing anything', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
await expect(
|
||||
|
|
@ -108,7 +304,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
|
||||
test('missing storage never silently produces synthetic prices', async () => {
|
||||
const storage = new StorageService({ logger }, null, null, null);
|
||||
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
|
||||
await expect(storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).rejects.toThrow(
|
||||
'explicit opt-in'
|
||||
);
|
||||
});
|
||||
|
|
@ -118,8 +314,8 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
allowSyntheticData: true,
|
||||
syntheticSeed: 7,
|
||||
});
|
||||
expect(await storage.getHistoricalBars('FIXTURE', start, end, '1d')).toEqual(
|
||||
await storage.getHistoricalBars('FIXTURE', start, end, '1d')
|
||||
expect(await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).toEqual(
|
||||
await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -128,7 +324,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
symbols: ['FIXTURE'],
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
|
|
@ -142,3 +338,15 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function datasetConfig() {
|
||||
return BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
symbols: [identity.eodSearchCode],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backte
|
|||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
|
|
@ -65,7 +66,11 @@ async function fixture() {
|
|||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id) ON DELETE CASCADE, completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb, execution_time numeric);`);
|
||||
for (const filename of ['09-backtest-run-contract.sql', '10-durable-backtest-dispatch.sql']) {
|
||||
for (const filename of [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
|
|
@ -103,7 +108,7 @@ async function fixture() {
|
|||
{
|
||||
name: 'Durable fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE'],
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
|
|
@ -112,25 +117,33 @@ async function fixture() {
|
|||
{ autoStart: false }
|
||||
);
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
async getHistoricalBars() {
|
||||
history.reads++;
|
||||
if (history.unavailable) {
|
||||
throw new Error('Provider history unavailable');
|
||||
}
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
symbol: 'FIXTURE.TEST',
|
||||
source: 'eod',
|
||||
timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
},
|
||||
} as unknown as StorageService;
|
||||
const engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger,
|
||||
custom: {
|
||||
StorageService: {
|
||||
async getHistoricalBars() {
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
},
|
||||
} as unknown as StorageService,
|
||||
StorageService: storage,
|
||||
},
|
||||
},
|
||||
{ timeoutMs: 5_000 }
|
||||
|
|
@ -189,10 +202,112 @@ async function fixture() {
|
|||
enqueueWorker,
|
||||
snapshot,
|
||||
expire,
|
||||
history,
|
||||
storage,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => {
|
||||
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
PERFORM pg_sleep(0.35); RETURN NEW; END $$;
|
||||
CREATE TRIGGER delay_snapshot BEFORE INSERT ON backtest_datasets FOR EACH ROW EXECUTE FUNCTION delay_snapshot()`);
|
||||
const short = new PostgresBacktestRunRepository(f.postgres, 250);
|
||||
const claim = await short.start(config);
|
||||
await expect(short.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0]
|
||||
.dataset_hash
|
||||
).toBeNull();
|
||||
});
|
||||
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
|
||||
const f = await fixture();
|
||||
const first = await f.runner.runQueued(
|
||||
(await f.api.createRun({ backtestId: f.definition.id })).id
|
||||
);
|
||||
const baseline = (await f.api.getRunResults(first.runId))!;
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadDataset(
|
||||
run.id,
|
||||
old.attemptId,
|
||||
baseline.config.dataset!.hash
|
||||
);
|
||||
expect(frozen?.bars).toHaveLength(70);
|
||||
await f.expire(run.id);
|
||||
await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
const reads = f.history.reads;
|
||||
f.history.unavailable = true;
|
||||
await f.dispatcher.tick();
|
||||
await f.runner.runQueued(run.id);
|
||||
const replay = (await f.api.getRunResults(run.id))!;
|
||||
expect(f.history.reads).toBe(reads);
|
||||
expect(replay.config.dataset).toEqual(baseline.config.dataset);
|
||||
expect(replay.trades).toEqual(baseline.trades);
|
||||
expect(replay.metrics).toEqual(baseline.metrics);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_dataset_pointer() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.dataset_hash IS NOT NULL THEN RAISE EXCEPTION 'injected snapshot pointer failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER reject_dataset_pointer BEFORE UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION reject_dataset_pointer()`);
|
||||
await expect(f.repository.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow(
|
||||
'injected'
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0]
|
||||
.dataset_hash
|
||||
).toBeNull();
|
||||
await f.pool.query('DROP TRIGGER reject_dataset_pointer ON runs');
|
||||
await f.repository.freezeDataset(run.id, claim.attemptId, dataset);
|
||||
const different = await loadDataset(f.storage, {
|
||||
...config,
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
endDate: '2024-03-16T00:00:00.000Z',
|
||||
});
|
||||
await expect(f.repository.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow(
|
||||
'already frozen'
|
||||
);
|
||||
expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe(
|
||||
dataset.manifest.hash
|
||||
);
|
||||
});
|
||||
|
||||
test('an explicit dataset replay rejects a different listing or date range', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.runner.runQueued(run.id);
|
||||
const result = (await f.api.getRunResults(run.id))!;
|
||||
await expect(
|
||||
f.runner.runBacktest({
|
||||
...(await f.snapshot(run.id)),
|
||||
runId: undefined,
|
||||
endDate: '2024-03-16T00:00:00.000Z',
|
||||
datasetHash: result.config.dataset!.hash,
|
||||
})
|
||||
).rejects.toThrow('does not match');
|
||||
});
|
||||
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
||||
const f = await fixture();
|
||||
await f.pool
|
||||
|
|
@ -218,7 +333,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
).toHaveLength(1);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
config: { fastPeriod: 999 },
|
||||
symbols: ['MUTATED'],
|
||||
symbols: ['MUTATED.TEST'],
|
||||
});
|
||||
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
|
||||
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
|
||||
|
|
@ -227,7 +342,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
expect(result?.config.symbols).toEqual(['FIXTURE']);
|
||||
expect(result?.config.symbols).toEqual(['FIXTURE.TEST']);
|
||||
expect(result?.config.parameters.fastPeriod).toBe(3);
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
|
@ -288,6 +403,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash);
|
||||
await f.repository.complete(result, replacement.attemptId);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue