Compare commits

...

5 Commits

Author SHA1 Message Date
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
14 changed files with 3169 additions and 293 deletions
+340 -36
View File
@@ -10,8 +10,10 @@ use crate::events::{
AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent, AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent,
ProcessEventKind, ProcessEventKind,
}; };
use crate::instrument::Instrument;
use crate::portfolio::PortfolioState; use crate::portfolio::PortfolioState;
use crate::rules::EquityRuleHooks; use crate::risk_control::ChinaAShareRiskControl;
use crate::rules::{EquityRuleHooks, RuleCheck};
use crate::strategy::{ use crate::strategy::{
AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision, TargetPortfolioOrderPricing, AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision, TargetPortfolioOrderPricing,
}; };
@@ -111,6 +113,7 @@ pub struct BrokerSimulator<C, R> {
inactive_limit: bool, inactive_limit: bool,
liquidity_limit: bool, liquidity_limit: bool,
strict_value_budget: bool, strict_value_budget: bool,
aiquant_rqalpha_execution_rules: bool,
same_day_buy_close_mark_at_fill: bool, same_day_buy_close_mark_at_fill: bool,
intraday_execution_start_time: Option<NaiveTime>, intraday_execution_start_time: Option<NaiveTime>,
runtime_intraday_start_time: Cell<Option<NaiveTime>>, runtime_intraday_start_time: Cell<Option<NaiveTime>>,
@@ -133,6 +136,7 @@ impl<C, R> BrokerSimulator<C, R> {
inactive_limit: true, inactive_limit: true,
liquidity_limit: true, liquidity_limit: true,
strict_value_budget: false, strict_value_budget: false,
aiquant_rqalpha_execution_rules: false,
same_day_buy_close_mark_at_fill: false, same_day_buy_close_mark_at_fill: false,
intraday_execution_start_time: None, intraday_execution_start_time: None,
runtime_intraday_start_time: Cell::new(None), runtime_intraday_start_time: Cell::new(None),
@@ -159,6 +163,7 @@ impl<C, R> BrokerSimulator<C, R> {
inactive_limit: true, inactive_limit: true,
liquidity_limit: true, liquidity_limit: true,
strict_value_budget: false, strict_value_budget: false,
aiquant_rqalpha_execution_rules: false,
same_day_buy_close_mark_at_fill: false, same_day_buy_close_mark_at_fill: false,
intraday_execution_start_time: None, intraday_execution_start_time: None,
runtime_intraday_start_time: Cell::new(None), runtime_intraday_start_time: Cell::new(None),
@@ -188,6 +193,11 @@ impl<C, R> BrokerSimulator<C, R> {
self self
} }
pub fn with_aiquant_rqalpha_execution_rules(mut self, enabled: bool) -> Self {
self.aiquant_rqalpha_execution_rules = enabled;
self
}
pub fn with_same_day_buy_close_mark_at_fill(mut self, enabled: bool) -> Self { pub fn with_same_day_buy_close_mark_at_fill(mut self, enabled: bool) -> Self {
self.same_day_buy_close_mark_at_fill = enabled; self.same_day_buy_close_mark_at_fill = enabled;
self self
@@ -1825,6 +1835,82 @@ where
Ok(()) Ok(())
} }
fn aiquant_limit_check_price(
&self,
snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide,
) -> f64 {
match (self.execution_price_field, side) {
(PriceField::Last, _) => snapshot.price(PriceField::Last),
(_, OrderSide::Buy) => snapshot.buy_price(self.execution_price_field),
(_, OrderSide::Sell) => snapshot.sell_price(self.execution_price_field),
}
}
fn buy_rule_check(
&self,
date: NaiveDate,
snapshot: &crate::data::DailyMarketSnapshot,
candidate: &crate::data::CandidateEligibility,
instrument: Option<&Instrument>,
) -> RuleCheck {
let check_price = if self.aiquant_rqalpha_execution_rules {
self.aiquant_limit_check_price(snapshot, OrderSide::Buy)
} else {
ChinaAShareRiskControl::buy_check_price(snapshot, self.execution_price_field)
};
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
date,
candidate,
snapshot,
instrument,
check_price,
) {
return RuleCheck::reject(reason);
}
if !self.aiquant_rqalpha_execution_rules {
return self
.rules
.can_buy(date, snapshot, candidate, self.execution_price_field);
}
RuleCheck::allow()
}
fn sell_rule_check(
&self,
date: NaiveDate,
snapshot: &crate::data::DailyMarketSnapshot,
candidate: &crate::data::CandidateEligibility,
instrument: Option<&Instrument>,
position: &crate::portfolio::Position,
) -> RuleCheck {
let check_price = if self.aiquant_rqalpha_execution_rules {
self.aiquant_limit_check_price(snapshot, OrderSide::Sell)
} else {
ChinaAShareRiskControl::sell_check_price(snapshot, self.execution_price_field)
};
if let Some(reason) = ChinaAShareRiskControl::sell_rejection_reason(
date,
candidate,
snapshot,
instrument,
Some(position),
check_price,
) {
return RuleCheck::reject(reason);
}
if !self.aiquant_rqalpha_execution_rules {
return self.rules.can_sell(
date,
snapshot,
candidate,
position,
self.execution_price_field,
);
}
RuleCheck::allow()
}
fn minimum_target_quantity( fn minimum_target_quantity(
&self, &self,
date: NaiveDate, date: NaiveDate,
@@ -1847,13 +1933,8 @@ where
let Ok(candidate) = data.require_candidate(date, symbol) else { let Ok(candidate) = data.require_candidate(date, symbol) else {
return current_qty; return current_qty;
}; };
let rule = self.rules.can_sell( let rule =
date, self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
snapshot,
candidate,
position,
self.execution_price_field,
);
if !rule.allowed { if !rule.allowed {
return current_qty; return current_qty;
} }
@@ -1891,9 +1972,7 @@ where
let Ok(candidate) = data.require_candidate(date, symbol) else { let Ok(candidate) = data.require_candidate(date, symbol) else {
return current_qty; return current_qty;
}; };
let rule = self let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
.rules
.can_buy(date, snapshot, candidate, self.execution_price_field);
if !rule.allowed { if !rule.allowed {
return current_qty; return current_qty;
} }
@@ -1937,13 +2016,8 @@ where
let position = portfolio.position(symbol)?; let position = portfolio.position(symbol)?;
let snapshot = data.require_market(date, symbol).ok()?; let snapshot = data.require_market(date, symbol).ok()?;
let candidate = data.require_candidate(date, symbol).ok()?; let candidate = data.require_candidate(date, symbol).ok()?;
let rule = self.rules.can_sell( let rule =
date, self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
snapshot,
candidate,
position,
self.execution_price_field,
);
if !rule.allowed { if !rule.allowed {
return rule.reason; return rule.reason;
} }
@@ -1983,9 +2057,7 @@ where
) -> Option<String> { ) -> Option<String> {
let snapshot = data.require_market(date, symbol).ok()?; let snapshot = data.require_market(date, symbol).ok()?;
let candidate = data.require_candidate(date, symbol).ok()?; let candidate = data.require_candidate(date, symbol).ok()?;
let rule = self let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
.rules
.can_buy(date, snapshot, candidate, self.execution_price_field);
if !rule.allowed { if !rule.allowed {
return rule.reason; return rule.reason;
} }
@@ -2055,18 +2127,15 @@ where
); );
} }
let rule = self.rules.can_sell( let rule =
date, self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
snapshot,
candidate,
position,
self.execution_price_field,
);
if !rule.allowed { if !rule.allowed {
let rule_reason = rule.reason.as_deref().unwrap_or_default().to_string(); let rule_reason = rule.reason.as_deref().unwrap_or_default().to_string();
let status = match rule.reason.as_deref() { let status = match rule.reason.as_deref() {
Some("paused") Some("paused")
| Some("sell disabled by eligibility flags") | Some("sell disabled by eligibility flags")
| Some("sell_disabled")
| Some("lower_limit")
| Some("open at or below lower limit") => OrderStatus::Canceled, | Some("open at or below lower limit") => OrderStatus::Canceled,
_ => OrderStatus::Rejected, _ => OrderStatus::Rejected,
}; };
@@ -2277,7 +2346,12 @@ where
(fill.quantity, fill.legs) (fill.quantity, fill.legs)
} else { } else {
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Sell); let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Sell);
if !self.price_satisfies_limit( if let Some(reason) =
self.execution_limit_rejection_reason(snapshot, OrderSide::Sell, execution_price)
{
partial_fill_reason = merge_partial_fill_reason(partial_fill_reason, Some(reason));
(0, Vec::new())
} else if !self.price_satisfies_limit(
OrderSide::Sell, OrderSide::Sell,
execution_price, execution_price,
limit_price, limit_price,
@@ -3489,14 +3563,14 @@ where
); );
} }
let rule = self let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
.rules
.can_buy(date, snapshot, candidate, self.execution_price_field);
if !rule.allowed { if !rule.allowed {
let rule_reason = rule.reason.as_deref().unwrap_or_default().to_string(); let rule_reason = rule.reason.as_deref().unwrap_or_default().to_string();
let status = match rule.reason.as_deref() { let status = match rule.reason.as_deref() {
Some("paused") Some("paused")
| Some("buy disabled by eligibility flags") | Some("buy disabled by eligibility flags")
| Some("buy_disabled")
| Some("upper_limit")
| Some("open at or above upper limit") => OrderStatus::Canceled, | Some("open at or above upper limit") => OrderStatus::Canceled,
_ => OrderStatus::Rejected, _ => OrderStatus::Rejected,
}; };
@@ -3641,7 +3715,12 @@ where
(fill.quantity, fill.legs) (fill.quantity, fill.legs)
} else { } else {
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Buy); let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Buy);
if !self.price_satisfies_limit( if let Some(reason) =
self.execution_limit_rejection_reason(snapshot, OrderSide::Buy, execution_price)
{
partial_fill_reason = merge_partial_fill_reason(partial_fill_reason, Some(reason));
(0, Vec::new())
} else if !self.price_satisfies_limit(
OrderSide::Buy, OrderSide::Buy,
execution_price, execution_price,
limit_price, limit_price,
@@ -4275,6 +4354,26 @@ where
} }
} }
fn execution_limit_rejection_reason(
&self,
snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide,
execution_price: f64,
) -> Option<&'static str> {
if !execution_price.is_finite() || execution_price <= 0.0 {
return None;
}
match side {
OrderSide::Buy if snapshot.is_at_upper_limit_price(execution_price) => {
Some("open at or above upper limit")
}
OrderSide::Sell if snapshot.is_at_lower_limit_price(execution_price) => {
Some("open at or below lower limit")
}
_ => None,
}
}
fn execution_price_with_limit_slippage( fn execution_price_with_limit_slippage(
&self, &self,
execution_price: f64, execution_price: f64,
@@ -4288,7 +4387,10 @@ where
fn limit_order_can_remain_open(partial_reason: Option<&str>) -> bool { fn limit_order_can_remain_open(partial_reason: Option<&str>) -> bool {
!partial_reason.is_some_and(|reason| { !partial_reason.is_some_and(|reason| {
reason.contains("insufficient cash") || reason.contains("value budget") reason.contains("insufficient cash")
|| reason.contains("value budget")
|| reason.contains("open at or above upper limit")
|| reason.contains("open at or below lower limit")
}) })
} }
@@ -4426,6 +4528,9 @@ where
let mut last_timestamp = None; let mut last_timestamp = None;
let mut legs = Vec::new(); let mut legs = Vec::new();
let mut budget_block_reason = None; let mut budget_block_reason = None;
let mut execution_block_reason = None;
let mut execution_block_timestamp = None;
let mut saw_non_blocked_execution_price = false;
let saw_quote_after_cursor = !eligible_quotes.is_empty(); let saw_quote_after_cursor = !eligible_quotes.is_empty();
for (quote_index, quote) in eligible_quotes.iter().enumerate() { for (quote_index, quote) in eligible_quotes.iter().enumerate() {
@@ -4437,6 +4542,13 @@ where
else { else {
continue; continue;
}; };
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, quote_price)
{
execution_block_reason.get_or_insert(reason);
execution_block_timestamp = Some(quote.timestamp);
continue;
}
saw_non_blocked_execution_price = true;
if !self.price_satisfies_limit( if !self.price_satisfies_limit(
side, side,
quote_price, quote_price,
@@ -4523,6 +4635,18 @@ where
} }
if filled_qty == 0 { if filled_qty == 0 {
if let Some(reason) = execution_block_reason
&& !saw_non_blocked_execution_price
{
return Some(ExecutionFill {
quantity: 0,
next_cursor: execution_block_timestamp
.expect("blocked execution quote timestamp")
+ Duration::seconds(1),
legs: Vec::new(),
unfilled_reason: Some(reason),
});
}
return None; return None;
} }
@@ -4619,7 +4743,11 @@ fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
"tick no volume" "tick no volume"
| "tick volume limit" | "tick volume limit"
| "intraday quote liquidity exhausted" | "intraday quote liquidity exhausted"
| "no execution quotes after start" => OrderStatus::Canceled, | "no execution quotes after start"
| "upper_limit"
| "lower_limit"
| "open at or above upper limit"
| "open at or below lower limit" => OrderStatus::Canceled,
_ => OrderStatus::Rejected, _ => OrderStatus::Rejected,
} }
} }
@@ -4629,7 +4757,11 @@ fn final_partial_fill_status(partial_reason: Option<&str>) -> OrderStatus {
Some(reason) Some(reason)
if reason.contains("market liquidity or volume limit") if reason.contains("market liquidity or volume limit")
|| reason.contains("intraday quote liquidity exhausted") || reason.contains("intraday quote liquidity exhausted")
|| reason.contains("no execution quotes after start") => || reason.contains("no execution quotes after start")
|| reason.contains("upper_limit")
|| reason.contains("lower_limit")
|| reason.contains("open at or above upper limit")
|| reason.contains("open at or below lower limit") =>
{ {
OrderStatus::Canceled OrderStatus::Canceled
} }
@@ -4658,8 +4790,71 @@ fn sell_reason(decision: &StrategyDecision, symbol: &str) -> &'static str {
mod tests { mod tests {
use super::{BrokerSimulator, MatchingType}; use super::{BrokerSimulator, MatchingType};
use crate::cost::ChinaAShareCostModel; use crate::cost::ChinaAShareCostModel;
use crate::data::{
CandidateEligibility, DailyMarketSnapshot, IntradayExecutionQuote, PriceField,
};
use crate::events::OrderSide;
use crate::rules::ChinaEquityRuleHooks; use crate::rules::ChinaEquityRuleHooks;
fn limit_test_snapshot() -> DailyMarketSnapshot {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
DailyMarketSnapshot {
date,
symbol: "000001.SZ".to_string(),
timestamp: Some("2025-01-02 09:33:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.5,
low: 9.5,
close: 10.0,
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
prev_close: 10.0,
volume: 1_000_000,
tick_volume: 10_000,
bid1_volume: 1_000,
ask1_volume: 1_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
}
}
fn limit_test_quote(last_price: f64, bid1: f64, ask1: f64) -> IntradayExecutionQuote {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
IntradayExecutionQuote {
date,
symbol: "000001.SZ".to_string(),
timestamp: date.and_hms_opt(9, 33, 0).expect("valid timestamp"),
last_price,
bid1,
ask1,
bid1_volume: 1_000,
ask1_volume: 1_000,
volume_delta: 1_000,
amount_delta: last_price * 1_000.0,
trading_phase: Some("continuous".to_string()),
}
}
fn limit_test_candidate(allow_buy: bool, allow_sell: bool) -> CandidateEligibility {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
CandidateEligibility {
date,
symbol: "000001.SZ".to_string(),
is_st: false,
is_new_listing: false,
is_paused: false,
allow_buy,
allow_sell,
is_kcb: false,
is_one_yuan: false,
}
}
#[test] #[test]
fn next_tick_last_without_volume_or_liquidity_limit_does_not_cap_quote_quantity() { fn next_tick_last_without_volume_or_liquidity_limit_does_not_cap_quote_quantity() {
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks) let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
@@ -4706,4 +4901,113 @@ mod tests {
Some(cursor + chrono::Duration::minutes(1)) Some(cursor + chrono::Duration::minutes(1))
)); ));
} }
#[test]
fn intraday_execution_rejects_buy_at_upper_limit_price() {
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 quote = limit_test_quote(11.0, 10.99, 11.0);
let start = quote.timestamp;
let fill = broker
.select_execution_fill(
&snapshot,
&[quote],
OrderSide::Buy,
MatchingType::NextTickLast,
Some(start),
None,
100,
100,
100,
100,
false,
None,
None,
None,
)
.expect("zero fill with rejection reason");
assert_eq!(fill.quantity, 0);
assert_eq!(fill.unfilled_reason, Some("open at or above upper limit"));
}
#[test]
fn aiquant_rules_keep_structured_buy_risk_while_using_aiquant_limit_price() {
let mut snapshot = limit_test_snapshot();
snapshot.open = 11.0;
snapshot.day_open = 11.0;
snapshot.last_price = 10.98;
snapshot.ask1 = 11.0;
let candidate = limit_test_candidate(false, true);
let date = snapshot.date;
let default_broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
);
let default_rule = default_broker.buy_rule_check(date, &snapshot, &candidate, None);
assert!(!default_rule.allowed);
assert_eq!(default_rule.reason.as_deref(), Some("trade_disabled"));
let aiquant_broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Last,
)
.with_aiquant_rqalpha_execution_rules(true);
let aiquant_rule = aiquant_broker.buy_rule_check(date, &snapshot, &candidate, None);
assert!(!aiquant_rule.allowed);
assert_eq!(aiquant_rule.reason.as_deref(), Some("trade_disabled"));
let tradable_candidate = limit_test_candidate(true, true);
let aiquant_rule =
aiquant_broker.buy_rule_check(date, &snapshot, &tradable_candidate, None);
assert!(aiquant_rule.allowed);
}
#[test]
fn intraday_execution_rejects_sell_at_lower_limit_price() {
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 quote = limit_test_quote(9.0, 9.0, 9.01);
let start = quote.timestamp;
let fill = broker
.select_execution_fill(
&snapshot,
&[quote],
OrderSide::Sell,
MatchingType::NextTickLast,
Some(start),
None,
100,
100,
100,
100,
false,
None,
None,
None,
)
.expect("zero fill with rejection reason");
assert_eq!(fill.quantity, 0);
assert_eq!(fill.unfilled_reason, Some("open at or below lower limit"));
}
} }
+8
View File
@@ -53,6 +53,14 @@ impl Default for ChinaAShareCostModel {
} }
impl 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 { pub fn commission_for(&self, gross_amount: f64) -> f64 {
if gross_amount <= 0.0 { if gross_amount <= 0.0 {
return 0.0; return 0.0;
+125 -28
View File
@@ -9,6 +9,7 @@ use thiserror::Error;
use crate::calendar::TradingCalendar; use crate::calendar::TradingCalendar;
use crate::futures::{FuturesCommissionType, FuturesTradingParameter}; use crate::futures::{FuturesCommissionType, FuturesTradingParameter};
use crate::instrument::Instrument; use crate::instrument::Instrument;
use crate::risk_control::ChinaAShareRiskControl;
mod date_format { mod date_format {
use chrono::NaiveDate; use chrono::NaiveDate;
@@ -452,11 +453,11 @@ struct SymbolPriceSeries {
closes: Vec<f64>, closes: Vec<f64>,
prev_closes: Vec<f64>, prev_closes: Vec<f64>,
last_prices: Vec<f64>, last_prices: Vec<f64>,
paused: Vec<bool>,
open_prefix: Vec<f64>, open_prefix: Vec<f64>,
close_prefix: Vec<f64>, close_prefix: Vec<f64>,
prev_close_prefix: Vec<f64>, prev_close_prefix: Vec<f64>,
last_prefix: Vec<f64>, last_prefix: Vec<f64>,
volume_prefix: Vec<f64>,
} }
impl SymbolPriceSeries { impl SymbolPriceSeries {
@@ -469,15 +470,11 @@ impl SymbolPriceSeries {
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>(); let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>(); let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>(); let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
let volumes = sorted let paused = sorted.iter().map(|row| row.paused).collect::<Vec<_>>();
.iter()
.map(|row| row.volume as f64)
.collect::<Vec<_>>();
let open_prefix = prefix_sums(&opens); let open_prefix = prefix_sums(&opens);
let close_prefix = prefix_sums(&closes); let close_prefix = prefix_sums(&closes);
let prev_close_prefix = prefix_sums(&prev_closes); let prev_close_prefix = prefix_sums(&prev_closes);
let last_prefix = prefix_sums(&last_prices); let last_prefix = prefix_sums(&last_prices);
let volume_prefix = prefix_sums(&volumes);
Self { Self {
snapshots: sorted, snapshots: sorted,
@@ -486,11 +483,11 @@ impl SymbolPriceSeries {
closes, closes,
prev_closes, prev_closes,
last_prices, last_prices,
paused,
open_prefix, open_prefix,
close_prefix, close_prefix,
prev_close_prefix, prev_close_prefix,
last_prefix, last_prefix,
volume_prefix,
} }
} }
@@ -587,15 +584,11 @@ impl SymbolPriceSeries {
} }
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> { fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
if lookback == 0 { let values = self.decision_volume_values(date, lookback)?;
if values.len() < lookback {
return None; return None;
} }
let end = self.previous_completed_end_index(date)?; let sum = values.iter().sum::<f64>();
if end < lookback {
return None;
}
let start = end - lookback;
let sum = self.volume_prefix[end] - self.volume_prefix[start];
Some(sum / lookback as f64) Some(sum / lookback as f64)
} }
@@ -604,11 +597,11 @@ impl SymbolPriceSeries {
return None; return None;
} }
let end = self.end_index(date)?; let end = self.end_index(date)?;
if end < lookback { let values = self.trailing_unpaused_volumes(end, lookback)?;
if values.len() < lookback {
return None; return None;
} }
let start = end - lookback; let sum = values.iter().sum::<f64>();
let sum = self.volume_prefix[end] - self.volume_prefix[start];
Some(sum / lookback as f64) Some(sum / lookback as f64)
} }
@@ -617,16 +610,33 @@ impl SymbolPriceSeries {
return None; return None;
} }
let end = self.previous_completed_end_index(date)?; let end = self.previous_completed_end_index(date)?;
if end < lookback { let values = self.trailing_unpaused_volumes(end, lookback)?;
if values.len() < lookback {
return None; return None;
} }
let start = end - lookback; Some(values)
Some( }
self.snapshots[start..end]
.iter() fn trailing_unpaused_volumes(&self, end: usize, lookback: usize) -> Option<Vec<f64>> {
.map(|snapshot| snapshot.volume as f64) if lookback == 0 || end == 0 {
.collect(), return None;
) }
let mut values = Vec::with_capacity(lookback);
for idx in (0..end).rev() {
if self.paused.get(idx).copied().unwrap_or(false) {
continue;
}
values.push(self.snapshots[idx].volume as f64);
if values.len() == lookback {
break;
}
}
if values.len() < lookback {
None
} else {
values.reverse();
Some(values)
}
} }
fn end_index(&self, date: NaiveDate) -> Option<usize> { fn end_index(&self, date: NaiveDate) -> Option<usize> {
@@ -1071,8 +1081,12 @@ impl DataSet {
let market_series_by_symbol = build_market_series(&market_by_date); let market_series_by_symbol = build_market_series(&market_by_date);
let benchmark_series_cache = let benchmark_series_cache =
BenchmarkPriceSeries::new(&benchmark_by_date.values().cloned().collect::<Vec<_>>()); BenchmarkPriceSeries::new(&benchmark_by_date.values().cloned().collect::<Vec<_>>());
let eligible_universe_by_date = let eligible_universe_by_date = build_eligible_universe(
build_eligible_universe(&factor_by_date, &candidate_index, &market_index); &factor_by_date,
&candidate_index,
&market_index,
&instruments,
);
let futures_params_by_symbol = build_futures_params_index(futures_params); let futures_params_by_symbol = build_futures_params_index(futures_params);
Ok(Self { Ok(Self {
@@ -3278,6 +3292,7 @@ fn build_eligible_universe(
factor_by_date: &BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>, factor_by_date: &BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
candidate_index: &HashMap<(NaiveDate, String), CandidateEligibility>, candidate_index: &HashMap<(NaiveDate, String), CandidateEligibility>,
market_index: &HashMap<(NaiveDate, String), DailyMarketSnapshot>, market_index: &HashMap<(NaiveDate, String), DailyMarketSnapshot>,
instruments: &HashMap<String, Instrument>,
) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> { ) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> {
let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new(); let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new();
@@ -3294,7 +3309,14 @@ fn build_eligible_universe(
let Some(market) = market_index.get(&key) else { let Some(market) = market_index.get(&key) else {
continue; continue;
}; };
if !candidate.eligible_for_selection() || market.paused { if ChinaAShareRiskControl::selection_rejection_reason(
*date,
candidate,
market,
instruments.get(&factor.symbol),
)
.is_some()
{
continue; continue;
} }
rows.push(EligibleUniverseSnapshot { rows.push(EligibleUniverseSnapshot {
@@ -3315,6 +3337,11 @@ fn build_eligible_universe(
per_date 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -3354,6 +3381,49 @@ mod tests {
} }
} }
#[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(
"正常名称",
"active",
Some(NaiveDate::parse_from_str("2025-01-01", "%Y-%m-%d").unwrap()),
)),
date
));
}
#[test] #[test]
fn decision_volume_average_uses_previous_completed_days_only() { fn decision_volume_average_uses_previous_completed_days_only() {
let series = SymbolPriceSeries::new(&[ let series = SymbolPriceSeries::new(&[
@@ -3385,6 +3455,33 @@ mod tests {
); );
} }
#[test]
fn decision_volume_average_skips_paused_days_before_counting_window() {
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(200.0)
);
assert_eq!(
series.decision_volume_moving_average(
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
3
),
None
);
}
#[test] #[test]
fn reads_mixed_numeric_and_text_extra_factors_from_quoted_csv_json() { fn reads_mixed_numeric_and_text_extra_factors_from_quoted_csv_json() {
let path = temp_csv_path("mixed_factor_maps"); let path = temp_csv_path("mixed_factor_maps");
+12 -12
View File
@@ -313,6 +313,7 @@ pub struct BacktestEngine<S, C, R> {
broker: BrokerSimulator<C, R>, broker: BrokerSimulator<C, R>,
config: BacktestConfig, config: BacktestConfig,
dividend_reinvestment: bool, dividend_reinvestment: bool,
cash_dividends_enabled: bool,
process_event_bus: ProcessEventBus, process_event_bus: ProcessEventBus,
dynamic_universe: Option<BTreeSet<String>>, dynamic_universe: Option<BTreeSet<String>>,
subscriptions: BTreeSet<String>, subscriptions: BTreeSet<String>,
@@ -338,6 +339,7 @@ impl<S, C, R> BacktestEngine<S, C, R> {
broker, broker,
config, config,
dividend_reinvestment: false, dividend_reinvestment: false,
cash_dividends_enabled: true,
process_event_bus: ProcessEventBus::new(), process_event_bus: ProcessEventBus::new(),
dynamic_universe: None, dynamic_universe: None,
subscriptions: BTreeSet::new(), subscriptions: BTreeSet::new(),
@@ -356,6 +358,11 @@ impl<S, C, R> BacktestEngine<S, C, R> {
self self
} }
pub fn with_cash_dividends(mut self, enabled: bool) -> Self {
self.cash_dividends_enabled = enabled;
self
}
pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self { pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self {
self.futures_account = Some(account); self.futures_account = Some(account);
self self
@@ -2521,7 +2528,7 @@ where
continue; 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_before = portfolio.cash();
let (cash_delta, quantity_after, average_cost) = { let (cash_delta, quantity_after, average_cost) = {
let position = portfolio let position = portfolio
@@ -2990,24 +2997,17 @@ where
} }
let quantity = position.quantity; 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 position.last_price
} else { } else if position.average_cost.is_finite() && position.average_cost > 0.0 {
position.average_cost position.average_cost
} else {
0.0
}; };
let effective_delisted_at = instrument let effective_delisted_at = instrument
.delisted_at .delisted_at
.or_else(|| self.data.calendar().previous_day(date)) .or_else(|| self.data.calendar().previous_day(date))
.unwrap_or(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 { if !settlement_price.is_finite() || settlement_price <= 0.0 {
return Err(BacktestError::Execution(format!( return Err(BacktestError::Execution(format!(
"missing delisting settlement price for {} on {}", "missing delisting settlement price for {} on {}",
+2
View File
@@ -12,6 +12,7 @@ pub mod platform_expr_strategy;
pub mod platform_runtime_schema; pub mod platform_runtime_schema;
pub mod platform_strategy_spec; pub mod platform_strategy_spec;
pub mod portfolio; pub mod portfolio;
pub mod risk_control;
pub mod rules; pub mod rules;
pub mod scheduler; pub mod scheduler;
pub mod strategy; pub mod strategy;
@@ -66,6 +67,7 @@ pub use platform_strategy_spec::{
StrategyRuntimeSpec, platform_expr_config_from_spec, platform_expr_config_from_value, StrategyRuntimeSpec, platform_expr_config_from_spec, platform_expr_config_from_value,
}; };
pub use portfolio::{CashReceivable, HoldingSummary, PendingCashFlow, PortfolioState, Position}; pub use portfolio::{CashReceivable, HoldingSummary, PendingCashFlow, PortfolioState, Position};
pub use risk_control::ChinaAShareRiskControl;
pub use rules::{ChinaEquityRuleHooks, EquityRuleHooks, RuleCheck}; pub use rules::{ChinaEquityRuleHooks, EquityRuleHooks, RuleCheck};
pub use scheduler::{ pub use scheduler::{
ScheduleFrequency, ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time, 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)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct StrategyExecutionSpec { pub struct StrategyExecutionSpec {
#[serde(default)]
pub compatibility_profile: Option<String>,
#[serde(default)] #[serde(default)]
pub matching_type: Option<String>, pub matching_type: Option<String>,
#[serde(default)] #[serde(default)]
@@ -370,6 +372,13 @@ pub fn platform_expr_config_from_spec(
{ {
cfg.rebalance_schedule = Some(schedule); 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(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
if let Some(days) = stock_ma_filter.short_days.filter(|value| *value > 0) { if let Some(days) = stock_ma_filter.short_days.filter(|value| *value > 0) {
cfg.stock_short_ma_days = days; cfg.stock_short_ma_days = days;
@@ -499,6 +508,13 @@ pub fn platform_expr_config_from_spec(
{ {
cfg.rebalance_schedule = Some(schedule); 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(selection) = runtime_expr.selection.as_ref() {
if let Some(expr) = selection if let Some(expr) = selection
.limit_expr .limit_expr
@@ -628,6 +644,13 @@ pub fn platform_expr_config_from_spec(
{ {
cfg.explicit_action_schedule = Some(schedule); 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 cfg.explicit_actions = trading
.actions .actions
.iter() .iter()
@@ -688,6 +711,16 @@ pub fn platform_expr_config_from_spec(
if !cfg.benchmark_symbol.trim().is_empty() { if !cfg.benchmark_symbol.trim().is_empty() {
cfg.benchmark_symbol = normalize_symbol(&cfg.benchmark_symbol, None); cfg.benchmark_symbol = normalize_symbol(&cfg.benchmark_symbol, None);
} }
if spec
.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")
{
cfg.calendar_rebalance_interval = true;
cfg.aiquant_transaction_cost = true;
}
cfg cfg
} }
@@ -744,6 +777,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> { fn parse_schedule_clock_time(raw: Option<&str>) -> Option<NaiveTime> {
let value = raw?.trim(); let value = raw?.trim();
if value.is_empty() { if value.is_empty() {
@@ -1060,6 +1103,7 @@ mod tests {
"signalSymbol": "000852.SH", "signalSymbol": "000852.SH",
"benchmark": { "instrumentId": "000852.SH" }, "benchmark": { "instrumentId": "000852.SH" },
"universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] }, "universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] },
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
"runtimeExpressions": { "runtimeExpressions": {
"prelude": "let stocknum = 8;", "prelude": "let stocknum = 8;",
"selection": { "selection": {
@@ -1094,10 +1138,32 @@ mod tests {
assert!(!cfg.rotation_enabled); assert!(!cfg.rotation_enabled);
assert!(cfg.daily_top_up_enabled); assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance); assert!(cfg.retry_empty_rebalance);
assert!(cfg.calendar_rebalance_interval);
assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.explicit_actions.len(), 1); assert_eq!(cfg.explicit_actions.len(), 1);
assert_eq!( assert_eq!(
cfg.explicit_action_stage, cfg.explicit_action_stage,
PlatformExplicitActionStage::OpenAuction PlatformExplicitActionStage::OpenAuction
); );
} }
#[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);
}
} }
+34 -2
View File
@@ -9,6 +9,7 @@ use crate::data::{DataSet, DataSetError, PriceField};
pub struct PositionLot { pub struct PositionLot {
pub acquired_date: NaiveDate, pub acquired_date: NaiveDate,
pub quantity: u32, pub quantity: u32,
pub entry_price: f64,
pub price: f64, pub price: f64,
} }
@@ -72,6 +73,7 @@ impl Position {
self.lots.push(PositionLot { self.lots.push(PositionLot {
acquired_date: date, acquired_date: date,
quantity, quantity,
entry_price: price,
price, price,
}); });
self.quantity += quantity; self.quantity += quantity;
@@ -230,13 +232,28 @@ impl Position {
} }
pub fn holding_return(&self, price: f64) -> Option<f64> { 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 None
} else { } 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) { fn recalculate_average_cost(&mut self) {
if self.quantity == 0 { if self.quantity == 0 {
self.average_cost = 0.0; self.average_cost = 0.0;
@@ -258,6 +275,7 @@ impl Position {
} }
for lot in &mut self.lots { for lot in &mut self.lots {
lot.entry_price -= dividend_per_share;
lot.price -= dividend_per_share; lot.price -= dividend_per_share;
} }
self.average_cost -= dividend_per_share; self.average_cost -= dividend_per_share;
@@ -280,6 +298,7 @@ impl Position {
.map(|lot| PositionLot { .map(|lot| PositionLot {
acquired_date: lot.acquired_date, acquired_date: lot.acquired_date,
quantity: round_half_up_u32(lot.quantity as f64 * ratio), quantity: round_half_up_u32(lot.quantity as f64 * ratio),
entry_price: lot.entry_price / ratio,
price: lot.price / ratio, price: lot.price / ratio,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -759,6 +778,7 @@ impl PortfolioState {
.map(|lot| PositionLot { .map(|lot| PositionLot {
acquired_date: lot.acquired_date, acquired_date: lot.acquired_date,
quantity: round_half_up_u32(lot.quantity as f64 * ratio), quantity: round_half_up_u32(lot.quantity as f64 * ratio),
entry_price: lot.entry_price / ratio,
price: lot.price / ratio, price: lot.price / ratio,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -855,6 +875,18 @@ 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] #[test]
fn portfolio_tracks_dividend_receivable_and_day_pnl() { fn portfolio_tracks_dividend_receivable_and_day_pnl() {
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap(); let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
+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();
if matches!(
status.as_str(),
"inactive" | "delisted" | "terminated" | "expired"
) || status.contains("delist")
{
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::data::{CandidateEligibility, DailyMarketSnapshot, PriceField};
use crate::portfolio::Position; use crate::portfolio::Position;
use crate::risk_control::ChinaAShareRiskControl;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RuleCheck { pub struct RuleCheck {
@@ -47,20 +48,6 @@ pub trait EquityRuleHooks {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct ChinaEquityRuleHooks; 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 { impl EquityRuleHooks for ChinaEquityRuleHooks {
fn can_buy( fn can_buy(
&self, &self,
@@ -69,14 +56,14 @@ impl EquityRuleHooks for ChinaEquityRuleHooks {
candidate: &CandidateEligibility, candidate: &CandidateEligibility,
price_field: PriceField, price_field: PriceField,
) -> RuleCheck { ) -> RuleCheck {
if snapshot.paused || candidate.is_paused { if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
return RuleCheck::reject("paused"); _execution_date,
} candidate,
if !candidate.allow_buy { snapshot,
return RuleCheck::reject("buy disabled by eligibility flags"); None,
} ChinaAShareRiskControl::buy_check_price(snapshot, price_field),
if Self::at_upper_limit(snapshot, price_field) { ) {
return RuleCheck::reject("open at or above upper limit"); return RuleCheck::reject(reason);
} }
RuleCheck::allow() RuleCheck::allow()
@@ -90,17 +77,15 @@ impl EquityRuleHooks for ChinaEquityRuleHooks {
position: &Position, position: &Position,
price_field: PriceField, price_field: PriceField,
) -> RuleCheck { ) -> RuleCheck {
if snapshot.paused || candidate.is_paused { if let Some(reason) = ChinaAShareRiskControl::sell_rejection_reason(
return RuleCheck::reject("paused"); execution_date,
} candidate,
if !candidate.allow_sell { snapshot,
return RuleCheck::reject("sell disabled by eligibility flags"); None,
} Some(position),
if Self::at_lower_limit(snapshot, price_field) { ChinaAShareRiskControl::sell_check_price(snapshot, price_field),
return RuleCheck::reject("open at or below lower limit"); ) {
} return RuleCheck::reject(reason);
if position.sellable_qty(execution_date) == 0 {
return RuleCheck::reject("t+1 sellable quantity is zero");
} }
RuleCheck::allow() RuleCheck::allow()
+19 -43
View File
@@ -17,6 +17,7 @@ use crate::events::{FillEvent, OrderEvent, OrderSide, OrderStatus, ProcessEvent}
use crate::futures::{FuturesAccountState, FuturesOrderIntent}; use crate::futures::{FuturesAccountState, FuturesOrderIntent};
use crate::instrument::Instrument; use crate::instrument::Instrument;
use crate::portfolio::PortfolioState; use crate::portfolio::PortfolioState;
use crate::risk_control::ChinaAShareRiskControl;
use crate::scheduler::ScheduleRule; use crate::scheduler::ScheduleRule;
use crate::universe::{DynamicMarketCapBandSelector, SelectionContext, UniverseSelector}; use crate::universe::{DynamicMarketCapBandSelector, SelectionContext, UniverseSelector};
@@ -2330,18 +2331,6 @@ impl OmniMicroCapStrategy {
true 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 { fn can_sell_position(&self, ctx: &StrategyContext<'_>, date: NaiveDate, symbol: &str) -> bool {
let Some(position) = ctx.portfolio.position(symbol) else { let Some(position) = ctx.portfolio.position(symbol) else {
return false; return false;
@@ -2355,11 +2344,15 @@ impl OmniMicroCapStrategy {
let Ok(candidate) = ctx.data.require_candidate(date, symbol) else { let Ok(candidate) = ctx.data.require_candidate(date, symbol) else {
return false; return false;
}; };
let lower_limit_check_price = market.price(PriceField::Last); ChinaAShareRiskControl::sell_rejection_reason(
!(market.paused date,
|| candidate.is_paused candidate,
|| !candidate.allow_sell market,
|| market.is_at_lower_limit_price(lower_limit_check_price)) ctx.data.instrument(symbol),
Some(position),
ChinaAShareRiskControl::sell_check_price(market, PriceField::Last),
)
.is_none()
} }
fn buy_rejection_reason( fn buy_rejection_reason(
@@ -2371,30 +2364,14 @@ impl OmniMicroCapStrategy {
let market = ctx.data.require_market(date, symbol)?; let market = ctx.data.require_market(date, symbol)?;
let candidate = ctx.data.require_candidate(date, symbol)?; let candidate = ctx.data.require_candidate(date, symbol)?;
if market.paused || candidate.is_paused { if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
return Ok(Some("paused".to_string())); date,
} candidate,
if candidate.is_st || self.special_name(ctx, symbol) { market,
return Ok(Some("st_or_special_name".to_string())); ctx.data.instrument(symbol),
} ChinaAShareRiskControl::buy_check_price(market, PriceField::Last),
if candidate.is_kcb { ) {
return Ok(Some("kcb".to_string())); return Ok(Some(reason.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 !self.truth_selection_contains(date, symbol) if !self.truth_selection_contains(date, symbol)
&& !self.stock_passes_ma_filter(ctx, date, symbol) && !self.stock_passes_ma_filter(ctx, date, symbol)
@@ -2744,8 +2721,7 @@ impl Strategy for OmniMicroCapStrategy {
let stop_hit = current_price let stop_hit = current_price
<= position.average_cost * self.config.stop_loss_ratio <= position.average_cost * self.config.stop_loss_ratio
+ self.stop_loss_tolerance(market); + self.stop_loss_tolerance(market);
let profit_hit = !market.is_at_upper_limit_price(current_price) let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
&& current_price / position.average_cost > self.config.take_profit_ratio;
let can_sell = self.can_sell_position(ctx, date, &position.symbol); let can_sell = self.can_sell_position(ctx, date, &position.symbol);
if stop_hit || profit_hit { if stop_hit || profit_hit {
let sell_reason = if stop_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("你是 OmniQuant 平台策略脚本优化器。必须输出完整、可运行的平台策略脚本,不要输出解释文本。\n");
prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n"); prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n");
prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n"); prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n");
prompt.push_str("只修改与优化目标相关的少量参数或过滤条件,保留原策略的市场、基准、信号指数和核心风控;不引入手册未列出的字段或外部平台 API 名称。\n"); prompt.push_str("优化不限制在原策略已有参数或少量扰动。只要 OmniQuant/FIDC 已支持,可以自由增加、修改、删除策略代码、参数、候选池、过滤函数、排序、仓位、止盈止损、调仓周期、指标因子和辅助函数;不引入手册未列出的字段或外部平台 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("可以使用所有已入库日频字段、指标因子和表达式函数,例如 rolling_mean/ma/vma/rolling_sum/rolling_stddev/pct_change/factor/factor_value/factors;如上一轮无交易或质量分过低,必须先扩大候选覆盖并修正不可交易过滤,再优化收益\n");
prompt.push_str("优化目标:\n"); prompt.push_str("优化目标:\n");
prompt.push_str(&format!("- {}\n\n", request.objective)); prompt.push_str(&format!("- {}\n\n", request.objective));
prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n"); prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n");
+1 -1
View File
@@ -300,7 +300,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
PriceField::Open, PriceField::Open,
), ),
BacktestConfig { BacktestConfig {
initial_cash: 11_005.0, initial_cash: 11_008.0,
benchmark_code: "000300.SH".to_string(), benchmark_code: "000300.SH".to_string(),
start_date: Some(buy_date), start_date: Some(buy_date),
end_date: Some(payable_date), end_date: Some(payable_date),
+2 -2
View File
@@ -492,7 +492,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
.iter() .iter()
.find(|holding| holding.symbol == "000002.SZ") .find(|holding| holding.symbol == "000002.SZ")
.expect("successor holding exists"); .expect("successor holding exists");
assert_eq!(successor_holding.quantity, 500); assert_eq!(successor_holding.quantity, 450);
assert!( assert!(
result result
.holdings_summary .holdings_summary
@@ -503,6 +503,6 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
event event
.note .note
.contains("successor_conversion 000001.SZ->000002.SZ") .contains("successor_conversion 000001.SZ->000002.SZ")
&& event.note.contains("cash=1000.00") && event.note.contains("cash=900.00")
})); }));
} }