Compare commits

...

10 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
10 changed files with 2468 additions and 324 deletions
+402 -59
View File
@@ -340,26 +340,59 @@ where
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
) -> f64 {
self.value_order_sizing_price(date, data, symbol, snapshot, OrderSide::Buy)
}
fn value_sell_sizing_price(
&self,
date: NaiveDate,
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
) -> f64 {
self.value_order_sizing_price(date, data, symbol, snapshot, OrderSide::Sell)
}
fn target_value_valuation_price(
&self,
date: NaiveDate,
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
) -> f64 {
let _ = (date, data, symbol);
if snapshot.close.is_finite() && snapshot.close > 0.0 {
snapshot.close
} else {
self.sizing_price(snapshot)
}
}
fn value_order_sizing_price(
&self,
date: NaiveDate,
data: &DataSet,
symbol: &str,
snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide,
) -> f64 {
let start_cursor = self
.runtime_intraday_start_time
.get()
.or(self.intraday_execution_start_time)
.map(|start_time| date.and_time(start_time));
data.execution_quotes_on(date, symbol)
.iter()
.filter(|quote| {
start_cursor
.map(|cursor| quote.timestamp >= cursor)
.unwrap_or(true)
})
.next()
.and_then(|quote| match self.execution_price_field {
PriceField::Last => (quote.last_price.is_finite() && quote.last_price > 0.0)
.then_some(quote.last_price),
_ => quote.buy_price(),
})
.unwrap_or_else(|| self.sizing_price(snapshot))
let matching_type = self.matching_type_for_algo_request(None);
self.latest_known_quote_at_or_before(
data.execution_quotes_on(date, symbol),
start_cursor,
snapshot,
side,
matching_type,
false,
)
.and_then(|quote| self.select_quote_reference_price(snapshot, quote, side, matching_type))
.unwrap_or_else(|| self.sizing_price(snapshot))
}
fn snapshot_execution_price(
@@ -1088,6 +1121,36 @@ where
}
}
fn latest_known_quote_at_or_before<'a>(
&self,
quotes: &'a [IntradayExecutionQuote],
cursor: Option<NaiveDateTime>,
snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide,
matching_type: MatchingType,
require_executable_liquidity: bool,
) -> Option<&'a IntradayExecutionQuote> {
let Some(cursor) = cursor else {
return quotes.iter().find(|quote| {
self.select_quote_reference_price(snapshot, quote, side, matching_type)
.is_some()
&& (!require_executable_liquidity
|| self.quote_has_executable_liquidity(quote, side, matching_type))
});
};
quotes
.iter()
.filter(|quote| {
quote.timestamp <= cursor
&& self
.select_quote_reference_price(snapshot, quote, side, matching_type)
.is_some()
&& (!require_executable_liquidity
|| self.quote_has_executable_liquidity(quote, side, matching_type))
})
.max_by_key(|quote| quote.timestamp)
}
fn process_limit_shares(
&self,
date: NaiveDate,
@@ -2677,9 +2740,8 @@ where
commission_state: &mut BTreeMap<u64, f64>,
report: &mut BrokerExecutionReport,
) -> Result<(), BacktestError> {
let price = data
let snapshot = data
.market(date, symbol)
.map(|snapshot| self.sizing_price(snapshot))
.ok_or_else(|| BacktestError::MissingPrice {
date,
symbol: symbol.to_string(),
@@ -2689,20 +2751,27 @@ where
.position(symbol)
.map(|pos| pos.quantity)
.unwrap_or(0);
let current_value = price * current_qty as f64;
let target_qty = self.round_buy_quantity(
((target_value.max(0.0)) / price).floor() as u32,
self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
);
if current_qty > target_qty {
if target_value <= f64::EPSILON {
if current_qty == 0 {
report.order_events.push(OrderEvent {
date,
order_id: None,
symbol: symbol.to_string(),
side: OrderSide::Sell,
requested_quantity: 0,
filled_quantity: 0,
status: OrderStatus::Filled,
reason: format!("{reason}: already at target value"),
});
return Ok(());
}
self.process_sell(
date,
portfolio,
data,
symbol,
current_qty - target_qty,
current_qty,
self.reserve_order_id(),
reason,
intraday_turnover,
@@ -2715,27 +2784,28 @@ where
None,
report,
)?;
} else if target_qty > current_qty {
self.process_buy(
return Ok(());
}
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
let current_value = valuation_price * current_qty as f64;
let cash_delta = target_value.max(0.0) - current_value;
if cash_delta.abs() > f64::EPSILON {
self.process_value(
date,
portfolio,
data,
symbol,
target_qty - current_qty,
self.reserve_order_id(),
cash_delta,
reason,
intraday_turnover,
execution_cursors,
global_execution_cursor,
commission_state,
None,
None,
false,
true,
None,
report,
)?;
} else if (current_value - target_value).abs() <= f64::EPSILON {
} else {
report.order_events.push(OrderEvent {
date,
order_id: None,
@@ -3142,7 +3212,7 @@ where
report,
)
} else {
let price = self.sizing_price(snapshot);
let price = self.value_sell_sizing_price(date, data, symbol, snapshot);
let requested_qty = self.round_buy_quantity(
((value.abs()) / price).floor() as u32,
self.minimum_order_quantity(data, symbol),
@@ -3587,16 +3657,11 @@ where
requested_qty
}
fn value_buy_gross_limit(
&self,
value_budget: Option<f64>,
requested_qty: u32,
reference_price: f64,
) -> Option<f64> {
fn value_buy_gross_limit(&self, value_budget: Option<f64>) -> Option<f64> {
if !self.strict_value_budget {
return None;
}
value_budget.map(|budget| budget.max(reference_price * requested_qty as f64))
value_budget.filter(|budget| budget.is_finite() && *budget > 0.0)
}
fn process_buy(
@@ -3755,8 +3820,15 @@ where
return Ok(());
}
};
let value_gross_limit =
self.value_buy_gross_limit(value_budget, constrained_qty, self.sizing_price(snapshot));
let value_gross_limit = self.value_buy_gross_limit(value_budget);
let buy_cash_limit = if self.strict_value_budget {
value_budget
.filter(|budget| budget.is_finite() && *budget > 0.0)
.map(|budget| portfolio.cash().min(budget))
.unwrap_or_else(|| portfolio.cash())
} else {
portfolio.cash()
};
let fill = self.resolve_execution_fill(
date,
@@ -3771,7 +3843,7 @@ where
false,
execution_cursors,
None,
Some(portfolio.cash()),
Some(buy_cash_limit),
value_gross_limit,
algo_request,
limit_price,
@@ -3808,7 +3880,7 @@ where
self.execution_price_with_limit_slippage(execution_price, limit_price);
let filled_qty = self.affordable_buy_quantity(
date,
portfolio.cash(),
buy_cash_limit,
value_gross_limit,
execution_price,
constrained_qty,
@@ -3825,7 +3897,7 @@ where
partial_fill_reason = merge_partial_fill_reason(
partial_fill_reason,
self.buy_reduction_reason(
portfolio.cash(),
buy_cash_limit,
value_gross_limit,
execution_price,
constrained_qty,
@@ -4544,6 +4616,7 @@ where
quotes,
start_cursor,
end_cursor,
matching_type == MatchingType::NextTickLast && start_cursor.is_some(),
)),
});
}
@@ -4556,7 +4629,16 @@ where
quotes: &[IntradayExecutionQuote],
start_cursor: Option<NaiveDateTime>,
end_cursor: Option<NaiveDateTime>,
use_decision_time_quote: bool,
) -> &'static str {
if use_decision_time_quote {
let saw_quote_at_or_before_start = start_cursor
.is_some_and(|cursor| quotes.iter().any(|quote| quote.timestamp <= cursor));
if saw_quote_at_or_before_start {
return "intraday quote liquidity exhausted";
}
return "no execution quotes at or before start";
}
let saw_quote_in_window = quotes.iter().any(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
@@ -4592,15 +4674,30 @@ where
let quote_quantity_limited =
self.quote_quantity_limited_for_window(matching_type, start_cursor, end_cursor);
let lot = round_lot.max(1);
let eligible_quotes: Vec<&IntradayExecutionQuote> = quotes
.iter()
.filter(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
&& (!quote_quantity_limited
|| self.quote_has_executable_liquidity(quote, side, matching_type))
})
.collect();
let use_decision_time_quote =
matching_type == MatchingType::NextTickLast && start_cursor.is_some();
let eligible_quotes: Vec<&IntradayExecutionQuote> = if use_decision_time_quote {
self.latest_known_quote_at_or_before(
quotes,
start_cursor,
snapshot,
side,
matching_type,
quote_quantity_limited,
)
.into_iter()
.collect()
} else {
quotes
.iter()
.filter(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
&& (!quote_quantity_limited
|| self.quote_has_executable_liquidity(quote, side, matching_type))
})
.collect()
};
let mut filled_qty = 0_u32;
let mut gross_amount = 0.0_f64;
let mut last_timestamp = None;
@@ -4694,7 +4791,11 @@ where
);
continue;
}
if candidate_gross <= cash + 1e-6 {
let candidate_cost = self
.cost_model
.calculate(snapshot.date, OrderSide::Buy, candidate_gross)
.total();
if candidate_gross + candidate_cost <= cash + 1e-6 {
break;
}
budget_block_reason = Some("insufficient cash after fees");
@@ -4835,6 +4936,7 @@ fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
"tick no volume"
| "tick volume limit"
| "intraday quote liquidity exhausted"
| "no execution quotes at or before start"
| "no execution quotes after start"
| "upper_limit"
| "lower_limit"
@@ -4849,6 +4951,7 @@ fn final_partial_fill_status(partial_reason: Option<&str>) -> OrderStatus {
Some(reason)
if reason.contains("market liquidity or volume limit")
|| reason.contains("intraday quote liquidity exhausted")
|| reason.contains("no execution quotes at or before start")
|| reason.contains("no execution quotes after start")
|| reason.contains("upper_limit")
|| reason.contains("lower_limit")
@@ -4880,12 +4983,17 @@ fn sell_reason(decision: &StrategyDecision, symbol: &str) -> &'static str {
#[cfg(test)]
mod tests {
use super::{BrokerSimulator, MatchingType};
use std::collections::BTreeMap;
use super::{BrokerExecutionReport, BrokerSimulator, MatchingType, SlippageModel};
use crate::cost::ChinaAShareCostModel;
use crate::data::{
CandidateEligibility, DailyMarketSnapshot, IntradayExecutionQuote, PriceField,
BenchmarkSnapshot, CandidateEligibility, DailyMarketSnapshot, DataSet,
IntradayExecutionQuote, PriceField,
};
use crate::events::OrderSide;
use crate::instrument::Instrument;
use crate::portfolio::PortfolioState;
use crate::rules::ChinaEquityRuleHooks;
fn limit_test_snapshot() -> DailyMarketSnapshot {
@@ -4947,6 +5055,30 @@ mod tests {
}
}
fn limit_test_instrument() -> Instrument {
Instrument {
symbol: "000001.SZ".to_string(),
name: "PingAn".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: None,
delisted_at: None,
status: "active".to_string(),
}
}
fn limit_test_benchmark() -> BenchmarkSnapshot {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 1000.0,
volume: 1_000_000,
}
}
#[test]
fn next_tick_last_without_volume_or_liquidity_limit_does_not_cap_quote_quantity() {
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
@@ -4972,6 +5104,217 @@ mod tests {
assert!(liquidity_limited.quote_quantity_limited(MatchingType::NextTickLast));
}
#[test]
fn target_value_valuation_uses_daily_snapshot_but_value_order_sizing_uses_intraday_tick() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_intraday_execution_start_time(date.and_hms_opt(9, 33, 0).unwrap().time());
let mut snapshot = limit_test_snapshot();
snapshot.last_price = 9.0;
snapshot.close = 10.0;
let mut quote = limit_test_quote(11.0, 10.99, 11.01);
quote.timestamp = date.and_hms_opt(9, 32, 58).expect("valid timestamp");
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot.clone()],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
vec![quote],
)
.expect("valid dataset");
let snapshot = data.market(date, "000001.SZ").expect("market snapshot");
assert_eq!(
broker.target_value_valuation_price(date, &data, "000001.SZ", snapshot),
10.0
);
assert_eq!(
broker.value_sell_sizing_price(date, &data, "000001.SZ", snapshot),
11.0
);
}
#[test]
fn next_tick_last_execution_uses_latest_quote_before_decision_time() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let snapshot = limit_test_snapshot();
let mut quote = limit_test_quote(10.8, 10.79, 10.81);
quote.timestamp = date.and_hms_opt(9, 32, 58).expect("valid timestamp");
let quote_timestamp = quote.timestamp;
let decision_time = date.and_hms_opt(9, 33, 0).expect("valid timestamp");
let fill = broker
.select_execution_fill(
&snapshot,
&[quote],
OrderSide::Sell,
MatchingType::NextTickLast,
Some(decision_time),
Some(decision_time),
200,
100,
100,
100,
false,
None,
None,
None,
)
.expect("fill from latest known quote before decision time");
assert_eq!(fill.quantity, 200);
assert_eq!(fill.legs.len(), 1);
assert_eq!(fill.legs[0].price, 10.8);
assert_eq!(
fill.next_cursor,
quote_timestamp + chrono::Duration::seconds(1)
);
}
#[test]
fn value_buy_process_uses_latest_quote_before_decision_time() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_intraday_execution_start_time(date.and_hms_opt(9, 33, 0).unwrap().time())
.with_slippage_model(SlippageModel::PriceRatio(0.002))
.with_strict_value_budget(true)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let mut snapshot = limit_test_snapshot();
snapshot.day_open = 8.70;
snapshot.open = 8.70;
snapshot.high = 8.95;
snapshot.low = 8.60;
snapshot.last_price = 8.94;
snapshot.bid1 = 8.93;
snapshot.ask1 = 8.94;
snapshot.close = 8.94;
snapshot.upper_limit = 9.72;
snapshot.lower_limit = 7.96;
let mut quote = limit_test_quote(8.69, 8.69, 8.70);
quote.timestamp = date.and_hms_opt(9, 32, 55).expect("valid timestamp");
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
vec![quote],
)
.expect("valid dataset");
let mut portfolio = PortfolioState::new(10_000_000.0);
let mut report = BrokerExecutionReport::default();
broker
.process_value(
date,
&mut portfolio,
&data,
"000001.SZ",
125_000.0,
"periodic_rebalance_buy",
&mut BTreeMap::new(),
&mut BTreeMap::new(),
&mut None,
&mut BTreeMap::new(),
&mut report,
)
.expect("value buy processed");
let position = portfolio.position("000001.SZ").unwrap_or_else(|| {
panic!(
"position created from latest known quote; events={:?}",
report.order_events
)
});
assert_eq!(position.quantity, 14_300);
assert_eq!(report.order_events.len(), 1);
assert_eq!(report.order_events[0].filled_quantity, 14_300);
}
#[test]
fn strict_value_buy_budget_includes_commission_at_execution_price() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_intraday_execution_start_time(date.and_hms_opt(9, 33, 0).unwrap().time())
.with_slippage_model(SlippageModel::PriceRatio(0.002))
.with_strict_value_budget(true)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let mut snapshot = limit_test_snapshot();
snapshot.day_open = 7.14;
snapshot.open = 7.14;
snapshot.high = 7.20;
snapshot.low = 7.10;
snapshot.last_price = 7.14;
snapshot.bid1 = 7.14;
snapshot.ask1 = 7.15;
snapshot.close = 7.14;
snapshot.upper_limit = 7.85;
snapshot.lower_limit = 6.43;
let mut quote = limit_test_quote(7.14, 7.14, 7.15);
quote.timestamp = date.and_hms_opt(9, 32, 55).expect("valid timestamp");
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
vec![quote],
)
.expect("valid dataset");
let value_budget = 125_216.8131;
let mut portfolio = PortfolioState::new(10_000_000.0);
let mut report = BrokerExecutionReport::default();
broker
.process_value(
date,
&mut portfolio,
&data,
"000001.SZ",
value_budget,
"periodic_rebalance_buy",
&mut BTreeMap::new(),
&mut BTreeMap::new(),
&mut None,
&mut BTreeMap::new(),
&mut report,
)
.expect("value buy processed");
let fill = report.fill_events.first().expect("fill event");
assert_eq!(fill.quantity, 17_400);
assert!(fill.gross_amount + fill.commission <= value_budget + 1e-6);
assert!((fill.price - 7.15428).abs() < 1e-6);
}
#[test]
fn instantaneous_twap_without_limits_does_not_cap_quote_quantity() {
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
+323 -70
View File
@@ -445,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>,
@@ -453,13 +485,12 @@ 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>,
last_prefix: Vec<f64>,
unpaused_volumes: Vec<f64>,
unpaused_volume_prefix: Vec<f64>,
unpaused_count_prefix: Vec<usize>,
volume_prefix: Vec<f64>,
}
impl SymbolPriceSeries {
@@ -472,20 +503,15 @@ impl SymbolPriceSeries {
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
let volumes = sorted
.iter()
.map(|row| row.volume as f64)
.collect::<Vec<_>>();
let open_prefix = prefix_sums(&opens);
let close_prefix = prefix_sums(&closes);
let prev_close_prefix = prefix_sums(&prev_closes);
let last_prefix = prefix_sums(&last_prices);
let mut unpaused_volumes = Vec::new();
let mut unpaused_count_prefix = Vec::with_capacity(sorted.len() + 1);
unpaused_count_prefix.push(0);
for row in &sorted {
if !row.paused {
unpaused_volumes.push(row.volume as f64);
}
unpaused_count_prefix.push(unpaused_volumes.len());
}
let unpaused_volume_prefix = prefix_sums(&unpaused_volumes);
let volume_prefix = prefix_sums(&volumes);
Self {
snapshots: sorted,
@@ -494,13 +520,12 @@ impl SymbolPriceSeries {
closes,
prev_closes,
last_prices,
volumes,
open_prefix,
close_prefix,
prev_close_prefix,
last_prefix,
unpaused_volumes,
unpaused_volume_prefix,
unpaused_count_prefix,
volume_prefix,
}
}
@@ -597,11 +622,15 @@ impl SymbolPriceSeries {
}
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
let values = self.decision_volume_values(date, lookback)?;
if values.len() < lookback {
if lookback == 0 {
return None;
}
let sum = values.iter().sum::<f64>();
let end = self.previous_completed_end_index(date)?;
if end < lookback {
return None;
}
let start = end - lookback;
let sum = self.volume_prefix[end] - self.volume_prefix[start];
Some(sum / lookback as f64)
}
@@ -610,12 +639,11 @@ impl SymbolPriceSeries {
return None;
}
let end = self.end_index(date)?;
let end_count = *self.unpaused_count_prefix.get(end)?;
if end_count < lookback {
if end < lookback {
return None;
}
let start_count = end_count - lookback;
let sum = self.unpaused_volume_prefix[end_count] - self.unpaused_volume_prefix[start_count];
let start = end - lookback;
let sum = self.volume_prefix[end] - self.volume_prefix[start];
Some(sum / lookback as f64)
}
@@ -624,23 +652,11 @@ impl SymbolPriceSeries {
return None;
}
let end = self.previous_completed_end_index(date)?;
let values = self.trailing_unpaused_volumes(end, lookback)?;
if values.len() < lookback {
if end < lookback {
return None;
}
Some(values)
}
fn trailing_unpaused_volumes(&self, end: usize, lookback: usize) -> Option<Vec<f64>> {
if lookback == 0 || end == 0 {
return None;
}
let end_count = *self.unpaused_count_prefix.get(end)?;
if end_count < lookback {
return None;
}
let start_count = end_count - lookback;
Some(self.unpaused_volumes[start_count..end_count].to_vec())
let start = end - lookback;
Some(self.volumes[start..end].to_vec())
}
fn end_index(&self, date: NaiveDate) -> Option<usize> {
@@ -691,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>,
}
@@ -702,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,
}
@@ -717,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;
@@ -734,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,
@@ -791,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>,
@@ -1075,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
@@ -1105,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,
@@ -1177,14 +1230,22 @@ 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_index.keys().cloned().collect()
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 {
@@ -1192,7 +1253,12 @@ impl DataSet {
let mut touched = HashSet::<(NaiveDate, String)>::new();
for quote in quotes {
let key = (quote.date, quote.symbol.clone());
let rows = self.execution_quotes_index.entry(key.clone()).or_default();
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
}) {
@@ -1202,8 +1268,12 @@ impl DataSet {
touched.insert(key);
added += 1;
}
for key in touched {
if let Some(rows) = self.execution_quotes_index.get_mut(&key) {
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);
}
}
@@ -1223,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
@@ -1346,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<_>>();
@@ -1846,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| {
@@ -2240,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,
@@ -2269,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,
@@ -3279,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
@@ -3348,10 +3443,15 @@ fn build_eligible_universe(
{
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| {
@@ -3410,6 +3510,17 @@ mod tests {
}
}
fn benchmark_row(date: &str, close: f64) -> BenchmarkSnapshot {
BenchmarkSnapshot {
date: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap(),
benchmark: "000852.SH".to_string(),
open: close,
close,
prev_close: close - 1.0,
volume: 1_000_000,
}
}
#[test]
fn baseline_selection_uses_structured_instrument_dates_and_status_only() {
let date = NaiveDate::parse_from_str("2025-01-02", "%Y-%m-%d").unwrap();
@@ -3443,6 +3554,14 @@ mod tests {
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(
"正常名称",
@@ -3485,7 +3604,29 @@ mod tests {
}
#[test]
fn decision_volume_average_skips_paused_days_before_counting_window() {
fn decision_close_average_ignores_current_day_close() {
let mut current = market_row("2025-01-06", 12.0, 10_000);
current.close = 9_999.0;
current.last_price = 9_999.0;
let series = SymbolPriceSeries::new(&[
market_row("2025-01-02", 10.0, 100),
market_row("2025-01-03", 11.0, 200),
current,
]);
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
assert_eq!(
series.decision_close_moving_average(decision_date, 2),
Some(11.5)
);
assert_eq!(
series.moving_average(decision_date, 2, PriceField::Close),
Some((11.0 + 9_999.0) / 2.0)
);
}
#[test]
fn decision_volume_average_includes_paused_zero_volume_days() {
let mut paused = market_row("2025-01-03", 11.0, 0);
paused.paused = true;
let series = SymbolPriceSeries::new(&[
@@ -3500,14 +3641,126 @@ mod tests {
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
2
),
Some(200.0)
Some(150.0)
);
assert_eq!(
series.decision_volume_moving_average(
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
3
),
None
Some((100.0 + 0.0 + 300.0) / 3.0)
);
}
#[test]
fn eligible_universe_uses_decision_market_cap_same_date() {
let date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
let instrument = |symbol: &str| Instrument {
symbol: symbol.to_string(),
name: symbol.to_string(),
board: if symbol.ends_with(".SH") { "SH" } else { "SZ" }.to_string(),
round_lot: 100,
listed_at: Some(NaiveDate::parse_from_str("2020-01-01", "%Y-%m-%d").unwrap()),
delisted_at: None,
status: "active".to_string(),
};
let market = |symbol: &str, prev_close: f64, close: f64| DailyMarketSnapshot {
date,
symbol: symbol.to_string(),
timestamp: Some("2025-01-06 10:18:00".to_string()),
day_open: prev_close,
open: prev_close,
high: close.max(prev_close),
low: close.min(prev_close),
close,
last_price: prev_close,
bid1: prev_close,
ask1: prev_close,
prev_close,
volume: 100_000,
tick_volume: 1_000,
bid1_volume: 1_000,
ask1_volume: 1_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: prev_close * 1.1,
lower_limit: prev_close * 0.9,
price_tick: 0.01,
};
let factor =
|symbol: &str, market_cap_bn: f64, free_float_cap_bn: f64| DailyFactorSnapshot {
date,
symbol: symbol.to_string(),
market_cap_bn,
free_float_cap_bn,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
};
let candidate = |symbol: &str| CandidateEligibility {
date,
symbol: symbol.to_string(),
is_st: false,
is_new_listing: false,
is_paused: false,
allow_buy: true,
allow_sell: true,
is_kcb: false,
is_one_yuan: false,
};
let data = DataSet::from_components(
vec![instrument("000001.SZ"), instrument("000002.SZ")],
vec![
market("000001.SZ", 10.0, 20.0),
market("000002.SZ", 10.0, 10.0),
],
vec![
factor("000001.SZ", 12.0, 4.0),
factor("000002.SZ", 10.0, 5.0),
],
vec![candidate("000001.SZ"), candidate("000002.SZ")],
vec![BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 100.0,
close: 101.0,
prev_close: 99.0,
volume: 1_000_000,
}],
)
.expect("dataset");
let rows = data.eligible_universe_on(date);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].symbol, "000001.SZ");
assert!((rows[0].market_cap_bn - 6.0).abs() < 1e-9);
assert!((rows[0].free_float_cap_bn - 2.0).abs() < 1e-9);
assert_eq!(rows[1].symbol, "000002.SZ");
assert!((rows[1].market_cap_bn - 10.0).abs() < 1e-9);
}
#[test]
fn benchmark_decision_close_windows_exclude_current_close() {
let series = BenchmarkPriceSeries::new(&[
benchmark_row("2025-01-02", 100.0),
benchmark_row("2025-01-03", 200.0),
benchmark_row("2025-01-06", 9_999.0),
]);
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
assert_eq!(series.decision_close(decision_date), Some(9_998.0));
assert_eq!(
series.decision_moving_average(decision_date, 2),
Some(150.0)
);
assert_eq!(
series.decision_values_for(decision_date, 2, PriceField::Close),
vec![100.0, 200.0]
);
assert_eq!(
series.moving_average(decision_date, 2),
Some((200.0 + 9_999.0) / 2.0)
);
}
+8
View File
@@ -3197,6 +3197,14 @@ fn has_execution_quote_in_window(
) -> 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)
+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())
}
}
File diff suppressed because it is too large Load Diff
+323 -3
View File
@@ -67,6 +67,14 @@ pub struct StrategyExecutionSpec {
#[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>,
}
@@ -108,6 +116,14 @@ pub struct StrategyEngineConfig {
#[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>,
@@ -258,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>,
@@ -341,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,
@@ -355,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
@@ -394,20 +551,25 @@ pub fn platform_expr_config_from_spec(
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
if let Some(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() {
@@ -438,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
@@ -619,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;
}
@@ -717,20 +893,51 @@ 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);
}
if spec
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")
{
.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
@@ -1124,6 +1331,7 @@ mod tests {
"stockFilterExpr": "stock_ma5 > stock_ma10"
},
"trading": {
"refreshRateExpr": "year >= 2024 ? 5 : 20",
"rotationEnabled": false,
"dailyTopUp": true,
"retryEmptyRebalance": true,
@@ -1145,6 +1353,7 @@ 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);
@@ -1158,6 +1367,117 @@ mod tests {
);
}
#[test]
fn parses_execution_cost_overrides_into_platform_config() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha",
"commissionRate": 0.0003,
"minimumCommission": 5.0,
"stampTaxRateBeforeChange": 0.0005,
"stampTaxRateAfterChange": 0.0005
},
"engineConfig": {
"commissionRate": 0.0008
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.commission_rate, Some(0.0003));
assert_eq!(cfg.minimum_commission, Some(5.0));
assert_eq!(cfg.stamp_tax_rate_before_change, Some(0.0005));
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
}
#[test]
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert!(cfg.aiquant_transaction_cost);
assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance);
let explicit_off = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
},
"runtimeExpressions": {
"trading": {
"dailyTopUp": false,
"retryEmptyRebalance": false
}
}
});
let cfg = platform_expr_config_from_value("", "", &explicit_off).expect("config");
assert!(!cfg.daily_top_up_enabled);
assert!(!cfg.retry_empty_rebalance);
}
#[test]
fn runtime_expressions_infer_ma_windows_from_literal_strategy_logic() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha"
},
"runtimeExpressions": {
"selection": {
"stockFilterExpr": "rolling_mean(\"close\", 5) > rolling_mean(\"close\", 10) && rolling_mean(\"close\", 10) > rolling_mean(\"close\", 30)"
},
"risk": {
"exposureExpr": "benchmark_ma5 > benchmark_ma20 ? 1.0 : weak_market_trade_rate"
}
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(cfg.benchmark_short_ma_days, 5);
assert_eq!(cfg.benchmark_long_ma_days, 20);
assert_eq!(cfg.stock_short_ma_days, 5);
assert_eq!(cfg.stock_mid_ma_days, 10);
assert_eq!(cfg.stock_long_ma_days, 30);
let explicit = serde_json::json!({
"engineConfig": {
"stockMaFilter": {
"shortDays": 4,
"midDays": 9,
"longDays": 21
},
"indexThrottle": {
"shortDays": 3,
"longDays": 13
}
},
"runtimeExpressions": {
"selection": {
"stockFilterExpr": "rolling_mean(\"close\", 5) > rolling_mean(\"close\", 10) && rolling_mean(\"close\", 10) > rolling_mean(\"close\", 30)"
},
"risk": {
"exposureExpr": "benchmark_ma5 > benchmark_ma20 ? 1.0 : 0.5"
}
}
});
let cfg = platform_expr_config_from_value("", "", &explicit).expect("config");
assert_eq!(cfg.benchmark_short_ma_days, 3);
assert_eq!(cfg.benchmark_long_ma_days, 13);
assert_eq!(cfg.stock_short_ma_days, 4);
assert_eq!(cfg.stock_mid_ma_days, 9);
assert_eq!(cfg.stock_long_ma_days, 21);
}
#[test]
fn parses_daily_schedule_time_for_aiquant_execution_quotes() {
let spec = serde_json::json!({
+3 -3
View File
@@ -26,11 +26,11 @@ impl ChinaAShareRiskControl {
return Some("inactive_or_delisted");
}
let status = instrument.status.trim().to_ascii_lowercase();
if matches!(
let terminal_status = matches!(
status.as_str(),
"inactive" | "delisted" | "terminated" | "expired"
) || status.contains("delist")
{
) || status.contains("delist");
if terminal_status && instrument.delisted_at.is_none() {
return Some("inactive_or_delisted");
}
None
+6 -5
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(),
+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(),
@@ -1658,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,
@@ -1804,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());
}
@@ -1993,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,