fix(engine): reconcile terminal equity after closing fees
This commit is contained in:
parent
1148673245
commit
74ba3b97f5
2 changed files with 307 additions and 0 deletions
|
|
@ -145,6 +145,9 @@ impl BacktestEngine {
|
|||
// Close all open positions at market prices
|
||||
self.close_all_positions().await?;
|
||||
|
||||
// Include closing costs in the final mark, replacing the same-time sample.
|
||||
self.update_portfolio_value();
|
||||
|
||||
// Generate results
|
||||
Ok(self.generate_results())
|
||||
}
|
||||
|
|
@ -690,3 +693,257 @@ impl BacktestEngine {
|
|||
|
||||
// Add uuid dependency
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(test)]
|
||||
mod terminal_valuation_tests {
|
||||
use super::*;
|
||||
use crate::core::{
|
||||
execution_handlers::{BacktestFillSimulator, SimulatedExecution},
|
||||
market_data_sources::HistoricalDataSource,
|
||||
time_providers::SimulatedTime,
|
||||
};
|
||||
use chrono::{Duration, TimeZone};
|
||||
|
||||
struct FixedEntries {
|
||||
quantities: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
impl Strategy for FixedEntries {
|
||||
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
|
||||
self.quantities
|
||||
.remove(&data.symbol)
|
||||
.map(|quantity| Signal {
|
||||
symbol: data.symbol.clone(),
|
||||
signal_type: SignalType::Buy,
|
||||
strength: 1.0,
|
||||
quantity: Some(quantity),
|
||||
reason: None,
|
||||
metadata: None,
|
||||
})
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn on_fill(&mut self, _: &str, _: f64, _: f64, _: &str) {}
|
||||
|
||||
fn get_name(&self) -> &str {
|
||||
"fixed-terminal-entries"
|
||||
}
|
||||
|
||||
fn get_parameters(&self) -> serde_json::Value {
|
||||
serde_json::json!({})
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture(
|
||||
commission: f64,
|
||||
entries: &[(&str, f64)],
|
||||
prices: &[(&str, f64, f64)],
|
||||
single_start_time: bool,
|
||||
) -> BacktestEngine {
|
||||
let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
|
||||
let end_time = if single_start_time {
|
||||
start_time
|
||||
} else {
|
||||
start_time + Duration::days(2)
|
||||
};
|
||||
let config = BacktestConfig {
|
||||
name: "Terminal valuation".to_string(),
|
||||
strategy: None,
|
||||
symbols: prices
|
||||
.iter()
|
||||
.map(|(symbol, _, _)| symbol.to_string())
|
||||
.collect(),
|
||||
start_time,
|
||||
end_time,
|
||||
initial_capital: 10.0,
|
||||
commission,
|
||||
slippage: 0.0,
|
||||
data_frequency: "1d".to_string(),
|
||||
};
|
||||
let mut updates = Vec::new();
|
||||
for &(symbol, entry, terminal) in prices {
|
||||
let observations = if single_start_time {
|
||||
vec![(start_time, entry)]
|
||||
} else {
|
||||
vec![
|
||||
(start_time + Duration::days(1), entry),
|
||||
(end_time, terminal),
|
||||
]
|
||||
};
|
||||
for (timestamp, price) in observations {
|
||||
updates.push(MarketUpdate {
|
||||
symbol: symbol.to_string(),
|
||||
timestamp,
|
||||
data: MarketDataType::Bar(crate::Bar {
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 1000.0,
|
||||
vwap: Some(price),
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
updates.sort_by_key(|update| update.timestamp);
|
||||
let source = HistoricalDataSource::new();
|
||||
source.load_data(updates);
|
||||
let mut engine = BacktestEngine::new(
|
||||
config,
|
||||
TradingMode::Backtest {
|
||||
start_time,
|
||||
end_time,
|
||||
speed_multiplier: 1.0,
|
||||
},
|
||||
Box::new(SimulatedTime::new(start_time)),
|
||||
Box::new(source),
|
||||
Box::new(SimulatedExecution::new(Box::new(
|
||||
BacktestFillSimulator::new(),
|
||||
))),
|
||||
);
|
||||
engine.add_strategy(Box::new(FixedEntries {
|
||||
quantities: entries
|
||||
.iter()
|
||||
.map(|&(symbol, quantity)| (symbol.to_string(), quantity))
|
||||
.collect(),
|
||||
}));
|
||||
engine
|
||||
}
|
||||
|
||||
fn assert_amount(actual: f64, expected: f64) {
|
||||
assert!(
|
||||
(actual - expected).abs() < 1e-10,
|
||||
"expected {expected}, got {actual}"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_terminal(
|
||||
engine: &BacktestEngine,
|
||||
result: &BacktestResult,
|
||||
cash: f64,
|
||||
equity: f64,
|
||||
fees: f64,
|
||||
fills: usize,
|
||||
) {
|
||||
let state = engine.state.read();
|
||||
assert_amount(state.cash, cash);
|
||||
assert_amount(state.portfolio_value, equity);
|
||||
assert_amount(state.equity_curve.last().unwrap().1, equity);
|
||||
assert_amount(result.equity.last().unwrap().value, equity);
|
||||
assert_amount(result.metrics.final_value, equity);
|
||||
assert_amount(result.metrics.total_pnl, equity - 10.0);
|
||||
assert_amount(result.trades.iter().map(|fill| fill.commission).sum(), fees);
|
||||
assert_eq!(state.completed_trades.len(), fills);
|
||||
assert_eq!(result.trades.len(), fills);
|
||||
assert_eq!(
|
||||
state
|
||||
.equity_curve
|
||||
.iter()
|
||||
.filter(|(time, _)| *time == state.current_time)
|
||||
.count(),
|
||||
1,
|
||||
);
|
||||
assert!(state
|
||||
.equity_curve
|
||||
.windows(2)
|
||||
.all(|points| points[0].0 < points[1].0));
|
||||
assert!(result
|
||||
.equity
|
||||
.windows(2)
|
||||
.all(|points| points[0].date < points[1].date));
|
||||
assert_eq!(
|
||||
result.equity.last().unwrap().date,
|
||||
state.current_time.to_rfc3339()
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_flat(engine: &BacktestEngine, result: &BacktestResult) {
|
||||
assert!(engine
|
||||
.position_tracker
|
||||
.get_all_positions()
|
||||
.iter()
|
||||
.all(|p| p.quantity == 0.0));
|
||||
assert!(result.positions.iter().all(|p| p.quantity == 0.0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_fee_equity() {
|
||||
let mut engine = fixture(0.01, &[("A", 1.0)], &[("A", 4.0, 4.0)], false);
|
||||
let result = engine.run().await.unwrap();
|
||||
// 10 - (4 + 0.04) + (4 - 0.04) = 9.92.
|
||||
assert_terminal(&engine, &result, 9.92, 9.92, 0.08, 2);
|
||||
assert_flat(&engine, &result);
|
||||
assert_eq!(result.metrics.total_trades, 1);
|
||||
assert_amount(result.metrics.max_drawdown, 0.008);
|
||||
assert_amount(result.trades[0].quantity, 1.0);
|
||||
assert_amount(result.trades[1].quantity, 1.0);
|
||||
assert_amount(result.trades[0].commission, 0.04);
|
||||
assert_amount(result.trades[1].commission, 0.04);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_no_positions() {
|
||||
let mut engine = fixture(0.01, &[], &[("A", 4.0, 4.0)], false);
|
||||
let result = engine.run().await.unwrap();
|
||||
assert_terminal(&engine, &result, 10.0, 10.0, 0.0, 0);
|
||||
assert_flat(&engine, &result);
|
||||
assert_eq!(result.metrics.total_trades, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_zero_fee() {
|
||||
let mut engine = fixture(0.0, &[("A", 1.0)], &[("A", 4.0, 5.0)], false);
|
||||
let result = engine.run().await.unwrap();
|
||||
assert_terminal(&engine, &result, 11.0, 11.0, 0.0, 2);
|
||||
assert_flat(&engine, &result);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_multiple_symbols() {
|
||||
let mut engine = fixture(
|
||||
0.01,
|
||||
&[("A", 1.0), ("B", 1.0)],
|
||||
&[("A", 4.0, 5.0), ("B", 2.0, 3.0)],
|
||||
false,
|
||||
);
|
||||
let result = engine.run().await.unwrap();
|
||||
// Gross gain 2, entry fees 0.06, closing fees 0.08.
|
||||
assert_terminal(&engine, &result, 11.86, 11.86, 0.14, 4);
|
||||
assert_flat(&engine, &result);
|
||||
assert_eq!(result.metrics.total_trades, 2);
|
||||
for (symbol, exit_price) in [("A", 5.0), ("B", 3.0)] {
|
||||
let closing: Vec<_> = result
|
||||
.trades
|
||||
.iter()
|
||||
.filter(|fill| fill.symbol == symbol && fill.side == "sell")
|
||||
.collect();
|
||||
assert_eq!(closing.len(), 1);
|
||||
assert_amount(closing[0].price, exit_price);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_timestamp_unique() {
|
||||
// At the initial timestamp, the event loop has not written another mark.
|
||||
let mut engine = fixture(0.01, &[("A", 1.0)], &[("A", 4.0, 4.0)], true);
|
||||
let result = engine.run().await.unwrap();
|
||||
assert_terminal(&engine, &result, 9.92, 9.92, 0.08, 2);
|
||||
assert_eq!(result.equity.len(), 1);
|
||||
assert_flat(&engine, &result);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_preserves_marked_micro_position() {
|
||||
let mut engine = fixture(0.01, &[("A", 0.001)], &[("A", 4.0, 8.0)], false);
|
||||
let result = engine.run().await.unwrap();
|
||||
// Existing liquidation policy retains quantities <= 0.001.
|
||||
assert_terminal(&engine, &result, 9.99596, 10.00396, 0.00004, 1);
|
||||
let position = engine.position_tracker.get_position("A").unwrap();
|
||||
assert_amount(position.quantity, 0.001);
|
||||
assert_amount(
|
||||
result.metrics.final_value,
|
||||
engine.state.read().cash + 0.001 * 8.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
50
test/integration/native-terminal-equity.test.ts
Normal file
50
test/integration/native-terminal-equity.test.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { nativeResultSchema } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
|
||||
test('native terminal liquidation reports both commissions in final equity', () => {
|
||||
const start = Date.parse('2024-01-01T00:00:00Z');
|
||||
const end = start + 3 * 86_400_000;
|
||||
const engine = new BacktestEngine({
|
||||
name: 'Terminal fee regression',
|
||||
symbols: ['A.US'],
|
||||
startDate: new Date(start).toISOString(),
|
||||
endDate: new Date(end).toISOString(),
|
||||
initialCapital: 10,
|
||||
commission: 0.01,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
engine.addNativeStrategy('sma_crossover', 'fixed-share SMA', 'terminal-fixture', {
|
||||
fastPeriod: 1,
|
||||
slowPeriod: 2,
|
||||
quantity: 1,
|
||||
});
|
||||
// The crossover buys exactly one share at 4 on day 3. Day 4 leaves it open
|
||||
// for terminal liquidation, also at 4; no production sizing is inferred.
|
||||
engine.loadMarketData(
|
||||
[4, 3, 4, 4].map((price, index) => ({
|
||||
symbol: 'A.US',
|
||||
timestamp: start + index * 86_400_000,
|
||||
type: 'bar',
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 1_000,
|
||||
vwap: price,
|
||||
}))
|
||||
);
|
||||
|
||||
const result = nativeResultSchema.parse(JSON.parse(engine.run()));
|
||||
expect(result.trades).toHaveLength(2);
|
||||
expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 1, price: 4 });
|
||||
expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 1, price: 4 });
|
||||
expect(Date.parse(result.trades[1]!.timestamp)).toBe(end);
|
||||
expect(result.trades.reduce((sum, fill) => sum + fill.commission, 0)).toBeCloseTo(0.08, 10);
|
||||
expect(result.metrics.finalValue).toBeCloseTo(9.92, 10);
|
||||
expect(result.equity.at(-1)!.value).toBeCloseTo(9.92, 10);
|
||||
expect(result.positions.every(position => position.quantity === 0)).toBe(true);
|
||||
expect(result.equity.filter(point => Date.parse(point.date) === end)).toHaveLength(1);
|
||||
expect(new Set(result.equity.map(point => point.date)).size).toBe(result.equity.length);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue