Compare commits

..

23 Commits

Author SHA1 Message Date
boris 0cfb7625bf 修正回测指标和成交时间口径 2026-06-14 01:08:29 +08:00
boris 4c3653e009 修正AiQuant兼容回测盘中估值口径 2026-06-13 23:32:24 +08:00
boris 9512a5dd2f 修正点时刻执行报价口径 2026-06-13 21:55:08 +08:00
boris 4f5e3f7162 统一调度时刻使用已知tick 2026-06-13 21:41:37 +08:00
boris 89c2ff58f8 修正点时刻回测使用最新tick 2026-06-13 21:27:21 +08:00
boris 0813ce3ffb 修正目标市值盘中估值口径 2026-06-13 21:09:38 +08:00
boris a030554ab6 修正平台策略滚动量能口径 2026-06-13 20:48:52 +08:00
boris e1d36fc0c7 修正平台表达式回测口径 2026-06-13 20:01:24 +08:00
boris 0dca8e0eff 完善策略调度执行价校验 2026-06-13 15:26:56 +08:00
boris 4cf90d83a3 修复执行价索引和平台表达式回退 2026-06-12 23:46:44 +08:00
boris 9b4462f880 修正策略止盈止损和补仓投影 2026-05-28 18:40:32 +08:00
boris 87b7b2642d 修正策略投影tick依赖 2026-05-28 18:17:33 +08:00
boris 5eee5c7c63 缩小tick查询到实际订单 2026-05-28 17:45:00 +08:00
boris c6dc1d1474 修正回测执行时tick取价 2026-05-28 17:32:40 +08:00
boris 8c86918970 修正微盘买入预算与表达式性能 2026-05-28 10:39:43 +08:00
boris 200d5d1f41 完善平台策略回测撮合和滑点 2026-05-28 08:59:14 +08:00
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
18 changed files with 8954 additions and 903 deletions
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;
+434 -41
View File
@@ -1,4 +1,4 @@
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::path::Path;
@@ -9,6 +9,7 @@ use thiserror::Error;
use crate::calendar::TradingCalendar;
use crate::futures::{FuturesCommissionType, FuturesTradingParameter};
use crate::instrument::Instrument;
use crate::risk_control::ChinaAShareRiskControl;
mod date_format {
use chrono::NaiveDate;
@@ -444,6 +445,38 @@ pub struct EligibleUniverseSnapshot {
pub free_float_cap_bn: f64,
}
pub fn decision_adjusted_cap_bn(
factor_date: NaiveDate,
raw_cap_bn: f64,
market: &DailyMarketSnapshot,
) -> f64 {
if !raw_cap_bn.is_finite() || raw_cap_bn <= 0.0 {
return f64::NAN;
}
if factor_date != market.date {
return raw_cap_bn;
}
if !market.close.is_finite()
|| market.close <= 0.0
|| !market.prev_close.is_finite()
|| market.prev_close <= 0.0
{
return f64::NAN;
}
raw_cap_bn * market.prev_close / market.close
}
pub fn decision_market_cap_bn(factor: &DailyFactorSnapshot, market: &DailyMarketSnapshot) -> f64 {
decision_adjusted_cap_bn(factor.date, factor.market_cap_bn, market)
}
pub fn decision_free_float_cap_bn(
factor: &DailyFactorSnapshot,
market: &DailyMarketSnapshot,
) -> f64 {
decision_adjusted_cap_bn(factor.date, factor.free_float_cap_bn, market)
}
#[derive(Debug, Clone)]
struct SymbolPriceSeries {
snapshots: Vec<DailyMarketSnapshot>,
@@ -452,6 +485,7 @@ struct SymbolPriceSeries {
closes: Vec<f64>,
prev_closes: Vec<f64>,
last_prices: Vec<f64>,
volumes: Vec<f64>,
open_prefix: Vec<f64>,
close_prefix: Vec<f64>,
prev_close_prefix: Vec<f64>,
@@ -486,6 +520,7 @@ impl SymbolPriceSeries {
closes,
prev_closes,
last_prices,
volumes,
open_prefix,
close_prefix,
prev_close_prefix,
@@ -621,12 +656,7 @@ impl SymbolPriceSeries {
return None;
}
let start = end - lookback;
Some(
self.snapshots[start..end]
.iter()
.map(|snapshot| snapshot.volume as f64)
.collect(),
)
Some(self.volumes[start..end].to_vec())
}
fn end_index(&self, date: NaiveDate) -> Option<usize> {
@@ -654,6 +684,14 @@ impl SymbolPriceSeries {
self.values_for(field).get(end - 1).copied()
}
fn snapshot_before(&self, date: NaiveDate) -> Option<&DailyMarketSnapshot> {
let end = self.previous_completed_end_index(date)?;
if end == 0 {
return None;
}
self.snapshots.get(end - 1)
}
fn prefix_for(&self, field: PriceField) -> &[f64] {
match field {
PriceField::DayOpen => &self.open_prefix,
@@ -669,6 +707,7 @@ struct BenchmarkPriceSeries {
dates: Vec<NaiveDate>,
opens: Vec<f64>,
closes: Vec<f64>,
prev_closes: Vec<f64>,
open_prefix: Vec<f64>,
close_prefix: Vec<f64>,
}
@@ -680,12 +719,14 @@ impl BenchmarkPriceSeries {
let dates = sorted.iter().map(|row| row.date).collect::<Vec<_>>();
let opens = sorted.iter().map(|row| row.open).collect::<Vec<_>>();
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
let open_prefix = prefix_sums(&opens);
let close_prefix = prefix_sums(&closes);
Self {
dates,
opens,
closes,
prev_closes,
open_prefix,
close_prefix,
}
@@ -695,6 +736,24 @@ impl BenchmarkPriceSeries {
self.moving_average_for(date, lookback, PriceField::Close)
}
fn decision_close(&self, date: NaiveDate) -> Option<f64> {
match self.dates.binary_search(&date) {
Ok(idx) => self
.prev_closes
.get(idx)
.copied()
.filter(|value| value.is_finite() && *value > 0.0)
.or_else(|| {
idx.checked_sub(1)
.and_then(|prev| self.closes.get(prev).copied())
}),
Err(0) => None,
Err(idx) => idx
.checked_sub(1)
.and_then(|prev| self.closes.get(prev).copied()),
}
}
fn decision_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
if lookback == 0 {
return None;
@@ -712,6 +771,22 @@ impl BenchmarkPriceSeries {
Some(sum / lookback as f64)
}
fn decision_values_for(&self, date: NaiveDate, lookback: usize, field: PriceField) -> Vec<f64> {
if lookback == 0 {
return Vec::new();
}
let end = match self.dates.binary_search(&date) {
Ok(idx) => idx,
Err(0) => return Vec::new(),
Err(idx) => idx,
};
let start = end.saturating_sub(lookback);
match field {
PriceField::DayOpen | PriceField::Open => self.opens[start..end].to_vec(),
PriceField::Close | PriceField::Last => self.closes[start..end].to_vec(),
}
}
fn moving_average_for(
&self,
date: NaiveDate,
@@ -769,7 +844,7 @@ pub struct DataSet {
candidate_by_date: BTreeMap<NaiveDate, Vec<CandidateEligibility>>,
candidate_index: HashMap<(NaiveDate, String), CandidateEligibility>,
corporate_actions_by_date: BTreeMap<NaiveDate, Vec<CorporateAction>>,
execution_quotes_index: HashMap<(NaiveDate, String), Vec<IntradayExecutionQuote>>,
execution_quotes_by_date: HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>,
order_book_depth_index: HashMap<(NaiveDate, String), Vec<IntradayOrderBookDepthLevel>>,
benchmark_by_date: BTreeMap<NaiveDate, BenchmarkSnapshot>,
market_series_by_symbol: HashMap<String, SymbolPriceSeries>,
@@ -1053,7 +1128,7 @@ impl DataSet {
.map(|item| ((item.date, item.symbol.clone()), item))
.collect::<HashMap<_, _>>();
let corporate_actions_by_date = group_by_date(corporate_actions, |item| item.date);
let execution_quotes_index = build_execution_quote_index(execution_quotes);
let execution_quotes_by_date = build_execution_quote_index(execution_quotes);
let order_book_depth_index = build_order_book_depth_index(order_book_depth);
let benchmark_by_date = benchmarks
@@ -1063,8 +1138,12 @@ impl DataSet {
let market_series_by_symbol = build_market_series(&market_by_date);
let benchmark_series_cache =
BenchmarkPriceSeries::new(&benchmark_by_date.values().cloned().collect::<Vec<_>>());
let eligible_universe_by_date =
build_eligible_universe(&factor_by_date, &candidate_index, &market_index);
let eligible_universe_by_date = build_eligible_universe(
&factor_by_date,
&candidate_index,
&market_index,
&instruments,
);
let futures_params_by_symbol = build_futures_params_index(futures_params);
Ok(Self {
@@ -1079,7 +1158,7 @@ impl DataSet {
candidate_by_date,
candidate_index,
corporate_actions_by_date,
execution_quotes_index,
execution_quotes_by_date,
order_book_depth_index,
benchmark_by_date,
market_series_by_symbol,
@@ -1151,12 +1230,56 @@ impl DataSet {
}
pub fn execution_quotes_on(&self, date: NaiveDate, symbol: &str) -> &[IntradayExecutionQuote] {
self.execution_quotes_index
.get(&(date, symbol.to_string()))
self.execution_quotes_by_date
.get(&date)
.and_then(|rows_by_symbol| rows_by_symbol.get(symbol))
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
self.execution_quotes_by_date
.iter()
.flat_map(|(date, rows_by_symbol)| {
rows_by_symbol
.keys()
.map(move |symbol| (*date, symbol.clone()))
})
.collect()
}
pub fn add_execution_quotes(&mut self, quotes: Vec<IntradayExecutionQuote>) -> usize {
let mut added = 0usize;
let mut touched = HashSet::<(NaiveDate, String)>::new();
for quote in quotes {
let key = (quote.date, quote.symbol.clone());
let rows = self
.execution_quotes_by_date
.entry(quote.date)
.or_default()
.entry(quote.symbol.clone())
.or_default();
if rows.iter().any(|existing| {
existing.timestamp == quote.timestamp && existing.symbol == quote.symbol
}) {
continue;
}
rows.push(quote);
touched.insert(key);
added += 1;
}
for (date, symbol) in touched {
if let Some(rows) = self
.execution_quotes_by_date
.get_mut(&date)
.and_then(|rows_by_symbol| rows_by_symbol.get_mut(&symbol))
{
rows.sort_by_key(|quote| quote.timestamp);
}
}
added
}
pub fn order_book_depth_on(
&self,
date: NaiveDate,
@@ -1170,10 +1293,11 @@ impl DataSet {
pub fn execution_quotes_on_date(&self, date: NaiveDate) -> Vec<IntradayExecutionQuote> {
let mut quotes = self
.execution_quotes_index
.iter()
.filter(|((quote_date, _), _)| *quote_date == date)
.flat_map(|(_, rows)| rows.iter().cloned())
.execution_quotes_by_date
.get(&date)
.into_iter()
.flat_map(|rows_by_symbol| rows_by_symbol.values())
.flat_map(|rows| rows.iter().cloned())
.collect::<Vec<_>>();
quotes.sort_by(|left, right| {
left.timestamp
@@ -1293,10 +1417,10 @@ impl DataSet {
return Vec::new();
}
let mut quotes = self
.execution_quotes_index
.iter()
.filter(|((_, quote_symbol), _)| quote_symbol == symbol)
.flat_map(|(_, rows)| rows.iter())
.execution_quotes_by_date
.values()
.filter_map(|rows_by_symbol| rows_by_symbol.get(symbol))
.flat_map(|rows| rows.iter())
.filter(|quote| intraday_quote_visible(quote, date, active_datetime, include_now))
.cloned()
.collect::<Vec<_>>();
@@ -1793,12 +1917,11 @@ impl DataSet {
.collect(),
Some("1m") | Some("tick") => {
let mut bars = self
.execution_quotes_index
.execution_quotes_by_date
.iter()
.filter(|((date, quote_symbol), _)| {
quote_symbol == symbol && *date >= start && *date <= end
})
.flat_map(|(_, rows)| rows.iter())
.filter(|(date, _)| **date >= start && **date <= end)
.filter_map(|(_, rows_by_symbol)| rows_by_symbol.get(symbol))
.flat_map(|rows| rows.iter())
.map(intraday_quote_price_bar)
.collect::<Vec<_>>();
bars.sort_by(|left, right| {
@@ -1828,6 +1951,12 @@ impl DataSet {
.and_then(|series| series.price_on_or_before(date, field))
}
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
self.market_series_by_symbol
.get(symbol)
.and_then(|series| series.snapshot_before(date))
}
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
self.factor_by_date
.get(&date)
@@ -2091,12 +2220,10 @@ impl DataSet {
self.market_moving_average(date, symbol, lookback, PriceField::Close)
}
"volume" | "stock_volume" => self
.factor_moving_average(date, symbol, "daily_volume", lookback)
.or_else(|| {
self.market_series_by_symbol
.get(symbol)
.and_then(|series| series.current_volume_moving_average(date, lookback))
}),
.market_series_by_symbol
.get(symbol)
.and_then(|series| series.current_volume_moving_average(date, lookback))
.or_else(|| self.factor_moving_average(date, symbol, "daily_volume", lookback)),
"day_open" | "dayopen" => {
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
}
@@ -2183,6 +2310,10 @@ impl DataSet {
self.benchmark_series_cache.moving_average(date, lookback)
}
pub fn benchmark_decision_close(&self, date: NaiveDate) -> Option<f64> {
self.benchmark_series_cache.decision_close(date)
}
pub fn benchmark_decision_moving_average(
&self,
date: NaiveDate,
@@ -2212,6 +2343,23 @@ impl DataSet {
}
}
pub fn benchmark_decision_numeric_values(
&self,
date: NaiveDate,
field: &str,
lookback: usize,
) -> Vec<f64> {
let field = normalize_field(field);
match field.as_str() {
"open" | "day_open" | "dayopen" | "benchmark_open" => self
.benchmark_series_cache
.trailing_values_for(date, lookback, PriceField::Open),
_ => self
.benchmark_series_cache
.decision_values_for(date, lookback, PriceField::Close),
}
}
pub fn market_open_moving_average(
&self,
date: NaiveDate,
@@ -3222,17 +3370,21 @@ fn build_futures_params_index(
fn build_execution_quote_index(
execution_quotes: Vec<IntradayExecutionQuote>,
) -> HashMap<(NaiveDate, String), Vec<IntradayExecutionQuote>> {
let mut grouped = HashMap::<(NaiveDate, String), Vec<IntradayExecutionQuote>>::new();
) -> HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>> {
let mut grouped = HashMap::<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>::new();
for quote in execution_quotes {
grouped
.entry((quote.date, quote.symbol.clone()))
.entry(quote.date)
.or_default()
.entry(quote.symbol.clone())
.or_default()
.push(quote);
}
for quotes in grouped.values_mut() {
quotes.sort_by_key(|quote| quote.timestamp);
for rows_by_symbol in grouped.values_mut() {
for quotes in rows_by_symbol.values_mut() {
quotes.sort_by_key(|quote| quote.timestamp);
}
}
grouped
@@ -3264,6 +3416,7 @@ fn build_eligible_universe(
factor_by_date: &BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
candidate_index: &HashMap<(NaiveDate, String), CandidateEligibility>,
market_index: &HashMap<(NaiveDate, String), DailyMarketSnapshot>,
instruments: &HashMap<String, Instrument>,
) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> {
let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new();
@@ -3280,13 +3433,25 @@ fn build_eligible_universe(
let Some(market) = market_index.get(&key) else {
continue;
};
if !candidate.eligible_for_selection() || market.paused {
if ChinaAShareRiskControl::selection_rejection_reason(
*date,
candidate,
market,
instruments.get(&factor.symbol),
)
.is_some()
{
continue;
}
let market_cap_bn = decision_market_cap_bn(factor, market);
if market_cap_bn <= 0.0 || !market_cap_bn.is_finite() {
continue;
}
let free_float_cap_bn = decision_free_float_cap_bn(factor, market);
rows.push(EligibleUniverseSnapshot {
symbol: factor.symbol.clone(),
market_cap_bn: factor.market_cap_bn,
free_float_cap_bn: factor.free_float_cap_bn,
market_cap_bn,
free_float_cap_bn,
});
}
rows.sort_by(|left, right| {
@@ -3301,6 +3466,11 @@ fn build_eligible_universe(
per_date
}
#[cfg(test)]
fn instrument_passes_baseline_selection(instrument: Option<&Instrument>, date: NaiveDate) -> bool {
ChinaAShareRiskControl::instrument_rejection_reason(instrument, date).is_none()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -3340,6 +3510,68 @@ mod tests {
}
}
fn benchmark_row(date: &str, close: f64) -> BenchmarkSnapshot {
BenchmarkSnapshot {
date: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap(),
benchmark: "000852.SH".to_string(),
open: close,
close,
prev_close: close - 1.0,
volume: 1_000_000,
}
}
#[test]
fn baseline_selection_uses_structured_instrument_dates_and_status_only() {
let date = NaiveDate::parse_from_str("2025-01-02", "%Y-%m-%d").unwrap();
let instrument = |name: &str, status: &str, delisted_at: Option<NaiveDate>| Instrument {
symbol: "000001.SZ".to_string(),
name: name.to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: Some(NaiveDate::parse_from_str("2020-01-01", "%Y-%m-%d").unwrap()),
delisted_at,
status: status.to_string(),
};
assert!(instrument_passes_baseline_selection(
Some(&instrument("Short History Stock", "active", None)),
date
));
assert!(instrument_passes_baseline_selection(
Some(&instrument("*ST测试", "active", None)),
date
));
assert!(instrument_passes_baseline_selection(
Some(&instrument("ST测试", "active", None)),
date
));
assert!(instrument_passes_baseline_selection(
Some(&instrument("退市测试", "active", None)),
date
));
assert!(!instrument_passes_baseline_selection(
Some(&instrument("正常名称", "delisted", None)),
date
));
assert!(instrument_passes_baseline_selection(
Some(&instrument(
"正常名称",
"delisted",
Some(NaiveDate::parse_from_str("2025-04-30", "%Y-%m-%d").unwrap()),
)),
date
));
assert!(!instrument_passes_baseline_selection(
Some(&instrument(
"正常名称",
"active",
Some(NaiveDate::parse_from_str("2025-01-01", "%Y-%m-%d").unwrap()),
)),
date
));
}
#[test]
fn decision_volume_average_uses_previous_completed_days_only() {
let series = SymbolPriceSeries::new(&[
@@ -3371,6 +3603,167 @@ mod tests {
);
}
#[test]
fn decision_close_average_ignores_current_day_close() {
let mut current = market_row("2025-01-06", 12.0, 10_000);
current.close = 9_999.0;
current.last_price = 9_999.0;
let series = SymbolPriceSeries::new(&[
market_row("2025-01-02", 10.0, 100),
market_row("2025-01-03", 11.0, 200),
current,
]);
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
assert_eq!(
series.decision_close_moving_average(decision_date, 2),
Some(11.5)
);
assert_eq!(
series.moving_average(decision_date, 2, PriceField::Close),
Some((11.0 + 9_999.0) / 2.0)
);
}
#[test]
fn decision_volume_average_includes_paused_zero_volume_days() {
let mut paused = market_row("2025-01-03", 11.0, 0);
paused.paused = true;
let series = SymbolPriceSeries::new(&[
market_row("2025-01-02", 10.0, 100),
paused,
market_row("2025-01-06", 12.0, 300),
market_row("2025-01-07", 13.0, 10_000),
]);
assert_eq!(
series.decision_volume_moving_average(
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
2
),
Some(150.0)
);
assert_eq!(
series.decision_volume_moving_average(
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
3
),
Some((100.0 + 0.0 + 300.0) / 3.0)
);
}
#[test]
fn eligible_universe_uses_decision_market_cap_same_date() {
let date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
let instrument = |symbol: &str| Instrument {
symbol: symbol.to_string(),
name: symbol.to_string(),
board: if symbol.ends_with(".SH") { "SH" } else { "SZ" }.to_string(),
round_lot: 100,
listed_at: Some(NaiveDate::parse_from_str("2020-01-01", "%Y-%m-%d").unwrap()),
delisted_at: None,
status: "active".to_string(),
};
let market = |symbol: &str, prev_close: f64, close: f64| DailyMarketSnapshot {
date,
symbol: symbol.to_string(),
timestamp: Some("2025-01-06 10:18:00".to_string()),
day_open: prev_close,
open: prev_close,
high: close.max(prev_close),
low: close.min(prev_close),
close,
last_price: prev_close,
bid1: prev_close,
ask1: prev_close,
prev_close,
volume: 100_000,
tick_volume: 1_000,
bid1_volume: 1_000,
ask1_volume: 1_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: prev_close * 1.1,
lower_limit: prev_close * 0.9,
price_tick: 0.01,
};
let factor =
|symbol: &str, market_cap_bn: f64, free_float_cap_bn: f64| DailyFactorSnapshot {
date,
symbol: symbol.to_string(),
market_cap_bn,
free_float_cap_bn,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
};
let candidate = |symbol: &str| CandidateEligibility {
date,
symbol: symbol.to_string(),
is_st: false,
is_new_listing: false,
is_paused: false,
allow_buy: true,
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
};
let data = DataSet::from_components(
vec![instrument("000001.SZ"), instrument("000002.SZ")],
vec![
market("000001.SZ", 10.0, 20.0),
market("000002.SZ", 10.0, 10.0),
],
vec![
factor("000001.SZ", 12.0, 4.0),
factor("000002.SZ", 10.0, 5.0),
],
vec![candidate("000001.SZ"), candidate("000002.SZ")],
vec![BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 100.0,
close: 101.0,
prev_close: 99.0,
volume: 1_000_000,
}],
)
.expect("dataset");
let rows = data.eligible_universe_on(date);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].symbol, "000001.SZ");
assert!((rows[0].market_cap_bn - 6.0).abs() < 1e-9);
assert!((rows[0].free_float_cap_bn - 2.0).abs() < 1e-9);
assert_eq!(rows[1].symbol, "000002.SZ");
assert!((rows[1].market_cap_bn - 10.0).abs() < 1e-9);
}
#[test]
fn benchmark_decision_close_windows_exclude_current_close() {
let series = BenchmarkPriceSeries::new(&[
benchmark_row("2025-01-02", 100.0),
benchmark_row("2025-01-03", 200.0),
benchmark_row("2025-01-06", 9_999.0),
]);
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
assert_eq!(series.decision_close(decision_date), Some(9_998.0));
assert_eq!(
series.decision_moving_average(decision_date, 2),
Some(150.0)
);
assert_eq!(
series.decision_values_for(decision_date, 2, PriceField::Close),
vec![100.0, 200.0]
);
assert_eq!(
series.moving_average(decision_date, 2),
Some((200.0 + 9_999.0) / 2.0)
);
}
#[test]
fn reads_mixed_numeric_and_text_extra_factors_from_quoted_csv_json() {
let path = temp_csv_path("mixed_factor_maps");
+227 -16
View File
@@ -6,7 +6,7 @@ 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,7 @@ pub struct BacktestEngine<S, C, R> {
futures_settlement_price_mode: String,
futures_cost_model: FuturesTransactionCostModel,
futures_validation_config: FuturesValidationConfig,
execution_quote_loader: Option<ExecutionQuoteLoader>,
}
impl<S, C, R> BacktestEngine<S, C, R> {
@@ -338,6 +356,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 +368,39 @@ 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,
}
}
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 +505,48 @@ 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 start_time = start_time.or_else(|| self.broker.intraday_execution_start_time());
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
symbols.retain(|symbol| {
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
});
if symbols.is_empty() {
return Ok(());
}
let request = ExecutionQuoteRequest {
date: execution_date,
start_time,
end_time,
symbols,
};
let quotes = self
.execution_quote_loader
.as_mut()
.expect("checked execution quote loader")
.as_mut()(request)?;
self.data.add_execution_quotes(quotes);
Ok(())
}
fn apply_strategy_directives(
&mut self,
execution_date: NaiveDate,
@@ -1721,6 +1808,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,
@@ -1925,6 +2021,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 +2187,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 +2241,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 +2635,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 +3108,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 +3188,101 @@ where
}
}
fn has_execution_quote_in_window(
data: &DataSet,
date: NaiveDate,
symbol: &str,
start_time: Option<chrono::NaiveTime>,
end_time: Option<chrono::NaiveTime>,
) -> bool {
let start_cursor = start_time.map(|time| date.and_time(time));
let end_cursor = end_time.map(|time| date.and_time(time));
if let Some(cursor) = start_cursor
&& end_cursor.is_none()
{
return data
.execution_quotes_on(date, symbol)
.iter()
.any(|quote| quote.timestamp <= cursor);
}
data.execution_quotes_on(date, symbol).iter().any(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
})
}
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
decision.order_intents.iter().any(|intent| {
matches!(
intent,
OrderIntent::AlgoValue { .. }
| OrderIntent::AlgoPercent { .. }
| OrderIntent::TargetPortfolioSmart {
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
..
}
)
})
}
fn execution_quote_symbols_for_decision(
decision: &StrategyDecision,
portfolio: &PortfolioState,
open_orders: &[OpenOrderView],
) -> BTreeSet<String> {
let mut symbols = BTreeSet::new();
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
if decision.rebalance {
symbols.extend(portfolio.positions().keys().cloned());
symbols.extend(decision.target_weights.keys().cloned());
}
if !decision.exit_symbols.is_empty() {
symbols.extend(decision.exit_symbols.iter().cloned());
}
for intent in &decision.order_intents {
match intent {
OrderIntent::Shares { symbol, .. }
| OrderIntent::LimitShares { symbol, .. }
| OrderIntent::Lots { symbol, .. }
| OrderIntent::LimitLots { symbol, .. }
| OrderIntent::TargetShares { symbol, .. }
| OrderIntent::LimitTargetShares { symbol, .. }
| OrderIntent::TargetValue { symbol, .. }
| OrderIntent::LimitTargetValue { symbol, .. }
| OrderIntent::Value { symbol, .. }
| OrderIntent::LimitValue { symbol, .. }
| OrderIntent::Percent { symbol, .. }
| OrderIntent::LimitPercent { symbol, .. }
| OrderIntent::TargetPercent { symbol, .. }
| OrderIntent::LimitTargetPercent { symbol, .. }
| OrderIntent::AlgoValue { symbol, .. }
| OrderIntent::AlgoPercent { symbol, .. }
| OrderIntent::CancelSymbol { symbol, .. } => {
symbols.insert(symbol.clone());
}
OrderIntent::TargetPortfolioSmart { target_weights, .. } => {
symbols.extend(portfolio.positions().keys().cloned());
symbols.extend(target_weights.keys().cloned());
}
OrderIntent::CancelAll { .. } => {
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
}
OrderIntent::UpdateUniverse { .. }
| OrderIntent::Subscribe { .. }
| OrderIntent::Unsubscribe { .. }
| OrderIntent::DepositWithdraw { .. }
| OrderIntent::FinanceRepay { .. }
| OrderIntent::SetManagementFeeRate { .. }
| OrderIntent::CancelOrder { .. }
| OrderIntent::Futures { .. } => {}
}
}
symbols.retain(|symbol| !symbol.trim().is_empty());
symbols
}
fn collect_scheduled_decisions<S: Strategy>(
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
@@ -52,6 +52,8 @@ pub struct StrategyUniverseSpec {
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StrategyExecutionSpec {
#[serde(default)]
pub compatibility_profile: Option<String>,
#[serde(default)]
pub matching_type: Option<String>,
#[serde(default)]
@@ -59,6 +61,20 @@ pub struct StrategyExecutionSpec {
#[serde(default)]
pub slippage_value: Option<f64>,
#[serde(default)]
pub slippage_impact_coefficient: Option<f64>,
#[serde(default)]
pub slippage_volatility_coefficient: Option<f64>,
#[serde(default)]
pub slippage_max_value: Option<f64>,
#[serde(default)]
pub commission_rate: Option<f64>,
#[serde(default)]
pub minimum_commission: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_before_change: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_after_change: Option<f64>,
#[serde(default)]
pub strict_value_budget: Option<bool>,
}
@@ -94,6 +110,20 @@ pub struct StrategyEngineConfig {
#[serde(default)]
pub slippage_value: Option<f64>,
#[serde(default)]
pub slippage_impact_coefficient: Option<f64>,
#[serde(default)]
pub slippage_volatility_coefficient: Option<f64>,
#[serde(default)]
pub slippage_max_value: Option<f64>,
#[serde(default)]
pub commission_rate: Option<f64>,
#[serde(default)]
pub minimum_commission: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_before_change: Option<f64>,
#[serde(default)]
pub stamp_tax_rate_after_change: Option<f64>,
#[serde(default)]
pub strict_value_budget: Option<bool>,
#[serde(default)]
pub dividend_reinvestment: Option<bool>,
@@ -244,6 +274,8 @@ pub struct StrategyExpressionTradingConfig {
#[serde(default)]
pub stage: Option<String>,
#[serde(default)]
pub refresh_rate_expr: Option<String>,
#[serde(default)]
pub schedule: Option<StrategyExpressionScheduleConfig>,
#[serde(default)]
pub rotation_enabled: Option<bool>,
@@ -327,6 +359,140 @@ pub fn platform_expr_config_from_value(
))
}
fn valid_non_negative(value: Option<f64>) -> Option<f64> {
value.filter(|item| item.is_finite() && *item >= 0.0)
}
fn apply_cost_overrides(
cfg: &mut PlatformExprStrategyConfig,
commission_rate: Option<f64>,
minimum_commission: Option<f64>,
stamp_tax_rate_before_change: Option<f64>,
stamp_tax_rate_after_change: Option<f64>,
) {
if let Some(value) = valid_non_negative(commission_rate) {
cfg.commission_rate = Some(value);
}
if let Some(value) = valid_non_negative(minimum_commission) {
cfg.minimum_commission = Some(value);
}
if let Some(value) = valid_non_negative(stamp_tax_rate_before_change) {
cfg.stamp_tax_rate_before_change = Some(value);
}
if let Some(value) = valid_non_negative(stamp_tax_rate_after_change) {
cfg.stamp_tax_rate_after_change = Some(value);
}
}
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
let bytes = text.as_bytes();
let mut end = start;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
}
if end == start {
return None;
}
text[start..end]
.parse::<usize>()
.ok()
.filter(|value| *value > 0)
.map(|value| (value, end))
}
fn prefixed_ma_lookbacks(expr: &str, prefix: &str) -> Vec<usize> {
let lower = expr.to_ascii_lowercase();
let mut values = Vec::new();
let mut cursor = 0;
while let Some(offset) = lower[cursor..].find(prefix) {
let start = cursor + offset + prefix.len();
if let Some((value, end)) = parse_usize_after(&lower, start) {
values.push(value);
cursor = end;
} else {
cursor = start;
}
}
values
}
fn compact_ascii_whitespace(value: &str) -> String {
value
.chars()
.filter(|ch| !ch.is_ascii_whitespace())
.collect::<String>()
.to_ascii_lowercase()
}
fn rolling_mean_lookbacks(expr: &str, field: &str) -> Vec<usize> {
let compact = compact_ascii_whitespace(expr);
let patterns = [
format!("rolling_mean(\"{field}\","),
format!("rolling_mean('{field}',"),
];
let mut values = Vec::new();
for pattern in patterns {
let mut cursor = 0;
while let Some(offset) = compact[cursor..].find(&pattern) {
let start = cursor + offset + pattern.len();
if let Some((value, end)) = parse_usize_after(&compact, start) {
values.push(value);
cursor = end;
} else {
cursor = start;
}
}
}
values
}
fn sorted_unique_positive(mut values: Vec<usize>) -> Vec<usize> {
values.retain(|value| *value > 0);
values.sort_unstable();
values.dedup();
values
}
fn infer_expression_windows(
cfg: &mut PlatformExprStrategyConfig,
benchmark_short_explicit: bool,
benchmark_long_explicit: bool,
stock_short_explicit: bool,
stock_mid_explicit: bool,
stock_long_explicit: bool,
) {
let mut benchmark_days = Vec::new();
for expr in [&cfg.exposure_expr, &cfg.buy_scale_expr] {
benchmark_days.extend(prefixed_ma_lookbacks(expr, "benchmark_ma"));
benchmark_days.extend(rolling_mean_lookbacks(expr, "benchmark_close"));
}
let benchmark_days = sorted_unique_positive(benchmark_days);
if !benchmark_short_explicit && let Some(short) = benchmark_days.first().copied() {
cfg.benchmark_short_ma_days = short;
}
if !benchmark_long_explicit && let Some(long) = benchmark_days.last().copied() {
cfg.benchmark_long_ma_days = long;
}
let mut stock_days = Vec::new();
for expr in [&cfg.stock_filter_expr, &cfg.buy_scale_expr] {
stock_days.extend(prefixed_ma_lookbacks(expr, "stock_ma"));
stock_days.extend(rolling_mean_lookbacks(expr, "close"));
}
let stock_days = sorted_unique_positive(stock_days);
if !stock_short_explicit && let Some(short) = stock_days.first().copied() {
cfg.stock_short_ma_days = short;
}
if !stock_mid_explicit {
if let Some(mid) = stock_days.get(1).copied() {
cfg.stock_mid_ma_days = mid;
}
}
if !stock_long_explicit && let Some(long) = stock_days.last().copied() {
cfg.stock_long_ma_days = long;
}
}
pub fn platform_expr_config_from_spec(
strategy_id: &str,
signal_symbol: &str,
@@ -341,6 +507,11 @@ pub fn platform_expr_config_from_spec(
let Some(spec) = strategy_spec else {
return cfg;
};
let mut benchmark_short_explicit = false;
let mut benchmark_long_explicit = false;
let mut stock_short_explicit = false;
let mut stock_mid_explicit = false;
let mut stock_long_explicit = false;
if let Some(spec_strategy_id) = spec
.strategy_id
@@ -370,23 +541,35 @@ pub fn platform_expr_config_from_spec(
{
cfg.rebalance_schedule = Some(schedule);
}
if let Some(time) = engine
.rebalance_schedule
.as_ref()
.and_then(parse_schedule_execution_time)
{
cfg.intraday_execution_time = Some(time);
}
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
if let Some(days) = stock_ma_filter.short_days.filter(|value| *value > 0) {
cfg.stock_short_ma_days = days;
stock_short_explicit = true;
}
if let Some(days) = stock_ma_filter.mid_days.filter(|value| *value > 0) {
cfg.stock_mid_ma_days = days;
stock_mid_explicit = true;
}
if let Some(days) = stock_ma_filter.long_days.filter(|value| *value > 0) {
cfg.stock_long_ma_days = days;
stock_long_explicit = true;
}
}
if let Some(index_throttle) = engine.index_throttle.as_ref() {
if let Some(days) = index_throttle.short_days.filter(|value| *value > 0) {
cfg.benchmark_short_ma_days = days;
benchmark_short_explicit = true;
}
if let Some(days) = index_throttle.long_days.filter(|value| *value > 0) {
cfg.benchmark_long_ma_days = days;
benchmark_long_explicit = true;
}
}
if !engine.skip_windows.is_empty() {
@@ -417,6 +600,13 @@ pub fn platform_expr_config_from_spec(
{
cfg.benchmark_symbol = spec_benchmark_symbol.clone();
}
apply_cost_overrides(
&mut cfg,
engine.commission_rate,
engine.minimum_commission,
engine.stamp_tax_rate_before_change,
engine.stamp_tax_rate_after_change,
);
}
if let Some(spec_signal_symbol) = spec
@@ -499,6 +689,13 @@ pub fn platform_expr_config_from_spec(
{
cfg.rebalance_schedule = Some(schedule);
}
if let Some(time) = runtime_expr
.schedule
.as_ref()
.and_then(parse_schedule_execution_time)
{
cfg.intraday_execution_time = Some(time);
}
if let Some(selection) = runtime_expr.selection.as_ref() {
if let Some(expr) = selection
.limit_expr
@@ -591,6 +788,13 @@ pub fn platform_expr_config_from_spec(
}
}
if let Some(trading) = runtime_expr.trading.as_ref() {
if let Some(expr) = trading
.refresh_rate_expr
.as_ref()
.filter(|value| !value.trim().is_empty())
{
cfg.refresh_rate_expr = expr.clone();
}
if let Some(enabled) = trading.rotation_enabled {
cfg.rotation_enabled = enabled;
}
@@ -628,6 +832,13 @@ pub fn platform_expr_config_from_spec(
{
cfg.explicit_action_schedule = Some(schedule);
}
if let Some(time) = trading
.schedule
.as_ref()
.and_then(parse_schedule_execution_time)
{
cfg.intraday_execution_time = Some(time);
}
cfg.explicit_actions = trading
.actions
.iter()
@@ -682,12 +893,52 @@ pub fn platform_expr_config_from_spec(
cfg.selection_limit_expr = cfg.max_positions.to_string();
}
infer_expression_windows(
&mut cfg,
benchmark_short_explicit,
benchmark_long_explicit,
stock_short_explicit,
stock_mid_explicit,
stock_long_explicit,
);
if !cfg.signal_symbol.trim().is_empty() {
cfg.signal_symbol = normalize_symbol(&cfg.signal_symbol, None);
}
if !cfg.benchmark_symbol.trim().is_empty() {
cfg.benchmark_symbol = normalize_symbol(&cfg.benchmark_symbol, None);
}
let aiquant_compat = spec
.execution
.as_ref()
.and_then(|execution| execution.compatibility_profile.as_deref())
.map(|value| value.trim().to_ascii_lowercase())
.is_some_and(|value| value == "aiquant_rqalpha" || value == "aiquant");
if aiquant_compat {
cfg.aiquant_transaction_cost = true;
let trading = spec
.runtime_expressions
.as_ref()
.and_then(|runtime_expr| runtime_expr.trading.as_ref());
if trading.and_then(|item| item.daily_top_up).is_none() {
cfg.daily_top_up_enabled = true;
}
if trading
.and_then(|item| item.retry_empty_rebalance)
.is_none()
{
cfg.retry_empty_rebalance = true;
}
}
if let Some(execution) = spec.execution.as_ref() {
apply_cost_overrides(
&mut cfg,
execution.commission_rate,
execution.minimum_commission,
execution.stamp_tax_rate_before_change,
execution.stamp_tax_rate_after_change,
);
}
cfg
}
@@ -744,6 +995,16 @@ fn parse_schedule_time_rule(
}
}
fn parse_schedule_execution_time(schedule: &StrategyExpressionScheduleConfig) -> Option<NaiveTime> {
match parse_schedule_time_rule(schedule)? {
ScheduleTimeRule::BeforeTrading => NaiveTime::from_hms_opt(9, 0, 0),
ScheduleTimeRule::MinuteOfDay(minutes) => {
let seconds = minutes.checked_mul(60)?;
NaiveTime::from_num_seconds_from_midnight_opt(seconds, 0)
}
}
}
fn parse_schedule_clock_time(raw: Option<&str>) -> Option<NaiveTime> {
let value = raw?.trim();
if value.is_empty() {
@@ -1060,6 +1321,7 @@ mod tests {
"signalSymbol": "000852.SH",
"benchmark": { "instrumentId": "000852.SH" },
"universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] },
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
"runtimeExpressions": {
"prelude": "let stocknum = 8;",
"selection": {
@@ -1069,6 +1331,7 @@ mod tests {
"stockFilterExpr": "stock_ma5 > stock_ma10"
},
"trading": {
"refreshRateExpr": "year >= 2024 ? 5 : 20",
"rotationEnabled": false,
"dailyTopUp": true,
"retryEmptyRebalance": true,
@@ -1090,14 +1353,148 @@ mod tests {
assert_eq!(cfg.strategy_name, "runtime_spec_test");
assert_eq!(cfg.signal_symbol, "000852.SH");
assert_eq!(cfg.selection_limit_expr, "stocknum");
assert_eq!(cfg.refresh_rate_expr, "year >= 2024 ? 5 : 20");
assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]);
assert!(!cfg.rotation_enabled);
assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance);
assert!(!cfg.calendar_rebalance_interval);
assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.explicit_actions.len(), 1);
assert_eq!(
cfg.explicit_action_stage,
PlatformExplicitActionStage::OpenAuction
);
}
#[test]
fn parses_execution_cost_overrides_into_platform_config() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha",
"commissionRate": 0.0003,
"minimumCommission": 5.0,
"stampTaxRateBeforeChange": 0.0005,
"stampTaxRateAfterChange": 0.0005
},
"engineConfig": {
"commissionRate": 0.0008
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.commission_rate, Some(0.0003));
assert_eq!(cfg.minimum_commission, Some(5.0));
assert_eq!(cfg.stamp_tax_rate_before_change, Some(0.0005));
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
}
#[test]
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert!(cfg.aiquant_transaction_cost);
assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance);
let explicit_off = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
},
"runtimeExpressions": {
"trading": {
"dailyTopUp": false,
"retryEmptyRebalance": false
}
}
});
let cfg = platform_expr_config_from_value("", "", &explicit_off).expect("config");
assert!(!cfg.daily_top_up_enabled);
assert!(!cfg.retry_empty_rebalance);
}
#[test]
fn runtime_expressions_infer_ma_windows_from_literal_strategy_logic() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
},
"runtimeExpressions": {
"selection": {
"stockFilterExpr": "rolling_mean(\"close\", 5) > rolling_mean(\"close\", 10) && rolling_mean(\"close\", 10) > rolling_mean(\"close\", 30)"
},
"risk": {
"exposureExpr": "benchmark_ma5 > benchmark_ma20 ? 1.0 : weak_market_trade_rate"
}
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(cfg.benchmark_short_ma_days, 5);
assert_eq!(cfg.benchmark_long_ma_days, 20);
assert_eq!(cfg.stock_short_ma_days, 5);
assert_eq!(cfg.stock_mid_ma_days, 10);
assert_eq!(cfg.stock_long_ma_days, 30);
let explicit = serde_json::json!({
"engineConfig": {
"stockMaFilter": {
"shortDays": 4,
"midDays": 9,
"longDays": 21
},
"indexThrottle": {
"shortDays": 3,
"longDays": 13
}
},
"runtimeExpressions": {
"selection": {
"stockFilterExpr": "rolling_mean(\"close\", 5) > rolling_mean(\"close\", 10) && rolling_mean(\"close\", 10) > rolling_mean(\"close\", 30)"
},
"risk": {
"exposureExpr": "benchmark_ma5 > benchmark_ma20 ? 1.0 : 0.5"
}
}
});
let cfg = platform_expr_config_from_value("", "", &explicit).expect("config");
assert_eq!(cfg.benchmark_short_ma_days, 3);
assert_eq!(cfg.benchmark_long_ma_days, 13);
assert_eq!(cfg.stock_short_ma_days, 4);
assert_eq!(cfg.stock_mid_ma_days, 9);
assert_eq!(cfg.stock_long_ma_days, 21);
}
#[test]
fn parses_daily_schedule_time_for_aiquant_execution_quotes() {
let spec = serde_json::json!({
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
"runtimeExpressions": {
"schedule": { "frequency": "daily", "time": "09:33" }
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(cfg.rebalance_schedule, None);
assert_eq!(
cfg.intraday_execution_time,
Some(NaiveTime::from_hms_opt(9, 33, 0).unwrap())
);
assert!(!cfg.calendar_rebalance_interval);
assert!(cfg.aiquant_transaction_cost);
}
}
+139 -8
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,
}
@@ -72,6 +73,7 @@ impl Position {
self.lots.push(PositionLot {
acquired_date: date,
quantity,
entry_price: price,
price,
});
self.quantity += quantity;
@@ -205,6 +207,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 +232,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 +270,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 +314,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<_>>();
@@ -316,6 +367,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 +400,7 @@ impl PortfolioState {
positions: IndexMap::new(),
cash_receivables: Vec::new(),
pending_cash_flows: Vec::new(),
day_sold_symbols: BTreeSet::new(),
}
}
@@ -402,7 +455,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 +602,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,9 +615,24 @@ 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() {
if field == PriceField::Close
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
@@ -714,6 +794,7 @@ impl PortfolioState {
.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<_>>();
@@ -810,6 +891,35 @@ 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 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();
@@ -1165,7 +1275,7 @@ mod tests {
.expect("dataset");
portfolio
.update_prices(buy_date, &dataset, PriceField::Close)
.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);
@@ -1178,6 +1288,27 @@ mod tests {
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]
+125
View File
@@ -0,0 +1,125 @@
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::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");
}
if !candidate.allow_buy || !candidate.allow_sell {
return Some("trade_disabled");
}
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::selection_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");
}
if !candidate.allow_sell {
return Some("sell_disabled");
}
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),
}
}
}
+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()
+39 -49
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};
@@ -1780,11 +1781,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,
@@ -1796,14 +1809,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 =
@@ -1818,7 +1832,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 =
@@ -1834,7 +1849,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);
@@ -2316,18 +2331,6 @@ impl OmniMicroCapStrategy {
true
}
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('退')
}
fn can_sell_position(&self, ctx: &StrategyContext<'_>, date: NaiveDate, symbol: &str) -> bool {
let Some(position) = ctx.portfolio.position(symbol) else {
return false;
@@ -2341,11 +2344,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(
@@ -2357,30 +2364,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)
@@ -2730,8 +2721,7 @@ 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 sell_reason = if stop_hit {
+2 -2
View File
@@ -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");
+2 -2
View File
@@ -61,7 +61,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 +112,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);
}
+1 -1
View File
@@ -300,7 +300,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),
+8 -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,
@@ -273,7 +274,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(),
@@ -492,7 +493,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 +504,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")
}));
}
+2 -2
View File
@@ -329,7 +329,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(),
@@ -3734,7 +3734,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(),
+254 -10
View File
@@ -1,9 +1,9 @@
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};
@@ -233,8 +233,148 @@ fn broker_order_value_rounds_to_nearest_lot_when_min_lot_is_affordable() {
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, 200);
assert_eq!(portfolio.position(symbol).expect("position").quantity, 200);
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,
}],
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]
@@ -905,7 +1045,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
@@ -1345,6 +1485,110 @@ 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,
}],
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();
@@ -1414,7 +1658,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,
@@ -1560,7 +1804,7 @@ 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());
}
@@ -1749,7 +1993,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,
@@ -2498,7 +2742,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()),