Compare commits

...

16 Commits

Author SHA1 Message Date
boris 0cfb7625bf 修正回测指标和成交时间口径 2026-06-14 01:08:29 +08:00
boris 4c3653e009 修正AiQuant兼容回测盘中估值口径 2026-06-13 23:32:24 +08:00
boris 9512a5dd2f 修正点时刻执行报价口径 2026-06-13 21:55:08 +08:00
boris 4f5e3f7162 统一调度时刻使用已知tick 2026-06-13 21:41:37 +08:00
boris 89c2ff58f8 修正点时刻回测使用最新tick 2026-06-13 21:27:21 +08:00
boris 0813ce3ffb 修正目标市值盘中估值口径 2026-06-13 21:09:38 +08:00
boris a030554ab6 修正平台策略滚动量能口径 2026-06-13 20:48:52 +08:00
boris e1d36fc0c7 修正平台表达式回测口径 2026-06-13 20:01:24 +08:00
boris 0dca8e0eff 完善策略调度执行价校验 2026-06-13 15:26:56 +08:00
boris 4cf90d83a3 修复执行价索引和平台表达式回退 2026-06-12 23:46:44 +08:00
boris 9b4462f880 修正策略止盈止损和补仓投影 2026-05-28 18:40:32 +08:00
boris 87b7b2642d 修正策略投影tick依赖 2026-05-28 18:17:33 +08:00
boris 5eee5c7c63 缩小tick查询到实际订单 2026-05-28 17:45:00 +08:00
boris c6dc1d1474 修正回测执行时tick取价 2026-05-28 17:32:40 +08:00
boris 8c86918970 修正微盘买入预算与表达式性能 2026-05-28 10:39:43 +08:00
boris 200d5d1f41 完善平台策略回测撮合和滑点 2026-05-28 08:59:14 +08:00
12 changed files with 4550 additions and 749 deletions
+522 -87
View File
@@ -80,12 +80,68 @@ pub enum MatchingType {
Twap, Twap,
} }
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DynamicSlippageConfig {
pub impact_coefficient: f64,
pub volatility_coefficient: f64,
pub max_ratio: f64,
}
impl DynamicSlippageConfig {
pub fn new(impact_coefficient: f64, volatility_coefficient: f64, max_ratio: f64) -> Self {
Self {
impact_coefficient: impact_coefficient.max(0.0),
volatility_coefficient: volatility_coefficient.max(0.0),
max_ratio: max_ratio.max(0.0),
}
}
fn ratio(
&self,
snapshot: &crate::data::DailyMarketSnapshot,
raw_price: f64,
order_value: Option<f64>,
) -> f64 {
let daily_amount = (snapshot.volume as f64 * raw_price).max(0.0);
let impact_ratio = match order_value {
Some(value) if value.is_finite() && value > 0.0 && daily_amount > 0.0 => {
value / daily_amount
}
_ => 0.0,
};
let volatility_base = if snapshot.prev_close.is_finite() && snapshot.prev_close > 0.0 {
snapshot.prev_close
} else {
raw_price
};
let volatility = if snapshot.high.is_finite()
&& snapshot.low.is_finite()
&& volatility_base.is_finite()
&& volatility_base > 0.0
{
((snapshot.high - snapshot.low).abs() / volatility_base).max(0.0)
} else {
0.0
};
let ratio =
impact_ratio * self.impact_coefficient + volatility * self.volatility_coefficient;
ratio.clamp(0.0, self.max_ratio)
}
}
impl Default for DynamicSlippageConfig {
fn default() -> Self {
Self::new(0.5, 0.3, 0.01)
}
}
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub enum SlippageModel { pub enum SlippageModel {
None, None,
PriceRatio(f64), PriceRatio(f64),
TickSize(f64), TickSize(f64),
LimitPrice, LimitPrice,
Dynamic(DynamicSlippageConfig),
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -235,6 +291,10 @@ impl<C, R> BrokerSimulator<C, R> {
self.execution_price_field self.execution_price_field
} }
pub fn intraday_execution_start_time(&self) -> Option<NaiveTime> {
self.intraday_execution_start_time
}
pub fn open_order_views(&self) -> Vec<OpenOrderView> { pub fn open_order_views(&self) -> Vec<OpenOrderView> {
self.open_orders self.open_orders
.borrow() .borrow()
@@ -280,32 +340,66 @@ where
data: &DataSet, data: &DataSet,
symbol: &str, symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot, snapshot: &crate::data::DailyMarketSnapshot,
) -> f64 {
self.value_order_sizing_price(date, data, symbol, snapshot, OrderSide::Buy)
}
fn value_sell_sizing_price(
&self,
date: NaiveDate,
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
) -> f64 {
self.value_order_sizing_price(date, data, symbol, snapshot, OrderSide::Sell)
}
fn target_value_valuation_price(
&self,
date: NaiveDate,
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
) -> f64 {
let _ = (date, data, symbol);
if snapshot.close.is_finite() && snapshot.close > 0.0 {
snapshot.close
} else {
self.sizing_price(snapshot)
}
}
fn value_order_sizing_price(
&self,
date: NaiveDate,
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide,
) -> f64 { ) -> f64 {
let start_cursor = self let start_cursor = self
.runtime_intraday_start_time .runtime_intraday_start_time
.get() .get()
.or(self.intraday_execution_start_time) .or(self.intraday_execution_start_time)
.map(|start_time| date.and_time(start_time)); .map(|start_time| date.and_time(start_time));
data.execution_quotes_on(date, symbol) let matching_type = self.matching_type_for_algo_request(None);
.iter() self.latest_known_quote_at_or_before(
.filter(|quote| { data.execution_quotes_on(date, symbol),
start_cursor start_cursor,
.map(|cursor| quote.timestamp >= cursor) snapshot,
.unwrap_or(true) side,
}) matching_type,
.next() false,
.and_then(|quote| match self.execution_price_field { )
PriceField::Last => (quote.last_price.is_finite() && quote.last_price > 0.0) .and_then(|quote| self.select_quote_reference_price(snapshot, quote, side, matching_type))
.then_some(quote.last_price), .unwrap_or_else(|| self.sizing_price(snapshot))
_ => quote.buy_price(),
})
.unwrap_or_else(|| self.sizing_price(snapshot))
} }
fn snapshot_execution_price( fn snapshot_execution_price(
&self, &self,
snapshot: &crate::data::DailyMarketSnapshot, snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide, side: OrderSide,
quantity: Option<u32>,
) -> f64 { ) -> f64 {
let raw_price = if self.execution_price_field == PriceField::Last let raw_price = if self.execution_price_field == PriceField::Last
&& self.intraday_execution_start_time.is_some() && self.intraday_execution_start_time.is_some()
@@ -319,7 +413,7 @@ where
} }
}; };
self.apply_slippage(snapshot, side, raw_price) self.apply_slippage(snapshot, side, raw_price, quantity)
} }
fn is_open_auction_matching(&self) -> bool { fn is_open_auction_matching(&self) -> bool {
@@ -331,6 +425,7 @@ where
snapshot: &crate::data::DailyMarketSnapshot, snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide, side: OrderSide,
raw_price: f64, raw_price: f64,
quantity: Option<u32>,
) -> f64 { ) -> f64 {
if !raw_price.is_finite() || raw_price <= 0.0 { if !raw_price.is_finite() || raw_price <= 0.0 {
return raw_price; return raw_price;
@@ -340,6 +435,7 @@ where
return self.clamp_execution_price(snapshot, side, raw_price); return self.clamp_execution_price(snapshot, side, raw_price);
} }
let order_value = quantity.and_then(|qty| (qty > 0).then_some(raw_price * qty as f64));
let adjusted = match self.slippage_model { let adjusted = match self.slippage_model {
SlippageModel::None => raw_price, SlippageModel::None => raw_price,
SlippageModel::PriceRatio(ratio) => { SlippageModel::PriceRatio(ratio) => {
@@ -358,6 +454,13 @@ where
} }
} }
SlippageModel::LimitPrice => raw_price, SlippageModel::LimitPrice => raw_price,
SlippageModel::Dynamic(config) => {
let ratio = config.ratio(snapshot, raw_price, order_value);
match side {
OrderSide::Buy => raw_price * (1.0 + ratio),
OrderSide::Sell => raw_price * (1.0 - ratio),
}
}
}; };
self.clamp_execution_price(snapshot, side, adjusted) self.clamp_execution_price(snapshot, side, adjusted)
@@ -394,8 +497,9 @@ where
snapshot: &crate::data::DailyMarketSnapshot, snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide, side: OrderSide,
raw_price: f64, raw_price: f64,
quantity: Option<u32>,
) -> f64 { ) -> f64 {
self.apply_slippage(snapshot, side, raw_price) self.apply_slippage(snapshot, side, raw_price, quantity)
} }
fn matching_type_for_algo_request( fn matching_type_for_algo_request(
@@ -411,7 +515,7 @@ where
fn select_quote_reference_price( fn select_quote_reference_price(
&self, &self,
snapshot: &crate::data::DailyMarketSnapshot, _snapshot: &crate::data::DailyMarketSnapshot,
quote: &IntradayExecutionQuote, quote: &IntradayExecutionQuote,
side: OrderSide, side: OrderSide,
matching_type: MatchingType, matching_type: MatchingType,
@@ -462,9 +566,8 @@ where
OrderSide::Sell => quote.sell_price(), OrderSide::Sell => quote.sell_price(),
}, },
}?; }?;
let execution_price = self.quote_execution_price(snapshot, side, raw_price); if raw_price.is_finite() && raw_price > 0.0 {
if execution_price.is_finite() && execution_price > 0.0 { Some(raw_price)
Some(execution_price)
} else { } else {
None None
} }
@@ -1018,6 +1121,36 @@ where
} }
} }
fn latest_known_quote_at_or_before<'a>(
&self,
quotes: &'a [IntradayExecutionQuote],
cursor: Option<NaiveDateTime>,
snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide,
matching_type: MatchingType,
require_executable_liquidity: bool,
) -> Option<&'a IntradayExecutionQuote> {
let Some(cursor) = cursor else {
return quotes.iter().find(|quote| {
self.select_quote_reference_price(snapshot, quote, side, matching_type)
.is_some()
&& (!require_executable_liquidity
|| self.quote_has_executable_liquidity(quote, side, matching_type))
});
};
quotes
.iter()
.filter(|quote| {
quote.timestamp <= cursor
&& self
.select_quote_reference_price(snapshot, quote, side, matching_type)
.is_some()
&& (!require_executable_liquidity
|| self.quote_has_executable_liquidity(quote, side, matching_type))
})
.max_by_key(|quote| quote.timestamp)
}
fn process_limit_shares( fn process_limit_shares(
&self, &self,
date: NaiveDate, date: NaiveDate,
@@ -2345,7 +2478,8 @@ where
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason); merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
(fill.quantity, fill.legs) (fill.quantity, fill.legs)
} else { } else {
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Sell); let mut execution_price =
self.snapshot_execution_price(snapshot, OrderSide::Sell, Some(fillable_qty));
if let Some(reason) = if let Some(reason) =
self.execution_limit_rejection_reason(snapshot, OrderSide::Sell, execution_price) self.execution_limit_rejection_reason(snapshot, OrderSide::Sell, execution_price)
{ {
@@ -2363,7 +2497,7 @@ where
); );
(0, Vec::new()) (0, Vec::new())
} else { } else {
let execution_price = execution_price =
self.execution_price_with_limit_slippage(execution_price, limit_price); self.execution_price_with_limit_slippage(execution_price, limit_price);
( (
fillable_qty, fillable_qty,
@@ -2606,9 +2740,8 @@ where
commission_state: &mut BTreeMap<u64, f64>, commission_state: &mut BTreeMap<u64, f64>,
report: &mut BrokerExecutionReport, report: &mut BrokerExecutionReport,
) -> Result<(), BacktestError> { ) -> Result<(), BacktestError> {
let price = data let snapshot = data
.market(date, symbol) .market(date, symbol)
.map(|snapshot| self.sizing_price(snapshot))
.ok_or_else(|| BacktestError::MissingPrice { .ok_or_else(|| BacktestError::MissingPrice {
date, date,
symbol: symbol.to_string(), symbol: symbol.to_string(),
@@ -2618,20 +2751,27 @@ where
.position(symbol) .position(symbol)
.map(|pos| pos.quantity) .map(|pos| pos.quantity)
.unwrap_or(0); .unwrap_or(0);
let current_value = price * current_qty as f64;
let target_qty = self.round_buy_quantity(
((target_value.max(0.0)) / price).floor() as u32,
self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
);
if current_qty > target_qty { if target_value <= f64::EPSILON {
if current_qty == 0 {
report.order_events.push(OrderEvent {
date,
order_id: None,
symbol: symbol.to_string(),
side: OrderSide::Sell,
requested_quantity: 0,
filled_quantity: 0,
status: OrderStatus::Filled,
reason: format!("{reason}: already at target value"),
});
return Ok(());
}
self.process_sell( self.process_sell(
date, date,
portfolio, portfolio,
data, data,
symbol, symbol,
current_qty - target_qty, current_qty,
self.reserve_order_id(), self.reserve_order_id(),
reason, reason,
intraday_turnover, intraday_turnover,
@@ -2644,27 +2784,28 @@ where
None, None,
report, report,
)?; )?;
} else if target_qty > current_qty { return Ok(());
self.process_buy( }
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
let current_value = valuation_price * current_qty as f64;
let cash_delta = target_value.max(0.0) - current_value;
if cash_delta.abs() > f64::EPSILON {
self.process_value(
date, date,
portfolio, portfolio,
data, data,
symbol, symbol,
target_qty - current_qty, cash_delta,
self.reserve_order_id(),
reason, reason,
intraday_turnover, intraday_turnover,
execution_cursors, execution_cursors,
global_execution_cursor, global_execution_cursor,
commission_state, commission_state,
None,
None,
false,
true,
None,
report, report,
)?; )?;
} else if (current_value - target_value).abs() <= f64::EPSILON { } else {
report.order_events.push(OrderEvent { report.order_events.push(OrderEvent {
date, date,
order_id: None, order_id: None,
@@ -3071,7 +3212,7 @@ where
report, report,
) )
} else { } else {
let price = self.sizing_price(snapshot); let price = self.value_sell_sizing_price(date, data, symbol, snapshot);
let requested_qty = self.round_buy_quantity( let requested_qty = self.round_buy_quantity(
((value.abs()) / price).floor() as u32, ((value.abs()) / price).floor() as u32,
self.minimum_order_quantity(data, symbol), self.minimum_order_quantity(data, symbol),
@@ -3516,16 +3657,11 @@ where
requested_qty requested_qty
} }
fn value_buy_gross_limit( fn value_buy_gross_limit(&self, value_budget: Option<f64>) -> Option<f64> {
&self,
value_budget: Option<f64>,
requested_qty: u32,
reference_price: f64,
) -> Option<f64> {
if !self.strict_value_budget { if !self.strict_value_budget {
return None; return None;
} }
value_budget.map(|budget| budget.max(reference_price * requested_qty as f64)) value_budget.filter(|budget| budget.is_finite() && *budget > 0.0)
} }
fn process_buy( fn process_buy(
@@ -3684,8 +3820,15 @@ where
return Ok(()); return Ok(());
} }
}; };
let value_gross_limit = let value_gross_limit = self.value_buy_gross_limit(value_budget);
self.value_buy_gross_limit(value_budget, constrained_qty, self.sizing_price(snapshot)); let buy_cash_limit = if self.strict_value_budget {
value_budget
.filter(|budget| budget.is_finite() && *budget > 0.0)
.map(|budget| portfolio.cash().min(budget))
.unwrap_or_else(|| portfolio.cash())
} else {
portfolio.cash()
};
let fill = self.resolve_execution_fill( let fill = self.resolve_execution_fill(
date, date,
@@ -3700,7 +3843,7 @@ where
false, false,
execution_cursors, execution_cursors,
None, None,
Some(portfolio.cash()), Some(buy_cash_limit),
value_gross_limit, value_gross_limit,
algo_request, algo_request,
limit_price, limit_price,
@@ -3714,7 +3857,8 @@ where
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason); merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
(fill.quantity, fill.legs) (fill.quantity, fill.legs)
} else { } else {
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Buy); let mut execution_price =
self.snapshot_execution_price(snapshot, OrderSide::Buy, Some(constrained_qty));
if let Some(reason) = if let Some(reason) =
self.execution_limit_rejection_reason(snapshot, OrderSide::Buy, execution_price) self.execution_limit_rejection_reason(snapshot, OrderSide::Buy, execution_price)
{ {
@@ -3732,22 +3876,28 @@ where
); );
(0, Vec::new()) (0, Vec::new())
} else { } else {
let execution_price = execution_price =
self.execution_price_with_limit_slippage(execution_price, limit_price); self.execution_price_with_limit_slippage(execution_price, limit_price);
let filled_qty = self.affordable_buy_quantity( let filled_qty = self.affordable_buy_quantity(
date, date,
portfolio.cash(), buy_cash_limit,
value_gross_limit, value_gross_limit,
execution_price, execution_price,
constrained_qty, constrained_qty,
self.minimum_order_quantity(data, symbol), self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol), self.order_step_size(data, symbol),
); );
if filled_qty > 0 {
execution_price =
self.snapshot_execution_price(snapshot, OrderSide::Buy, Some(filled_qty));
execution_price =
self.execution_price_with_limit_slippage(execution_price, limit_price);
}
if filled_qty < constrained_qty { if filled_qty < constrained_qty {
partial_fill_reason = merge_partial_fill_reason( partial_fill_reason = merge_partial_fill_reason(
partial_fill_reason, partial_fill_reason,
self.buy_reduction_reason( self.buy_reduction_reason(
portfolio.cash(), buy_cash_limit,
value_gross_limit, value_gross_limit,
execution_price, execution_price,
constrained_qty, constrained_qty,
@@ -4466,6 +4616,7 @@ where
quotes, quotes,
start_cursor, start_cursor,
end_cursor, end_cursor,
matching_type == MatchingType::NextTickLast && start_cursor.is_some(),
)), )),
}); });
} }
@@ -4478,7 +4629,16 @@ where
quotes: &[IntradayExecutionQuote], quotes: &[IntradayExecutionQuote],
start_cursor: Option<NaiveDateTime>, start_cursor: Option<NaiveDateTime>,
end_cursor: Option<NaiveDateTime>, end_cursor: Option<NaiveDateTime>,
use_decision_time_quote: bool,
) -> &'static str { ) -> &'static str {
if use_decision_time_quote {
let saw_quote_at_or_before_start = start_cursor
.is_some_and(|cursor| quotes.iter().any(|quote| quote.timestamp <= cursor));
if saw_quote_at_or_before_start {
return "intraday quote liquidity exhausted";
}
return "no execution quotes at or before start";
}
let saw_quote_in_window = quotes.iter().any(|quote| { let saw_quote_in_window = quotes.iter().any(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor) !start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor) && !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
@@ -4514,15 +4674,30 @@ where
let quote_quantity_limited = let quote_quantity_limited =
self.quote_quantity_limited_for_window(matching_type, start_cursor, end_cursor); self.quote_quantity_limited_for_window(matching_type, start_cursor, end_cursor);
let lot = round_lot.max(1); let lot = round_lot.max(1);
let eligible_quotes: Vec<&IntradayExecutionQuote> = quotes let use_decision_time_quote =
.iter() matching_type == MatchingType::NextTickLast && start_cursor.is_some();
.filter(|quote| { let eligible_quotes: Vec<&IntradayExecutionQuote> = if use_decision_time_quote {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor) self.latest_known_quote_at_or_before(
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor) quotes,
&& (!quote_quantity_limited start_cursor,
|| self.quote_has_executable_liquidity(quote, side, matching_type)) snapshot,
}) side,
.collect(); matching_type,
quote_quantity_limited,
)
.into_iter()
.collect()
} else {
quotes
.iter()
.filter(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
&& (!quote_quantity_limited
|| self.quote_has_executable_liquidity(quote, side, matching_type))
})
.collect()
};
let mut filled_qty = 0_u32; let mut filled_qty = 0_u32;
let mut gross_amount = 0.0_f64; let mut gross_amount = 0.0_f64;
let mut last_timestamp = None; let mut last_timestamp = None;
@@ -4537,28 +4712,11 @@ where
// Approximate platform-native market-order fills with the evolving L1 book after // Approximate platform-native market-order fills with the evolving L1 book after
// the decision time instead of trade VWAP. This keeps quantities/prices // the decision time instead of trade VWAP. This keeps quantities/prices
// closer to the observed 10:18 execution logs. // closer to the observed 10:18 execution logs.
let Some(quote_price) = let Some(raw_quote_price) =
self.select_quote_reference_price(snapshot, quote, side, matching_type) self.select_quote_reference_price(snapshot, quote, side, matching_type)
else { else {
continue; continue;
}; };
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, quote_price)
{
execution_block_reason.get_or_insert(reason);
execution_block_timestamp = Some(quote.timestamp);
continue;
}
saw_non_blocked_execution_price = true;
if !self.price_satisfies_limit(
side,
quote_price,
limit_price,
snapshot.effective_price_tick(),
) {
continue;
}
let quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
let remaining_qty = requested_qty.saturating_sub(filled_qty); let remaining_qty = requested_qty.saturating_sub(filled_qty);
if remaining_qty == 0 { if remaining_qty == 0 {
break; break;
@@ -4594,8 +4752,35 @@ where
continue; continue;
} }
let mut quote_price =
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, quote_price)
{
execution_block_reason.get_or_insert(reason);
execution_block_timestamp = Some(quote.timestamp);
continue;
}
saw_non_blocked_execution_price = true;
if !self.price_satisfies_limit(
side,
quote_price,
limit_price,
snapshot.effective_price_tick(),
) {
continue;
}
if let Some(cash) = cash_limit { if let Some(cash) = cash_limit {
while take_qty > 0 { while take_qty > 0 {
quote_price =
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
if !quote_price.is_finite() || quote_price <= 0.0 {
budget_block_reason = Some("invalid execution price");
take_qty = 0;
break;
}
quote_price =
self.execution_price_with_limit_slippage(quote_price, limit_price);
let candidate_gross = gross_amount + quote_price * take_qty as f64; let candidate_gross = gross_amount + quote_price * take_qty as f64;
if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) { if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) {
budget_block_reason = Some("value budget limit"); budget_block_reason = Some("value budget limit");
@@ -4606,7 +4791,11 @@ where
); );
continue; continue;
} }
if candidate_gross <= cash + 1e-6 { let candidate_cost = self
.cost_model
.calculate(snapshot.date, OrderSide::Buy, candidate_gross)
.total();
if candidate_gross + candidate_cost <= cash + 1e-6 {
break; break;
} }
budget_block_reason = Some("insufficient cash after fees"); budget_block_reason = Some("insufficient cash after fees");
@@ -4621,6 +4810,10 @@ where
} }
} }
quote_price =
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
gross_amount += quote_price * take_qty as f64; gross_amount += quote_price * take_qty as f64;
filled_qty += take_qty; filled_qty += take_qty;
last_timestamp = Some(quote.timestamp); last_timestamp = Some(quote.timestamp);
@@ -4743,6 +4936,7 @@ fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
"tick no volume" "tick no volume"
| "tick volume limit" | "tick volume limit"
| "intraday quote liquidity exhausted" | "intraday quote liquidity exhausted"
| "no execution quotes at or before start"
| "no execution quotes after start" | "no execution quotes after start"
| "upper_limit" | "upper_limit"
| "lower_limit" | "lower_limit"
@@ -4757,6 +4951,7 @@ fn final_partial_fill_status(partial_reason: Option<&str>) -> OrderStatus {
Some(reason) Some(reason)
if reason.contains("market liquidity or volume limit") if reason.contains("market liquidity or volume limit")
|| reason.contains("intraday quote liquidity exhausted") || reason.contains("intraday quote liquidity exhausted")
|| reason.contains("no execution quotes at or before start")
|| reason.contains("no execution quotes after start") || reason.contains("no execution quotes after start")
|| reason.contains("upper_limit") || reason.contains("upper_limit")
|| reason.contains("lower_limit") || reason.contains("lower_limit")
@@ -4788,12 +4983,17 @@ fn sell_reason(decision: &StrategyDecision, symbol: &str) -> &'static str {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{BrokerSimulator, MatchingType}; use std::collections::BTreeMap;
use super::{BrokerExecutionReport, BrokerSimulator, MatchingType, SlippageModel};
use crate::cost::ChinaAShareCostModel; use crate::cost::ChinaAShareCostModel;
use crate::data::{ use crate::data::{
CandidateEligibility, DailyMarketSnapshot, IntradayExecutionQuote, PriceField, BenchmarkSnapshot, CandidateEligibility, DailyMarketSnapshot, DataSet,
IntradayExecutionQuote, PriceField,
}; };
use crate::events::OrderSide; use crate::events::OrderSide;
use crate::instrument::Instrument;
use crate::portfolio::PortfolioState;
use crate::rules::ChinaEquityRuleHooks; use crate::rules::ChinaEquityRuleHooks;
fn limit_test_snapshot() -> DailyMarketSnapshot { fn limit_test_snapshot() -> DailyMarketSnapshot {
@@ -4855,6 +5055,30 @@ mod tests {
} }
} }
fn limit_test_instrument() -> Instrument {
Instrument {
symbol: "000001.SZ".to_string(),
name: "PingAn".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: None,
delisted_at: None,
status: "active".to_string(),
}
}
fn limit_test_benchmark() -> BenchmarkSnapshot {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 1000.0,
volume: 1_000_000,
}
}
#[test] #[test]
fn next_tick_last_without_volume_or_liquidity_limit_does_not_cap_quote_quantity() { fn next_tick_last_without_volume_or_liquidity_limit_does_not_cap_quote_quantity() {
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks) let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
@@ -4880,6 +5104,217 @@ mod tests {
assert!(liquidity_limited.quote_quantity_limited(MatchingType::NextTickLast)); assert!(liquidity_limited.quote_quantity_limited(MatchingType::NextTickLast));
} }
#[test]
fn target_value_valuation_uses_daily_snapshot_but_value_order_sizing_uses_intraday_tick() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_intraday_execution_start_time(date.and_hms_opt(9, 33, 0).unwrap().time());
let mut snapshot = limit_test_snapshot();
snapshot.last_price = 9.0;
snapshot.close = 10.0;
let mut quote = limit_test_quote(11.0, 10.99, 11.01);
quote.timestamp = date.and_hms_opt(9, 32, 58).expect("valid timestamp");
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot.clone()],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
vec![quote],
)
.expect("valid dataset");
let snapshot = data.market(date, "000001.SZ").expect("market snapshot");
assert_eq!(
broker.target_value_valuation_price(date, &data, "000001.SZ", snapshot),
10.0
);
assert_eq!(
broker.value_sell_sizing_price(date, &data, "000001.SZ", snapshot),
11.0
);
}
#[test]
fn next_tick_last_execution_uses_latest_quote_before_decision_time() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let snapshot = limit_test_snapshot();
let mut quote = limit_test_quote(10.8, 10.79, 10.81);
quote.timestamp = date.and_hms_opt(9, 32, 58).expect("valid timestamp");
let quote_timestamp = quote.timestamp;
let decision_time = date.and_hms_opt(9, 33, 0).expect("valid timestamp");
let fill = broker
.select_execution_fill(
&snapshot,
&[quote],
OrderSide::Sell,
MatchingType::NextTickLast,
Some(decision_time),
Some(decision_time),
200,
100,
100,
100,
false,
None,
None,
None,
)
.expect("fill from latest known quote before decision time");
assert_eq!(fill.quantity, 200);
assert_eq!(fill.legs.len(), 1);
assert_eq!(fill.legs[0].price, 10.8);
assert_eq!(
fill.next_cursor,
quote_timestamp + chrono::Duration::seconds(1)
);
}
#[test]
fn value_buy_process_uses_latest_quote_before_decision_time() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_intraday_execution_start_time(date.and_hms_opt(9, 33, 0).unwrap().time())
.with_slippage_model(SlippageModel::PriceRatio(0.002))
.with_strict_value_budget(true)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let mut snapshot = limit_test_snapshot();
snapshot.day_open = 8.70;
snapshot.open = 8.70;
snapshot.high = 8.95;
snapshot.low = 8.60;
snapshot.last_price = 8.94;
snapshot.bid1 = 8.93;
snapshot.ask1 = 8.94;
snapshot.close = 8.94;
snapshot.upper_limit = 9.72;
snapshot.lower_limit = 7.96;
let mut quote = limit_test_quote(8.69, 8.69, 8.70);
quote.timestamp = date.and_hms_opt(9, 32, 55).expect("valid timestamp");
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
vec![quote],
)
.expect("valid dataset");
let mut portfolio = PortfolioState::new(10_000_000.0);
let mut report = BrokerExecutionReport::default();
broker
.process_value(
date,
&mut portfolio,
&data,
"000001.SZ",
125_000.0,
"periodic_rebalance_buy",
&mut BTreeMap::new(),
&mut BTreeMap::new(),
&mut None,
&mut BTreeMap::new(),
&mut report,
)
.expect("value buy processed");
let position = portfolio.position("000001.SZ").unwrap_or_else(|| {
panic!(
"position created from latest known quote; events={:?}",
report.order_events
)
});
assert_eq!(position.quantity, 14_300);
assert_eq!(report.order_events.len(), 1);
assert_eq!(report.order_events[0].filled_quantity, 14_300);
}
#[test]
fn strict_value_buy_budget_includes_commission_at_execution_price() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_intraday_execution_start_time(date.and_hms_opt(9, 33, 0).unwrap().time())
.with_slippage_model(SlippageModel::PriceRatio(0.002))
.with_strict_value_budget(true)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let mut snapshot = limit_test_snapshot();
snapshot.day_open = 7.14;
snapshot.open = 7.14;
snapshot.high = 7.20;
snapshot.low = 7.10;
snapshot.last_price = 7.14;
snapshot.bid1 = 7.14;
snapshot.ask1 = 7.15;
snapshot.close = 7.14;
snapshot.upper_limit = 7.85;
snapshot.lower_limit = 6.43;
let mut quote = limit_test_quote(7.14, 7.14, 7.15);
quote.timestamp = date.and_hms_opt(9, 32, 55).expect("valid timestamp");
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
vec![quote],
)
.expect("valid dataset");
let value_budget = 125_216.8131;
let mut portfolio = PortfolioState::new(10_000_000.0);
let mut report = BrokerExecutionReport::default();
broker
.process_value(
date,
&mut portfolio,
&data,
"000001.SZ",
value_budget,
"periodic_rebalance_buy",
&mut BTreeMap::new(),
&mut BTreeMap::new(),
&mut None,
&mut BTreeMap::new(),
&mut report,
)
.expect("value buy processed");
let fill = report.fill_events.first().expect("fill event");
assert_eq!(fill.quantity, 17_400);
assert!(fill.gross_amount + fill.commission <= value_budget + 1e-6);
assert!((fill.price - 7.15428).abs() < 1e-6);
}
#[test] #[test]
fn instantaneous_twap_without_limits_does_not_cap_quote_quantity() { fn instantaneous_twap_without_limits_does_not_cap_quote_quantity() {
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks) let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
+351 -69
View File
@@ -1,4 +1,4 @@
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
@@ -445,6 +445,38 @@ pub struct EligibleUniverseSnapshot {
pub free_float_cap_bn: f64, pub free_float_cap_bn: f64,
} }
pub fn decision_adjusted_cap_bn(
factor_date: NaiveDate,
raw_cap_bn: f64,
market: &DailyMarketSnapshot,
) -> f64 {
if !raw_cap_bn.is_finite() || raw_cap_bn <= 0.0 {
return f64::NAN;
}
if factor_date != market.date {
return raw_cap_bn;
}
if !market.close.is_finite()
|| market.close <= 0.0
|| !market.prev_close.is_finite()
|| market.prev_close <= 0.0
{
return f64::NAN;
}
raw_cap_bn * market.prev_close / market.close
}
pub fn decision_market_cap_bn(factor: &DailyFactorSnapshot, market: &DailyMarketSnapshot) -> f64 {
decision_adjusted_cap_bn(factor.date, factor.market_cap_bn, market)
}
pub fn decision_free_float_cap_bn(
factor: &DailyFactorSnapshot,
market: &DailyMarketSnapshot,
) -> f64 {
decision_adjusted_cap_bn(factor.date, factor.free_float_cap_bn, market)
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct SymbolPriceSeries { struct SymbolPriceSeries {
snapshots: Vec<DailyMarketSnapshot>, snapshots: Vec<DailyMarketSnapshot>,
@@ -453,11 +485,12 @@ struct SymbolPriceSeries {
closes: Vec<f64>, closes: Vec<f64>,
prev_closes: Vec<f64>, prev_closes: Vec<f64>,
last_prices: Vec<f64>, last_prices: Vec<f64>,
paused: Vec<bool>, volumes: Vec<f64>,
open_prefix: Vec<f64>, open_prefix: Vec<f64>,
close_prefix: Vec<f64>, close_prefix: Vec<f64>,
prev_close_prefix: Vec<f64>, prev_close_prefix: Vec<f64>,
last_prefix: Vec<f64>, last_prefix: Vec<f64>,
volume_prefix: Vec<f64>,
} }
impl SymbolPriceSeries { impl SymbolPriceSeries {
@@ -470,11 +503,15 @@ impl SymbolPriceSeries {
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>(); let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>(); let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>(); let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
let paused = sorted.iter().map(|row| row.paused).collect::<Vec<_>>(); let volumes = sorted
.iter()
.map(|row| row.volume as f64)
.collect::<Vec<_>>();
let open_prefix = prefix_sums(&opens); let open_prefix = prefix_sums(&opens);
let close_prefix = prefix_sums(&closes); let close_prefix = prefix_sums(&closes);
let prev_close_prefix = prefix_sums(&prev_closes); let prev_close_prefix = prefix_sums(&prev_closes);
let last_prefix = prefix_sums(&last_prices); let last_prefix = prefix_sums(&last_prices);
let volume_prefix = prefix_sums(&volumes);
Self { Self {
snapshots: sorted, snapshots: sorted,
@@ -483,11 +520,12 @@ impl SymbolPriceSeries {
closes, closes,
prev_closes, prev_closes,
last_prices, last_prices,
paused, volumes,
open_prefix, open_prefix,
close_prefix, close_prefix,
prev_close_prefix, prev_close_prefix,
last_prefix, last_prefix,
volume_prefix,
} }
} }
@@ -584,11 +622,15 @@ impl SymbolPriceSeries {
} }
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> { fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
let values = self.decision_volume_values(date, lookback)?; if lookback == 0 {
if values.len() < lookback {
return None; return None;
} }
let sum = values.iter().sum::<f64>(); let end = self.previous_completed_end_index(date)?;
if end < lookback {
return None;
}
let start = end - lookback;
let sum = self.volume_prefix[end] - self.volume_prefix[start];
Some(sum / lookback as f64) Some(sum / lookback as f64)
} }
@@ -597,11 +639,11 @@ impl SymbolPriceSeries {
return None; return None;
} }
let end = self.end_index(date)?; let end = self.end_index(date)?;
let values = self.trailing_unpaused_volumes(end, lookback)?; if end < lookback {
if values.len() < lookback {
return None; return None;
} }
let sum = values.iter().sum::<f64>(); let start = end - lookback;
let sum = self.volume_prefix[end] - self.volume_prefix[start];
Some(sum / lookback as f64) Some(sum / lookback as f64)
} }
@@ -610,33 +652,11 @@ impl SymbolPriceSeries {
return None; return None;
} }
let end = self.previous_completed_end_index(date)?; let end = self.previous_completed_end_index(date)?;
let values = self.trailing_unpaused_volumes(end, lookback)?; if end < lookback {
if values.len() < lookback {
return None; return None;
} }
Some(values) let start = end - lookback;
} Some(self.volumes[start..end].to_vec())
fn trailing_unpaused_volumes(&self, end: usize, lookback: usize) -> Option<Vec<f64>> {
if lookback == 0 || end == 0 {
return None;
}
let mut values = Vec::with_capacity(lookback);
for idx in (0..end).rev() {
if self.paused.get(idx).copied().unwrap_or(false) {
continue;
}
values.push(self.snapshots[idx].volume as f64);
if values.len() == lookback {
break;
}
}
if values.len() < lookback {
None
} else {
values.reverse();
Some(values)
}
} }
fn end_index(&self, date: NaiveDate) -> Option<usize> { fn end_index(&self, date: NaiveDate) -> Option<usize> {
@@ -687,6 +707,7 @@ struct BenchmarkPriceSeries {
dates: Vec<NaiveDate>, dates: Vec<NaiveDate>,
opens: Vec<f64>, opens: Vec<f64>,
closes: Vec<f64>, closes: Vec<f64>,
prev_closes: Vec<f64>,
open_prefix: Vec<f64>, open_prefix: Vec<f64>,
close_prefix: Vec<f64>, close_prefix: Vec<f64>,
} }
@@ -698,12 +719,14 @@ impl BenchmarkPriceSeries {
let dates = sorted.iter().map(|row| row.date).collect::<Vec<_>>(); let dates = sorted.iter().map(|row| row.date).collect::<Vec<_>>();
let opens = sorted.iter().map(|row| row.open).collect::<Vec<_>>(); let opens = sorted.iter().map(|row| row.open).collect::<Vec<_>>();
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>(); let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
let open_prefix = prefix_sums(&opens); let open_prefix = prefix_sums(&opens);
let close_prefix = prefix_sums(&closes); let close_prefix = prefix_sums(&closes);
Self { Self {
dates, dates,
opens, opens,
closes, closes,
prev_closes,
open_prefix, open_prefix,
close_prefix, close_prefix,
} }
@@ -713,6 +736,24 @@ impl BenchmarkPriceSeries {
self.moving_average_for(date, lookback, PriceField::Close) self.moving_average_for(date, lookback, PriceField::Close)
} }
fn decision_close(&self, date: NaiveDate) -> Option<f64> {
match self.dates.binary_search(&date) {
Ok(idx) => self
.prev_closes
.get(idx)
.copied()
.filter(|value| value.is_finite() && *value > 0.0)
.or_else(|| {
idx.checked_sub(1)
.and_then(|prev| self.closes.get(prev).copied())
}),
Err(0) => None,
Err(idx) => idx
.checked_sub(1)
.and_then(|prev| self.closes.get(prev).copied()),
}
}
fn decision_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> { fn decision_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
if lookback == 0 { if lookback == 0 {
return None; return None;
@@ -730,6 +771,22 @@ impl BenchmarkPriceSeries {
Some(sum / lookback as f64) Some(sum / lookback as f64)
} }
fn decision_values_for(&self, date: NaiveDate, lookback: usize, field: PriceField) -> Vec<f64> {
if lookback == 0 {
return Vec::new();
}
let end = match self.dates.binary_search(&date) {
Ok(idx) => idx,
Err(0) => return Vec::new(),
Err(idx) => idx,
};
let start = end.saturating_sub(lookback);
match field {
PriceField::DayOpen | PriceField::Open => self.opens[start..end].to_vec(),
PriceField::Close | PriceField::Last => self.closes[start..end].to_vec(),
}
}
fn moving_average_for( fn moving_average_for(
&self, &self,
date: NaiveDate, date: NaiveDate,
@@ -787,7 +844,7 @@ pub struct DataSet {
candidate_by_date: BTreeMap<NaiveDate, Vec<CandidateEligibility>>, candidate_by_date: BTreeMap<NaiveDate, Vec<CandidateEligibility>>,
candidate_index: HashMap<(NaiveDate, String), CandidateEligibility>, candidate_index: HashMap<(NaiveDate, String), CandidateEligibility>,
corporate_actions_by_date: BTreeMap<NaiveDate, Vec<CorporateAction>>, corporate_actions_by_date: BTreeMap<NaiveDate, Vec<CorporateAction>>,
execution_quotes_index: HashMap<(NaiveDate, String), Vec<IntradayExecutionQuote>>, execution_quotes_by_date: HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>,
order_book_depth_index: HashMap<(NaiveDate, String), Vec<IntradayOrderBookDepthLevel>>, order_book_depth_index: HashMap<(NaiveDate, String), Vec<IntradayOrderBookDepthLevel>>,
benchmark_by_date: BTreeMap<NaiveDate, BenchmarkSnapshot>, benchmark_by_date: BTreeMap<NaiveDate, BenchmarkSnapshot>,
market_series_by_symbol: HashMap<String, SymbolPriceSeries>, market_series_by_symbol: HashMap<String, SymbolPriceSeries>,
@@ -1071,7 +1128,7 @@ impl DataSet {
.map(|item| ((item.date, item.symbol.clone()), item)) .map(|item| ((item.date, item.symbol.clone()), item))
.collect::<HashMap<_, _>>(); .collect::<HashMap<_, _>>();
let corporate_actions_by_date = group_by_date(corporate_actions, |item| item.date); let corporate_actions_by_date = group_by_date(corporate_actions, |item| item.date);
let execution_quotes_index = build_execution_quote_index(execution_quotes); let execution_quotes_by_date = build_execution_quote_index(execution_quotes);
let order_book_depth_index = build_order_book_depth_index(order_book_depth); let order_book_depth_index = build_order_book_depth_index(order_book_depth);
let benchmark_by_date = benchmarks let benchmark_by_date = benchmarks
@@ -1101,7 +1158,7 @@ impl DataSet {
candidate_by_date, candidate_by_date,
candidate_index, candidate_index,
corporate_actions_by_date, corporate_actions_by_date,
execution_quotes_index, execution_quotes_by_date,
order_book_depth_index, order_book_depth_index,
benchmark_by_date, benchmark_by_date,
market_series_by_symbol, market_series_by_symbol,
@@ -1173,12 +1230,56 @@ impl DataSet {
} }
pub fn execution_quotes_on(&self, date: NaiveDate, symbol: &str) -> &[IntradayExecutionQuote] { pub fn execution_quotes_on(&self, date: NaiveDate, symbol: &str) -> &[IntradayExecutionQuote] {
self.execution_quotes_index self.execution_quotes_by_date
.get(&(date, symbol.to_string())) .get(&date)
.and_then(|rows_by_symbol| rows_by_symbol.get(symbol))
.map(Vec::as_slice) .map(Vec::as_slice)
.unwrap_or(&[]) .unwrap_or(&[])
} }
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
self.execution_quotes_by_date
.iter()
.flat_map(|(date, rows_by_symbol)| {
rows_by_symbol
.keys()
.map(move |symbol| (*date, symbol.clone()))
})
.collect()
}
pub fn add_execution_quotes(&mut self, quotes: Vec<IntradayExecutionQuote>) -> usize {
let mut added = 0usize;
let mut touched = HashSet::<(NaiveDate, String)>::new();
for quote in quotes {
let key = (quote.date, quote.symbol.clone());
let rows = self
.execution_quotes_by_date
.entry(quote.date)
.or_default()
.entry(quote.symbol.clone())
.or_default();
if rows.iter().any(|existing| {
existing.timestamp == quote.timestamp && existing.symbol == quote.symbol
}) {
continue;
}
rows.push(quote);
touched.insert(key);
added += 1;
}
for (date, symbol) in touched {
if let Some(rows) = self
.execution_quotes_by_date
.get_mut(&date)
.and_then(|rows_by_symbol| rows_by_symbol.get_mut(&symbol))
{
rows.sort_by_key(|quote| quote.timestamp);
}
}
added
}
pub fn order_book_depth_on( pub fn order_book_depth_on(
&self, &self,
date: NaiveDate, date: NaiveDate,
@@ -1192,10 +1293,11 @@ impl DataSet {
pub fn execution_quotes_on_date(&self, date: NaiveDate) -> Vec<IntradayExecutionQuote> { pub fn execution_quotes_on_date(&self, date: NaiveDate) -> Vec<IntradayExecutionQuote> {
let mut quotes = self let mut quotes = self
.execution_quotes_index .execution_quotes_by_date
.iter() .get(&date)
.filter(|((quote_date, _), _)| *quote_date == date) .into_iter()
.flat_map(|(_, rows)| rows.iter().cloned()) .flat_map(|rows_by_symbol| rows_by_symbol.values())
.flat_map(|rows| rows.iter().cloned())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
quotes.sort_by(|left, right| { quotes.sort_by(|left, right| {
left.timestamp left.timestamp
@@ -1315,10 +1417,10 @@ impl DataSet {
return Vec::new(); return Vec::new();
} }
let mut quotes = self let mut quotes = self
.execution_quotes_index .execution_quotes_by_date
.iter() .values()
.filter(|((_, quote_symbol), _)| quote_symbol == symbol) .filter_map(|rows_by_symbol| rows_by_symbol.get(symbol))
.flat_map(|(_, rows)| rows.iter()) .flat_map(|rows| rows.iter())
.filter(|quote| intraday_quote_visible(quote, date, active_datetime, include_now)) .filter(|quote| intraday_quote_visible(quote, date, active_datetime, include_now))
.cloned() .cloned()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -1815,12 +1917,11 @@ impl DataSet {
.collect(), .collect(),
Some("1m") | Some("tick") => { Some("1m") | Some("tick") => {
let mut bars = self let mut bars = self
.execution_quotes_index .execution_quotes_by_date
.iter() .iter()
.filter(|((date, quote_symbol), _)| { .filter(|(date, _)| **date >= start && **date <= end)
quote_symbol == symbol && *date >= start && *date <= end .filter_map(|(_, rows_by_symbol)| rows_by_symbol.get(symbol))
}) .flat_map(|rows| rows.iter())
.flat_map(|(_, rows)| rows.iter())
.map(intraday_quote_price_bar) .map(intraday_quote_price_bar)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
bars.sort_by(|left, right| { bars.sort_by(|left, right| {
@@ -2119,12 +2220,10 @@ impl DataSet {
self.market_moving_average(date, symbol, lookback, PriceField::Close) self.market_moving_average(date, symbol, lookback, PriceField::Close)
} }
"volume" | "stock_volume" => self "volume" | "stock_volume" => self
.factor_moving_average(date, symbol, "daily_volume", lookback) .market_series_by_symbol
.or_else(|| { .get(symbol)
self.market_series_by_symbol .and_then(|series| series.current_volume_moving_average(date, lookback))
.get(symbol) .or_else(|| self.factor_moving_average(date, symbol, "daily_volume", lookback)),
.and_then(|series| series.current_volume_moving_average(date, lookback))
}),
"day_open" | "dayopen" => { "day_open" | "dayopen" => {
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen) self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
} }
@@ -2211,6 +2310,10 @@ impl DataSet {
self.benchmark_series_cache.moving_average(date, lookback) self.benchmark_series_cache.moving_average(date, lookback)
} }
pub fn benchmark_decision_close(&self, date: NaiveDate) -> Option<f64> {
self.benchmark_series_cache.decision_close(date)
}
pub fn benchmark_decision_moving_average( pub fn benchmark_decision_moving_average(
&self, &self,
date: NaiveDate, date: NaiveDate,
@@ -2240,6 +2343,23 @@ impl DataSet {
} }
} }
pub fn benchmark_decision_numeric_values(
&self,
date: NaiveDate,
field: &str,
lookback: usize,
) -> Vec<f64> {
let field = normalize_field(field);
match field.as_str() {
"open" | "day_open" | "dayopen" | "benchmark_open" => self
.benchmark_series_cache
.trailing_values_for(date, lookback, PriceField::Open),
_ => self
.benchmark_series_cache
.decision_values_for(date, lookback, PriceField::Close),
}
}
pub fn market_open_moving_average( pub fn market_open_moving_average(
&self, &self,
date: NaiveDate, date: NaiveDate,
@@ -3250,17 +3370,21 @@ fn build_futures_params_index(
fn build_execution_quote_index( fn build_execution_quote_index(
execution_quotes: Vec<IntradayExecutionQuote>, execution_quotes: Vec<IntradayExecutionQuote>,
) -> HashMap<(NaiveDate, String), Vec<IntradayExecutionQuote>> { ) -> HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>> {
let mut grouped = HashMap::<(NaiveDate, String), Vec<IntradayExecutionQuote>>::new(); let mut grouped = HashMap::<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>::new();
for quote in execution_quotes { for quote in execution_quotes {
grouped grouped
.entry((quote.date, quote.symbol.clone())) .entry(quote.date)
.or_default()
.entry(quote.symbol.clone())
.or_default() .or_default()
.push(quote); .push(quote);
} }
for quotes in grouped.values_mut() { for rows_by_symbol in grouped.values_mut() {
quotes.sort_by_key(|quote| quote.timestamp); for quotes in rows_by_symbol.values_mut() {
quotes.sort_by_key(|quote| quote.timestamp);
}
} }
grouped grouped
@@ -3319,10 +3443,15 @@ fn build_eligible_universe(
{ {
continue; continue;
} }
let market_cap_bn = decision_market_cap_bn(factor, market);
if market_cap_bn <= 0.0 || !market_cap_bn.is_finite() {
continue;
}
let free_float_cap_bn = decision_free_float_cap_bn(factor, market);
rows.push(EligibleUniverseSnapshot { rows.push(EligibleUniverseSnapshot {
symbol: factor.symbol.clone(), symbol: factor.symbol.clone(),
market_cap_bn: factor.market_cap_bn, market_cap_bn,
free_float_cap_bn: factor.free_float_cap_bn, free_float_cap_bn,
}); });
} }
rows.sort_by(|left, right| { rows.sort_by(|left, right| {
@@ -3381,6 +3510,17 @@ mod tests {
} }
} }
fn benchmark_row(date: &str, close: f64) -> BenchmarkSnapshot {
BenchmarkSnapshot {
date: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap(),
benchmark: "000852.SH".to_string(),
open: close,
close,
prev_close: close - 1.0,
volume: 1_000_000,
}
}
#[test] #[test]
fn baseline_selection_uses_structured_instrument_dates_and_status_only() { fn baseline_selection_uses_structured_instrument_dates_and_status_only() {
let date = NaiveDate::parse_from_str("2025-01-02", "%Y-%m-%d").unwrap(); let date = NaiveDate::parse_from_str("2025-01-02", "%Y-%m-%d").unwrap();
@@ -3414,6 +3554,14 @@ mod tests {
Some(&instrument("正常名称", "delisted", None)), Some(&instrument("正常名称", "delisted", None)),
date date
)); ));
assert!(instrument_passes_baseline_selection(
Some(&instrument(
"正常名称",
"delisted",
Some(NaiveDate::parse_from_str("2025-04-30", "%Y-%m-%d").unwrap()),
)),
date
));
assert!(!instrument_passes_baseline_selection( assert!(!instrument_passes_baseline_selection(
Some(&instrument( Some(&instrument(
"正常名称", "正常名称",
@@ -3456,7 +3604,29 @@ mod tests {
} }
#[test] #[test]
fn decision_volume_average_skips_paused_days_before_counting_window() { fn decision_close_average_ignores_current_day_close() {
let mut current = market_row("2025-01-06", 12.0, 10_000);
current.close = 9_999.0;
current.last_price = 9_999.0;
let series = SymbolPriceSeries::new(&[
market_row("2025-01-02", 10.0, 100),
market_row("2025-01-03", 11.0, 200),
current,
]);
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
assert_eq!(
series.decision_close_moving_average(decision_date, 2),
Some(11.5)
);
assert_eq!(
series.moving_average(decision_date, 2, PriceField::Close),
Some((11.0 + 9_999.0) / 2.0)
);
}
#[test]
fn decision_volume_average_includes_paused_zero_volume_days() {
let mut paused = market_row("2025-01-03", 11.0, 0); let mut paused = market_row("2025-01-03", 11.0, 0);
paused.paused = true; paused.paused = true;
let series = SymbolPriceSeries::new(&[ let series = SymbolPriceSeries::new(&[
@@ -3471,14 +3641,126 @@ mod tests {
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(), NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
2 2
), ),
Some(200.0) Some(150.0)
); );
assert_eq!( assert_eq!(
series.decision_volume_moving_average( series.decision_volume_moving_average(
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(), NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
3 3
), ),
None Some((100.0 + 0.0 + 300.0) / 3.0)
);
}
#[test]
fn eligible_universe_uses_decision_market_cap_same_date() {
let date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
let instrument = |symbol: &str| Instrument {
symbol: symbol.to_string(),
name: symbol.to_string(),
board: if symbol.ends_with(".SH") { "SH" } else { "SZ" }.to_string(),
round_lot: 100,
listed_at: Some(NaiveDate::parse_from_str("2020-01-01", "%Y-%m-%d").unwrap()),
delisted_at: None,
status: "active".to_string(),
};
let market = |symbol: &str, prev_close: f64, close: f64| DailyMarketSnapshot {
date,
symbol: symbol.to_string(),
timestamp: Some("2025-01-06 10:18:00".to_string()),
day_open: prev_close,
open: prev_close,
high: close.max(prev_close),
low: close.min(prev_close),
close,
last_price: prev_close,
bid1: prev_close,
ask1: prev_close,
prev_close,
volume: 100_000,
tick_volume: 1_000,
bid1_volume: 1_000,
ask1_volume: 1_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: prev_close * 1.1,
lower_limit: prev_close * 0.9,
price_tick: 0.01,
};
let factor =
|symbol: &str, market_cap_bn: f64, free_float_cap_bn: f64| DailyFactorSnapshot {
date,
symbol: symbol.to_string(),
market_cap_bn,
free_float_cap_bn,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
};
let candidate = |symbol: &str| CandidateEligibility {
date,
symbol: symbol.to_string(),
is_st: false,
is_new_listing: false,
is_paused: false,
allow_buy: true,
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
};
let data = DataSet::from_components(
vec![instrument("000001.SZ"), instrument("000002.SZ")],
vec![
market("000001.SZ", 10.0, 20.0),
market("000002.SZ", 10.0, 10.0),
],
vec![
factor("000001.SZ", 12.0, 4.0),
factor("000002.SZ", 10.0, 5.0),
],
vec![candidate("000001.SZ"), candidate("000002.SZ")],
vec![BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 100.0,
close: 101.0,
prev_close: 99.0,
volume: 1_000_000,
}],
)
.expect("dataset");
let rows = data.eligible_universe_on(date);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].symbol, "000001.SZ");
assert!((rows[0].market_cap_bn - 6.0).abs() < 1e-9);
assert!((rows[0].free_float_cap_bn - 2.0).abs() < 1e-9);
assert_eq!(rows[1].symbol, "000002.SZ");
assert!((rows[1].market_cap_bn - 10.0).abs() < 1e-9);
}
#[test]
fn benchmark_decision_close_windows_exclude_current_close() {
let series = BenchmarkPriceSeries::new(&[
benchmark_row("2025-01-02", 100.0),
benchmark_row("2025-01-03", 200.0),
benchmark_row("2025-01-06", 9_999.0),
]);
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
assert_eq!(series.decision_close(decision_date), Some(9_998.0));
assert_eq!(
series.decision_moving_average(decision_date, 2),
Some(150.0)
);
assert_eq!(
series.decision_values_for(decision_date, 2, PriceField::Close),
vec![100.0, 200.0]
);
assert_eq!(
series.moving_average(decision_date, 2),
Some((200.0 + 9_999.0) / 2.0)
); );
} }
+209 -3
View File
@@ -6,7 +6,7 @@ use thiserror::Error;
use crate::broker::{BrokerExecutionReport, BrokerSimulator, MatchingType}; use crate::broker::{BrokerExecutionReport, BrokerSimulator, MatchingType};
use crate::cost::CostModel; use crate::cost::CostModel;
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, PriceField}; use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, IntradayExecutionQuote, PriceField};
use crate::event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus}; use crate::event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
use crate::events::{ use crate::events::{
AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent, AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent,
@@ -20,7 +20,10 @@ use crate::metrics::{BacktestMetrics, compute_backtest_metrics};
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState}; use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
use crate::rules::EquityRuleHooks; use crate::rules::EquityRuleHooks;
use crate::scheduler::{ScheduleRule, ScheduleStage, Scheduler, default_stage_time}; use crate::scheduler::{ScheduleRule, ScheduleStage, Scheduler, default_stage_time};
use crate::strategy::{Strategy, StrategyContext}; use crate::strategy::{
OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision,
TargetPortfolioOrderPricing,
};
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum BacktestError { pub enum BacktestError {
@@ -95,6 +98,18 @@ pub struct BacktestResult {
pub metrics: BacktestMetrics, pub metrics: BacktestMetrics,
} }
#[derive(Debug, Clone)]
pub struct ExecutionQuoteRequest {
pub date: NaiveDate,
pub start_time: Option<chrono::NaiveTime>,
pub end_time: Option<chrono::NaiveTime>,
pub symbols: BTreeSet<String>,
}
type ExecutionQuoteLoader = Box<
dyn FnMut(ExecutionQuoteRequest) -> Result<Vec<IntradayExecutionQuote>, BacktestError> + Send,
>;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct AnalyzerTradeRow { pub struct AnalyzerTradeRow {
#[serde(with = "date_format")] #[serde(with = "date_format")]
@@ -314,6 +329,7 @@ pub struct BacktestEngine<S, C, R> {
config: BacktestConfig, config: BacktestConfig,
dividend_reinvestment: bool, dividend_reinvestment: bool,
cash_dividends_enabled: bool, cash_dividends_enabled: bool,
cash_dividend_adjusts_cost_basis: bool,
process_event_bus: ProcessEventBus, process_event_bus: ProcessEventBus,
dynamic_universe: Option<BTreeSet<String>>, dynamic_universe: Option<BTreeSet<String>>,
subscriptions: BTreeSet<String>, subscriptions: BTreeSet<String>,
@@ -324,6 +340,7 @@ pub struct BacktestEngine<S, C, R> {
futures_settlement_price_mode: String, futures_settlement_price_mode: String,
futures_cost_model: FuturesTransactionCostModel, futures_cost_model: FuturesTransactionCostModel,
futures_validation_config: FuturesValidationConfig, futures_validation_config: FuturesValidationConfig,
execution_quote_loader: Option<ExecutionQuoteLoader>,
} }
impl<S, C, R> BacktestEngine<S, C, R> { impl<S, C, R> BacktestEngine<S, C, R> {
@@ -340,6 +357,7 @@ impl<S, C, R> BacktestEngine<S, C, R> {
config, config,
dividend_reinvestment: false, dividend_reinvestment: false,
cash_dividends_enabled: true, cash_dividends_enabled: true,
cash_dividend_adjusts_cost_basis: true,
process_event_bus: ProcessEventBus::new(), process_event_bus: ProcessEventBus::new(),
dynamic_universe: None, dynamic_universe: None,
subscriptions: BTreeSet::new(), subscriptions: BTreeSet::new(),
@@ -350,9 +368,24 @@ impl<S, C, R> BacktestEngine<S, C, R> {
futures_settlement_price_mode: "close".to_string(), futures_settlement_price_mode: "close".to_string(),
futures_cost_model: FuturesTransactionCostModel::default(), futures_cost_model: FuturesTransactionCostModel::default(),
futures_validation_config: FuturesValidationConfig::default(), futures_validation_config: FuturesValidationConfig::default(),
execution_quote_loader: None,
} }
} }
pub fn into_data(self) -> DataSet {
self.data
}
pub fn with_execution_quote_loader<F>(mut self, loader: F) -> Self
where
F: FnMut(ExecutionQuoteRequest) -> Result<Vec<IntradayExecutionQuote>, BacktestError>
+ Send
+ 'static,
{
self.execution_quote_loader = Some(Box::new(loader));
self
}
pub fn with_dividend_reinvestment(mut self, enabled: bool) -> Self { pub fn with_dividend_reinvestment(mut self, enabled: bool) -> Self {
self.dividend_reinvestment = enabled; self.dividend_reinvestment = enabled;
self self
@@ -363,6 +396,11 @@ impl<S, C, R> BacktestEngine<S, C, R> {
self self
} }
pub fn with_cash_dividend_cost_basis_adjustment(mut self, enabled: bool) -> Self {
self.cash_dividend_adjusts_cost_basis = enabled;
self
}
pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self { pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self {
self.futures_account = Some(account); self.futures_account = Some(account);
self self
@@ -467,6 +505,48 @@ where
C: CostModel, C: CostModel,
R: EquityRuleHooks, R: EquityRuleHooks,
{ {
fn ensure_execution_quotes_for_decision(
&mut self,
execution_date: NaiveDate,
portfolio: &PortfolioState,
open_orders: &[OpenOrderView],
decision: &StrategyDecision,
start_time: Option<chrono::NaiveTime>,
end_time: Option<chrono::NaiveTime>,
) -> Result<(), BacktestError> {
if self.execution_quote_loader.is_none() {
return Ok(());
}
if self.broker.execution_price_field() != PriceField::Last
&& !decision_has_algo_execution(decision)
{
return Ok(());
}
let start_time = start_time.or_else(|| self.broker.intraday_execution_start_time());
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
symbols.retain(|symbol| {
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
});
if symbols.is_empty() {
return Ok(());
}
let request = ExecutionQuoteRequest {
date: execution_date,
start_time,
end_time,
symbols,
};
let quotes = self
.execution_quote_loader
.as_mut()
.expect("checked execution quote loader")
.as_mut()(request)?;
self.data.add_execution_quotes(quotes);
Ok(())
}
fn apply_strategy_directives( fn apply_strategy_directives(
&mut self, &mut self,
execution_date: NaiveDate, execution_date: NaiveDate,
@@ -1728,6 +1808,15 @@ where
&mut auction_decision, &mut auction_decision,
&mut directive_report, &mut directive_report,
)?; )?;
let pre_auction_execution_orders = self.open_order_views();
self.ensure_execution_quotes_for_decision(
execution_date,
&portfolio,
&pre_auction_execution_orders,
&auction_decision,
None,
None,
)?;
let mut report = self.broker.execute( let mut report = self.broker.execute(
execution_date, execution_date,
&mut portfolio, &mut portfolio,
@@ -1932,6 +2021,15 @@ where
&mut directive_report, &mut directive_report,
)?; )?;
let pre_intraday_execution_orders = self.open_order_views();
self.ensure_execution_quotes_for_decision(
execution_date,
&portfolio,
&pre_intraday_execution_orders,
&decision,
None,
None,
)?;
let mut intraday_report = let mut intraday_report =
self.broker self.broker
.execute(execution_date, &mut portfolio, &self.data, &decision)?; .execute(execution_date, &mut portfolio, &self.data, &decision)?;
@@ -2089,6 +2187,15 @@ where
&mut tick_decision, &mut tick_decision,
&mut directive_report, &mut directive_report,
)?; )?;
let pre_tick_execution_orders = self.open_order_views();
self.ensure_execution_quotes_for_decision(
execution_date,
&portfolio,
&pre_tick_execution_orders,
&tick_decision,
Some(tick_time),
Some(tick_time),
)?;
let mut tick_report = self.broker.execute_between( let mut tick_report = self.broker.execute_between(
execution_date, execution_date,
&mut portfolio, &mut portfolio,
@@ -2534,7 +2641,11 @@ where
let position = portfolio let position = portfolio
.position_mut_if_exists(&action.symbol) .position_mut_if_exists(&action.symbol)
.expect("position exists for dividend action"); .expect("position exists for dividend action");
let cash_delta = position.apply_cash_dividend(action.share_cash); let cash_delta = if self.cash_dividend_adjusts_cost_basis {
position.apply_cash_dividend(action.share_cash)
} else {
position.apply_cash_dividend_preserve_cost_basis(action.share_cash)
};
(cash_delta, position.quantity, position.average_cost) (cash_delta, position.quantity, position.average_cost)
}; };
if cash_delta.abs() > f64::EPSILON { if cash_delta.abs() > f64::EPSILON {
@@ -3077,6 +3188,101 @@ where
} }
} }
fn has_execution_quote_in_window(
data: &DataSet,
date: NaiveDate,
symbol: &str,
start_time: Option<chrono::NaiveTime>,
end_time: Option<chrono::NaiveTime>,
) -> bool {
let start_cursor = start_time.map(|time| date.and_time(time));
let end_cursor = end_time.map(|time| date.and_time(time));
if let Some(cursor) = start_cursor
&& end_cursor.is_none()
{
return data
.execution_quotes_on(date, symbol)
.iter()
.any(|quote| quote.timestamp <= cursor);
}
data.execution_quotes_on(date, symbol).iter().any(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
})
}
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
decision.order_intents.iter().any(|intent| {
matches!(
intent,
OrderIntent::AlgoValue { .. }
| OrderIntent::AlgoPercent { .. }
| OrderIntent::TargetPortfolioSmart {
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
..
}
)
})
}
fn execution_quote_symbols_for_decision(
decision: &StrategyDecision,
portfolio: &PortfolioState,
open_orders: &[OpenOrderView],
) -> BTreeSet<String> {
let mut symbols = BTreeSet::new();
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
if decision.rebalance {
symbols.extend(portfolio.positions().keys().cloned());
symbols.extend(decision.target_weights.keys().cloned());
}
if !decision.exit_symbols.is_empty() {
symbols.extend(decision.exit_symbols.iter().cloned());
}
for intent in &decision.order_intents {
match intent {
OrderIntent::Shares { symbol, .. }
| OrderIntent::LimitShares { symbol, .. }
| OrderIntent::Lots { symbol, .. }
| OrderIntent::LimitLots { symbol, .. }
| OrderIntent::TargetShares { symbol, .. }
| OrderIntent::LimitTargetShares { symbol, .. }
| OrderIntent::TargetValue { symbol, .. }
| OrderIntent::LimitTargetValue { symbol, .. }
| OrderIntent::Value { symbol, .. }
| OrderIntent::LimitValue { symbol, .. }
| OrderIntent::Percent { symbol, .. }
| OrderIntent::LimitPercent { symbol, .. }
| OrderIntent::TargetPercent { symbol, .. }
| OrderIntent::LimitTargetPercent { symbol, .. }
| OrderIntent::AlgoValue { symbol, .. }
| OrderIntent::AlgoPercent { symbol, .. }
| OrderIntent::CancelSymbol { symbol, .. } => {
symbols.insert(symbol.clone());
}
OrderIntent::TargetPortfolioSmart { target_weights, .. } => {
symbols.extend(portfolio.positions().keys().cloned());
symbols.extend(target_weights.keys().cloned());
}
OrderIntent::CancelAll { .. } => {
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
}
OrderIntent::UpdateUniverse { .. }
| OrderIntent::Subscribe { .. }
| OrderIntent::Unsubscribe { .. }
| OrderIntent::DepositWithdraw { .. }
| OrderIntent::FinanceRepay { .. }
| OrderIntent::SetManagementFeeRate { .. }
| OrderIntent::CancelOrder { .. }
| OrderIntent::Futures { .. } => {}
}
}
symbols.retain(|symbol| !symbol.trim().is_empty());
symbols
}
fn collect_scheduled_decisions<S: Strategy>( fn collect_scheduled_decisions<S: Strategy>(
strategy: &mut S, strategy: &mut S,
scheduler: &Scheduler<'_>, scheduler: &Scheduler<'_>,
+1 -1
View File
@@ -43,7 +43,7 @@ impl Instrument {
pub fn is_active_on(&self, date: NaiveDate) -> bool { pub fn is_active_on(&self, date: NaiveDate) -> bool {
self.listed_at.is_none_or(|listed_at| listed_at <= date) self.listed_at.is_none_or(|listed_at| listed_at <= date)
&& !self.is_delisted_before(date) && !self.is_delisted_before(date)
&& !self.status.eq_ignore_ascii_case("inactive") && !(self.status.eq_ignore_ascii_case("inactive") && self.delisted_at.is_none())
} }
} }
+6 -4
View File
@@ -19,7 +19,9 @@ pub mod strategy;
pub mod strategy_ai; pub mod strategy_ai;
pub mod universe; pub mod universe;
pub use broker::{BrokerExecutionReport, BrokerSimulator, MatchingType, SlippageModel}; pub use broker::{
BrokerExecutionReport, BrokerSimulator, DynamicSlippageConfig, MatchingType, SlippageModel,
};
pub use calendar::TradingCalendar; pub use calendar::TradingCalendar;
pub use cost::{ChinaAShareCostModel, CostModel, TradingCost}; pub use cost::{ChinaAShareCostModel, CostModel, TradingCost};
pub use data::{ pub use data::{
@@ -32,7 +34,7 @@ pub use data::{
pub use engine::{ pub use engine::{
AnalyzerMonthlyReturnRow, AnalyzerPositionRow, AnalyzerReport, AnalyzerRiskSummary, AnalyzerMonthlyReturnRow, AnalyzerPositionRow, AnalyzerReport, AnalyzerRiskSummary,
AnalyzerTradeRow, BacktestConfig, BacktestDayProgress, BacktestEngine, BacktestError, AnalyzerTradeRow, BacktestConfig, BacktestDayProgress, BacktestEngine, BacktestError,
BacktestResult, DailyEquityPoint, FuturesValidationConfig, BacktestResult, DailyEquityPoint, ExecutionQuoteRequest, FuturesValidationConfig,
}; };
pub use event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus}; pub use event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
pub use events::{ pub use events::{
@@ -49,8 +51,8 @@ pub use metrics::{BacktestMetrics, compute_backtest_metrics};
pub use platform_expr_strategy::{ pub use platform_expr_strategy::{
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind, PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
PlatformExplicitOrderKind, PlatformExprStrategy, PlatformExprStrategyConfig, PlatformExplicitOrderKind, PlatformExprStrategy, PlatformExprStrategyConfig,
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction, PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformSelectionQuotePlan,
PlatformUniverseActionKind, PlatformTradeAction, PlatformUniverseActionKind,
}; };
pub use platform_runtime_schema::{ pub use platform_runtime_schema::{
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names, PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
File diff suppressed because it is too large Load Diff
+337 -6
View File
@@ -61,6 +61,20 @@ pub struct StrategyExecutionSpec {
#[serde(default)] #[serde(default)]
pub slippage_value: Option<f64>, pub slippage_value: Option<f64>,
#[serde(default)] #[serde(default)]
pub slippage_impact_coefficient: Option<f64>,
#[serde(default)]
pub slippage_volatility_coefficient: Option<f64>,
#[serde(default)]
pub slippage_max_value: Option<f64>,
#[serde(default)]
pub commission_rate: Option<f64>,
#[serde(default)]
pub minimum_commission: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_before_change: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_after_change: Option<f64>,
#[serde(default)]
pub strict_value_budget: Option<bool>, pub strict_value_budget: Option<bool>,
} }
@@ -96,6 +110,20 @@ pub struct StrategyEngineConfig {
#[serde(default)] #[serde(default)]
pub slippage_value: Option<f64>, pub slippage_value: Option<f64>,
#[serde(default)] #[serde(default)]
pub slippage_impact_coefficient: Option<f64>,
#[serde(default)]
pub slippage_volatility_coefficient: Option<f64>,
#[serde(default)]
pub slippage_max_value: Option<f64>,
#[serde(default)]
pub commission_rate: Option<f64>,
#[serde(default)]
pub minimum_commission: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_before_change: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_after_change: Option<f64>,
#[serde(default)]
pub strict_value_budget: Option<bool>, pub strict_value_budget: Option<bool>,
#[serde(default)] #[serde(default)]
pub dividend_reinvestment: Option<bool>, pub dividend_reinvestment: Option<bool>,
@@ -246,6 +274,8 @@ pub struct StrategyExpressionTradingConfig {
#[serde(default)] #[serde(default)]
pub stage: Option<String>, pub stage: Option<String>,
#[serde(default)] #[serde(default)]
pub refresh_rate_expr: Option<String>,
#[serde(default)]
pub schedule: Option<StrategyExpressionScheduleConfig>, pub schedule: Option<StrategyExpressionScheduleConfig>,
#[serde(default)] #[serde(default)]
pub rotation_enabled: Option<bool>, pub rotation_enabled: Option<bool>,
@@ -329,6 +359,140 @@ pub fn platform_expr_config_from_value(
)) ))
} }
fn valid_non_negative(value: Option<f64>) -> Option<f64> {
value.filter(|item| item.is_finite() && *item >= 0.0)
}
fn apply_cost_overrides(
cfg: &mut PlatformExprStrategyConfig,
commission_rate: Option<f64>,
minimum_commission: Option<f64>,
stamp_tax_rate_before_change: Option<f64>,
stamp_tax_rate_after_change: Option<f64>,
) {
if let Some(value) = valid_non_negative(commission_rate) {
cfg.commission_rate = Some(value);
}
if let Some(value) = valid_non_negative(minimum_commission) {
cfg.minimum_commission = Some(value);
}
if let Some(value) = valid_non_negative(stamp_tax_rate_before_change) {
cfg.stamp_tax_rate_before_change = Some(value);
}
if let Some(value) = valid_non_negative(stamp_tax_rate_after_change) {
cfg.stamp_tax_rate_after_change = Some(value);
}
}
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
let bytes = text.as_bytes();
let mut end = start;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
}
if end == start {
return None;
}
text[start..end]
.parse::<usize>()
.ok()
.filter(|value| *value > 0)
.map(|value| (value, end))
}
fn prefixed_ma_lookbacks(expr: &str, prefix: &str) -> Vec<usize> {
let lower = expr.to_ascii_lowercase();
let mut values = Vec::new();
let mut cursor = 0;
while let Some(offset) = lower[cursor..].find(prefix) {
let start = cursor + offset + prefix.len();
if let Some((value, end)) = parse_usize_after(&lower, start) {
values.push(value);
cursor = end;
} else {
cursor = start;
}
}
values
}
fn compact_ascii_whitespace(value: &str) -> String {
value
.chars()
.filter(|ch| !ch.is_ascii_whitespace())
.collect::<String>()
.to_ascii_lowercase()
}
fn rolling_mean_lookbacks(expr: &str, field: &str) -> Vec<usize> {
let compact = compact_ascii_whitespace(expr);
let patterns = [
format!("rolling_mean(\"{field}\","),
format!("rolling_mean('{field}',"),
];
let mut values = Vec::new();
for pattern in patterns {
let mut cursor = 0;
while let Some(offset) = compact[cursor..].find(&pattern) {
let start = cursor + offset + pattern.len();
if let Some((value, end)) = parse_usize_after(&compact, start) {
values.push(value);
cursor = end;
} else {
cursor = start;
}
}
}
values
}
fn sorted_unique_positive(mut values: Vec<usize>) -> Vec<usize> {
values.retain(|value| *value > 0);
values.sort_unstable();
values.dedup();
values
}
fn infer_expression_windows(
cfg: &mut PlatformExprStrategyConfig,
benchmark_short_explicit: bool,
benchmark_long_explicit: bool,
stock_short_explicit: bool,
stock_mid_explicit: bool,
stock_long_explicit: bool,
) {
let mut benchmark_days = Vec::new();
for expr in [&cfg.exposure_expr, &cfg.buy_scale_expr] {
benchmark_days.extend(prefixed_ma_lookbacks(expr, "benchmark_ma"));
benchmark_days.extend(rolling_mean_lookbacks(expr, "benchmark_close"));
}
let benchmark_days = sorted_unique_positive(benchmark_days);
if !benchmark_short_explicit && let Some(short) = benchmark_days.first().copied() {
cfg.benchmark_short_ma_days = short;
}
if !benchmark_long_explicit && let Some(long) = benchmark_days.last().copied() {
cfg.benchmark_long_ma_days = long;
}
let mut stock_days = Vec::new();
for expr in [&cfg.stock_filter_expr, &cfg.buy_scale_expr] {
stock_days.extend(prefixed_ma_lookbacks(expr, "stock_ma"));
stock_days.extend(rolling_mean_lookbacks(expr, "close"));
}
let stock_days = sorted_unique_positive(stock_days);
if !stock_short_explicit && let Some(short) = stock_days.first().copied() {
cfg.stock_short_ma_days = short;
}
if !stock_mid_explicit {
if let Some(mid) = stock_days.get(1).copied() {
cfg.stock_mid_ma_days = mid;
}
}
if !stock_long_explicit && let Some(long) = stock_days.last().copied() {
cfg.stock_long_ma_days = long;
}
}
pub fn platform_expr_config_from_spec( pub fn platform_expr_config_from_spec(
strategy_id: &str, strategy_id: &str,
signal_symbol: &str, signal_symbol: &str,
@@ -343,6 +507,11 @@ pub fn platform_expr_config_from_spec(
let Some(spec) = strategy_spec else { let Some(spec) = strategy_spec else {
return cfg; return cfg;
}; };
let mut benchmark_short_explicit = false;
let mut benchmark_long_explicit = false;
let mut stock_short_explicit = false;
let mut stock_mid_explicit = false;
let mut stock_long_explicit = false;
if let Some(spec_strategy_id) = spec if let Some(spec_strategy_id) = spec
.strategy_id .strategy_id
@@ -382,20 +551,25 @@ pub fn platform_expr_config_from_spec(
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() { if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
if let Some(days) = stock_ma_filter.short_days.filter(|value| *value > 0) { if let Some(days) = stock_ma_filter.short_days.filter(|value| *value > 0) {
cfg.stock_short_ma_days = days; cfg.stock_short_ma_days = days;
stock_short_explicit = true;
} }
if let Some(days) = stock_ma_filter.mid_days.filter(|value| *value > 0) { if let Some(days) = stock_ma_filter.mid_days.filter(|value| *value > 0) {
cfg.stock_mid_ma_days = days; cfg.stock_mid_ma_days = days;
stock_mid_explicit = true;
} }
if let Some(days) = stock_ma_filter.long_days.filter(|value| *value > 0) { if let Some(days) = stock_ma_filter.long_days.filter(|value| *value > 0) {
cfg.stock_long_ma_days = days; cfg.stock_long_ma_days = days;
stock_long_explicit = true;
} }
} }
if let Some(index_throttle) = engine.index_throttle.as_ref() { if let Some(index_throttle) = engine.index_throttle.as_ref() {
if let Some(days) = index_throttle.short_days.filter(|value| *value > 0) { if let Some(days) = index_throttle.short_days.filter(|value| *value > 0) {
cfg.benchmark_short_ma_days = days; cfg.benchmark_short_ma_days = days;
benchmark_short_explicit = true;
} }
if let Some(days) = index_throttle.long_days.filter(|value| *value > 0) { if let Some(days) = index_throttle.long_days.filter(|value| *value > 0) {
cfg.benchmark_long_ma_days = days; cfg.benchmark_long_ma_days = days;
benchmark_long_explicit = true;
} }
} }
if !engine.skip_windows.is_empty() { if !engine.skip_windows.is_empty() {
@@ -426,6 +600,13 @@ pub fn platform_expr_config_from_spec(
{ {
cfg.benchmark_symbol = spec_benchmark_symbol.clone(); cfg.benchmark_symbol = spec_benchmark_symbol.clone();
} }
apply_cost_overrides(
&mut cfg,
engine.commission_rate,
engine.minimum_commission,
engine.stamp_tax_rate_before_change,
engine.stamp_tax_rate_after_change,
);
} }
if let Some(spec_signal_symbol) = spec if let Some(spec_signal_symbol) = spec
@@ -607,6 +788,13 @@ pub fn platform_expr_config_from_spec(
} }
} }
if let Some(trading) = runtime_expr.trading.as_ref() { if let Some(trading) = runtime_expr.trading.as_ref() {
if let Some(expr) = trading
.refresh_rate_expr
.as_ref()
.filter(|value| !value.trim().is_empty())
{
cfg.refresh_rate_expr = expr.clone();
}
if let Some(enabled) = trading.rotation_enabled { if let Some(enabled) = trading.rotation_enabled {
cfg.rotation_enabled = enabled; cfg.rotation_enabled = enabled;
} }
@@ -705,21 +893,51 @@ pub fn platform_expr_config_from_spec(
cfg.selection_limit_expr = cfg.max_positions.to_string(); cfg.selection_limit_expr = cfg.max_positions.to_string();
} }
infer_expression_windows(
&mut cfg,
benchmark_short_explicit,
benchmark_long_explicit,
stock_short_explicit,
stock_mid_explicit,
stock_long_explicit,
);
if !cfg.signal_symbol.trim().is_empty() { if !cfg.signal_symbol.trim().is_empty() {
cfg.signal_symbol = normalize_symbol(&cfg.signal_symbol, None); cfg.signal_symbol = normalize_symbol(&cfg.signal_symbol, None);
} }
if !cfg.benchmark_symbol.trim().is_empty() { if !cfg.benchmark_symbol.trim().is_empty() {
cfg.benchmark_symbol = normalize_symbol(&cfg.benchmark_symbol, None); cfg.benchmark_symbol = normalize_symbol(&cfg.benchmark_symbol, None);
} }
if spec let aiquant_compat = spec
.execution .execution
.as_ref() .as_ref()
.and_then(|execution| execution.compatibility_profile.as_deref()) .and_then(|execution| execution.compatibility_profile.as_deref())
.map(|value| value.trim().to_ascii_lowercase()) .map(|value| value.trim().to_ascii_lowercase())
.is_some_and(|value| value == "aiquant_rqalpha" || value == "aiquant") .is_some_and(|value| value == "aiquant_rqalpha" || value == "aiquant");
{ if aiquant_compat {
cfg.calendar_rebalance_interval = true;
cfg.aiquant_transaction_cost = true; cfg.aiquant_transaction_cost = true;
let trading = spec
.runtime_expressions
.as_ref()
.and_then(|runtime_expr| runtime_expr.trading.as_ref());
if trading.and_then(|item| item.daily_top_up).is_none() {
cfg.daily_top_up_enabled = true;
}
if trading
.and_then(|item| item.retry_empty_rebalance)
.is_none()
{
cfg.retry_empty_rebalance = true;
}
}
if let Some(execution) = spec.execution.as_ref() {
apply_cost_overrides(
&mut cfg,
execution.commission_rate,
execution.minimum_commission,
execution.stamp_tax_rate_before_change,
execution.stamp_tax_rate_after_change,
);
} }
cfg cfg
@@ -1113,6 +1331,7 @@ mod tests {
"stockFilterExpr": "stock_ma5 > stock_ma10" "stockFilterExpr": "stock_ma5 > stock_ma10"
}, },
"trading": { "trading": {
"refreshRateExpr": "year >= 2024 ? 5 : 20",
"rotationEnabled": false, "rotationEnabled": false,
"dailyTopUp": true, "dailyTopUp": true,
"retryEmptyRebalance": true, "retryEmptyRebalance": true,
@@ -1134,11 +1353,12 @@ mod tests {
assert_eq!(cfg.strategy_name, "runtime_spec_test"); assert_eq!(cfg.strategy_name, "runtime_spec_test");
assert_eq!(cfg.signal_symbol, "000852.SH"); assert_eq!(cfg.signal_symbol, "000852.SH");
assert_eq!(cfg.selection_limit_expr, "stocknum"); assert_eq!(cfg.selection_limit_expr, "stocknum");
assert_eq!(cfg.refresh_rate_expr, "year >= 2024 ? 5 : 20");
assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]); assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]);
assert!(!cfg.rotation_enabled); assert!(!cfg.rotation_enabled);
assert!(cfg.daily_top_up_enabled); assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance); assert!(cfg.retry_empty_rebalance);
assert!(cfg.calendar_rebalance_interval); assert!(!cfg.calendar_rebalance_interval);
assert!(cfg.aiquant_transaction_cost); assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.explicit_actions.len(), 1); assert_eq!(cfg.explicit_actions.len(), 1);
assert_eq!( assert_eq!(
@@ -1147,6 +1367,117 @@ mod tests {
); );
} }
#[test]
fn parses_execution_cost_overrides_into_platform_config() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha",
"commissionRate": 0.0003,
"minimumCommission": 5.0,
"stampTaxRateBeforeChange": 0.0005,
"stampTaxRateAfterChange": 0.0005
},
"engineConfig": {
"commissionRate": 0.0008
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.commission_rate, Some(0.0003));
assert_eq!(cfg.minimum_commission, Some(5.0));
assert_eq!(cfg.stamp_tax_rate_before_change, Some(0.0005));
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
}
#[test]
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert!(cfg.aiquant_transaction_cost);
assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance);
let explicit_off = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
},
"runtimeExpressions": {
"trading": {
"dailyTopUp": false,
"retryEmptyRebalance": false
}
}
});
let cfg = platform_expr_config_from_value("", "", &explicit_off).expect("config");
assert!(!cfg.daily_top_up_enabled);
assert!(!cfg.retry_empty_rebalance);
}
#[test]
fn runtime_expressions_infer_ma_windows_from_literal_strategy_logic() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
},
"runtimeExpressions": {
"selection": {
"stockFilterExpr": "rolling_mean(\"close\", 5) > rolling_mean(\"close\", 10) && rolling_mean(\"close\", 10) > rolling_mean(\"close\", 30)"
},
"risk": {
"exposureExpr": "benchmark_ma5 > benchmark_ma20 ? 1.0 : weak_market_trade_rate"
}
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(cfg.benchmark_short_ma_days, 5);
assert_eq!(cfg.benchmark_long_ma_days, 20);
assert_eq!(cfg.stock_short_ma_days, 5);
assert_eq!(cfg.stock_mid_ma_days, 10);
assert_eq!(cfg.stock_long_ma_days, 30);
let explicit = serde_json::json!({
"engineConfig": {
"stockMaFilter": {
"shortDays": 4,
"midDays": 9,
"longDays": 21
},
"indexThrottle": {
"shortDays": 3,
"longDays": 13
}
},
"runtimeExpressions": {
"selection": {
"stockFilterExpr": "rolling_mean(\"close\", 5) > rolling_mean(\"close\", 10) && rolling_mean(\"close\", 10) > rolling_mean(\"close\", 30)"
},
"risk": {
"exposureExpr": "benchmark_ma5 > benchmark_ma20 ? 1.0 : 0.5"
}
}
});
let cfg = platform_expr_config_from_value("", "", &explicit).expect("config");
assert_eq!(cfg.benchmark_short_ma_days, 3);
assert_eq!(cfg.benchmark_long_ma_days, 13);
assert_eq!(cfg.stock_short_ma_days, 4);
assert_eq!(cfg.stock_mid_ma_days, 9);
assert_eq!(cfg.stock_long_ma_days, 21);
}
#[test] #[test]
fn parses_daily_schedule_time_for_aiquant_execution_quotes() { fn parses_daily_schedule_time_for_aiquant_execution_quotes() {
let spec = serde_json::json!({ let spec = serde_json::json!({
@@ -1163,7 +1494,7 @@ mod tests {
cfg.intraday_execution_time, cfg.intraday_execution_time,
Some(NaiveTime::from_hms_opt(9, 33, 0).unwrap()) Some(NaiveTime::from_hms_opt(9, 33, 0).unwrap())
); );
assert!(cfg.calendar_rebalance_interval); assert!(!cfg.calendar_rebalance_interval);
assert!(cfg.aiquant_transaction_cost); assert!(cfg.aiquant_transaction_cost);
} }
} }
+35 -2
View File
@@ -270,15 +270,31 @@ impl Position {
} }
pub fn apply_cash_dividend(&mut self, dividend_per_share: f64) -> f64 { pub fn apply_cash_dividend(&mut self, dividend_per_share: f64) -> f64 {
self.apply_cash_dividend_internal(dividend_per_share, true)
}
pub fn apply_cash_dividend_preserve_cost_basis(&mut self, dividend_per_share: f64) -> f64 {
self.apply_cash_dividend_internal(dividend_per_share, false)
}
fn apply_cash_dividend_internal(
&mut self,
dividend_per_share: f64,
adjust_cost_basis: bool,
) -> f64 {
if self.quantity == 0 || !dividend_per_share.is_finite() || dividend_per_share == 0.0 { if self.quantity == 0 || !dividend_per_share.is_finite() || dividend_per_share == 0.0 {
return 0.0; return 0.0;
} }
for lot in &mut self.lots { for lot in &mut self.lots {
lot.entry_price -= dividend_per_share; lot.entry_price -= dividend_per_share;
lot.price -= dividend_per_share; if adjust_cost_basis {
lot.price -= dividend_per_share;
}
}
if adjust_cost_basis {
self.average_cost -= dividend_per_share;
} }
self.average_cost -= dividend_per_share;
self.last_price -= dividend_per_share; self.last_price -= dividend_per_share;
let cash_delta = self.quantity as f64 * dividend_per_share; let cash_delta = self.quantity as f64 * dividend_per_share;
self.day_dividend_cash += cash_delta; self.day_dividend_cash += cash_delta;
@@ -887,6 +903,23 @@ mod tests {
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12); assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
} }
#[test]
fn cash_dividend_can_preserve_avg_cost_for_aiquant_compatibility() {
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
let mut position = Position::new("603102.SH");
position.buy(date, 1000, 46.45);
position.record_buy_trade_cost(1000, 37.16);
let cost_before = position.average_cost;
let entry_before = position.average_entry_price().unwrap();
let cash = position.apply_cash_dividend_preserve_cost_basis(0.6);
assert!((cash - 600.0).abs() < 1e-12);
assert!((position.average_cost - cost_before).abs() < 1e-12);
assert!((position.average_entry_price().unwrap() - (entry_before - 0.6)).abs() < 1e-12);
assert!((position.last_price - 45.85).abs() < 1e-12);
}
#[test] #[test]
fn portfolio_tracks_dividend_receivable_and_day_pnl() { fn portfolio_tracks_dividend_receivable_and_day_pnl() {
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap(); let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
+3 -3
View File
@@ -26,11 +26,11 @@ impl ChinaAShareRiskControl {
return Some("inactive_or_delisted"); return Some("inactive_or_delisted");
} }
let status = instrument.status.trim().to_ascii_lowercase(); let status = instrument.status.trim().to_ascii_lowercase();
if matches!( let terminal_status = matches!(
status.as_str(), status.as_str(),
"inactive" | "delisted" | "terminated" | "expired" "inactive" | "delisted" | "terminated" | "expired"
) || status.contains("delist") ) || status.contains("delist");
{ if terminal_status && instrument.delisted_at.is_none() {
return Some("inactive_or_delisted"); return Some("inactive_or_delisted");
} }
None None
+6 -5
View File
@@ -43,7 +43,8 @@ impl Strategy for BuyThenHoldStrategy {
#[test] #[test]
fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run() { fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run() {
let date1 = d(2025, 1, 2); let date1 = d(2025, 1, 2);
let date2 = d(2025, 1, 3); let delist_date = d(2025, 1, 3);
let date2 = d(2025, 1, 6);
let data = DataSet::from_components( let data = DataSet::from_components(
vec![ vec![
Instrument { Instrument {
@@ -52,8 +53,8 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
board: "SZ".to_string(), board: "SZ".to_string(),
round_lot: 100, round_lot: 100,
listed_at: Some(d(2020, 1, 1)), listed_at: Some(d(2020, 1, 1)),
delisted_at: Some(date1), delisted_at: Some(delist_date),
status: "delisted".to_string(), status: "active".to_string(),
}, },
Instrument { Instrument {
symbol: "000002.SZ".to_string(), symbol: "000002.SZ".to_string(),
@@ -115,7 +116,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
DailyMarketSnapshot { DailyMarketSnapshot {
date: date2, date: date2,
symbol: "000002.SZ".to_string(), symbol: "000002.SZ".to_string(),
timestamp: Some("2025-01-03 10:18:00".to_string()), timestamp: Some("2025-01-06 10:18:00".to_string()),
day_open: 5.1, day_open: 5.1,
open: 5.1, open: 5.1,
high: 5.2, high: 5.2,
@@ -273,7 +274,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
round_lot: 100, round_lot: 100,
listed_at: Some(d(2020, 1, 1)), listed_at: Some(d(2020, 1, 1)),
delisted_at: Some(date2), delisted_at: Some(date2),
status: "delisted".to_string(), status: "active".to_string(),
}, },
Instrument { Instrument {
symbol: "000002.SZ".to_string(), symbol: "000002.SZ".to_string(),
+2 -2
View File
@@ -329,7 +329,7 @@ impl Strategy for AuctionOrderStrategy {
exit_symbols: BTreeSet::new(), exit_symbols: BTreeSet::new(),
order_intents: vec![fidc_core::OrderIntent::Value { order_intents: vec![fidc_core::OrderIntent::Value {
symbol: "000001.SZ".to_string(), symbol: "000001.SZ".to_string(),
value: 1_000.0, value: 1_010.0,
reason: "auction_buy".to_string(), reason: "auction_buy".to_string(),
}], }],
notes: Vec::new(), notes: Vec::new(),
@@ -3734,7 +3734,7 @@ impl Strategy for BuyMissingRowThenHoldStrategy {
exit_symbols: BTreeSet::new(), exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::Value { order_intents: vec![OrderIntent::Value {
symbol: "601028.SH".to_string(), symbol: "601028.SH".to_string(),
value: 1_000.0, value: 1_010.0,
reason: "seed_position".to_string(), reason: "seed_position".to_string(),
}], }],
notes: Vec::new(), notes: Vec::new(),
+110 -6
View File
@@ -1,9 +1,9 @@
use chrono::{NaiveDate, NaiveTime}; use chrono::{NaiveDate, NaiveTime};
use fidc_core::{ use fidc_core::{
AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel, AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel,
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, Instrument, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, DynamicSlippageConfig,
IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState, PriceField, Instrument, IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState,
ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing, PriceField, ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
}; };
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
@@ -1485,6 +1485,110 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9); assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
} }
#[test]
fn broker_applies_dynamic_slippage_on_snapshot_fills() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components(
vec![Instrument {
symbol: "000002.SZ".to_string(),
name: "Test".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: None,
delisted_at: None,
status: "active".to_string(),
}],
vec![DailyMarketSnapshot {
date,
symbol: "000002.SZ".to_string(),
timestamp: Some("2024-01-10 10:18:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.1,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
prev_close: 10.0,
volume: 100_000,
tick_volume: 100_000,
bid1_volume: 80_000,
ask1_volume: 80_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
}],
vec![DailyFactorSnapshot {
date,
symbol: "000002.SZ".to_string(),
market_cap_bn: 50.0,
free_float_cap_bn: 45.0,
pe_ttm: 15.0,
turnover_ratio: Some(2.0),
effective_turnover_ratio: Some(1.8),
extra_factors: BTreeMap::new(),
}],
vec![CandidateEligibility {
date,
symbol: "000002.SZ".to_string(),
is_st: false,
is_new_listing: false,
is_paused: false,
allow_buy: true,
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
}],
vec![BenchmarkSnapshot {
date,
benchmark: "000300.SH".to_string(),
open: 100.0,
close: 100.0,
prev_close: 99.0,
volume: 1_000_000,
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000_000.0);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Open,
)
.with_slippage_model(SlippageModel::Dynamic(DynamicSlippageConfig::new(
0.5, 0.3, 0.1,
)));
let report = broker
.execute(
date,
&mut portfolio,
&data,
&StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::Value {
symbol: "000002.SZ".to_string(),
value: 100_000.0,
reason: "dynamic_slippage".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
assert_eq!(report.fill_events.len(), 1);
let expected_ratio = ((10.0 * report.fill_events[0].quantity as f64) / (100_000.0 * 10.0))
* 0.5
+ ((10.1 - 9.9) / 10.0) * 0.3;
assert!((report.fill_events[0].price - 10.0 * (1.0 + expected_ratio)).abs() < 1e-9);
}
#[test] #[test]
fn broker_applies_tick_size_slippage_on_intraday_last_fills() { fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap(); let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -1554,7 +1658,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
vec![IntradayExecutionQuote { vec![IntradayExecutionQuote {
date, date,
symbol: "000002.SZ".to_string(), symbol: "000002.SZ".to_string(),
timestamp: date.and_hms_opt(10, 18, 3).unwrap(), timestamp: date.and_hms_opt(10, 18, 0).unwrap(),
last_price: 10.0, last_price: 10.0,
bid1: 9.99, bid1: 9.99,
ask1: 10.01, ask1: 10.01,
@@ -1700,7 +1804,7 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
assert!( assert!(
report.order_events[0] report.order_events[0]
.reason .reason
.contains("no execution quotes after start") .contains("no execution quotes at or before start")
); );
assert!(portfolio.position("000002.SZ").is_none()); assert!(portfolio.position("000002.SZ").is_none());
} }
@@ -1889,7 +1993,7 @@ fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted
vec![IntradayExecutionQuote { vec![IntradayExecutionQuote {
date, date,
symbol: "000002.SZ".to_string(), symbol: "000002.SZ".to_string(),
timestamp: date.and_hms_opt(10, 18, 3).unwrap(), timestamp: date.and_hms_opt(10, 18, 0).unwrap(),
last_price: 10.02, last_price: 10.02,
bid1: 10.01, bid1: 10.01,
ask1: 10.03, ask1: 10.03,