Compare commits

..

111 Commits

Author SHA1 Message Date
boris c83526a6a4 懒加载日线序列缓存降低回测内存 2026-06-21 03:57:07 +08:00
boris 9bd19aa042 瘦身回测数据集按日索引内存 2026-06-21 03:48:22 +08:00
boris 2f62d82420 优化回测数据集内存并修复rolling依赖识别 2026-06-21 03:31:45 +08:00
boris 7f809fd875 修复涨停持仓普通调仓提前卖出 2026-06-21 02:53:38 +08:00
boris 8495bf6ad8 允许弱市涨停持仓部分减仓 2026-06-21 02:19:59 +08:00
boris 9d41971d3f 共享日线行情索引存储 2026-06-21 02:11:44 +08:00
boris c409d500b3 减少市场序列构建克隆 2026-06-21 02:06:28 +08:00
boris d0ab59669f 复用已预载执行报价 2026-06-21 01:59:51 +08:00
boris d264e39285 懒加载策略额外因子状态 2026-06-21 01:42:06 +08:00
boris 5b34f3b55b 按选股表达式跳过无关盘中quote 2026-06-21 01:37:04 +08:00
boris 192ac3f843 缓存调度执行quote查询 2026-06-21 01:29:15 +08:00
boris 581d4e32d0 复用选股候选股票状态 2026-06-21 01:20:57 +08:00
boris bb87d69224 按需保留股票额外因子状态 2026-06-21 01:13:22 +08:00
boris 0714d1f77b 移除股票rolling临时哈希开销 2026-06-21 01:06:05 +08:00
boris 78af8c3219 按表达式裁剪股票rolling状态 2026-06-21 01:01:23 +08:00
boris fd27429713 去重股票状态rolling计算 2026-06-21 00:54:33 +08:00
boris a270e368c8 缓存日内股票表达式状态 2026-06-21 00:47:42 +08:00
boris a368fd5d7f 短路预计算rolling因子读取 2026-06-21 00:37:51 +08:00
boris 0f982887a3 缓存平台策略表达式元数据 2026-06-21 00:20:56 +08:00
boris beebc5fa58 修复候选池风险等级二进制缓存 2026-06-20 23:59:44 +08:00
boris f8bc0679ee 修正FiRisk强平触发来源 2026-06-20 23:07:59 +08:00
boris cdca7984ed 修正FiRisk强平执行时间口径 2026-06-20 22:46:43 +08:00
boris 816fc48077 修复FiRisk禁持清仓判定 2026-06-20 19:51:38 +08:00
boris 144483be4c 修复买入禁入误触发强平 2026-06-20 19:24:31 +08:00
boris eb4e77f8c5 补齐AiQuant风控清仓优先级 2026-06-20 18:10:00 +08:00
boris 6ddbdac9cd 修复涨停持仓弱市缩仓保护 2026-06-20 18:01:59 +08:00
boris ecb9a1cfaf 修复AiQuant模式买入禁用过滤 2026-06-20 17:53:37 +08:00
boris 61fc93abf1 Revert "修复AiQuant部分成交补仓预算"
This reverts commit 7ce28e6d0f.
2026-06-20 17:28:55 +08:00
boris 7ce28e6d0f 修复AiQuant部分成交补仓预算 2026-06-20 17:24:30 +08:00
boris 1a4936d250 修复AiQuant调仓现金可用语义 2026-06-20 17:15:30 +08:00
boris 9692557746 修复停运窗口涨停延迟卖出 2026-06-20 16:20:09 +08:00
boris 8df6bfd19c 修正弱市减仓涨停待开板处理 2026-06-20 14:07:13 +08:00
boris 5e66e9799c 优化回测撮合与涨跌停约束 2026-06-20 07:59:22 +08:00
boris 5ecb0e7986 修复策略表达式卖出投影槽位释放 2026-06-19 18:33:07 +08:00
boris c3a5161db1 修正跌停卖出未成交仓位释放 2026-06-19 14:25:10 +08:00
boris 57aebe97ec 修正预计算市值决策口径 2026-06-19 10:20:12 +08:00
boris 651174dc57 修正平台策略市值选股日期口径 2026-06-19 09:26:22 +08:00
boris 4b6301cb37 增加日内补仓预算诊断 2026-06-19 06:03:17 +08:00
boris 1db80e1e13 修正停运窗口延迟卖出顺序 2026-06-18 20:54:59 +08:00
boris 938f4fec13 修正AiQuant止盈止损成本基准 2026-06-18 20:43:53 +08:00
boris daa505152a 修正AiQuant日内补仓预算口径 2026-06-18 20:26:34 +08:00
boris 02d4ea9ca7 优化回测数据集索引查找 2026-06-18 20:09:25 +08:00
boris 3633905459 支持策略决策前批量加载执行价 2026-06-18 17:08:36 +08:00
boris 2265a5dc67 增加执行价快照计数接口 2026-06-18 16:39:49 +08:00
boris 616d9cdce2 支持回测数据集快照组件导出 2026-06-18 16:32:41 +08:00
boris 213deb6e99 优化平台表达式选股快路径 2026-06-18 16:15:34 +08:00
boris 7ff443898c 修正弱市缩仓补买预算 2026-06-18 11:51:16 +08:00
boris d7c1674c6c 修正弱市缩仓阈值语义 2026-06-18 11:39:13 +08:00
boris 4f39ac7dfe 修复平台策略选股表达式口径 2026-06-18 11:12:12 +08:00
boris 8d24badcf2 修正持仓盈亏展示口径 2026-06-17 21:03:45 +08:00
boris 6c7f7130cf 修复平台策略金额买入预算 2026-06-17 19:35:19 +08:00
boris d8b6130428 修复平台策略执行行情投影判断 2026-06-17 19:08:19 +08:00
boris dae573e318 修复AiQuant补位买入预算口径 2026-06-17 18:21:35 +08:00
boris 674e4b0b14 修复非周期补买候选失败中断 2026-06-17 12:15:43 +08:00
boris 828b55c747 共享因子候选索引内存 2026-06-17 10:05:55 +08:00
boris 596d64280b 优化行情序列内存结构 2026-06-17 09:55:31 +08:00
boris 1683d875a0 修正平台策略延迟卖出预算口径 2026-06-17 09:04:50 +08:00
boris ed4658ccd0 修正平台策略选股和弱市调仓口径 2026-06-17 07:40:27 +08:00
boris bc39df0ee5 修复FIDC策略滑点配置解析 2026-06-17 05:31:46 +08:00
boris 70695d8c92 恢复点时刻tick加载语义 2026-06-16 15:35:54 +08:00
boris 0533e2db3a 避免已预取tick重复懒加载 2026-06-16 15:18:43 +08:00
boris 716149c06c 修正平台策略滚动因子优先级 2026-06-16 14:49:41 +08:00
boris 0628dd528a 修复止损卖出受限时的目标仓位预判 2026-06-16 10:20:55 +08:00
boris e146ad6e7d 补充涨停买入撮合约束测试 2026-06-16 09:15:13 +08:00
boris cf2c4fd179 修正AiQuant补仓预算口径 2026-06-16 08:38:19 +08:00
boris 6ba61ef80b 修正跌停止损预判调仓口径 2026-06-16 08:22:15 +08:00
boris e45f990487 修正平台目标调仓执行口径 2026-06-16 08:06:19 +08:00
boris 8e6c912a07 修正AiQuant目标市值估值口径 2026-06-16 07:49:10 +08:00
boris 9a411f2403 修正平台策略弱市调仓顺序 2026-06-16 07:23:51 +08:00
boris d2c65c91b7 修正平台策略投影撮合价口径 2026-06-16 06:22:40 +08:00
boris 5078aec840 修正AiQuant盘中组合估值口径 2026-06-16 06:04:37 +08:00
boris df949ab8ee 修正AiQuant兼容买入数量语义 2026-06-16 05:45:15 +08:00
boris 2e036783bf 修正止损前弱市补仓顺序 2026-06-16 00:29:01 +08:00
boris ff145300b4 修正执行价quote多时间加载 2026-06-16 00:05:34 +08:00
boris c2de9d8e83 修正AiQuant目标市值持仓估值 2026-06-15 20:40:31 +08:00
boris baeda3773d 修正调仓持仓报价预加载语义 2026-06-15 20:29:14 +08:00
boris 725f1845d9 修复涨跌停最终执行价约束 2026-06-15 20:04:42 +08:00
boris e0949a0eaa 统一表达式策略涨跌停触价口径 2026-06-15 19:33:40 +08:00
boris 5d2bcd8366 修正A股涨跌停严格触价规则 2026-06-15 18:50:10 +08:00
boris 5181d0e403 修正平台策略费用和表达式口径 2026-06-15 18:03:21 +08:00
boris 1c31fa80d2 修复AiQuant策略表达式回测执行语义 2026-06-15 11:16:04 +08:00
boris d3d08276ae 修正AiQuant多时间调仓语义 2026-06-14 02:37:26 +08:00
boris 80b34280c2 修正滑点成交后的持仓估值 2026-06-14 02:09:44 +08:00
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
boris 3499d4aa74 chore: 更新 fidc-backtest-engine - 2026-05-22 2026-05-22 17:22:33 +08:00
boris 7dbd66b467 修复止盈关闭时的延迟卖出误触发 2026-05-20 17:51:29 +08:00
boris db8b0bf142 修复AiQuant回测撮合一致性 2026-05-20 12:09:01 +08:00
boris 6e54471e57 修复回测撮合与AiQuant兼容语义 2026-05-18 23:06:47 +08:00
boris 3f383c1a88 修复平台策略撮合限价与回补语义 2026-05-18 11:14:51 +08:00
boris 4577657c90 对齐 AiQuant RQAlpha 回测语义 2026-05-15 11:48:10 +08:00
boris 94662b6e75 chore: 更新 fidc-backtest-engine - 2026-05-13 2026-05-13 23:48:16 +08:00
boris 616cab0e7e chore: 更新 fidc-backtest-engine - 2026-05-13 2026-05-13 21:57:57 +08:00
boris db72f6f515 修复 AiQuant 微盘回测撮合语义 2026-05-13 18:43:02 +08:00
boris 2165831708 使用前一交易日指数价格计算市值区间,模拟实盘场景
- 修改trading_ratio()返回5个值,包含prev_level
- 使用prev_level计算市值区间,符合实盘决策逻辑
- 调整默认参数对齐AiQuant实际运行版本(xs=0.008, cap_span=10)
- 增强MA过滤调试日志,输出首个决策日所有股票的过滤详情
- 添加市值区间计算调试日志
2026-05-12 18:03:56 +08:00
boris 1a402f2048 实现市值区间padding机制
- 添加padding_ratio、min_padding、max_padding配置参数
- 在市值区间计算中应用padding扩大选股范围
- 更新OmniMicroCapConfig、CnSmallCapRotationConfig和DynamicMarketCapBandSelector
- AiQuant V1.0.4默认padding: ratio=0.5, min=12.5, max=30.0
- 目标:增加候选股票数量,匹配AiQuant行为
2026-05-11 20:38:12 +08:00
boris bbe60537ff 修复MA过滤器逻辑错误和成交量过滤器策略名称匹配
- 修复MA过滤器:第二个比较添加 * rsi_rate (ma10 * rsi_rate > ma30)
- 修复成交量过滤器:使用contains匹配策略名称而非精确匹配
- 添加调试日志用于诊断MA过滤问题
- 同时修复strategy.rs和platform_strategy_spec.rs中的逻辑
2026-05-11 20:13:52 +08:00
22 changed files with 20376 additions and 1471 deletions
+51
View File
@@ -100,6 +100,57 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut engine = BacktestEngine::new(data, strategy, broker, config);
engine.run()?
}
"aiquant-v104" => {
let mut strategy_cfg = OmniMicroCapConfig::aiquant_v104();
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
if !signal_symbol.trim().is_empty() {
strategy_cfg.benchmark_signal_symbol = signal_symbol;
}
}
if let Some(date) = debug_date {
let eligible = data.eligible_universe_on(date);
eprintln!(
"DEBUG eligible_universe_on {} count={}",
date,
eligible.len()
);
for row in eligible.iter().take(20) {
eprintln!(" {} {:.6}", row.symbol, row.market_cap_bn);
}
let mut debug_strategy = OmniMicroCapStrategy::new(strategy_cfg.clone());
let debug_subscriptions = BTreeSet::new();
let decision = debug_strategy.on_day(&StrategyContext {
execution_date: date,
decision_date: date,
decision_index: 1,
data: &data,
portfolio: &PortfolioState::new(20_000.0),
futures_account: None,
open_orders: &[],
dynamic_universe: None,
subscriptions: &debug_subscriptions,
process_events: &[],
active_process_event: None,
active_datetime: None,
order_events: &[],
fills: &[],
})?;
eprintln!("DEBUG notes={:?}", decision.notes);
eprintln!("DEBUG diagnostics={:?}", decision.diagnostics);
return Ok(());
}
config.decision_lag_trading_days = decision_lag.unwrap_or(1);
config.execution_price_field = execution_price.unwrap_or(PriceField::Close);
config.initial_cash = initial_cash.unwrap_or(20_000.0);
let strategy = OmniMicroCapStrategy::new(strategy_cfg);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
config.execution_price_field,
);
let mut engine = BacktestEngine::new(data, strategy, broker, config);
engine.run()?
}
_ => {
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
File diff suppressed because it is too large Load Diff
+9 -1
View File
@@ -44,7 +44,7 @@ pub struct ChinaAShareCostModel {
impl Default for ChinaAShareCostModel {
fn default() -> Self {
Self {
commission_rate: 0.0003,
commission_rate: 0.0008,
stamp_tax_rate_before_change: 0.001,
stamp_tax_rate_after_change: 0.0005,
minimum_commission: 5.0,
@@ -53,6 +53,14 @@ impl Default for ChinaAShareCostModel {
}
impl ChinaAShareCostModel {
pub fn aiquant_rqalpha_default() -> Self {
Self {
stamp_tax_rate_before_change: 0.0005,
stamp_tax_rate_after_change: 0.0005,
..Self::default()
}
}
pub fn commission_for(&self, gross_amount: f64) -> f64 {
if gross_amount <= 0.0 {
return 0.0;
File diff suppressed because it is too large Load Diff
+444 -17
View File
@@ -1,12 +1,12 @@
use std::collections::{BTreeMap, BTreeSet};
use chrono::{Datelike, NaiveDate};
use chrono::{Datelike, Duration, NaiveDate, NaiveTime};
use serde::Serialize;
use thiserror::Error;
use crate::broker::{BrokerExecutionReport, BrokerSimulator, MatchingType};
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::events::{
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::rules::EquityRuleHooks;
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)]
pub enum BacktestError {
@@ -95,6 +98,18 @@ pub struct BacktestResult {
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)]
pub struct AnalyzerTradeRow {
#[serde(with = "date_format")]
@@ -313,6 +328,8 @@ pub struct BacktestEngine<S, C, R> {
broker: BrokerSimulator<C, R>,
config: BacktestConfig,
dividend_reinvestment: bool,
cash_dividends_enabled: bool,
cash_dividend_adjusts_cost_basis: bool,
process_event_bus: ProcessEventBus,
dynamic_universe: Option<BTreeSet<String>>,
subscriptions: BTreeSet<String>,
@@ -323,6 +340,9 @@ pub struct BacktestEngine<S, C, R> {
futures_settlement_price_mode: String,
futures_cost_model: FuturesTransactionCostModel,
futures_validation_config: FuturesValidationConfig,
execution_quote_loader: Option<ExecutionQuoteLoader>,
execution_quote_request_cache:
BTreeSet<(NaiveDate, String, Option<NaiveTime>, Option<NaiveTime>)>,
}
impl<S, C, R> BacktestEngine<S, C, R> {
@@ -338,6 +358,8 @@ impl<S, C, R> BacktestEngine<S, C, R> {
broker,
config,
dividend_reinvestment: false,
cash_dividends_enabled: true,
cash_dividend_adjusts_cost_basis: true,
process_event_bus: ProcessEventBus::new(),
dynamic_universe: None,
subscriptions: BTreeSet::new(),
@@ -348,14 +370,40 @@ impl<S, C, R> BacktestEngine<S, C, R> {
futures_settlement_price_mode: "close".to_string(),
futures_cost_model: FuturesTransactionCostModel::default(),
futures_validation_config: FuturesValidationConfig::default(),
execution_quote_loader: None,
execution_quote_request_cache: BTreeSet::new(),
}
}
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 {
self.dividend_reinvestment = enabled;
self
}
pub fn with_cash_dividends(mut self, enabled: bool) -> Self {
self.cash_dividends_enabled = enabled;
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 {
self.futures_account = Some(account);
self
@@ -460,6 +508,154 @@ where
C: CostModel,
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 caller_start_time = start_time;
let caller_end_time = end_time;
let start_time = caller_start_time.or_else(|| self.broker.intraday_execution_start_time());
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
self.load_missing_execution_quotes(execution_date, start_time, end_time, &mut symbols)?;
if caller_start_time.is_none() && caller_end_time.is_none() {
for ((intent_start_time, intent_end_time), mut intent_symbols) in
algo_execution_quote_windows_for_decision(decision, portfolio)
{
self.load_missing_execution_quotes(
execution_date,
intent_start_time,
intent_end_time,
&mut intent_symbols,
)?;
}
}
Ok(())
}
fn load_missing_execution_quotes(
&mut self,
execution_date: NaiveDate,
start_time: Option<NaiveTime>,
end_time: Option<NaiveTime>,
symbols: &mut BTreeSet<String>,
) -> Result<(), BacktestError> {
symbols.retain(|symbol| {
let request_key = (execution_date, symbol.clone(), start_time, end_time);
if self.execution_quote_request_cache.contains(&request_key) {
return false;
}
if start_time.is_some() && end_time.is_none() {
return !has_execution_quote_near_start_time(
&self.data,
execution_date,
symbol,
start_time.expect("checked start_time"),
);
}
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
});
if symbols.is_empty() {
return Ok(());
}
let requested_symbols = symbols.iter().cloned().collect::<Vec<_>>();
let request = ExecutionQuoteRequest {
date: execution_date,
start_time,
end_time,
symbols: std::mem::take(symbols),
};
let quotes = self
.execution_quote_loader
.as_mut()
.expect("checked execution quote loader")
.as_mut()(request)?;
self.data.add_execution_quotes(quotes);
for symbol in requested_symbols {
self.execution_quote_request_cache.insert((
execution_date,
symbol,
start_time,
end_time,
));
}
Ok(())
}
fn ensure_execution_quotes_for_portfolio_times(
&mut self,
execution_date: NaiveDate,
portfolio: &PortfolioState,
quote_times: &[NaiveTime],
) -> Result<(), BacktestError> {
if self.execution_quote_loader.is_none() || quote_times.is_empty() {
return Ok(());
}
let base_symbols = portfolio
.positions()
.keys()
.cloned()
.collect::<BTreeSet<_>>();
if base_symbols.is_empty() {
return Ok(());
}
for quote_time in quote_times {
let mut symbols = base_symbols.clone();
self.load_missing_execution_quotes(
execution_date,
Some(*quote_time),
None,
&mut symbols,
)?;
}
Ok(())
}
fn ensure_execution_quotes_for_symbols_at_times(
&mut self,
execution_date: NaiveDate,
symbols: &BTreeSet<String>,
quote_times: &[NaiveTime],
) -> Result<(), BacktestError> {
if self.execution_quote_loader.is_none() || quote_times.is_empty() || symbols.is_empty() {
return Ok(());
}
let base_symbols = symbols
.iter()
.filter(|symbol| !symbol.trim().is_empty())
.cloned()
.collect::<BTreeSet<_>>();
if base_symbols.is_empty() {
return Ok(());
}
for quote_time in quote_times {
let mut symbols = base_symbols.clone();
self.load_missing_execution_quotes(
execution_date,
Some(*quote_time),
None,
&mut symbols,
)?;
}
Ok(())
}
fn apply_strategy_directives(
&mut self,
execution_date: NaiveDate,
@@ -1721,6 +1917,15 @@ where
&mut auction_decision,
&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(
execution_date,
&mut portfolio,
@@ -1779,6 +1984,39 @@ where
"on_day:pre",
)?;
let on_day_open_orders = self.open_order_views();
let decision_quote_times = self.strategy.decision_quote_times();
if !decision_quote_times.is_empty() {
let decision_quote_symbols =
self.strategy.decision_quote_symbols(&StrategyContext {
execution_date,
decision_date,
decision_index,
data: &self.data,
portfolio: &portfolio,
futures_account: self.futures_account.as_ref(),
open_orders: &on_day_open_orders,
dynamic_universe: self.dynamic_universe.as_ref(),
subscriptions: &self.subscriptions,
process_events: &process_events,
active_process_event: None,
active_datetime: stage_datetime(
execution_date,
default_stage_time(ScheduleStage::OnDay),
),
order_events: result.order_events.as_slice(),
fills: result.fills.as_slice(),
})?;
self.ensure_execution_quotes_for_symbols_at_times(
execution_date,
&decision_quote_symbols,
&decision_quote_times,
)?;
}
self.ensure_execution_quotes_for_portfolio_times(
execution_date,
&portfolio,
&decision_quote_times,
)?;
let mut decision = decision_slot
.map(|(decision_idx, decision_date)| {
self.strategy.on_day(&StrategyContext {
@@ -1925,6 +2163,15 @@ where
&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 =
self.broker
.execute(execution_date, &mut portfolio, &self.data, &decision)?;
@@ -2082,6 +2329,15 @@ where
&mut tick_decision,
&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(
execution_date,
&mut portfolio,
@@ -2127,7 +2383,12 @@ where
}
}
portfolio.update_prices(execution_date, &self.data, PriceField::Close)?;
portfolio.update_prices_with_options(
execution_date,
&self.data,
PriceField::Close,
self.broker.same_day_buy_close_mark_at_fill(),
)?;
let post_trade_open_orders = self.open_order_views();
let visible_order_events = result
@@ -2516,13 +2777,17 @@ where
continue;
}
if action.share_cash.abs() > f64::EPSILON {
if self.cash_dividends_enabled && action.share_cash.abs() > f64::EPSILON {
let cash_before = portfolio.cash();
let (cash_delta, quantity_after, average_cost) = {
let position = portfolio
.position_mut_if_exists(&action.symbol)
.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)
};
if cash_delta.abs() > f64::EPSILON {
@@ -2985,24 +3250,17 @@ where
}
let quantity = position.quantity;
let fallback_reference_price = if position.last_price > 0.0 {
let settlement_price = if position.last_price.is_finite() && position.last_price > 0.0 {
position.last_price
} else {
} else if position.average_cost.is_finite() && position.average_cost > 0.0 {
position.average_cost
} else {
0.0
};
let effective_delisted_at = instrument
.delisted_at
.or_else(|| self.data.calendar().previous_day(date))
.unwrap_or(date);
let settlement_price = self
.data
.price_on_or_before(effective_delisted_at, &symbol, PriceField::Close)
.or_else(|| {
self.data
.price_on_or_before(date, &symbol, PriceField::Close)
})
.filter(|price| price.is_finite() && *price > 0.0)
.unwrap_or(fallback_reference_price);
if !settlement_price.is_finite() || settlement_price <= 0.0 {
return Err(BacktestError::Execution(format!(
"missing delisting settlement price for {} on {}",
@@ -3072,6 +3330,175 @@ 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 has_execution_quote_near_start_time(
data: &DataSet,
date: NaiveDate,
symbol: &str,
start_time: NaiveTime,
) -> bool {
let cursor = date.and_time(start_time);
let Some(latest) = data
.execution_quotes_on(date, symbol)
.iter()
.filter(|quote| quote.timestamp <= cursor)
.max_by_key(|quote| quote.timestamp)
else {
return false;
};
cursor.signed_duration_since(latest.timestamp) <= Duration::seconds(90)
}
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
decision.order_intents.iter().any(|intent| {
matches!(
intent,
OrderIntent::AlgoValue { .. }
| OrderIntent::AlgoPercent { .. }
| OrderIntent::TimedTargetValue { .. }
| 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::TimedTargetValue { 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 algo_execution_quote_windows_for_decision(
decision: &StrategyDecision,
portfolio: &PortfolioState,
) -> BTreeMap<(Option<NaiveTime>, Option<NaiveTime>), BTreeSet<String>> {
let mut groups = BTreeMap::<(Option<NaiveTime>, Option<NaiveTime>), BTreeSet<String>>::new();
for intent in &decision.order_intents {
match intent {
OrderIntent::AlgoValue {
symbol,
start_time,
end_time,
..
}
| OrderIntent::AlgoPercent {
symbol,
start_time,
end_time,
..
}
| OrderIntent::TimedTargetValue {
symbol,
start_time,
end_time,
..
} => {
if start_time.is_some() || end_time.is_some() {
groups
.entry((*start_time, *end_time))
.or_default()
.insert(symbol.clone());
}
}
OrderIntent::TargetPortfolioSmart {
target_weights,
order_prices:
Some(TargetPortfolioOrderPricing::AlgoOrder {
start_time,
end_time,
..
}),
..
} => {
if start_time.is_some() || end_time.is_some() {
let symbols = groups.entry((*start_time, *end_time)).or_default();
symbols.extend(portfolio.positions().keys().cloned());
symbols.extend(target_weights.keys().cloned());
}
}
_ => {}
}
}
groups
}
fn collect_scheduled_decisions<S: Strategy>(
strategy: &mut S,
scheduler: &Scheduler<'_>,
+1 -1
View File
@@ -43,7 +43,7 @@ impl Instrument {
pub fn is_active_on(&self, date: NaiveDate) -> bool {
self.listed_at.is_none_or(|listed_at| listed_at <= 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())
}
}
+8 -4
View File
@@ -12,13 +12,16 @@ pub mod platform_expr_strategy;
pub mod platform_runtime_schema;
pub mod platform_strategy_spec;
pub mod portfolio;
pub mod risk_control;
pub mod rules;
pub mod scheduler;
pub mod strategy;
pub mod strategy_ai;
pub mod universe;
pub use broker::{BrokerExecutionReport, BrokerSimulator, MatchingType, SlippageModel};
pub use broker::{
BrokerExecutionReport, BrokerSimulator, DynamicSlippageConfig, MatchingType, SlippageModel,
};
pub use calendar::TradingCalendar;
pub use cost::{ChinaAShareCostModel, CostModel, TradingCost};
pub use data::{
@@ -31,7 +34,7 @@ pub use data::{
pub use engine::{
AnalyzerMonthlyReturnRow, AnalyzerPositionRow, AnalyzerReport, AnalyzerRiskSummary,
AnalyzerTradeRow, BacktestConfig, BacktestDayProgress, BacktestEngine, BacktestError,
BacktestResult, DailyEquityPoint, FuturesValidationConfig,
BacktestResult, DailyEquityPoint, ExecutionQuoteRequest, FuturesValidationConfig,
};
pub use event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
pub use events::{
@@ -48,8 +51,8 @@ pub use metrics::{BacktestMetrics, compute_backtest_metrics};
pub use platform_expr_strategy::{
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
PlatformExplicitOrderKind, PlatformExprStrategy, PlatformExprStrategyConfig,
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
PlatformUniverseActionKind,
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformSelectionQuotePlan,
PlatformTradeAction, PlatformUniverseActionKind,
};
pub use platform_runtime_schema::{
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
@@ -66,6 +69,7 @@ pub use platform_strategy_spec::{
StrategyRuntimeSpec, platform_expr_config_from_spec, platform_expr_config_from_value,
};
pub use portfolio::{CashReceivable, HoldingSummary, PendingCashFlow, PortfolioState, Position};
pub use risk_control::ChinaAShareRiskControl;
pub use rules::{ChinaEquityRuleHooks, EquityRuleHooks, RuleCheck};
pub use scheduler::{
ScheduleFrequency, ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time,
File diff suppressed because it is too large Load Diff
@@ -223,6 +223,7 @@ const RUNTIME_HELPER_FUNCTIONS: &[&str] = &[
"factor",
"day_factor",
"rolling_mean",
"rolling_mean_current",
"ma",
"sma",
"vma",
File diff suppressed because it is too large Load Diff
+363 -39
View File
@@ -1,7 +1,7 @@
use chrono::NaiveDate;
use indexmap::IndexMap;
use serde::Serialize;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use crate::data::{DataSet, DataSetError, PriceField};
@@ -9,6 +9,7 @@ use crate::data::{DataSet, DataSetError, PriceField};
pub struct PositionLot {
pub acquired_date: NaiveDate,
pub quantity: u32,
pub entry_price: f64,
pub price: f64,
}
@@ -19,6 +20,7 @@ pub struct Position {
pub average_cost: f64,
pub last_price: f64,
pub realized_pnl: f64,
realized_entry_pnl: f64,
pub trading_pnl: f64,
pub position_pnl: f64,
pub dividend_receivable: f64,
@@ -43,6 +45,7 @@ impl Position {
average_cost: 0.0,
last_price: 0.0,
realized_pnl: 0.0,
realized_entry_pnl: 0.0,
trading_pnl: 0.0,
position_pnl: 0.0,
dividend_receivable: 0.0,
@@ -65,6 +68,16 @@ impl Position {
}
pub fn buy(&mut self, date: NaiveDate, quantity: u32, price: f64) {
self.buy_with_mark_price(date, quantity, price, price);
}
pub fn buy_with_mark_price(
&mut self,
date: NaiveDate,
quantity: u32,
execution_price: f64,
mark_price: f64,
) {
if quantity == 0 {
return;
}
@@ -72,18 +85,28 @@ impl Position {
self.lots.push(PositionLot {
acquired_date: date,
quantity,
price,
entry_price: execution_price,
price: execution_price,
});
self.quantity += quantity;
self.last_price = price;
self.last_price = normalized_mark_price(mark_price, execution_price);
self.day_trade_quantity_delta += quantity as i32;
self.day_buy_quantity += quantity;
self.day_buy_value += price * quantity as f64;
self.day_buy_value += execution_price * quantity as f64;
self.recalculate_average_cost();
self.refresh_day_pnl();
}
pub fn sell(&mut self, quantity: u32, price: f64) -> Result<f64, String> {
self.sell_with_mark_price(quantity, price, price)
}
pub fn sell_with_mark_price(
&mut self,
quantity: u32,
execution_price: f64,
mark_price: f64,
) -> Result<f64, String> {
if quantity > self.quantity {
return Err(format!(
"sell quantity {} exceeds current quantity {} for {}",
@@ -93,6 +116,7 @@ impl Position {
let mut remaining = quantity;
let mut realized = 0.0;
let mut realized_entry = 0.0;
while remaining > 0 {
let Some(first_lot) = self.lots.first_mut() else {
@@ -100,7 +124,8 @@ impl Position {
};
let lot_sell = remaining.min(first_lot.quantity);
realized += (price - first_lot.price) * lot_sell as f64;
realized += (execution_price - first_lot.price) * lot_sell as f64;
realized_entry += (execution_price - first_lot.entry_price) * lot_sell as f64;
first_lot.quantity -= lot_sell;
remaining -= lot_sell;
@@ -110,11 +135,12 @@ impl Position {
}
self.quantity -= quantity;
self.last_price = price;
self.last_price = normalized_mark_price(mark_price, execution_price);
self.realized_pnl += realized;
self.realized_entry_pnl += realized_entry;
self.day_trade_quantity_delta -= quantity as i32;
self.day_sell_quantity += quantity;
self.day_sell_value += price * quantity as f64;
self.day_sell_value += execution_price * quantity as f64;
self.recalculate_average_cost();
self.refresh_day_pnl();
Ok(realized)
@@ -136,10 +162,21 @@ impl Position {
(self.last_price - self.average_cost) * self.quantity as f64
}
pub fn unrealized_entry_pnl(&self) -> f64 {
let Some(avg_price) = self.average_entry_price() else {
return 0.0;
};
(self.last_price - avg_price) * self.quantity as f64
}
pub fn pnl(&self) -> f64 {
self.realized_pnl + self.unrealized_pnl()
}
pub fn entry_pnl(&self) -> f64 {
self.realized_entry_pnl + self.unrealized_entry_pnl()
}
pub fn day_start_quantity(&self) -> u32 {
self.day_start_quantity
}
@@ -205,6 +242,22 @@ impl Position {
}
}
pub fn record_buy_trade_cost(&mut self, quantity: u32, value: f64) {
if quantity == 0 || !value.is_finite() {
return;
}
let cost = value.max(0.0);
if cost <= 0.0 {
return;
}
if let Some(lot) = self.lots.last_mut() {
lot.price += cost / quantity as f64;
self.recalculate_average_cost();
}
self.day_trade_cost += cost;
self.refresh_day_pnl();
}
pub fn set_dividend_receivable(&mut self, value: f64) {
self.dividend_receivable = if value.is_finite() {
value.max(0.0)
@@ -214,13 +267,28 @@ impl Position {
}
pub fn holding_return(&self, price: f64) -> Option<f64> {
if self.quantity == 0 || self.average_cost <= 0.0 {
let Some(avg_price) = self.average_entry_price() else {
return None;
};
if avg_price <= 0.0 {
None
} else {
Some((price / self.average_cost) - 1.0)
Some((price / avg_price) - 1.0)
}
}
pub fn average_entry_price(&self) -> Option<f64> {
if self.quantity == 0 {
return None;
}
let total = self
.lots
.iter()
.map(|lot| lot.entry_price * lot.quantity as f64)
.sum::<f64>();
Some(total / self.quantity as f64)
}
fn recalculate_average_cost(&mut self) {
if self.quantity == 0 {
self.average_cost = 0.0;
@@ -237,14 +305,31 @@ impl Position {
}
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 {
return 0.0;
}
for lot in &mut self.lots {
lot.price -= dividend_per_share;
lot.entry_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;
let cash_delta = self.quantity as f64 * dividend_per_share;
self.day_dividend_cash += cash_delta;
@@ -264,6 +349,7 @@ impl Position {
.map(|lot| PositionLot {
acquired_date: lot.acquired_date,
quantity: round_half_up_u32(lot.quantity as f64 * ratio),
entry_price: lot.entry_price / ratio,
price: lot.price / ratio,
})
.collect::<Vec<_>>();
@@ -305,6 +391,14 @@ impl Position {
}
}
fn normalized_mark_price(mark_price: f64, fallback: f64) -> f64 {
if mark_price.is_finite() && mark_price > 0.0 {
mark_price
} else {
fallback
}
}
#[derive(Debug, Clone)]
pub struct PortfolioState {
initial_cash: f64,
@@ -316,6 +410,7 @@ pub struct PortfolioState {
positions: IndexMap<String, Position>,
cash_receivables: Vec<CashReceivable>,
pending_cash_flows: Vec<PendingCashFlow>,
day_sold_symbols: BTreeSet<String>,
}
#[derive(Debug, Clone)]
@@ -348,6 +443,7 @@ impl PortfolioState {
positions: IndexMap::new(),
cash_receivables: Vec::new(),
pending_cash_flows: Vec::new(),
day_sold_symbols: BTreeSet::new(),
}
}
@@ -402,7 +498,18 @@ impl PortfolioState {
}
pub fn prune_flat_positions(&mut self) {
self.positions.retain(|_, position| !position.is_flat());
let mut sold_symbols = Vec::new();
self.positions.retain(|symbol, position| {
if position.is_flat() {
if position.sold_quantity() > 0 {
sold_symbols.push(symbol.clone());
}
false
} else {
true
}
});
self.day_sold_symbols.extend(sold_symbols);
}
pub fn add_cash_receivable(&mut self, receivable: CashReceivable) {
@@ -538,6 +645,7 @@ impl PortfolioState {
}
pub fn begin_trading_day(&mut self) {
self.day_sold_symbols.clear();
for position in self.positions.values_mut() {
position.begin_trading_day();
}
@@ -550,7 +658,31 @@ impl PortfolioState {
data: &DataSet,
field: PriceField,
) -> Result<(), DataSetError> {
self.update_prices_with_options(date, data, field, false)
}
pub fn update_prices_with_options(
&mut self,
date: NaiveDate,
data: &DataSet,
field: PriceField,
same_day_buy_close_mark_at_fill: bool,
) -> Result<(), DataSetError> {
let day_sold_symbols = self.day_sold_symbols.clone();
for position in self.positions.values_mut() {
let sold_today =
position.sold_quantity() > 0 || day_sold_symbols.contains(&position.symbol);
if same_day_buy_close_mark_at_fill
&& field == PriceField::Close
&& position.day_buy_quantity > 0
&& !sold_today
&& position.sellable_qty(date) == 0
&& position.last_price.is_finite()
&& position.last_price > 0.0
{
position.refresh_day_pnl();
continue;
}
let price = data
.price(date, &position.symbol, field)
.or_else(|| data.price_on_or_before(date, &position.symbol, field))
@@ -649,33 +781,40 @@ impl PortfolioState {
self.positions
.values()
.filter(|position| position.quantity > 0)
.map(|position| HoldingSummary {
date,
symbol: position.symbol.clone(),
quantity: position.quantity,
average_cost: position.average_cost,
last_price: position.last_price,
market_value: position.market_value(),
value_percent: if total_equity > 0.0 {
position.market_value() / total_equity
} else {
0.0
},
unrealized_pnl: position.unrealized_pnl(),
realized_pnl: position.realized_pnl,
pnl: position.pnl(),
trading_pnl: position.trading_pnl,
position_pnl: position.position_pnl,
dividend_receivable: position.dividend_receivable,
old_quantity: position.day_start_quantity(),
bought_quantity: position.bought_quantity(),
sold_quantity: position.sold_quantity(),
buy_avg_price: position.buy_avg_price(),
sell_avg_price: position.sell_avg_price(),
bought_value: position.bought_value(),
sold_value: position.sold_value(),
transaction_cost: position.transaction_cost(),
day_trade_quantity_delta: position.day_trade_quantity_delta(),
.map(|position| {
let market_value = position.market_value();
let entry_average_cost = position
.average_entry_price()
.filter(|value| value.is_finite() && *value > 0.0)
.unwrap_or(position.average_cost);
HoldingSummary {
date,
symbol: position.symbol.clone(),
quantity: position.quantity,
average_cost: entry_average_cost,
last_price: position.last_price,
market_value,
value_percent: if total_equity > 0.0 {
market_value / total_equity
} else {
0.0
},
unrealized_pnl: position.unrealized_entry_pnl(),
realized_pnl: position.realized_entry_pnl,
pnl: position.entry_pnl(),
trading_pnl: position.trading_pnl,
position_pnl: position.position_pnl,
dividend_receivable: position.dividend_receivable,
old_quantity: position.day_start_quantity(),
bought_quantity: position.bought_quantity(),
sold_quantity: position.sold_quantity(),
buy_avg_price: position.buy_avg_price(),
sell_avg_price: position.sell_avg_price(),
bought_value: position.bought_value(),
sold_value: position.sold_value(),
transaction_cost: position.transaction_cost(),
day_trade_quantity_delta: position.day_trade_quantity_delta(),
}
})
.collect()
}
@@ -699,12 +838,14 @@ impl PortfolioState {
let old_quantity = old_position.quantity;
let last_price = old_position.last_price;
let realized_pnl = old_position.realized_pnl;
let realized_entry_pnl = old_position.realized_entry_pnl;
let mut converted_lots = old_position
.lots
.into_iter()
.map(|lot| PositionLot {
acquired_date: lot.acquired_date,
quantity: round_half_up_u32(lot.quantity as f64 * ratio),
entry_price: lot.entry_price / ratio,
price: lot.price / ratio,
})
.collect::<Vec<_>>();
@@ -734,6 +875,7 @@ impl PortfolioState {
successor.lots.extend(converted_lots);
successor.quantity = successor.lots.iter().map(|lot| lot.quantity).sum();
successor.realized_pnl += realized_pnl;
successor.realized_entry_pnl += realized_entry_pnl;
if converted_last_price > 0.0 {
successor.last_price = converted_last_price;
}
@@ -801,6 +943,60 @@ mod tests {
);
}
#[test]
fn strategy_entry_price_excludes_buy_commission_cost_basis() {
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
let mut position = Position::new("600561.SH");
position.buy(date, 22_200, 5.66);
position.record_buy_trade_cost(22_200, 100.0);
assert!(position.average_cost > 5.66);
assert!((position.average_entry_price().unwrap() - 5.66).abs() < 1e-12);
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
}
#[test]
fn holdings_summary_reports_entry_price_pnl_excluding_buy_commission() {
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
let mut portfolio = PortfolioState::new(10_000.0);
{
let position = portfolio.position_mut("600561.SH");
position.buy(date, 100, 10.0);
position.record_buy_trade_cost(100, 5.0);
position.last_price = 10.5;
}
let summary = portfolio.holdings_summary(date);
assert_eq!(summary.len(), 1);
assert!((summary[0].average_cost - 10.0).abs() < 1e-12);
assert!((summary[0].unrealized_pnl - 50.0).abs() < 1e-12);
assert!((summary[0].realized_pnl - 0.0).abs() < 1e-12);
assert!(
portfolio
.position("600561.SH")
.expect("position")
.average_cost
> summary[0].average_cost
);
}
#[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]
fn portfolio_tracks_dividend_receivable_and_day_pnl() {
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
@@ -890,6 +1086,7 @@ mod tests {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -976,6 +1173,7 @@ mod tests {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1066,6 +1264,132 @@ mod tests {
assert!(position.position_pnl.abs() < 1e-6);
}
#[test]
fn portfolio_marks_same_day_buy_at_fill_until_next_trading_day() {
let buy_date = NaiveDate::from_ymd_opt(2025, 2, 10).unwrap();
let next_date = NaiveDate::from_ymd_opt(2025, 2, 11).unwrap();
let symbol = "002652.SZ";
let mut portfolio = PortfolioState::new(20_000.0);
portfolio.position_mut(symbol).buy(buy_date, 1300, 3.01);
let dataset = DataSet::from_components(
vec![Instrument {
symbol: symbol.to_string(),
name: "Same Day Buy Test".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: None,
delisted_at: None,
status: "active".to_string(),
}],
vec![
DailyMarketSnapshot {
date: buy_date,
symbol: symbol.to_string(),
timestamp: None,
day_open: 2.99,
open: 2.99,
high: 3.06,
low: 2.98,
close: 3.06,
last_price: 3.06,
bid1: 3.01,
ask1: 3.02,
prev_close: 2.98,
volume: 152_975,
tick_volume: 152_975,
bid1_volume: 338,
ask1_volume: 2476,
trading_phase: None,
paused: false,
upper_limit: 3.28,
lower_limit: 2.68,
price_tick: 0.01,
},
DailyMarketSnapshot {
date: next_date,
symbol: symbol.to_string(),
timestamp: None,
day_open: 3.03,
open: 3.03,
high: 3.08,
low: 3.00,
close: 3.07,
last_price: 3.07,
bid1: 3.06,
ask1: 3.07,
prev_close: 3.06,
volume: 160_000,
tick_volume: 160_000,
bid1_volume: 1000,
ask1_volume: 1000,
trading_phase: None,
paused: false,
upper_limit: 3.37,
lower_limit: 2.75,
price_tick: 0.01,
},
],
Vec::new(),
Vec::new(),
vec![
BenchmarkSnapshot {
date: buy_date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 999.0,
volume: 1000,
},
BenchmarkSnapshot {
date: next_date,
benchmark: "000852.SH".to_string(),
open: 1001.0,
close: 1001.0,
prev_close: 1000.0,
volume: 1000,
},
],
)
.expect("dataset");
portfolio
.update_prices_with_options(buy_date, &dataset, PriceField::Close, true)
.expect("same day close");
let position = portfolio.position(symbol).expect("position");
assert!((position.last_price - 3.01).abs() < 1e-9);
assert!((position.market_value() - 3913.0).abs() < 1e-6);
portfolio.begin_trading_day();
portfolio
.update_prices(next_date, &dataset, PriceField::Close)
.expect("next day close");
let position = portfolio.position(symbol).expect("position");
assert!((position.last_price - 3.07).abs() < 1e-9);
assert!((position.market_value() - 3991.0).abs() < 1e-6);
let prev_date = NaiveDate::from_ymd_opt(2025, 2, 7).unwrap();
let mut roundtrip_portfolio = PortfolioState::new(20_000.0);
roundtrip_portfolio
.position_mut(symbol)
.buy(prev_date, 2000, 2.90);
roundtrip_portfolio.begin_trading_day();
roundtrip_portfolio
.position_mut(symbol)
.sell(2000, 3.01)
.expect("same day sell");
roundtrip_portfolio.prune_flat_positions();
roundtrip_portfolio
.position_mut(symbol)
.buy(buy_date, 1800, 3.01);
roundtrip_portfolio
.update_prices(buy_date, &dataset, PriceField::Close)
.expect("same day roundtrip close");
let position = roundtrip_portfolio.position(symbol).expect("position");
assert!((position.last_price - 3.06).abs() < 1e-9);
assert!((position.market_value() - 5508.0).abs() < 1e-6);
}
#[test]
fn position_tracks_day_lifecycle_fields() {
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
+233
View File
@@ -0,0 +1,233 @@
use chrono::NaiveDate;
use crate::data::{CandidateEligibility, DailyMarketSnapshot, PriceField};
use crate::instrument::Instrument;
use crate::portfolio::Position;
#[derive(Debug, Clone, Copy, Default)]
pub struct ChinaAShareRiskControl;
impl ChinaAShareRiskControl {
pub fn instrument_rejection_reason(
instrument: Option<&Instrument>,
date: NaiveDate,
) -> Option<&'static str> {
let instrument = instrument?;
if instrument
.listed_at
.is_some_and(|listed_at| listed_at > date)
{
return Some("not_listed");
}
if instrument
.delisted_at
.is_some_and(|delisted_at| delisted_at <= date)
{
return Some("inactive_or_delisted");
}
let status = instrument.status.trim().to_ascii_lowercase();
let terminal_status = matches!(
status.as_str(),
"inactive" | "delisted" | "terminated" | "expired"
) || status.contains("delist");
if terminal_status && instrument.delisted_at.is_none() {
return Some("inactive_or_delisted");
}
None
}
pub fn selection_rejection_reason(
date: NaiveDate,
candidate: &CandidateEligibility,
market: &DailyMarketSnapshot,
instrument: Option<&Instrument>,
) -> Option<&'static str> {
if let Some(reason) = Self::baseline_rejection_reason(date, candidate, market, instrument) {
return Some(reason);
}
if !candidate.allow_buy || !candidate.allow_sell {
return Some("trade_disabled");
}
None
}
pub fn baseline_rejection_reason(
date: NaiveDate,
candidate: &CandidateEligibility,
market: &DailyMarketSnapshot,
instrument: Option<&Instrument>,
) -> Option<&'static str> {
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
return Some(reason);
}
if market.paused || candidate.is_paused {
return Some("paused");
}
if candidate.is_st {
return Some("st");
}
if candidate.is_new_listing {
return Some("new_listing");
}
if candidate.is_kcb {
return Some("kcb");
}
if candidate.is_one_yuan || market.day_open <= 1.0 {
return Some("one_yuan");
}
None
}
pub fn buy_rejection_reason(
date: NaiveDate,
candidate: &CandidateEligibility,
market: &DailyMarketSnapshot,
instrument: Option<&Instrument>,
check_price: f64,
) -> Option<&'static str> {
if let Some(reason) = Self::baseline_rejection_reason(date, candidate, market, instrument) {
return Some(reason);
}
if !candidate.allow_buy {
return Some("buy_disabled");
}
if market.is_at_upper_limit_price(check_price) {
return Some("open at or above upper limit");
}
None
}
pub fn sell_rejection_reason(
date: NaiveDate,
candidate: &CandidateEligibility,
market: &DailyMarketSnapshot,
instrument: Option<&Instrument>,
position: Option<&Position>,
check_price: f64,
) -> Option<&'static str> {
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
return Some(reason);
}
if market.paused || candidate.is_paused {
return Some("paused");
}
// `allow_sell` is derived from the daily candidate snapshot and may
// reflect an open/close fallback rather than the actual execution tick.
// A sell order must be blocked by the execution price lower-limit check
// below, while suspension and delisting are handled above.
if market.is_at_lower_limit_price(check_price) {
return Some("open at or below lower limit");
}
if position.is_some_and(|position| position.sellable_qty(date) == 0) {
return Some("t+1 sellable quantity is zero");
}
None
}
pub fn buy_check_price(market: &DailyMarketSnapshot, price_field: PriceField) -> f64 {
market.buy_price(price_field)
}
pub fn sell_check_price(market: &DailyMarketSnapshot, price_field: PriceField) -> f64 {
match price_field {
PriceField::Last => market.price(PriceField::Last),
_ => market.sell_price(price_field),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
}
fn candidate(date: NaiveDate) -> CandidateEligibility {
CandidateEligibility {
date,
symbol: "002633.SZ".to_string(),
is_st: false,
is_new_listing: false,
is_paused: false,
allow_buy: true,
allow_sell: false,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}
}
fn market(date: NaiveDate, last_price: f64, lower_limit: f64) -> DailyMarketSnapshot {
DailyMarketSnapshot {
date,
symbol: "002633.SZ".to_string(),
timestamp: Some(format!("{date} 10:18:00")),
day_open: last_price,
open: last_price,
high: last_price,
low: last_price,
close: last_price,
last_price,
bid1: last_price,
ask1: last_price,
prev_close: 6.25,
volume: 1_000_000,
tick_volume: 10_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 6.89,
lower_limit,
price_tick: 0.01,
}
}
fn position(prev_date: NaiveDate) -> Position {
let mut position = Position::new("002633.SZ");
position.buy(prev_date, 7_200, 8.48);
position
}
#[test]
fn sell_rejection_uses_execution_price_not_stale_allow_sell() {
let prev_date = d(2024, 4, 16);
let date = d(2024, 4, 17);
let candidate = candidate(date);
let market = market(date, 6.27, 5.63);
let position = position(prev_date);
let reason = ChinaAShareRiskControl::sell_rejection_reason(
date,
&candidate,
&market,
None,
Some(&position),
6.27,
);
assert_eq!(reason, None);
}
#[test]
fn sell_rejection_blocks_execution_price_at_lower_limit() {
let prev_date = d(2024, 4, 16);
let date = d(2024, 4, 17);
let candidate = candidate(date);
let market = market(date, 5.63, 5.63);
let position = position(prev_date);
let reason = ChinaAShareRiskControl::sell_rejection_reason(
date,
&candidate,
&market,
None,
Some(&position),
5.63,
);
assert_eq!(reason, Some("open at or below lower limit"));
}
}
+18 -33
View File
@@ -2,6 +2,7 @@ use chrono::NaiveDate;
use crate::data::{CandidateEligibility, DailyMarketSnapshot, PriceField};
use crate::portfolio::Position;
use crate::risk_control::ChinaAShareRiskControl;
#[derive(Debug, Clone)]
pub struct RuleCheck {
@@ -47,20 +48,6 @@ pub trait EquityRuleHooks {
#[derive(Debug, Clone, Default)]
pub struct ChinaEquityRuleHooks;
impl ChinaEquityRuleHooks {
fn at_upper_limit(snapshot: &DailyMarketSnapshot, price_field: PriceField) -> bool {
snapshot.is_at_upper_limit_price(snapshot.buy_price(price_field))
}
fn at_lower_limit(snapshot: &DailyMarketSnapshot, price_field: PriceField) -> bool {
let check_price = match price_field {
PriceField::Last => snapshot.price(PriceField::Last),
_ => snapshot.sell_price(price_field),
};
snapshot.is_at_lower_limit_price(check_price)
}
}
impl EquityRuleHooks for ChinaEquityRuleHooks {
fn can_buy(
&self,
@@ -69,14 +56,14 @@ impl EquityRuleHooks for ChinaEquityRuleHooks {
candidate: &CandidateEligibility,
price_field: PriceField,
) -> RuleCheck {
if snapshot.paused || candidate.is_paused {
return RuleCheck::reject("paused");
}
if !candidate.allow_buy {
return RuleCheck::reject("buy disabled by eligibility flags");
}
if Self::at_upper_limit(snapshot, price_field) {
return RuleCheck::reject("open at or above upper limit");
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
_execution_date,
candidate,
snapshot,
None,
ChinaAShareRiskControl::buy_check_price(snapshot, price_field),
) {
return RuleCheck::reject(reason);
}
RuleCheck::allow()
@@ -90,17 +77,15 @@ impl EquityRuleHooks for ChinaEquityRuleHooks {
position: &Position,
price_field: PriceField,
) -> RuleCheck {
if snapshot.paused || candidate.is_paused {
return RuleCheck::reject("paused");
}
if !candidate.allow_sell {
return RuleCheck::reject("sell disabled by eligibility flags");
}
if Self::at_lower_limit(snapshot, price_field) {
return RuleCheck::reject("open at or below lower limit");
}
if position.sellable_qty(execution_date) == 0 {
return RuleCheck::reject("t+1 sellable quantity is zero");
if let Some(reason) = ChinaAShareRiskControl::sell_rejection_reason(
execution_date,
candidate,
snapshot,
None,
Some(position),
ChinaAShareRiskControl::sell_check_price(snapshot, price_field),
) {
return RuleCheck::reject(reason);
}
RuleCheck::allow()
+206 -93
View File
@@ -17,6 +17,7 @@ use crate::events::{FillEvent, OrderEvent, OrderSide, OrderStatus, ProcessEvent}
use crate::futures::{FuturesAccountState, FuturesOrderIntent};
use crate::instrument::Instrument;
use crate::portfolio::PortfolioState;
use crate::risk_control::ChinaAShareRiskControl;
use crate::scheduler::ScheduleRule;
use crate::universe::{DynamicMarketCapBandSelector, SelectionContext, UniverseSelector};
@@ -39,6 +40,15 @@ pub trait Strategy {
fn schedule_rules(&self) -> Vec<ScheduleRule> {
Vec::new()
}
fn decision_quote_times(&self) -> Vec<NaiveTime> {
Vec::new()
}
fn decision_quote_symbols(
&mut self,
_ctx: &StrategyContext<'_>,
) -> Result<BTreeSet<String>, BacktestError> {
Ok(BTreeSet::new())
}
fn on_scheduled(
&mut self,
_ctx: &StrategyContext<'_>,
@@ -979,6 +989,14 @@ pub enum OrderIntent {
target_value: f64,
reason: String,
},
TimedTargetValue {
symbol: String,
target_value: f64,
style: AlgoOrderStyle,
start_time: Option<NaiveTime>,
end_time: Option<NaiveTime>,
reason: String,
},
LimitTargetValue {
symbol: String,
target_value: f64,
@@ -1090,6 +1108,9 @@ pub struct CnSmallCapRotationConfig {
pub base_index_level: f64,
pub base_cap_floor: f64,
pub cap_span: f64,
pub padding_ratio: f64,
pub min_padding: f64,
pub max_padding: f64,
pub short_ma_days: usize,
pub long_ma_days: usize,
pub stock_short_ma_days: usize,
@@ -1101,7 +1122,7 @@ pub struct CnSmallCapRotationConfig {
pub take_profit_pct: f64,
pub signal_symbol: Option<String>,
pub skip_months: Vec<u32>,
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
pub skip_month_day_ranges: Vec<(Option<u32>, u32, u32, u32)>,
}
impl CnSmallCapRotationConfig {
@@ -1114,6 +1135,9 @@ impl CnSmallCapRotationConfig {
base_index_level: 2000.0,
base_cap_floor: 7.0,
cap_span: 10.0,
padding_ratio: 0.5,
min_padding: 8.0,
max_padding: 20.0,
short_ma_days: 3,
long_ma_days: 5,
stock_short_ma_days: 3,
@@ -1138,6 +1162,9 @@ impl CnSmallCapRotationConfig {
base_index_level: 2000.0,
base_cap_floor: 7.0,
cap_span: 10.0,
padding_ratio: 0.5,
min_padding: 8.0,
max_padding: 20.0,
short_ma_days: 5,
long_ma_days: 10,
stock_short_ma_days: 5,
@@ -1150,23 +1177,29 @@ impl CnSmallCapRotationConfig {
signal_symbol: Some("000852.SH".to_string()),
skip_months: vec![],
skip_month_day_ranges: vec![
(1, 15, 30),
(4, 15, 29),
(8, 15, 31),
(10, 20, 30),
(12, 20, 30),
(None, 1, 15, 30),
(None, 4, 15, 29),
(None, 8, 15, 31),
(None, 10, 20, 30),
(None, 12, 20, 30),
],
}
}
fn in_skip_window(&self, date: NaiveDate) -> bool {
let year = date.year() as u32;
let month = date.month();
let day = date.day();
self.skip_months.contains(&month)
|| self
.skip_month_day_ranges
.iter()
.any(|(m, start_day, end_day)| month == *m && day >= *start_day && day <= *end_day)
.any(|(window_year, m, start_day, end_day)| {
window_year.map(|value| value == year).unwrap_or(true)
&& month == *m
&& day >= *start_day
&& day <= *end_day
})
}
}
@@ -1185,6 +1218,9 @@ impl CnSmallCapRotationStrategy {
config.cap_span,
config.xs,
config.stocknum,
config.padding_ratio,
config.min_padding,
config.max_padding,
),
config,
last_gross_exposure: None,
@@ -1508,17 +1544,22 @@ pub struct OmniMicroCapConfig {
pub base_index_level: f64,
pub base_cap_floor: f64,
pub cap_span: f64,
pub padding_ratio: f64,
pub min_padding: f64,
pub max_padding: f64,
pub benchmark_signal_symbol: String,
pub benchmark_short_ma_days: usize,
pub benchmark_long_ma_days: usize,
pub stock_short_ma_days: usize,
pub stock_mid_ma_days: usize,
pub stock_long_ma_days: usize,
pub stock_volume_short_ma_days: usize,
pub stock_volume_long_ma_days: usize,
pub rsi_rate: f64,
pub trade_rate: f64,
pub stop_loss_ratio: f64,
pub take_profit_ratio: f64,
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
pub skip_month_day_ranges: Vec<(Option<u32>, u32, u32, u32)>,
}
impl OmniMicroCapConfig {
@@ -1531,12 +1572,17 @@ impl OmniMicroCapConfig {
base_index_level: 2000.0,
base_cap_floor: 7.0,
cap_span: 10.0,
padding_ratio: 0.5,
min_padding: 8.0,
max_padding: 20.0,
benchmark_signal_symbol: "000001.SH".to_string(),
benchmark_short_ma_days: 5,
benchmark_long_ma_days: 10,
stock_short_ma_days: 5,
stock_mid_ma_days: 10,
stock_long_ma_days: 20,
stock_volume_short_ma_days: 5,
stock_volume_long_ma_days: 60,
rsi_rate: 1.0001,
trade_rate: 0.5,
stop_loss_ratio: 0.93,
@@ -1547,12 +1593,46 @@ impl OmniMicroCapConfig {
}
}
pub fn aiquant_v104() -> Self {
Self {
strategy_name: "aiquant-v1.0.4".to_string(),
refresh_rate: 120,
stocknum: 5,
xs: 4.0 / 500.0,
base_index_level: 2000.0,
base_cap_floor: 7.0,
cap_span: 10.0,
padding_ratio: 1.2,
min_padding: 29.5,
max_padding: 50.0,
benchmark_signal_symbol: "000852.SH".to_string(),
benchmark_short_ma_days: 5,
benchmark_long_ma_days: 20,
stock_short_ma_days: 5,
stock_mid_ma_days: 10,
stock_long_ma_days: 30,
stock_volume_short_ma_days: 5,
stock_volume_long_ma_days: 60,
rsi_rate: 1.0001,
trade_rate: 0.5,
stop_loss_ratio: 0.92,
take_profit_ratio: 1.16,
skip_month_day_ranges: Vec::new(),
}
}
fn in_skip_window(&self, date: NaiveDate) -> bool {
let year = date.year() as u32;
let month = date.month();
let day = date.day();
self.skip_month_day_ranges
.iter()
.any(|(m, start_day, end_day)| month == *m && day >= *start_day && day <= *end_day)
.any(|(window_year, m, start_day, end_day)| {
window_year.map(|value| value == year).unwrap_or(true)
&& month == *m
&& day >= *start_day
&& day <= *end_day
})
}
}
@@ -1724,11 +1804,23 @@ impl OmniMicroCapStrategy {
if !sizing_price.is_finite() || sizing_price <= 0.0 {
return 0;
}
let snapshot_requested_qty = self.round_lot_quantity(
let mut snapshot_requested_qty = self.round_lot_quantity(
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
minimum_order_quantity,
order_step_size,
);
while snapshot_requested_qty > 0 {
let gross_amount = sizing_price * snapshot_requested_qty as f64;
let cash_out = gross_amount + self.buy_commission(gross_amount);
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
break;
}
snapshot_requested_qty = self.decrement_order_quantity(
snapshot_requested_qty,
minimum_order_quantity,
order_step_size,
);
}
let projected_execution_price = self.projected_execution_price(market, OrderSide::Buy);
let projected_fill = self.projected_select_execution_fill(
ctx,
@@ -1740,14 +1832,15 @@ impl OmniMicroCapStrategy {
minimum_order_quantity,
order_step_size,
false,
Some(projected.cash()),
Some(order_value + 400.0),
Some(projected.cash().min(order_value)),
Some(order_value),
execution_state,
);
let mut quantity = snapshot_requested_qty;
while quantity > 0 {
let gross_amount = projected_execution_price * quantity as f64;
if gross_amount <= order_value + 400.0 && gross_amount <= projected.cash() + 1e-6 {
let cash_out = gross_amount + self.buy_commission(gross_amount);
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
break;
}
quantity =
@@ -1762,7 +1855,8 @@ impl OmniMicroCapStrategy {
.unwrap_or(projected_execution_price);
while quantity > 0 {
let gross_amount = execution_price * quantity as f64;
if gross_amount <= projected.cash() + 1e-6 {
let cash_out = gross_amount + self.buy_commission(gross_amount);
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
break;
}
quantity =
@@ -1778,7 +1872,7 @@ impl OmniMicroCapStrategy {
};
let gross_amount = fill.price * fill.quantity as f64;
let cash_out = gross_amount + self.buy_commission(gross_amount);
if gross_amount > projected.cash() + 1e-6 {
if cash_out > projected.cash() + 1e-6 || cash_out > order_value + 1e-6 {
return 0;
}
projected.apply_cash_delta(-cash_out);
@@ -2097,7 +2191,8 @@ impl OmniMicroCapStrategy {
&self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
) -> Result<(f64, f64, f64, f64), BacktestError> {
) -> Result<(f64, f64, f64, f64, f64), BacktestError> {
// 当前交易日的指数价格(用于MA计算和仓位控制)
let current_level = ctx
.data
.market_decision_close(date, &self.config.benchmark_signal_symbol)
@@ -2106,6 +2201,16 @@ impl OmniMicroCapStrategy {
symbol: self.config.benchmark_signal_symbol.clone(),
field: "decision_close",
})?;
// 前一交易日的指数价格(用于市值区间计算,模拟实盘场景)
let prev_level = if let Some(prev_date) = ctx.data.previous_trading_date(date, 1) {
ctx.data
.market_decision_close(prev_date, &self.config.benchmark_signal_symbol)
.unwrap_or(current_level)
} else {
current_level
};
let ma_short = ctx
.data
.market_decision_close_moving_average(
@@ -2137,14 +2242,25 @@ impl OmniMicroCapStrategy {
} else {
1.0
};
Ok((current_level, ma_short, ma_long, trading_ratio))
Ok((current_level, prev_level, ma_short, ma_long, trading_ratio))
}
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
let y = (index_level - self.config.base_index_level) * self.config.xs
+ self.config.base_cap_floor;
let start = y.round();
(start, start + self.config.cap_span)
let end = start + self.config.cap_span;
// Apply padding to expand the range
let span = end - start;
let padding = (span * self.config.padding_ratio)
.max(self.config.min_padding)
.min(self.config.max_padding);
let lower_bound = (start - padding).max(0.0);
let upper_bound = end + padding;
(lower_bound, upper_bound)
}
fn stock_passes_ma_filter(
@@ -2175,19 +2291,38 @@ impl OmniMicroCapStrategy {
return false;
};
ma_short > ma_mid * self.config.rsi_rate && ma_mid > ma_long
}
let ma_pass =
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
let instrument_name = ctx
.data
.instruments()
.get(symbol)
.map(|instrument| instrument.name.as_str())
.unwrap_or("");
instrument_name.contains("ST")
|| instrument_name.contains('*')
|| instrument_name.contains('退')
if !ma_pass {
return false;
}
if self.config.strategy_name.contains("aiquant")
|| self.config.strategy_name.contains("AiQuant")
|| self.config.strategy_name.contains("omni")
{
let Some(volume_ma5) = ctx.data.market_decision_volume_moving_average(
date,
symbol,
self.config.stock_volume_short_ma_days,
) else {
return false;
};
let Some(volume_ma_long) = ctx.data.market_decision_volume_moving_average(
date,
symbol,
self.config.stock_volume_long_ma_days,
) else {
return false;
};
if volume_ma5 >= volume_ma_long {
return false;
}
}
true
}
fn can_sell_position(&self, ctx: &StrategyContext<'_>, date: NaiveDate, symbol: &str) -> bool {
@@ -2203,11 +2338,15 @@ impl OmniMicroCapStrategy {
let Ok(candidate) = ctx.data.require_candidate(date, symbol) else {
return false;
};
let lower_limit_check_price = market.price(PriceField::Last);
!(market.paused
|| candidate.is_paused
|| !candidate.allow_sell
|| market.is_at_lower_limit_price(lower_limit_check_price))
ChinaAShareRiskControl::sell_rejection_reason(
date,
candidate,
market,
ctx.data.instrument(symbol),
Some(position),
ChinaAShareRiskControl::sell_check_price(market, PriceField::Last),
)
.is_none()
}
fn buy_rejection_reason(
@@ -2219,30 +2358,14 @@ impl OmniMicroCapStrategy {
let market = ctx.data.require_market(date, symbol)?;
let candidate = ctx.data.require_candidate(date, symbol)?;
if market.paused || candidate.is_paused {
return Ok(Some("paused".to_string()));
}
if candidate.is_st || self.special_name(ctx, symbol) {
return Ok(Some("st_or_special_name".to_string()));
}
if candidate.is_kcb {
return Ok(Some("kcb".to_string()));
}
if !candidate.allow_buy {
return Ok(Some("buy_disabled".to_string()));
}
if market.is_at_upper_limit_price(market.day_open)
|| market.is_at_upper_limit_price(market.buy_price(PriceField::Last))
{
return Ok(Some("upper_limit".to_string()));
}
if market.is_at_lower_limit_price(market.day_open)
|| market.is_at_lower_limit_price(market.sell_price(PriceField::Last))
{
return Ok(Some("lower_limit".to_string()));
}
if market.day_open <= 1.0 {
return Ok(Some("one_yuan".to_string()));
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
date,
candidate,
market,
ctx.data.instrument(symbol),
ChinaAShareRiskControl::buy_check_price(market, PriceField::Last),
) {
return Ok(Some(reason.to_string()));
}
if !self.truth_selection_contains(date, symbol)
&& !self.stock_passes_ma_filter(ctx, date, symbol)
@@ -2387,18 +2510,6 @@ fn omni_truth_stock_list_candidates() -> Vec<PathBuf> {
}
}
}
let suffix = PathBuf::from("data/demo/engine_truth_stock_list.csv");
let manifest_root = Path::new(env!("CARGO_MANIFEST_DIR"));
push_unique_truth_path(
&mut candidates,
manifest_root.join("../../../").join(&suffix),
);
if let Ok(current_dir) = env::current_dir() {
for ancestor in current_dir.ancestors() {
push_unique_truth_path(&mut candidates, ancestor.join(&suffix));
}
}
candidates
}
@@ -2546,25 +2657,27 @@ impl Strategy for OmniMicroCapStrategy {
});
}
let (index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
Ok(value) => value,
Err(BacktestError::Execution(message))
if message.contains("insufficient benchmark") =>
{
return Ok(StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: Vec::new(),
notes: vec![format!("warmup: {}", message)],
diagnostics: vec![
"insufficient history; skip trading on warmup dates".to_string(),
],
});
}
Err(err) => return Err(err),
};
let (band_low, band_high) = self.market_cap_band(index_level);
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) =
match self.trading_ratio(ctx, date) {
Ok(value) => value,
Err(BacktestError::Execution(message))
if message.contains("insufficient benchmark") =>
{
return Ok(StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: Vec::new(),
notes: vec![format!("warmup: {}", message)],
diagnostics: vec![
"insufficient history; skip trading on warmup dates".to_string(),
],
});
}
Err(err) => return Err(err),
};
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
let (band_low, band_high) = self.market_cap_band(prev_index_level);
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
let mut projected = ctx.portfolio.clone();
@@ -2586,10 +2699,10 @@ impl Strategy for OmniMicroCapStrategy {
let stop_hit = current_price
<= position.average_cost * self.config.stop_loss_ratio
+ self.stop_loss_tolerance(market);
let profit_hit = !market.is_at_upper_limit_price(current_price)
&& current_price / position.average_cost > self.config.take_profit_ratio;
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
if stop_hit || profit_hit {
let at_upper_limit = market.is_at_upper_limit_price(current_price);
if stop_hit || (profit_hit && !at_upper_limit) {
let sell_reason = if stop_hit {
"stop_loss_exit"
} else {
+3 -3
View File
@@ -277,7 +277,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
ManualField { name: "latest_symbol_open_order_status/latest_symbol_open_order_unfilled_qty".to_string(), field_type: "string/int".to_string(), detail: "当前证券最近一笔挂单的状态和未成交数量。".to_string() },
ManualField { name: "in_dynamic_universe/is_subscribed".to_string(), field_type: "bool".to_string(), detail: "当前证券是否在动态 universe 内,以及是否仍在订阅集合中。".to_string() },
ManualField { name: "stock_ma5/stock_ma10/stock_ma20/stock_ma30".to_string(), field_type: "float".to_string(), detail: "个股价格均线内建别名,按当前交易日前 N 个已完成交易日的收盘价计算;历史窗口不足时为 NaN,比较条件会自然不通过;15 日、45 日等任意窗口请改用 sma(\"close\", n)。".to_string() },
ManualField { name: "stock_volume_ma5/stock_volume_ma10/stock_volume_ma20/stock_volume_ma60".to_string(), field_type: "float".to_string(), detail: "个股成交量均线内建别名,按当前交易日前 N 个已完成交易日的成交量计算,不包含回测当天未来成交量;历史窗口不足时为 NaN,比较条件会自然不通过;任意窗口请改用 rolling_mean(\"volume\", n)。".to_string() },
ManualField { name: "stock_volume_ma5/stock_volume_ma10/stock_volume_ma20/stock_volume_ma60/stock_volume_ma100".to_string(), field_type: "float".to_string(), detail: "个股成交量均线内建别名,按当前交易日前 N 个已完成交易日的成交量计算,不包含回测当天未来成交量;历史窗口不足时为 NaN,比较条件会自然不通过;任意窗口请改用 rolling_mean(\"volume\", n)。".to_string() },
ManualField { name: "factors[\"field\"] / factor(\"field\")".to_string(), field_type: "float/string".to_string(), detail: "当前证券当日可用因子。默认可用字段以手册的“可用指标、参数和字段”清单为准;自定义因子需要预先写入策略数据或 extra_factors。数值字段返回数字,字符串字段返回字符串。".to_string() },
ManualField { name: "listed_days".to_string(), field_type: "int".to_string(), detail: "上市天数。".to_string() },
],
@@ -546,8 +546,8 @@ pub fn build_optimization_prompt(
prompt.push_str("你是 OmniQuant 平台策略脚本优化器。必须输出完整、可运行的平台策略脚本,不要输出解释文本。\n");
prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n");
prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n");
prompt.push_str("只修改与优化目标相关的少量参数或过滤条件,保留原策略的市场、基准、信号指数和核心风控;不引入手册未列出的字段或外部平台 API 名称。\n");
prompt.push_str("优化可以调整调仓周期、持仓数、市值带、filter.stock_expr、ordering.rank_expr、allocation.buy_scale、止盈止损;如上一轮无交易或质量分过低,必须先放宽过滤条件并优先使用已入库指标因子、rolling_mean/ma/vma/rolling_stddev/pct_change 等支持函数\n");
prompt.push_str("优化不限制在原策略已有参数或少量扰动。只要 OmniQuant/FIDC 已支持,可以自由增加、修改、删除策略代码、参数、候选池、过滤函数、排序、仓位、止盈止损、调仓周期、指标因子和辅助函数;不引入手册未列出的字段或外部平台 API 名称。\n");
prompt.push_str("可以使用所有已入库日频字段、指标因子和表达式函数,例如 rolling_mean/ma/vma/rolling_sum/rolling_stddev/pct_change/factor/factor_value/factors;如上一轮无交易或质量分过低,必须先扩大候选覆盖并修正不可交易过滤,再优化收益\n");
prompt.push_str("优化目标:\n");
prompt.push_str(&format!("- {}\n\n", request.objective));
prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n");
+22 -2
View File
@@ -78,6 +78,9 @@ pub struct DynamicMarketCapBandSelector {
pub cap_span: f64,
pub xs: f64,
pub top_n: usize,
pub padding_ratio: f64,
pub min_padding: f64,
pub max_padding: f64,
}
impl DynamicMarketCapBandSelector {
@@ -87,6 +90,9 @@ impl DynamicMarketCapBandSelector {
cap_span: f64,
xs: f64,
top_n: usize,
padding_ratio: f64,
min_padding: f64,
max_padding: f64,
) -> Self {
Self {
base_index_level,
@@ -94,11 +100,14 @@ impl DynamicMarketCapBandSelector {
cap_span,
xs,
top_n,
padding_ratio,
min_padding,
max_padding,
}
}
pub fn demo(top_n: usize) -> Self {
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n)
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n, 0.5, 8.0, 20.0)
}
pub fn regime(&self, benchmark_level: f64) -> BandRegime {
@@ -114,7 +123,18 @@ impl DynamicMarketCapBandSelector {
pub fn band_for_level(&self, benchmark_level: f64) -> (f64, f64) {
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
let low = start.round();
(low, low + self.cap_span)
let high = low + self.cap_span;
// Apply padding to expand the range
let span = high - low;
let padding = (span * self.padding_ratio)
.max(self.min_padding)
.min(self.max_padding);
let lower_bound = (low - padding).max(0.0);
let upper_bound = high + padding;
(lower_bound, upper_bound)
}
}
+24 -3
View File
@@ -23,6 +23,7 @@ fn candidate() -> CandidateEligibility {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}
}
@@ -61,7 +62,7 @@ fn china_cost_model_applies_minimum_commission_and_stamp_tax() {
assert_eq!(buy.stamp_tax, 0.0);
let sell = model.calculate(d(2023, 8, 25), OrderSide::Sell, 100_000.0);
assert!((sell.commission - 30.0).abs() < 1e-9);
assert!((sell.commission - 80.0).abs() < 1e-9);
assert!((sell.stamp_tax - 100.0).abs() < 1e-9);
}
@@ -112,7 +113,7 @@ fn china_cost_model_tracks_minimum_commission_per_order_id() {
assert!((first.commission - 5.0).abs() < 1e-9);
assert!(second.commission.abs() < 1e-9);
assert!((third.commission - 1.6).abs() < 1e-9);
assert!((third.commission - 12.6).abs() < 1e-9);
assert!((another_order.commission - 5.0).abs() < 1e-9);
}
@@ -175,7 +176,7 @@ fn china_rule_hooks_block_buy_at_limit_up_and_sell_at_limit_down() {
}
#[test]
fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
fn china_rule_hooks_use_strict_price_limits() {
let hooks = ChinaEquityRuleHooks;
let candidate = candidate();
@@ -184,6 +185,13 @@ fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
..snapshot(10.9995, 11.0, 9.0)
};
let buy_check = hooks.can_buy(d(2024, 1, 3), &near_upper, &candidate, PriceField::Open);
assert!(buy_check.allowed);
let exact_upper = DailyMarketSnapshot {
price_tick: 0.001,
..snapshot(11.0, 11.0, 9.0)
};
let buy_check = hooks.can_buy(d(2024, 1, 3), &exact_upper, &candidate, PriceField::Open);
assert!(!buy_check.allowed);
let near_lower = DailyMarketSnapshot {
@@ -199,6 +207,19 @@ fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
&position,
PriceField::Open,
);
assert!(sell_check.allowed);
let exact_lower = DailyMarketSnapshot {
price_tick: 0.001,
..snapshot(9.0, 11.0, 9.0)
};
let sell_check = hooks.can_sell(
d(2024, 1, 3),
&exact_lower,
&candidate,
&position,
PriceField::Open,
);
assert!(!sell_check.allowed);
}
+4 -1
View File
@@ -221,6 +221,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: ex_date,
@@ -232,6 +233,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: payable_date,
@@ -243,6 +245,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -300,7 +303,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
PriceField::Open,
),
BacktestConfig {
initial_cash: 11_005.0,
initial_cash: 11_008.0,
benchmark_code: "000300.SH".to_string(),
start_date: Some(buy_date),
end_date: Some(payable_date),
@@ -0,0 +1,646 @@
use chrono::{Duration, NaiveDate, NaiveTime};
use fidc_core::{
BacktestConfig, BacktestEngine, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility,
ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet,
IntradayExecutionQuote, MatchingType, OrderIntent, PriceField, Strategy, StrategyContext,
StrategyDecision,
};
use std::sync::{Arc, Mutex};
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
}
fn t(hour: u32, minute: u32, second: u32) -> NaiveTime {
NaiveTime::from_hms_opt(hour, minute, second).expect("valid time")
}
#[derive(Default)]
struct DecisionQuoteReader {
day_count: usize,
}
impl Strategy for DecisionQuoteReader {
fn name(&self) -> &str {
"decision_quote_reader"
}
fn decision_quote_times(&self) -> Vec<NaiveTime> {
vec![t(10, 40, 0)]
}
fn on_day(
&mut self,
ctx: &StrategyContext<'_>,
) -> Result<StrategyDecision, fidc_core::BacktestError> {
self.day_count += 1;
if self.day_count == 1 {
return Ok(StrategyDecision {
order_intents: vec![OrderIntent::Value {
symbol: "000001.SZ".to_string(),
value: 5_000.0,
reason: "seed_position".to_string(),
}],
..StrategyDecision::default()
});
}
assert!(
ctx.portfolio.position("000001.SZ").is_some(),
"second day should carry the first day position"
);
let quote_loaded_before_decision = ctx
.data
.execution_quotes_on(ctx.execution_date, "000001.SZ")
.iter()
.any(|quote| quote.timestamp.time() == t(10, 39, 59) && quote.last_price == 11.0);
assert!(
quote_loaded_before_decision,
"engine must load declared decision quote before strategy.on_day"
);
Ok(StrategyDecision::default())
}
}
#[test]
fn engine_preloads_declared_decision_quotes_for_current_positions() {
let first = d(2026, 1, 5);
let second = d(2026, 1, 6);
let data = DataSet::from_components(
Vec::new(),
vec![
DailyMarketSnapshot {
date: first,
symbol: "000001.SZ".to_string(),
timestamp: Some("2026-01-05 15:00:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.2,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
prev_close: 9.8,
volume: 10_000,
tick_volume: 1_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 10.78,
lower_limit: 8.82,
price_tick: 0.01,
},
DailyMarketSnapshot {
date: second,
symbol: "000001.SZ".to_string(),
timestamp: Some("2026-01-06 15:00:00".to_string()),
day_open: 10.5,
open: 10.5,
high: 11.2,
low: 10.4,
close: 10.6,
last_price: 10.6,
bid1: 10.6,
ask1: 10.6,
prev_close: 10.0,
volume: 10_000,
tick_volume: 1_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
},
],
vec![
DailyFactorSnapshot {
date: first,
symbol: "000001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 10.0,
turnover_ratio: None,
effective_turnover_ratio: None,
extra_factors: Default::default(),
},
DailyFactorSnapshot {
date: second,
symbol: "000001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 10.0,
turnover_ratio: None,
effective_turnover_ratio: None,
extra_factors: Default::default(),
},
],
vec![
CandidateEligibility {
date: first,
symbol: "000001.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,
risk_level_code: None,
},
CandidateEligibility {
date: second,
symbol: "000001.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,
risk_level_code: None,
},
],
vec![
BenchmarkSnapshot {
date: first,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 990.0,
volume: 1_000_000,
},
BenchmarkSnapshot {
date: second,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1001.0,
prev_close: 1000.0,
volume: 1_000_000,
},
],
)
.expect("dataset");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_matching_type(MatchingType::NextTickLast)
.with_intraday_execution_start_time(t(10, 40, 0));
let config = BacktestConfig {
initial_cash: 10_000.0,
benchmark_code: "000852.SH".to_string(),
start_date: Some(first),
end_date: Some(second),
decision_lag_trading_days: 0,
execution_price_field: PriceField::Last,
};
let mut engine = BacktestEngine::new(data, DecisionQuoteReader::default(), broker, config)
.with_execution_quote_loader(move |request| {
assert_eq!(
request.end_time, None,
"decision quote preload must request latest quote at or before start_time"
);
Ok(request
.symbols
.into_iter()
.map(|symbol| IntradayExecutionQuote {
date: request.date,
symbol,
timestamp: request.date.and_time(t(10, 39, 59)),
last_price: if request.date == second { 11.0 } else { 10.0 },
bid1: if request.date == second { 11.0 } else { 10.0 },
ask1: if request.date == second { 11.0 } else { 10.0 },
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 100_000.0,
trading_phase: Some("continuous".to_string()),
})
.collect())
});
engine.run().expect("backtest should run");
}
#[test]
fn engine_reuses_preloaded_decision_quotes_without_loader_call() {
let first = d(2026, 1, 5);
let second = d(2026, 1, 6);
let data = DataSet::from_components_with_actions_and_quotes(
Vec::new(),
vec![
DailyMarketSnapshot {
date: first,
symbol: "000001.SZ".to_string(),
timestamp: Some("2026-01-05 15:00:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.2,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
prev_close: 9.8,
volume: 10_000,
tick_volume: 1_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 10.78,
lower_limit: 8.82,
price_tick: 0.01,
},
DailyMarketSnapshot {
date: second,
symbol: "000001.SZ".to_string(),
timestamp: Some("2026-01-06 15:00:00".to_string()),
day_open: 10.5,
open: 10.5,
high: 11.2,
low: 10.4,
close: 10.6,
last_price: 10.6,
bid1: 10.6,
ask1: 10.6,
prev_close: 10.0,
volume: 10_000,
tick_volume: 1_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
},
],
vec![
DailyFactorSnapshot {
date: first,
symbol: "000001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 10.0,
turnover_ratio: None,
effective_turnover_ratio: None,
extra_factors: Default::default(),
},
DailyFactorSnapshot {
date: second,
symbol: "000001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 10.0,
turnover_ratio: None,
effective_turnover_ratio: None,
extra_factors: Default::default(),
},
],
vec![
CandidateEligibility {
date: first,
symbol: "000001.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,
risk_level_code: None,
},
CandidateEligibility {
date: second,
symbol: "000001.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,
risk_level_code: None,
},
],
vec![
BenchmarkSnapshot {
date: first,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 990.0,
volume: 1_000_000,
},
BenchmarkSnapshot {
date: second,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1001.0,
prev_close: 1000.0,
volume: 1_000_000,
},
],
Vec::new(),
vec![
IntradayExecutionQuote {
date: first,
symbol: "000001.SZ".to_string(),
timestamp: first.and_time(t(10, 39, 59)),
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 100_000.0,
trading_phase: Some("continuous".to_string()),
},
IntradayExecutionQuote {
date: second,
symbol: "000001.SZ".to_string(),
timestamp: second.and_time(t(10, 39, 59)),
last_price: 11.0,
bid1: 11.0,
ask1: 11.0,
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 100_000.0,
trading_phase: Some("continuous".to_string()),
},
],
)
.expect("dataset");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_matching_type(MatchingType::NextTickLast)
.with_intraday_execution_start_time(t(10, 40, 0));
let config = BacktestConfig {
initial_cash: 10_000.0,
benchmark_code: "000852.SH".to_string(),
start_date: Some(first),
end_date: Some(second),
decision_lag_trading_days: 0,
execution_price_field: PriceField::Last,
};
let loader_calls = Arc::new(Mutex::new(0usize));
let captured_loader_calls = Arc::clone(&loader_calls);
let mut engine = BacktestEngine::new(data, DecisionQuoteReader::default(), broker, config)
.with_execution_quote_loader(move |_| {
*captured_loader_calls.lock().expect("loader mutex") += 1;
Ok(Vec::new())
});
engine.run().expect("backtest should run");
assert_eq!(
*loader_calls.lock().expect("loader mutex"),
0,
"preloaded execution quotes should satisfy decision-time quote requests"
);
}
#[derive(Default)]
struct MultiTimeDecisionQuoteReader {
day_count: usize,
}
impl Strategy for MultiTimeDecisionQuoteReader {
fn name(&self) -> &str {
"multi_time_decision_quote_reader"
}
fn decision_quote_times(&self) -> Vec<NaiveTime> {
vec![t(10, 31, 0), t(10, 40, 0)]
}
fn on_day(
&mut self,
ctx: &StrategyContext<'_>,
) -> Result<StrategyDecision, fidc_core::BacktestError> {
self.day_count += 1;
if self.day_count == 1 {
return Ok(StrategyDecision {
order_intents: vec![OrderIntent::Value {
symbol: "000001.SZ".to_string(),
value: 5_000.0,
reason: "seed_position".to_string(),
}],
..StrategyDecision::default()
});
}
let quote_times = ctx
.data
.execution_quotes_on(ctx.execution_date, "000001.SZ")
.iter()
.map(|quote| quote.timestamp.time())
.collect::<Vec<_>>();
assert!(
quote_times.contains(&t(10, 30, 59)),
"10:31 decision quote must be loaded"
);
assert!(
quote_times.contains(&t(10, 39, 59)),
"10:40 decision quote must not be skipped because 10:31 was loaded"
);
Ok(StrategyDecision::default())
}
}
#[test]
fn engine_loads_distinct_decision_quote_times_on_same_day() {
let first = d(2026, 1, 5);
let second = d(2026, 1, 6);
let data = DataSet::from_components(
Vec::new(),
vec![
DailyMarketSnapshot {
date: first,
symbol: "000001.SZ".to_string(),
timestamp: Some("2026-01-05 15:00:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.2,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
prev_close: 9.8,
volume: 10_000,
tick_volume: 1_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 10.78,
lower_limit: 8.82,
price_tick: 0.01,
},
DailyMarketSnapshot {
date: second,
symbol: "000001.SZ".to_string(),
timestamp: Some("2026-01-06 15:00:00".to_string()),
day_open: 10.5,
open: 10.5,
high: 11.2,
low: 10.4,
close: 10.6,
last_price: 10.6,
bid1: 10.6,
ask1: 10.6,
prev_close: 10.0,
volume: 10_000,
tick_volume: 1_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
},
],
vec![
DailyFactorSnapshot {
date: first,
symbol: "000001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 10.0,
turnover_ratio: None,
effective_turnover_ratio: None,
extra_factors: Default::default(),
},
DailyFactorSnapshot {
date: second,
symbol: "000001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 10.0,
turnover_ratio: None,
effective_turnover_ratio: None,
extra_factors: Default::default(),
},
],
vec![
CandidateEligibility {
date: first,
symbol: "000001.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,
risk_level_code: None,
},
CandidateEligibility {
date: second,
symbol: "000001.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,
risk_level_code: None,
},
],
vec![
BenchmarkSnapshot {
date: first,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 990.0,
volume: 1_000_000,
},
BenchmarkSnapshot {
date: second,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1001.0,
prev_close: 1000.0,
volume: 1_000_000,
},
],
)
.expect("dataset");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_matching_type(MatchingType::NextTickLast)
.with_intraday_execution_start_time(t(10, 40, 0));
let config = BacktestConfig {
initial_cash: 10_000.0,
benchmark_code: "000852.SH".to_string(),
start_date: Some(first),
end_date: Some(second),
decision_lag_trading_days: 0,
execution_price_field: PriceField::Last,
};
let requests = Arc::new(Mutex::new(Vec::<(NaiveDate, NaiveTime)>::new()));
let captured_requests = Arc::clone(&requests);
let mut engine = BacktestEngine::new(
data,
MultiTimeDecisionQuoteReader::default(),
broker,
config,
)
.with_execution_quote_loader(move |request| {
let start_time = request
.start_time
.expect("decision quote loader request must include start_time");
captured_requests
.lock()
.expect("request mutex")
.push((request.date, start_time));
Ok(request
.symbols
.into_iter()
.map(|symbol| IntradayExecutionQuote {
date: request.date,
symbol,
timestamp: request.date.and_time(start_time) - Duration::seconds(1),
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 100_000.0,
trading_phase: Some("continuous".to_string()),
})
.collect())
});
engine.run().expect("backtest should run");
let requests = requests.lock().expect("request mutex").clone();
assert!(
requests.contains(&(second, t(10, 31, 0))),
"second-day 10:31 quote request is required"
);
assert!(
requests.contains(&(second, t(10, 40, 0))),
"second-day 10:40 quote request must not be skipped by earlier quote"
);
}
+14 -7
View File
@@ -43,7 +43,8 @@ impl Strategy for BuyThenHoldStrategy {
#[test]
fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run() {
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(
vec![
Instrument {
@@ -52,8 +53,8 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
board: "SZ".to_string(),
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: Some(date1),
status: "delisted".to_string(),
delisted_at: Some(delist_date),
status: "active".to_string(),
},
Instrument {
symbol: "000002.SZ".to_string(),
@@ -115,7 +116,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
DailyMarketSnapshot {
date: date2,
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,
open: 5.1,
high: 5.2,
@@ -179,6 +180,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date1,
@@ -190,6 +192,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -201,6 +204,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -273,7 +277,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: Some(date2),
status: "delisted".to_string(),
status: "active".to_string(),
},
Instrument {
symbol: "000002.SZ".to_string(),
@@ -399,6 +403,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date1,
@@ -410,6 +415,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -421,6 +427,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -492,7 +499,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
.iter()
.find(|holding| holding.symbol == "000002.SZ")
.expect("successor holding exists");
assert_eq!(successor_holding.quantity, 500);
assert_eq!(successor_holding.quantity, 450);
assert!(
result
.holdings_summary
@@ -503,6 +510,6 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
event
.note
.contains("successor_conversion 000001.SZ->000002.SZ")
&& event.note.contains("cash=1000.00")
&& event.note.contains("cash=900.00")
}));
}
+24 -2
View File
@@ -87,6 +87,7 @@ fn single_day_anchor_data(date: NaiveDate) -> DataSet {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -154,6 +155,7 @@ fn candidate_row(date: NaiveDate, symbol: &str) -> CandidateEligibility {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}
}
@@ -329,7 +331,7 @@ impl Strategy for AuctionOrderStrategy {
exit_symbols: BTreeSet::new(),
order_intents: vec![fidc_core::OrderIntent::Value {
symbol: "000001.SZ".to_string(),
value: 1_000.0,
value: 1_010.0,
reason: "auction_buy".to_string(),
}],
notes: Vec::new(),
@@ -1116,6 +1118,7 @@ fn engine_runs_strategy_hooks_in_daily_order() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -1127,6 +1130,7 @@ fn engine_runs_strategy_hooks_in_daily_order() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -1273,6 +1277,7 @@ fn engine_executes_open_auction_decisions_before_on_day() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1371,6 +1376,7 @@ fn engine_executes_futures_order_intents_against_future_account() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1960,6 +1966,7 @@ fn engine_runs_subscribed_tick_hooks_and_executes_tick_orders() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2143,6 +2150,7 @@ fn strategy_context_exposes_engine_native_data_helpers() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
})
.collect::<Vec<_>>();
let benchmarks = [
@@ -2302,6 +2310,7 @@ fn strategy_context_exposes_final_order_runtime_view() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2555,6 +2564,7 @@ fn engine_applies_account_cash_flow_and_financing_intents() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -2566,6 +2576,7 @@ fn engine_applies_account_cash_flow_and_financing_intents() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -2737,6 +2748,7 @@ fn engine_rejects_pending_limit_orders_at_market_close() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -2748,6 +2760,7 @@ fn engine_rejects_pending_limit_orders_at_market_close() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -2938,6 +2951,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -2949,6 +2963,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date3,
@@ -2960,6 +2975,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -3184,6 +3200,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date2,
@@ -3195,6 +3212,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: date3,
@@ -3206,6 +3224,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -3538,6 +3557,7 @@ fn engine_applies_dynamic_universe_and_subscription_directives() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: *date,
@@ -3549,6 +3569,7 @@ fn engine_applies_dynamic_universe_and_subscription_directives() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
]
})
@@ -3671,6 +3692,7 @@ fn engine_exposes_current_process_context_to_strategies() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -3734,7 +3756,7 @@ impl Strategy for BuyMissingRowThenHoldStrategy {
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::Value {
symbol: "601028.SH".to_string(),
value: 1_000.0,
value: 1_010.0,
reason: "seed_position".to_string(),
}],
notes: Vec::new(),
+579 -8
View File
@@ -1,12 +1,115 @@
use chrono::{NaiveDate, NaiveTime};
use fidc_core::{
AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel,
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, Instrument,
IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState, PriceField,
ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, DynamicSlippageConfig,
Instrument, IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState,
PriceField, ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
};
use std::collections::{BTreeMap, BTreeSet};
fn order_value_rounding_data(date: NaiveDate, symbol: &str, price: f64) -> DataSet {
DataSet::from_components(
vec![Instrument {
symbol: symbol.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: symbol.to_string(),
timestamp: Some(format!("{date} 09:33:00")),
day_open: price,
open: price,
high: price,
low: price,
close: price,
last_price: price,
bid1: price,
ask1: price,
prev_close: price,
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: price * 1.1,
lower_limit: price * 0.9,
price_tick: 0.01,
}],
vec![DailyFactorSnapshot {
date,
symbol: symbol.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: 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,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
benchmark: "000300.SH".to_string(),
open: 100.0,
close: 100.0,
prev_close: 99.0,
volume: 1_000_000,
}],
)
.expect("dataset")
}
fn execute_single_value_order(
date: NaiveDate,
data: &DataSet,
symbol: &str,
value: f64,
) -> (PortfolioState, fidc_core::BrokerExecutionReport) {
let mut portfolio = PortfolioState::new(20_000.0);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Open,
)
.with_strict_value_budget(true);
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: symbol.to_string(),
value,
reason: "test_order_value_rounding".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
(portfolio, report)
}
#[test]
fn broker_executes_explicit_order_value_buy() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -63,6 +166,7 @@ fn broker_executes_explicit_order_value_buy() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -122,6 +226,172 @@ fn broker_executes_explicit_order_value_buy() {
assert!(portfolio.cash() < 1_000_000.0);
}
#[test]
fn broker_order_value_rounds_to_nearest_lot_when_min_lot_is_affordable() {
let date = NaiveDate::from_ymd_opt(2025, 1, 24).unwrap();
let symbol = "003017.SZ";
let data = order_value_rounding_data(date, symbol, 19.97);
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 3_938.13);
assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 100);
assert_eq!(portfolio.position(symbol).expect("position").quantity, 100);
}
#[test]
fn broker_order_value_budget_includes_buy_commission() {
let date = NaiveDate::from_ymd_opt(2025, 6, 23).unwrap();
let symbol = "605303.SH";
let data = order_value_rounding_data(date, symbol, 11.93);
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_776.0);
assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 300);
assert_eq!(portfolio.position(symbol).expect("position").quantity, 300);
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_848.0);
assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 400);
assert_eq!(portfolio.position(symbol).expect("position").quantity, 400);
}
#[test]
fn broker_delayed_limit_open_sell_uses_tick_price() {
let date = NaiveDate::from_ymd_opt(2025, 6, 27).unwrap();
let prev_date = NaiveDate::from_ymd_opt(2025, 6, 26).unwrap();
let symbol = "300635.SZ";
let data = DataSet::from_components_with_actions_and_quotes(
vec![Instrument {
symbol: symbol.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: symbol.to_string(),
timestamp: Some("2025-06-27 09:31:00".to_string()),
day_open: 12.55,
open: 12.55,
high: 13.16,
low: 12.26,
close: 12.36,
last_price: 12.39,
bid1: 12.39,
ask1: 12.40,
prev_close: 13.24,
volume: 329_575,
tick_volume: 10_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 14.56,
lower_limit: 11.92,
price_tick: 0.01,
}],
vec![DailyFactorSnapshot {
date,
symbol: symbol.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: 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,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
benchmark: "000300.SH".to_string(),
open: 100.0,
close: 100.0,
prev_close: 99.0,
volume: 1_000_000,
}],
Vec::new(),
vec![IntradayExecutionQuote {
date,
symbol: symbol.to_string(),
timestamp: date.and_hms_opt(9, 31, 0).unwrap(),
last_price: 12.39,
bid1: 12.39,
ask1: 12.40,
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 123_900.0,
trading_phase: Some("continuous".to_string()),
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000.0);
portfolio.position_mut(symbol).buy(prev_date, 800, 10.92);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Last,
)
.with_matching_type(MatchingType::NextTickLast)
.with_intraday_execution_start_time(NaiveTime::from_hms_opt(9, 31, 0).unwrap())
.with_volume_limit(false)
.with_liquidity_limit(false);
let report = broker
.execute(
date,
&mut portfolio,
&data,
&StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::TargetValue {
symbol: symbol.to_string(),
target_value: 0.0,
reason: "delayed_limit_open_sell".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 800);
assert_eq!(report.fill_events[0].price, 12.39);
assert!(portfolio.position(symbol).is_none());
}
#[test]
fn broker_order_value_skips_when_one_lot_exceeds_budget() {
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
let symbol = "300321.SZ";
let data = order_value_rounding_data(date, symbol, 20.38);
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 2_000.0);
assert!(report.fill_events.is_empty());
assert!(portfolio.position(symbol).is_none());
}
#[test]
fn broker_executes_order_shares_and_order_lots() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -178,6 +448,7 @@ fn broker_executes_order_shares_and_order_lots() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -303,6 +574,7 @@ fn broker_executes_target_shares_like_order_to() {
allow_buy: true,
allow_sell: true,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -459,6 +731,7 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date,
@@ -470,6 +743,7 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![BenchmarkSnapshot {
@@ -600,6 +874,7 @@ fn broker_executes_target_portfolio_smart_with_algo_order_style() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -740,6 +1015,7 @@ fn broker_executes_order_percent_and_target_percent() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -778,7 +1054,7 @@ fn broker_executes_order_percent_and_target_percent() {
)
.expect("percent execution");
assert_eq!(percent_report.fill_events.len(), 1);
assert_eq!(percent_report.fill_events[0].quantity, 10_000);
assert_eq!(percent_report.fill_events[0].quantity, 9_900);
let mut target_percent_portfolio = PortfolioState::new(1_000_000.0);
let target_percent_report = broker
@@ -860,6 +1136,7 @@ fn broker_uses_day_open_price_for_open_auction_matching() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -963,6 +1240,7 @@ fn broker_open_auction_uses_auction_volume_without_quote_liquidity() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1063,6 +1341,7 @@ fn broker_cancels_buy_when_open_hits_upper_limit() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1175,6 +1454,7 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1218,6 +1498,111 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
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,
risk_level_code: None,
}],
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]
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -1274,6 +1659,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1287,7 +1673,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
vec![IntradayExecutionQuote {
date,
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,
bid1: 9.99,
ask1: 10.01,
@@ -1330,6 +1716,9 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
assert_eq!(report.fill_events.len(), 1);
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
let position = portfolio.position("000002.SZ").expect("position");
assert!((position.last_price - 10.0).abs() < 1e-9);
assert!((position.market_value() - position.quantity as f64 * 10.0).abs() < 1e-6);
}
#[test]
@@ -1388,6 +1777,7 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1433,11 +1823,127 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
assert!(
report.order_events[0]
.reason
.contains("no execution quotes after start")
.contains("no execution quotes at or before start")
);
assert!(portfolio.position("000002.SZ").is_none());
}
#[test]
fn broker_executes_intraday_last_on_start_quote_without_trade_delta() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components_with_actions_and_quotes(
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 09:33:00".to_string()),
day_open: 15.0,
open: 15.0,
high: 15.5,
low: 14.8,
close: 15.2,
last_price: 15.2,
bid1: 15.19,
ask1: 15.21,
prev_close: 15.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: 16.5,
lower_limit: 13.5,
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,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
benchmark: "000300.SH".to_string(),
open: 100.0,
close: 100.0,
prev_close: 99.0,
volume: 1_000_000,
}],
Vec::new(),
vec![IntradayExecutionQuote {
date,
symbol: "000002.SZ".to_string(),
timestamp: date.and_hms_opt(9, 33, 0).unwrap(),
last_price: 15.2,
bid1: 15.19,
ask1: 15.21,
bid1_volume: 8,
ask1_volume: 8,
volume_delta: 0,
amount_delta: 0.0,
trading_phase: Some("continuous".to_string()),
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000_000.0);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Last,
)
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(9, 33, 0).unwrap());
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: 4_000.0,
reason: "start_quote".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 200);
assert!((report.fill_events[0].price - 15.2).abs() < 1e-9);
assert_eq!(report.order_events[0].status, OrderStatus::Filled);
}
#[test]
fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -1494,6 +2000,7 @@ fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1507,7 +2014,7 @@ fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted
vec![IntradayExecutionQuote {
date,
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,
bid1: 10.01,
ask1: 10.03,
@@ -1621,6 +2128,7 @@ fn broker_cancels_market_buy_when_tick_has_no_volume() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1724,6 +2232,7 @@ fn broker_splits_intraday_quote_fills_and_tracks_commission_by_order() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -1884,6 +2393,7 @@ fn broker_aggregates_intraday_quote_fills_into_vwap_leg() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2028,6 +2538,7 @@ fn broker_executes_algo_vwap_value_with_time_window() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2185,6 +2696,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2256,7 +2768,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::AlgoPercent {
symbol: "000002.SZ".to_string(),
percent: 0.0036,
percent: 0.0037,
style: AlgoOrderStyle::Twap,
start_time: Some(NaiveTime::from_hms_opt(10, 0, 0).unwrap()),
end_time: Some(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
@@ -2344,6 +2856,7 @@ fn broker_uses_best_own_price_for_intraday_matching() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2458,6 +2971,7 @@ fn broker_uses_best_counterparty_price_for_intraday_matching() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -2622,6 +3136,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
allow_sell: false,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date,
@@ -2633,6 +3148,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![BenchmarkSnapshot {
@@ -2809,6 +3325,7 @@ fn rebalance_uses_prev_close_for_open_auction_valuation() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date,
@@ -2820,6 +3337,7 @@ fn rebalance_uses_prev_close_for_open_auction_valuation() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![BenchmarkSnapshot {
@@ -2990,6 +3508,7 @@ fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date,
@@ -3001,6 +3520,7 @@ fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![BenchmarkSnapshot {
@@ -3126,6 +3646,7 @@ fn broker_uses_board_specific_min_quantity_and_step_size_for_buy_sizing() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -3224,6 +3745,7 @@ fn broker_allows_bjse_quantities_above_minimum_without_round_lot_step() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -3324,6 +3846,7 @@ fn broker_allows_full_odd_lot_sell_when_liquidating_position() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,
@@ -3438,6 +3961,7 @@ fn same_day_sell_then_rebuy_reinserts_position_at_end() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
})
.collect::<Vec<_>>();
let data = DataSet::from_components(
@@ -3605,6 +4129,7 @@ fn two_day_limit_order_data(day1_open: f64, day2_open: f64) -> DataSet {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
CandidateEligibility {
date: day2,
@@ -3616,6 +4141,7 @@ fn two_day_limit_order_data(day1_open: f64, day2_open: f64) -> DataSet {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
},
],
vec![
@@ -3748,6 +4274,50 @@ fn broker_uses_limit_price_slippage_for_limit_orders() {
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
}
#[test]
fn broker_rejects_limit_buy_when_final_execution_price_reaches_upper_limit() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = two_day_limit_order_data(10.0, 10.2);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Open,
)
.with_slippage_model(SlippageModel::LimitPrice);
let mut portfolio = PortfolioState::new(1_000_000.0);
let report = broker
.execute(
date,
&mut portfolio,
&data,
&StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::LimitShares {
symbol: "000002.SZ".to_string(),
quantity: 200,
limit_price: 11.0,
reason: "limit_entry_at_upper_limit".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
assert!(report.fill_events.is_empty());
assert_eq!(report.order_events.len(), 1);
assert_eq!(report.order_events[0].status, OrderStatus::Canceled);
assert!(
report.order_events[0]
.reason
.contains("open at or above upper limit")
);
assert!(portfolio.position("000002.SZ").is_none());
}
#[test]
fn broker_executes_limit_value_and_limit_percent_intents() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -3969,6 +4539,7 @@ fn broker_reserves_sellable_quantity_for_open_limit_sells() {
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
risk_level_code: None,
}],
vec![BenchmarkSnapshot {
date,