moving engine to rust
This commit is contained in:
parent
d14380d740
commit
16ac28a565
16 changed files with 1598 additions and 3 deletions
424
apps/stock/core/src/backtest/engine.rs
Normal file
424
apps/stock/core/src/backtest/engine.rs
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use crate::{
|
||||
TradingMode, MarketDataSource, ExecutionHandler, TimeProvider,
|
||||
MarketUpdate, MarketDataType, Order, Fill, Side,
|
||||
positions::PositionTracker,
|
||||
risk::RiskEngine,
|
||||
orderbook::OrderBookManager,
|
||||
};
|
||||
|
||||
use super::{
|
||||
BacktestConfig, BacktestState, EventQueue, BacktestEvent, EventType,
|
||||
Strategy, Signal, SignalType, BacktestResult,
|
||||
};
|
||||
|
||||
pub struct BacktestEngine {
|
||||
config: BacktestConfig,
|
||||
state: Arc<RwLock<BacktestState>>,
|
||||
event_queue: Arc<RwLock<EventQueue>>,
|
||||
strategies: Arc<RwLock<Vec<Box<dyn Strategy>>>>,
|
||||
|
||||
// Core components
|
||||
position_tracker: Arc<PositionTracker>,
|
||||
risk_engine: Arc<RiskEngine>,
|
||||
orderbook_manager: Arc<OrderBookManager>,
|
||||
time_provider: Arc<Box<dyn TimeProvider>>,
|
||||
market_data_source: Arc<RwLock<Box<dyn MarketDataSource>>>,
|
||||
execution_handler: Arc<RwLock<Box<dyn ExecutionHandler>>>,
|
||||
|
||||
// Metrics
|
||||
total_trades: usize,
|
||||
profitable_trades: usize,
|
||||
total_pnl: f64,
|
||||
}
|
||||
|
||||
impl BacktestEngine {
|
||||
pub fn new(
|
||||
config: BacktestConfig,
|
||||
mode: TradingMode,
|
||||
time_provider: Box<dyn TimeProvider>,
|
||||
market_data_source: Box<dyn MarketDataSource>,
|
||||
execution_handler: Box<dyn ExecutionHandler>,
|
||||
) -> Self {
|
||||
let state = Arc::new(RwLock::new(
|
||||
BacktestState::new(config.initial_capital, config.start_time)
|
||||
));
|
||||
|
||||
Self {
|
||||
config,
|
||||
state,
|
||||
event_queue: Arc::new(RwLock::new(EventQueue::new())),
|
||||
strategies: Arc::new(RwLock::new(Vec::new())),
|
||||
position_tracker: Arc::new(PositionTracker::new()),
|
||||
risk_engine: Arc::new(RiskEngine::new()),
|
||||
orderbook_manager: Arc::new(OrderBookManager::new()),
|
||||
time_provider: Arc::new(time_provider),
|
||||
market_data_source: Arc::new(RwLock::new(market_data_source)),
|
||||
execution_handler: Arc::new(RwLock::new(execution_handler)),
|
||||
total_trades: 0,
|
||||
profitable_trades: 0,
|
||||
total_pnl: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_strategy(&mut self, strategy: Box<dyn Strategy>) {
|
||||
self.strategies.write().push(strategy);
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Result<BacktestResult, String> {
|
||||
// Initialize start time
|
||||
if let Some(simulated_time) = self.time_provider.as_any()
|
||||
.downcast_ref::<crate::core::time_providers::SimulatedTime>()
|
||||
{
|
||||
simulated_time.advance_to(self.config.start_time);
|
||||
}
|
||||
|
||||
// Load market data
|
||||
self.load_market_data().await?;
|
||||
|
||||
// Main event loop
|
||||
while !self.event_queue.read().is_empty() ||
|
||||
self.time_provider.now() < self.config.end_time
|
||||
{
|
||||
// Get next batch of events
|
||||
let current_time = self.time_provider.now();
|
||||
let events = self.event_queue.write().pop_until(current_time);
|
||||
|
||||
for event in events {
|
||||
self.process_event(event).await?;
|
||||
}
|
||||
|
||||
// Update portfolio value
|
||||
self.update_portfolio_value();
|
||||
|
||||
// Check if we should advance time
|
||||
if self.event_queue.read().is_empty() {
|
||||
// Advance to next data point or end time
|
||||
if let Some(next_time) = self.get_next_event_time() {
|
||||
if next_time < self.config.end_time {
|
||||
self.advance_time(next_time);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate results
|
||||
Ok(self.generate_results())
|
||||
}
|
||||
|
||||
async fn load_market_data(&mut self) -> Result<(), String> {
|
||||
let mut data_source = self.market_data_source.write();
|
||||
|
||||
// Seek to start time
|
||||
data_source.seek_to_time(self.config.start_time)?;
|
||||
|
||||
// Load all data into event queue
|
||||
while let Some(update) = data_source.get_next_update().await {
|
||||
if update.timestamp > self.config.end_time {
|
||||
break;
|
||||
}
|
||||
|
||||
let event = BacktestEvent::market_data(update.timestamp, update);
|
||||
self.event_queue.write().push(event);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn process_event(&mut self, event: BacktestEvent) -> Result<(), String> {
|
||||
match event.event_type {
|
||||
EventType::MarketData(data) => {
|
||||
self.process_market_data(data).await?;
|
||||
}
|
||||
EventType::OrderSubmitted(order) => {
|
||||
self.process_order_submission(order).await?;
|
||||
}
|
||||
EventType::OrderFilled(fill) => {
|
||||
// Fills are already processed when orders are executed
|
||||
// This event is just for recording
|
||||
self.state.write().record_fill(fill);
|
||||
}
|
||||
EventType::OrderCancelled(order_id) => {
|
||||
self.process_order_cancellation(&order_id)?;
|
||||
}
|
||||
EventType::TimeUpdate(time) => {
|
||||
self.advance_time(time);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn process_market_data(&mut self, data: MarketUpdate) -> Result<(), String> {
|
||||
// Update orderbook if it's quote data
|
||||
match &data.data {
|
||||
MarketDataType::Quote(quote) => {
|
||||
// For now, skip orderbook updates
|
||||
// self.orderbook_manager.update_quote(&data.symbol, quote.bid, quote.ask);
|
||||
}
|
||||
MarketDataType::Trade(trade) => {
|
||||
// For now, skip orderbook updates
|
||||
// self.orderbook_manager.update_last_trade(&data.symbol, trade.price, trade.size);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Convert to simpler MarketData for strategies
|
||||
let market_data = self.convert_to_market_data(&data);
|
||||
|
||||
// Send to strategies
|
||||
let mut all_signals = Vec::new();
|
||||
{
|
||||
let mut strategies = self.strategies.write();
|
||||
for strategy in strategies.iter_mut() {
|
||||
let signals = strategy.on_market_data(&market_data);
|
||||
all_signals.extend(signals);
|
||||
}
|
||||
}
|
||||
|
||||
// Process signals
|
||||
for signal in all_signals {
|
||||
self.process_signal(signal).await?;
|
||||
}
|
||||
|
||||
// Check pending orders for fills
|
||||
self.check_pending_orders(&data).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_to_market_data(&self, update: &MarketUpdate) -> MarketUpdate {
|
||||
// MarketData is a type alias for MarketUpdate
|
||||
update.clone()
|
||||
}
|
||||
|
||||
async fn process_signal(&mut self, signal: Signal) -> Result<(), String> {
|
||||
// Only process strong signals
|
||||
if signal.strength.abs() < 0.7 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Convert signal to order
|
||||
let order = self.signal_to_order(signal)?;
|
||||
|
||||
// Submit order
|
||||
self.process_order_submission(order).await
|
||||
}
|
||||
|
||||
fn signal_to_order(&self, signal: Signal) -> Result<Order, String> {
|
||||
let quantity = signal.quantity.unwrap_or_else(|| {
|
||||
// Calculate position size based on portfolio
|
||||
self.calculate_position_size(&signal.symbol, signal.strength)
|
||||
});
|
||||
|
||||
let side = match signal.signal_type {
|
||||
SignalType::Buy => Side::Buy,
|
||||
SignalType::Sell => Side::Sell,
|
||||
SignalType::Close => {
|
||||
// Determine side based on current position
|
||||
let position = self.position_tracker.get_position(&signal.symbol);
|
||||
if position.as_ref().map(|p| p.quantity > 0.0).unwrap_or(false) {
|
||||
Side::Sell
|
||||
} else {
|
||||
Side::Buy
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(crate::Order {
|
||||
id: format!("order_{}", uuid::Uuid::new_v4()),
|
||||
symbol: signal.symbol,
|
||||
side,
|
||||
quantity,
|
||||
order_type: crate::OrderType::Market,
|
||||
time_in_force: crate::TimeInForce::Day,
|
||||
})
|
||||
}
|
||||
|
||||
async fn process_order_submission(&mut self, order: Order) -> Result<(), String> {
|
||||
// Risk checks
|
||||
// Get current position for the symbol
|
||||
let current_position = self.position_tracker
|
||||
.get_position(&order.symbol)
|
||||
.map(|p| p.quantity);
|
||||
|
||||
let risk_check = self.risk_engine.check_order(&order, current_position);
|
||||
if !risk_check.passed {
|
||||
return Err(format!("Risk check failed: {:?}", risk_check.violations));
|
||||
}
|
||||
|
||||
// Add to pending orders
|
||||
self.state.write().add_pending_order(order.clone());
|
||||
|
||||
// For market orders in backtesting, fill immediately
|
||||
if matches!(order.order_type, crate::OrderType::Market) {
|
||||
self.check_order_fill(&order).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn check_pending_orders(&mut self, market_data: &MarketUpdate) -> Result<(), String> {
|
||||
let orders_to_check: Vec<Order> = {
|
||||
let state = self.state.read();
|
||||
state.pending_orders.values()
|
||||
.filter(|o| o.symbol == market_data.symbol)
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
|
||||
for order in orders_to_check {
|
||||
self.check_order_fill(&order).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn check_order_fill(&mut self, order: &Order) -> Result<(), String> {
|
||||
// Get current market price
|
||||
// For now, use a simple fill model with last known price
|
||||
// In a real backtest, this would use orderbook data
|
||||
let base_price = 100.0; // TODO: Get from market data
|
||||
|
||||
// Apply slippage
|
||||
let fill_price = match order.side {
|
||||
crate::Side::Buy => base_price * (1.0 + self.config.slippage),
|
||||
crate::Side::Sell => base_price * (1.0 - self.config.slippage),
|
||||
};
|
||||
|
||||
// Create fill
|
||||
let fill = crate::Fill {
|
||||
timestamp: self.time_provider.now(),
|
||||
price: fill_price,
|
||||
quantity: order.quantity,
|
||||
commission: order.quantity * fill_price * self.config.commission,
|
||||
};
|
||||
|
||||
// Process the fill
|
||||
self.process_fill(&order, fill).await
|
||||
}
|
||||
|
||||
async fn process_fill(&mut self, order: &crate::Order, fill: crate::Fill) -> Result<(), String> {
|
||||
// Remove from pending orders
|
||||
self.state.write().remove_pending_order(&order.id);
|
||||
|
||||
// Update positions
|
||||
let update = self.position_tracker.process_fill(
|
||||
&order.symbol,
|
||||
&fill,
|
||||
order.side,
|
||||
);
|
||||
|
||||
// Record the fill
|
||||
self.state.write().record_fill(fill.clone());
|
||||
|
||||
// Update cash
|
||||
let cash_change = match order.side {
|
||||
crate::Side::Buy => -(fill.quantity * fill.price + fill.commission),
|
||||
crate::Side::Sell => fill.quantity * fill.price - fill.commission,
|
||||
};
|
||||
self.state.write().cash += cash_change;
|
||||
|
||||
// Notify strategies
|
||||
{
|
||||
let mut strategies = self.strategies.write();
|
||||
for strategy in strategies.iter_mut() {
|
||||
strategy.on_fill(&order.symbol, fill.quantity, fill.price,
|
||||
&format!("{:?}", order.side));
|
||||
}
|
||||
}
|
||||
|
||||
// Update metrics
|
||||
self.total_trades += 1;
|
||||
if update.resulting_position.realized_pnl > 0.0 {
|
||||
self.profitable_trades += 1;
|
||||
}
|
||||
self.total_pnl = update.resulting_position.realized_pnl;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_order_cancellation(&mut self, order_id: &str) -> Result<(), String> {
|
||||
self.state.write().remove_pending_order(order_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn advance_time(&mut self, time: DateTime<Utc>) {
|
||||
if let Some(simulated_time) = self.time_provider.as_any()
|
||||
.downcast_ref::<crate::core::time_providers::SimulatedTime>()
|
||||
{
|
||||
simulated_time.advance_to(time);
|
||||
}
|
||||
self.state.write().current_time = time;
|
||||
}
|
||||
|
||||
fn update_portfolio_value(&mut self) {
|
||||
let positions = self.position_tracker.get_all_positions();
|
||||
let mut portfolio_value = self.state.read().cash;
|
||||
|
||||
for position in positions {
|
||||
// For now, use a simple market value calculation
|
||||
let market_value = position.quantity * 100.0; // TODO: Get actual price
|
||||
portfolio_value += market_value;
|
||||
}
|
||||
|
||||
self.state.write().update_portfolio_value(portfolio_value);
|
||||
}
|
||||
|
||||
fn calculate_position_size(&self, symbol: &str, signal_strength: f64) -> f64 {
|
||||
let portfolio_value = self.state.read().portfolio_value;
|
||||
let allocation = 0.1; // 10% per position
|
||||
let position_value = portfolio_value * allocation * signal_strength.abs();
|
||||
let price = 100.0; // TODO: Get actual price from market data
|
||||
|
||||
(position_value / price).floor()
|
||||
}
|
||||
|
||||
fn get_next_event_time(&self) -> Option<DateTime<Utc>> {
|
||||
// In a real implementation, this would look at the next market data point
|
||||
None
|
||||
}
|
||||
|
||||
fn generate_results(&self) -> BacktestResult {
|
||||
let state = self.state.read();
|
||||
let (realized_pnl, unrealized_pnl) = self.position_tracker.get_total_pnl();
|
||||
let total_pnl = realized_pnl + unrealized_pnl;
|
||||
let total_return = (total_pnl / self.config.initial_capital) * 100.0;
|
||||
|
||||
BacktestResult {
|
||||
config: self.config.clone(),
|
||||
metrics: super::BacktestMetrics {
|
||||
total_return,
|
||||
total_trades: self.total_trades,
|
||||
profitable_trades: self.profitable_trades,
|
||||
win_rate: if self.total_trades > 0 {
|
||||
(self.profitable_trades as f64 / self.total_trades as f64) * 100.0
|
||||
} else { 0.0 },
|
||||
profit_factor: 0.0, // TODO: Calculate properly
|
||||
sharpe_ratio: 0.0, // TODO: Calculate properly
|
||||
max_drawdown: 0.0, // TODO: Calculate properly
|
||||
total_pnl,
|
||||
avg_win: 0.0, // TODO: Calculate properly
|
||||
avg_loss: 0.0, // TODO: Calculate properly
|
||||
},
|
||||
equity_curve: state.equity_curve.clone(),
|
||||
trades: state.completed_trades.clone(),
|
||||
final_positions: self.position_tracker.get_all_positions()
|
||||
.into_iter()
|
||||
.map(|p| (p.symbol.clone(), p))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add uuid dependency
|
||||
use uuid::Uuid;
|
||||
Loading…
Add table
Add a link
Reference in a new issue