Compare commits
8 Commits
v2026.5.20
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b4462f880 | |||
| 87b7b2642d | |||
| 5eee5c7c63 | |||
| c6dc1d1474 | |||
| 8c86918970 | |||
| 200d5d1f41 | |||
| 3499d4aa74 | |||
| 7dbd66b467 |
+180
-58
@@ -10,7 +10,9 @@ 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::risk_control::ChinaAShareRiskControl;
|
||||||
use crate::rules::{EquityRuleHooks, RuleCheck};
|
use crate::rules::{EquityRuleHooks, RuleCheck};
|
||||||
use crate::strategy::{
|
use crate::strategy::{
|
||||||
AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision, TargetPortfolioOrderPricing,
|
AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision, TargetPortfolioOrderPricing,
|
||||||
@@ -78,12 +80,68 @@ pub enum MatchingType {
|
|||||||
Twap,
|
Twap,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub struct DynamicSlippageConfig {
|
||||||
|
pub impact_coefficient: f64,
|
||||||
|
pub volatility_coefficient: f64,
|
||||||
|
pub max_ratio: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DynamicSlippageConfig {
|
||||||
|
pub fn new(impact_coefficient: f64, volatility_coefficient: f64, max_ratio: f64) -> Self {
|
||||||
|
Self {
|
||||||
|
impact_coefficient: impact_coefficient.max(0.0),
|
||||||
|
volatility_coefficient: volatility_coefficient.max(0.0),
|
||||||
|
max_ratio: max_ratio.max(0.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ratio(
|
||||||
|
&self,
|
||||||
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
|
raw_price: f64,
|
||||||
|
order_value: Option<f64>,
|
||||||
|
) -> f64 {
|
||||||
|
let daily_amount = (snapshot.volume as f64 * raw_price).max(0.0);
|
||||||
|
let impact_ratio = match order_value {
|
||||||
|
Some(value) if value.is_finite() && value > 0.0 && daily_amount > 0.0 => {
|
||||||
|
value / daily_amount
|
||||||
|
}
|
||||||
|
_ => 0.0,
|
||||||
|
};
|
||||||
|
let volatility_base = if snapshot.prev_close.is_finite() && snapshot.prev_close > 0.0 {
|
||||||
|
snapshot.prev_close
|
||||||
|
} else {
|
||||||
|
raw_price
|
||||||
|
};
|
||||||
|
let volatility = if snapshot.high.is_finite()
|
||||||
|
&& snapshot.low.is_finite()
|
||||||
|
&& volatility_base.is_finite()
|
||||||
|
&& volatility_base > 0.0
|
||||||
|
{
|
||||||
|
((snapshot.high - snapshot.low).abs() / volatility_base).max(0.0)
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
let ratio =
|
||||||
|
impact_ratio * self.impact_coefficient + volatility * self.volatility_coefficient;
|
||||||
|
ratio.clamp(0.0, self.max_ratio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DynamicSlippageConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new(0.5, 0.3, 0.01)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub enum SlippageModel {
|
pub enum SlippageModel {
|
||||||
None,
|
None,
|
||||||
PriceRatio(f64),
|
PriceRatio(f64),
|
||||||
TickSize(f64),
|
TickSize(f64),
|
||||||
LimitPrice,
|
LimitPrice,
|
||||||
|
Dynamic(DynamicSlippageConfig),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -233,6 +291,10 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
self.execution_price_field
|
self.execution_price_field
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn intraday_execution_start_time(&self) -> Option<NaiveTime> {
|
||||||
|
self.intraday_execution_start_time
|
||||||
|
}
|
||||||
|
|
||||||
pub fn open_order_views(&self) -> Vec<OpenOrderView> {
|
pub fn open_order_views(&self) -> Vec<OpenOrderView> {
|
||||||
self.open_orders
|
self.open_orders
|
||||||
.borrow()
|
.borrow()
|
||||||
@@ -304,6 +366,7 @@ where
|
|||||||
&self,
|
&self,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
side: OrderSide,
|
side: OrderSide,
|
||||||
|
quantity: Option<u32>,
|
||||||
) -> f64 {
|
) -> f64 {
|
||||||
let raw_price = if self.execution_price_field == PriceField::Last
|
let raw_price = if self.execution_price_field == PriceField::Last
|
||||||
&& self.intraday_execution_start_time.is_some()
|
&& self.intraday_execution_start_time.is_some()
|
||||||
@@ -317,7 +380,7 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
self.apply_slippage(snapshot, side, raw_price)
|
self.apply_slippage(snapshot, side, raw_price, quantity)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_open_auction_matching(&self) -> bool {
|
fn is_open_auction_matching(&self) -> bool {
|
||||||
@@ -329,6 +392,7 @@ where
|
|||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
side: OrderSide,
|
side: OrderSide,
|
||||||
raw_price: f64,
|
raw_price: f64,
|
||||||
|
quantity: Option<u32>,
|
||||||
) -> f64 {
|
) -> f64 {
|
||||||
if !raw_price.is_finite() || raw_price <= 0.0 {
|
if !raw_price.is_finite() || raw_price <= 0.0 {
|
||||||
return raw_price;
|
return raw_price;
|
||||||
@@ -338,6 +402,7 @@ where
|
|||||||
return self.clamp_execution_price(snapshot, side, raw_price);
|
return self.clamp_execution_price(snapshot, side, raw_price);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let order_value = quantity.and_then(|qty| (qty > 0).then_some(raw_price * qty as f64));
|
||||||
let adjusted = match self.slippage_model {
|
let adjusted = match self.slippage_model {
|
||||||
SlippageModel::None => raw_price,
|
SlippageModel::None => raw_price,
|
||||||
SlippageModel::PriceRatio(ratio) => {
|
SlippageModel::PriceRatio(ratio) => {
|
||||||
@@ -356,6 +421,13 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
SlippageModel::LimitPrice => raw_price,
|
SlippageModel::LimitPrice => raw_price,
|
||||||
|
SlippageModel::Dynamic(config) => {
|
||||||
|
let ratio = config.ratio(snapshot, raw_price, order_value);
|
||||||
|
match side {
|
||||||
|
OrderSide::Buy => raw_price * (1.0 + ratio),
|
||||||
|
OrderSide::Sell => raw_price * (1.0 - ratio),
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
self.clamp_execution_price(snapshot, side, adjusted)
|
self.clamp_execution_price(snapshot, side, adjusted)
|
||||||
@@ -392,8 +464,9 @@ where
|
|||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
side: OrderSide,
|
side: OrderSide,
|
||||||
raw_price: f64,
|
raw_price: f64,
|
||||||
|
quantity: Option<u32>,
|
||||||
) -> f64 {
|
) -> f64 {
|
||||||
self.apply_slippage(snapshot, side, raw_price)
|
self.apply_slippage(snapshot, side, raw_price, quantity)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn matching_type_for_algo_request(
|
fn matching_type_for_algo_request(
|
||||||
@@ -409,7 +482,7 @@ where
|
|||||||
|
|
||||||
fn select_quote_reference_price(
|
fn select_quote_reference_price(
|
||||||
&self,
|
&self,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
_snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
quote: &IntradayExecutionQuote,
|
quote: &IntradayExecutionQuote,
|
||||||
side: OrderSide,
|
side: OrderSide,
|
||||||
matching_type: MatchingType,
|
matching_type: MatchingType,
|
||||||
@@ -460,9 +533,8 @@ where
|
|||||||
OrderSide::Sell => quote.sell_price(),
|
OrderSide::Sell => quote.sell_price(),
|
||||||
},
|
},
|
||||||
}?;
|
}?;
|
||||||
let execution_price = self.quote_execution_price(snapshot, side, raw_price);
|
if raw_price.is_finite() && raw_price > 0.0 {
|
||||||
if execution_price.is_finite() && execution_price > 0.0 {
|
Some(raw_price)
|
||||||
Some(execution_price)
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -1850,19 +1922,27 @@ where
|
|||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
candidate: &crate::data::CandidateEligibility,
|
candidate: &crate::data::CandidateEligibility,
|
||||||
|
instrument: Option<&Instrument>,
|
||||||
) -> RuleCheck {
|
) -> 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 {
|
if !self.aiquant_rqalpha_execution_rules {
|
||||||
return self
|
return self
|
||||||
.rules
|
.rules
|
||||||
.can_buy(date, snapshot, candidate, self.execution_price_field);
|
.can_buy(date, snapshot, candidate, self.execution_price_field);
|
||||||
}
|
}
|
||||||
if snapshot.paused || candidate.is_paused {
|
|
||||||
return RuleCheck::reject("paused");
|
|
||||||
}
|
|
||||||
let check_price = self.aiquant_limit_check_price(snapshot, OrderSide::Buy);
|
|
||||||
if snapshot.is_at_upper_limit_price(check_price) {
|
|
||||||
return RuleCheck::reject("open at or above upper limit");
|
|
||||||
}
|
|
||||||
RuleCheck::allow()
|
RuleCheck::allow()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1871,8 +1951,24 @@ where
|
|||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
candidate: &crate::data::CandidateEligibility,
|
candidate: &crate::data::CandidateEligibility,
|
||||||
|
instrument: Option<&Instrument>,
|
||||||
position: &crate::portfolio::Position,
|
position: &crate::portfolio::Position,
|
||||||
) -> RuleCheck {
|
) -> 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 {
|
if !self.aiquant_rqalpha_execution_rules {
|
||||||
return self.rules.can_sell(
|
return self.rules.can_sell(
|
||||||
date,
|
date,
|
||||||
@@ -1882,16 +1978,6 @@ where
|
|||||||
self.execution_price_field,
|
self.execution_price_field,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if snapshot.paused || candidate.is_paused {
|
|
||||||
return RuleCheck::reject("paused");
|
|
||||||
}
|
|
||||||
let check_price = self.aiquant_limit_check_price(snapshot, OrderSide::Sell);
|
|
||||||
if snapshot.is_at_lower_limit_price(check_price) {
|
|
||||||
return RuleCheck::reject("open at or below lower limit");
|
|
||||||
}
|
|
||||||
if position.sellable_qty(date) == 0 {
|
|
||||||
return RuleCheck::reject("t+1 sellable quantity is zero");
|
|
||||||
}
|
|
||||||
RuleCheck::allow()
|
RuleCheck::allow()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1917,7 +2003,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.sell_rule_check(date, snapshot, candidate, position);
|
let rule =
|
||||||
|
self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
|
||||||
if !rule.allowed {
|
if !rule.allowed {
|
||||||
return current_qty;
|
return current_qty;
|
||||||
}
|
}
|
||||||
@@ -1955,7 +2042,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.buy_rule_check(date, snapshot, candidate);
|
let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
|
||||||
if !rule.allowed {
|
if !rule.allowed {
|
||||||
return current_qty;
|
return current_qty;
|
||||||
}
|
}
|
||||||
@@ -1999,7 +2086,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.sell_rule_check(date, snapshot, candidate, position);
|
let rule =
|
||||||
|
self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
|
||||||
if !rule.allowed {
|
if !rule.allowed {
|
||||||
return rule.reason;
|
return rule.reason;
|
||||||
}
|
}
|
||||||
@@ -2039,7 +2127,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.buy_rule_check(date, snapshot, candidate);
|
let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
|
||||||
if !rule.allowed {
|
if !rule.allowed {
|
||||||
return rule.reason;
|
return rule.reason;
|
||||||
}
|
}
|
||||||
@@ -2109,12 +2197,15 @@ where
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let rule = self.sell_rule_check(date, snapshot, candidate, position);
|
let rule =
|
||||||
|
self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
|
||||||
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,
|
||||||
};
|
};
|
||||||
@@ -2324,7 +2415,8 @@ where
|
|||||||
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
||||||
(fill.quantity, fill.legs)
|
(fill.quantity, fill.legs)
|
||||||
} else {
|
} else {
|
||||||
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Sell);
|
let mut execution_price =
|
||||||
|
self.snapshot_execution_price(snapshot, OrderSide::Sell, Some(fillable_qty));
|
||||||
if let Some(reason) =
|
if let Some(reason) =
|
||||||
self.execution_limit_rejection_reason(snapshot, OrderSide::Sell, execution_price)
|
self.execution_limit_rejection_reason(snapshot, OrderSide::Sell, execution_price)
|
||||||
{
|
{
|
||||||
@@ -2342,7 +2434,7 @@ where
|
|||||||
);
|
);
|
||||||
(0, Vec::new())
|
(0, Vec::new())
|
||||||
} else {
|
} else {
|
||||||
let execution_price =
|
execution_price =
|
||||||
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||||
(
|
(
|
||||||
fillable_qty,
|
fillable_qty,
|
||||||
@@ -3542,12 +3634,14 @@ where
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let rule = self.buy_rule_check(date, snapshot, candidate);
|
let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
|
||||||
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,
|
||||||
};
|
};
|
||||||
@@ -3691,7 +3785,8 @@ where
|
|||||||
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
||||||
(fill.quantity, fill.legs)
|
(fill.quantity, fill.legs)
|
||||||
} else {
|
} else {
|
||||||
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Buy);
|
let mut execution_price =
|
||||||
|
self.snapshot_execution_price(snapshot, OrderSide::Buy, Some(constrained_qty));
|
||||||
if let Some(reason) =
|
if let Some(reason) =
|
||||||
self.execution_limit_rejection_reason(snapshot, OrderSide::Buy, execution_price)
|
self.execution_limit_rejection_reason(snapshot, OrderSide::Buy, execution_price)
|
||||||
{
|
{
|
||||||
@@ -3709,7 +3804,7 @@ where
|
|||||||
);
|
);
|
||||||
(0, Vec::new())
|
(0, Vec::new())
|
||||||
} else {
|
} else {
|
||||||
let execution_price =
|
execution_price =
|
||||||
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||||
let filled_qty = self.affordable_buy_quantity(
|
let filled_qty = self.affordable_buy_quantity(
|
||||||
date,
|
date,
|
||||||
@@ -3720,6 +3815,12 @@ where
|
|||||||
self.minimum_order_quantity(data, symbol),
|
self.minimum_order_quantity(data, symbol),
|
||||||
self.order_step_size(data, symbol),
|
self.order_step_size(data, symbol),
|
||||||
);
|
);
|
||||||
|
if filled_qty > 0 {
|
||||||
|
execution_price =
|
||||||
|
self.snapshot_execution_price(snapshot, OrderSide::Buy, Some(filled_qty));
|
||||||
|
execution_price =
|
||||||
|
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||||
|
}
|
||||||
if filled_qty < constrained_qty {
|
if filled_qty < constrained_qty {
|
||||||
partial_fill_reason = merge_partial_fill_reason(
|
partial_fill_reason = merge_partial_fill_reason(
|
||||||
partial_fill_reason,
|
partial_fill_reason,
|
||||||
@@ -4514,28 +4615,11 @@ where
|
|||||||
// Approximate platform-native market-order fills with the evolving L1 book after
|
// Approximate platform-native market-order fills with the evolving L1 book after
|
||||||
// the decision time instead of trade VWAP. This keeps quantities/prices
|
// the decision time instead of trade VWAP. This keeps quantities/prices
|
||||||
// closer to the observed 10:18 execution logs.
|
// closer to the observed 10:18 execution logs.
|
||||||
let Some(quote_price) =
|
let Some(raw_quote_price) =
|
||||||
self.select_quote_reference_price(snapshot, quote, side, matching_type)
|
self.select_quote_reference_price(snapshot, quote, side, matching_type)
|
||||||
else {
|
else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, quote_price)
|
|
||||||
{
|
|
||||||
execution_block_reason.get_or_insert(reason);
|
|
||||||
execution_block_timestamp = Some(quote.timestamp);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
saw_non_blocked_execution_price = true;
|
|
||||||
if !self.price_satisfies_limit(
|
|
||||||
side,
|
|
||||||
quote_price,
|
|
||||||
limit_price,
|
|
||||||
snapshot.effective_price_tick(),
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
|
|
||||||
|
|
||||||
let remaining_qty = requested_qty.saturating_sub(filled_qty);
|
let remaining_qty = requested_qty.saturating_sub(filled_qty);
|
||||||
if remaining_qty == 0 {
|
if remaining_qty == 0 {
|
||||||
break;
|
break;
|
||||||
@@ -4571,8 +4655,35 @@ where
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut quote_price =
|
||||||
|
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
|
||||||
|
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, quote_price)
|
||||||
|
{
|
||||||
|
execution_block_reason.get_or_insert(reason);
|
||||||
|
execution_block_timestamp = Some(quote.timestamp);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
saw_non_blocked_execution_price = true;
|
||||||
|
if !self.price_satisfies_limit(
|
||||||
|
side,
|
||||||
|
quote_price,
|
||||||
|
limit_price,
|
||||||
|
snapshot.effective_price_tick(),
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(cash) = cash_limit {
|
if let Some(cash) = cash_limit {
|
||||||
while take_qty > 0 {
|
while take_qty > 0 {
|
||||||
|
quote_price =
|
||||||
|
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
|
||||||
|
if !quote_price.is_finite() || quote_price <= 0.0 {
|
||||||
|
budget_block_reason = Some("invalid execution price");
|
||||||
|
take_qty = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
quote_price =
|
||||||
|
self.execution_price_with_limit_slippage(quote_price, limit_price);
|
||||||
let candidate_gross = gross_amount + quote_price * take_qty as f64;
|
let candidate_gross = gross_amount + quote_price * take_qty as f64;
|
||||||
if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) {
|
if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) {
|
||||||
budget_block_reason = Some("value budget limit");
|
budget_block_reason = Some("value budget limit");
|
||||||
@@ -4598,6 +4709,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
quote_price =
|
||||||
|
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
|
||||||
|
quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
|
||||||
|
|
||||||
gross_amount += quote_price * take_qty as f64;
|
gross_amount += quote_price * take_qty as f64;
|
||||||
filled_qty += take_qty;
|
filled_qty += take_qty;
|
||||||
last_timestamp = Some(quote.timestamp);
|
last_timestamp = Some(quote.timestamp);
|
||||||
@@ -4721,6 +4836,8 @@ fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
|
|||||||
| "tick volume limit"
|
| "tick volume limit"
|
||||||
| "intraday quote liquidity exhausted"
|
| "intraday quote liquidity exhausted"
|
||||||
| "no execution quotes after start"
|
| "no execution quotes after start"
|
||||||
|
| "upper_limit"
|
||||||
|
| "lower_limit"
|
||||||
| "open at or above upper limit"
|
| "open at or above upper limit"
|
||||||
| "open at or below lower limit" => OrderStatus::Canceled,
|
| "open at or below lower limit" => OrderStatus::Canceled,
|
||||||
_ => OrderStatus::Rejected,
|
_ => OrderStatus::Rejected,
|
||||||
@@ -4733,6 +4850,8 @@ fn final_partial_fill_status(partial_reason: Option<&str>) -> OrderStatus {
|
|||||||
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 above upper limit")
|
||||||
|| reason.contains("open at or below lower limit") =>
|
|| reason.contains("open at or below lower limit") =>
|
||||||
{
|
{
|
||||||
@@ -4913,7 +5032,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn aiquant_rules_allow_buy_when_day_flags_block_but_last_price_is_tradable() {
|
fn aiquant_rules_keep_structured_buy_risk_while_using_aiquant_limit_price() {
|
||||||
let mut snapshot = limit_test_snapshot();
|
let mut snapshot = limit_test_snapshot();
|
||||||
snapshot.open = 11.0;
|
snapshot.open = 11.0;
|
||||||
snapshot.day_open = 11.0;
|
snapshot.day_open = 11.0;
|
||||||
@@ -4927,12 +5046,9 @@ mod tests {
|
|||||||
ChinaEquityRuleHooks,
|
ChinaEquityRuleHooks,
|
||||||
PriceField::Last,
|
PriceField::Last,
|
||||||
);
|
);
|
||||||
let default_rule = default_broker.buy_rule_check(date, &snapshot, &candidate);
|
let default_rule = default_broker.buy_rule_check(date, &snapshot, &candidate, None);
|
||||||
assert!(!default_rule.allowed);
|
assert!(!default_rule.allowed);
|
||||||
assert_eq!(
|
assert_eq!(default_rule.reason.as_deref(), Some("trade_disabled"));
|
||||||
default_rule.reason.as_deref(),
|
|
||||||
Some("buy disabled by eligibility flags")
|
|
||||||
);
|
|
||||||
|
|
||||||
let aiquant_broker = BrokerSimulator::new_with_execution_price(
|
let aiquant_broker = BrokerSimulator::new_with_execution_price(
|
||||||
ChinaAShareCostModel::default(),
|
ChinaAShareCostModel::default(),
|
||||||
@@ -4940,7 +5056,13 @@ mod tests {
|
|||||||
PriceField::Last,
|
PriceField::Last,
|
||||||
)
|
)
|
||||||
.with_aiquant_rqalpha_execution_rules(true);
|
.with_aiquant_rqalpha_execution_rules(true);
|
||||||
let aiquant_rule = aiquant_broker.buy_rule_check(date, &snapshot, &candidate);
|
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);
|
assert!(aiquant_rule.allowed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+121
-31
@@ -1,4 +1,4 @@
|
|||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
@@ -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,13 @@ 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>,
|
||||||
|
unpaused_volumes: Vec<f64>,
|
||||||
|
unpaused_volume_prefix: Vec<f64>,
|
||||||
|
unpaused_count_prefix: Vec<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SymbolPriceSeries {
|
impl SymbolPriceSeries {
|
||||||
@@ -469,11 +472,20 @@ impl SymbolPriceSeries {
|
|||||||
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
|
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
|
||||||
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
|
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
|
||||||
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
|
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
|
||||||
let paused = sorted.iter().map(|row| row.paused).collect::<Vec<_>>();
|
|
||||||
let 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 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);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
snapshots: sorted,
|
snapshots: sorted,
|
||||||
@@ -482,11 +494,13 @@ 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,
|
||||||
|
unpaused_volumes,
|
||||||
|
unpaused_volume_prefix,
|
||||||
|
unpaused_count_prefix,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -596,11 +610,12 @@ impl SymbolPriceSeries {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let end = self.end_index(date)?;
|
let end = self.end_index(date)?;
|
||||||
let values = self.trailing_unpaused_volumes(end, lookback)?;
|
let end_count = *self.unpaused_count_prefix.get(end)?;
|
||||||
if values.len() < lookback {
|
if end_count < lookback {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let sum = values.iter().sum::<f64>();
|
let start_count = end_count - lookback;
|
||||||
|
let sum = self.unpaused_volume_prefix[end_count] - self.unpaused_volume_prefix[start_count];
|
||||||
Some(sum / lookback as f64)
|
Some(sum / lookback as f64)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -620,22 +635,12 @@ impl SymbolPriceSeries {
|
|||||||
if lookback == 0 || end == 0 {
|
if lookback == 0 || end == 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let mut values = Vec::with_capacity(lookback);
|
let end_count = *self.unpaused_count_prefix.get(end)?;
|
||||||
for idx in (0..end).rev() {
|
if end_count < lookback {
|
||||||
if self.paused.get(idx).copied().unwrap_or(false) {
|
return None;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
values.push(self.snapshots[idx].volume as f64);
|
|
||||||
if values.len() == lookback {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if values.len() < lookback {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
values.reverse();
|
|
||||||
Some(values)
|
|
||||||
}
|
}
|
||||||
|
let start_count = end_count - lookback;
|
||||||
|
Some(self.unpaused_volumes[start_count..end_count].to_vec())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn end_index(&self, date: NaiveDate) -> Option<usize> {
|
fn end_index(&self, date: NaiveDate) -> Option<usize> {
|
||||||
@@ -1080,8 +1085,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 {
|
||||||
@@ -1174,6 +1183,33 @@ impl DataSet {
|
|||||||
.unwrap_or(&[])
|
.unwrap_or(&[])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
|
||||||
|
self.execution_quotes_index.keys().cloned().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_execution_quotes(&mut self, quotes: Vec<IntradayExecutionQuote>) -> usize {
|
||||||
|
let mut added = 0usize;
|
||||||
|
let mut touched = HashSet::<(NaiveDate, String)>::new();
|
||||||
|
for quote in quotes {
|
||||||
|
let key = (quote.date, quote.symbol.clone());
|
||||||
|
let rows = self.execution_quotes_index.entry(key.clone()).or_default();
|
||||||
|
if rows.iter().any(|existing| {
|
||||||
|
existing.timestamp == quote.timestamp && existing.symbol == quote.symbol
|
||||||
|
}) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rows.push(quote);
|
||||||
|
touched.insert(key);
|
||||||
|
added += 1;
|
||||||
|
}
|
||||||
|
for key in touched {
|
||||||
|
if let Some(rows) = self.execution_quotes_index.get_mut(&key) {
|
||||||
|
rows.sort_by_key(|quote| quote.timestamp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
added
|
||||||
|
}
|
||||||
|
|
||||||
pub fn order_book_depth_on(
|
pub fn order_book_depth_on(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
@@ -2114,12 +2150,10 @@ impl DataSet {
|
|||||||
self.market_moving_average(date, symbol, lookback, PriceField::Close)
|
self.market_moving_average(date, symbol, lookback, PriceField::Close)
|
||||||
}
|
}
|
||||||
"volume" | "stock_volume" => self
|
"volume" | "stock_volume" => self
|
||||||
.factor_moving_average(date, symbol, "daily_volume", lookback)
|
.market_series_by_symbol
|
||||||
.or_else(|| {
|
.get(symbol)
|
||||||
self.market_series_by_symbol
|
.and_then(|series| series.current_volume_moving_average(date, lookback))
|
||||||
.get(symbol)
|
.or_else(|| self.factor_moving_average(date, symbol, "daily_volume", lookback)),
|
||||||
.and_then(|series| series.current_volume_moving_average(date, lookback))
|
|
||||||
}),
|
|
||||||
"day_open" | "dayopen" => {
|
"day_open" | "dayopen" => {
|
||||||
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
|
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
|
||||||
}
|
}
|
||||||
@@ -3287,6 +3321,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();
|
||||||
|
|
||||||
@@ -3303,7 +3338,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 {
|
||||||
@@ -3324,6 +3366,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::*;
|
||||||
@@ -3363,6 +3410,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(&[
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use thiserror::Error;
|
|||||||
|
|
||||||
use crate::broker::{BrokerExecutionReport, BrokerSimulator, MatchingType};
|
use crate::broker::{BrokerExecutionReport, BrokerSimulator, MatchingType};
|
||||||
use crate::cost::CostModel;
|
use crate::cost::CostModel;
|
||||||
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, PriceField};
|
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, IntradayExecutionQuote, PriceField};
|
||||||
use crate::event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
|
use crate::event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
|
||||||
use crate::events::{
|
use crate::events::{
|
||||||
AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent,
|
AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent,
|
||||||
@@ -20,7 +20,10 @@ use crate::metrics::{BacktestMetrics, compute_backtest_metrics};
|
|||||||
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
|
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
|
||||||
use crate::rules::EquityRuleHooks;
|
use crate::rules::EquityRuleHooks;
|
||||||
use crate::scheduler::{ScheduleRule, ScheduleStage, Scheduler, default_stage_time};
|
use crate::scheduler::{ScheduleRule, ScheduleStage, Scheduler, default_stage_time};
|
||||||
use crate::strategy::{Strategy, StrategyContext};
|
use crate::strategy::{
|
||||||
|
OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision,
|
||||||
|
TargetPortfolioOrderPricing,
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum BacktestError {
|
pub enum BacktestError {
|
||||||
@@ -95,6 +98,18 @@ pub struct BacktestResult {
|
|||||||
pub metrics: BacktestMetrics,
|
pub metrics: BacktestMetrics,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ExecutionQuoteRequest {
|
||||||
|
pub date: NaiveDate,
|
||||||
|
pub start_time: Option<chrono::NaiveTime>,
|
||||||
|
pub end_time: Option<chrono::NaiveTime>,
|
||||||
|
pub symbols: BTreeSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type ExecutionQuoteLoader = Box<
|
||||||
|
dyn FnMut(ExecutionQuoteRequest) -> Result<Vec<IntradayExecutionQuote>, BacktestError> + Send,
|
||||||
|
>;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct AnalyzerTradeRow {
|
pub struct AnalyzerTradeRow {
|
||||||
#[serde(with = "date_format")]
|
#[serde(with = "date_format")]
|
||||||
@@ -314,6 +329,7 @@ pub struct BacktestEngine<S, C, R> {
|
|||||||
config: BacktestConfig,
|
config: BacktestConfig,
|
||||||
dividend_reinvestment: bool,
|
dividend_reinvestment: bool,
|
||||||
cash_dividends_enabled: bool,
|
cash_dividends_enabled: bool,
|
||||||
|
cash_dividend_adjusts_cost_basis: bool,
|
||||||
process_event_bus: ProcessEventBus,
|
process_event_bus: ProcessEventBus,
|
||||||
dynamic_universe: Option<BTreeSet<String>>,
|
dynamic_universe: Option<BTreeSet<String>>,
|
||||||
subscriptions: BTreeSet<String>,
|
subscriptions: BTreeSet<String>,
|
||||||
@@ -324,6 +340,7 @@ pub struct BacktestEngine<S, C, R> {
|
|||||||
futures_settlement_price_mode: String,
|
futures_settlement_price_mode: String,
|
||||||
futures_cost_model: FuturesTransactionCostModel,
|
futures_cost_model: FuturesTransactionCostModel,
|
||||||
futures_validation_config: FuturesValidationConfig,
|
futures_validation_config: FuturesValidationConfig,
|
||||||
|
execution_quote_loader: Option<ExecutionQuoteLoader>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, C, R> BacktestEngine<S, C, R> {
|
impl<S, C, R> BacktestEngine<S, C, R> {
|
||||||
@@ -340,6 +357,7 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
|||||||
config,
|
config,
|
||||||
dividend_reinvestment: false,
|
dividend_reinvestment: false,
|
||||||
cash_dividends_enabled: true,
|
cash_dividends_enabled: true,
|
||||||
|
cash_dividend_adjusts_cost_basis: true,
|
||||||
process_event_bus: ProcessEventBus::new(),
|
process_event_bus: ProcessEventBus::new(),
|
||||||
dynamic_universe: None,
|
dynamic_universe: None,
|
||||||
subscriptions: BTreeSet::new(),
|
subscriptions: BTreeSet::new(),
|
||||||
@@ -350,9 +368,24 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
|||||||
futures_settlement_price_mode: "close".to_string(),
|
futures_settlement_price_mode: "close".to_string(),
|
||||||
futures_cost_model: FuturesTransactionCostModel::default(),
|
futures_cost_model: FuturesTransactionCostModel::default(),
|
||||||
futures_validation_config: FuturesValidationConfig::default(),
|
futures_validation_config: FuturesValidationConfig::default(),
|
||||||
|
execution_quote_loader: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn into_data(self) -> DataSet {
|
||||||
|
self.data
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_execution_quote_loader<F>(mut self, loader: F) -> Self
|
||||||
|
where
|
||||||
|
F: FnMut(ExecutionQuoteRequest) -> Result<Vec<IntradayExecutionQuote>, BacktestError>
|
||||||
|
+ Send
|
||||||
|
+ 'static,
|
||||||
|
{
|
||||||
|
self.execution_quote_loader = Some(Box::new(loader));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn with_dividend_reinvestment(mut self, enabled: bool) -> Self {
|
pub fn with_dividend_reinvestment(mut self, enabled: bool) -> Self {
|
||||||
self.dividend_reinvestment = enabled;
|
self.dividend_reinvestment = enabled;
|
||||||
self
|
self
|
||||||
@@ -363,6 +396,11 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_cash_dividend_cost_basis_adjustment(mut self, enabled: bool) -> Self {
|
||||||
|
self.cash_dividend_adjusts_cost_basis = enabled;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self {
|
pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self {
|
||||||
self.futures_account = Some(account);
|
self.futures_account = Some(account);
|
||||||
self
|
self
|
||||||
@@ -467,6 +505,48 @@ where
|
|||||||
C: CostModel,
|
C: CostModel,
|
||||||
R: EquityRuleHooks,
|
R: EquityRuleHooks,
|
||||||
{
|
{
|
||||||
|
fn ensure_execution_quotes_for_decision(
|
||||||
|
&mut self,
|
||||||
|
execution_date: NaiveDate,
|
||||||
|
portfolio: &PortfolioState,
|
||||||
|
open_orders: &[OpenOrderView],
|
||||||
|
decision: &StrategyDecision,
|
||||||
|
start_time: Option<chrono::NaiveTime>,
|
||||||
|
end_time: Option<chrono::NaiveTime>,
|
||||||
|
) -> Result<(), BacktestError> {
|
||||||
|
if self.execution_quote_loader.is_none() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if self.broker.execution_price_field() != PriceField::Last
|
||||||
|
&& !decision_has_algo_execution(decision)
|
||||||
|
{
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let start_time = start_time.or_else(|| self.broker.intraday_execution_start_time());
|
||||||
|
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
|
||||||
|
symbols.retain(|symbol| {
|
||||||
|
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
|
||||||
|
});
|
||||||
|
if symbols.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let request = ExecutionQuoteRequest {
|
||||||
|
date: execution_date,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
symbols,
|
||||||
|
};
|
||||||
|
let quotes = self
|
||||||
|
.execution_quote_loader
|
||||||
|
.as_mut()
|
||||||
|
.expect("checked execution quote loader")
|
||||||
|
.as_mut()(request)?;
|
||||||
|
self.data.add_execution_quotes(quotes);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn apply_strategy_directives(
|
fn apply_strategy_directives(
|
||||||
&mut self,
|
&mut self,
|
||||||
execution_date: NaiveDate,
|
execution_date: NaiveDate,
|
||||||
@@ -1728,6 +1808,15 @@ where
|
|||||||
&mut auction_decision,
|
&mut auction_decision,
|
||||||
&mut directive_report,
|
&mut directive_report,
|
||||||
)?;
|
)?;
|
||||||
|
let pre_auction_execution_orders = self.open_order_views();
|
||||||
|
self.ensure_execution_quotes_for_decision(
|
||||||
|
execution_date,
|
||||||
|
&portfolio,
|
||||||
|
&pre_auction_execution_orders,
|
||||||
|
&auction_decision,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
let mut report = self.broker.execute(
|
let mut report = self.broker.execute(
|
||||||
execution_date,
|
execution_date,
|
||||||
&mut portfolio,
|
&mut portfolio,
|
||||||
@@ -1932,6 +2021,15 @@ where
|
|||||||
&mut directive_report,
|
&mut directive_report,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
let pre_intraday_execution_orders = self.open_order_views();
|
||||||
|
self.ensure_execution_quotes_for_decision(
|
||||||
|
execution_date,
|
||||||
|
&portfolio,
|
||||||
|
&pre_intraday_execution_orders,
|
||||||
|
&decision,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
let mut intraday_report =
|
let mut intraday_report =
|
||||||
self.broker
|
self.broker
|
||||||
.execute(execution_date, &mut portfolio, &self.data, &decision)?;
|
.execute(execution_date, &mut portfolio, &self.data, &decision)?;
|
||||||
@@ -2089,6 +2187,15 @@ where
|
|||||||
&mut tick_decision,
|
&mut tick_decision,
|
||||||
&mut directive_report,
|
&mut directive_report,
|
||||||
)?;
|
)?;
|
||||||
|
let pre_tick_execution_orders = self.open_order_views();
|
||||||
|
self.ensure_execution_quotes_for_decision(
|
||||||
|
execution_date,
|
||||||
|
&portfolio,
|
||||||
|
&pre_tick_execution_orders,
|
||||||
|
&tick_decision,
|
||||||
|
Some(tick_time),
|
||||||
|
Some(tick_time),
|
||||||
|
)?;
|
||||||
let mut tick_report = self.broker.execute_between(
|
let mut tick_report = self.broker.execute_between(
|
||||||
execution_date,
|
execution_date,
|
||||||
&mut portfolio,
|
&mut portfolio,
|
||||||
@@ -2534,7 +2641,11 @@ where
|
|||||||
let position = portfolio
|
let position = portfolio
|
||||||
.position_mut_if_exists(&action.symbol)
|
.position_mut_if_exists(&action.symbol)
|
||||||
.expect("position exists for dividend action");
|
.expect("position exists for dividend action");
|
||||||
let cash_delta = position.apply_cash_dividend(action.share_cash);
|
let cash_delta = if self.cash_dividend_adjusts_cost_basis {
|
||||||
|
position.apply_cash_dividend(action.share_cash)
|
||||||
|
} else {
|
||||||
|
position.apply_cash_dividend_preserve_cost_basis(action.share_cash)
|
||||||
|
};
|
||||||
(cash_delta, position.quantity, position.average_cost)
|
(cash_delta, position.quantity, position.average_cost)
|
||||||
};
|
};
|
||||||
if cash_delta.abs() > f64::EPSILON {
|
if cash_delta.abs() > f64::EPSILON {
|
||||||
@@ -3077,6 +3188,93 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn has_execution_quote_in_window(
|
||||||
|
data: &DataSet,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
start_time: Option<chrono::NaiveTime>,
|
||||||
|
end_time: Option<chrono::NaiveTime>,
|
||||||
|
) -> bool {
|
||||||
|
let start_cursor = start_time.map(|time| date.and_time(time));
|
||||||
|
let end_cursor = end_time.map(|time| date.and_time(time));
|
||||||
|
data.execution_quotes_on(date, symbol).iter().any(|quote| {
|
||||||
|
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
|
||||||
|
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
|
||||||
|
decision.order_intents.iter().any(|intent| {
|
||||||
|
matches!(
|
||||||
|
intent,
|
||||||
|
OrderIntent::AlgoValue { .. }
|
||||||
|
| OrderIntent::AlgoPercent { .. }
|
||||||
|
| OrderIntent::TargetPortfolioSmart {
|
||||||
|
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
|
||||||
|
..
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execution_quote_symbols_for_decision(
|
||||||
|
decision: &StrategyDecision,
|
||||||
|
portfolio: &PortfolioState,
|
||||||
|
open_orders: &[OpenOrderView],
|
||||||
|
) -> BTreeSet<String> {
|
||||||
|
let mut symbols = BTreeSet::new();
|
||||||
|
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
|
||||||
|
if decision.rebalance {
|
||||||
|
symbols.extend(portfolio.positions().keys().cloned());
|
||||||
|
symbols.extend(decision.target_weights.keys().cloned());
|
||||||
|
}
|
||||||
|
if !decision.exit_symbols.is_empty() {
|
||||||
|
symbols.extend(decision.exit_symbols.iter().cloned());
|
||||||
|
}
|
||||||
|
|
||||||
|
for intent in &decision.order_intents {
|
||||||
|
match intent {
|
||||||
|
OrderIntent::Shares { symbol, .. }
|
||||||
|
| OrderIntent::LimitShares { symbol, .. }
|
||||||
|
| OrderIntent::Lots { symbol, .. }
|
||||||
|
| OrderIntent::LimitLots { symbol, .. }
|
||||||
|
| OrderIntent::TargetShares { symbol, .. }
|
||||||
|
| OrderIntent::LimitTargetShares { symbol, .. }
|
||||||
|
| OrderIntent::TargetValue { symbol, .. }
|
||||||
|
| OrderIntent::LimitTargetValue { symbol, .. }
|
||||||
|
| OrderIntent::Value { symbol, .. }
|
||||||
|
| OrderIntent::LimitValue { symbol, .. }
|
||||||
|
| OrderIntent::Percent { symbol, .. }
|
||||||
|
| OrderIntent::LimitPercent { symbol, .. }
|
||||||
|
| OrderIntent::TargetPercent { symbol, .. }
|
||||||
|
| OrderIntent::LimitTargetPercent { symbol, .. }
|
||||||
|
| OrderIntent::AlgoValue { symbol, .. }
|
||||||
|
| OrderIntent::AlgoPercent { symbol, .. }
|
||||||
|
| OrderIntent::CancelSymbol { symbol, .. } => {
|
||||||
|
symbols.insert(symbol.clone());
|
||||||
|
}
|
||||||
|
OrderIntent::TargetPortfolioSmart { target_weights, .. } => {
|
||||||
|
symbols.extend(portfolio.positions().keys().cloned());
|
||||||
|
symbols.extend(target_weights.keys().cloned());
|
||||||
|
}
|
||||||
|
OrderIntent::CancelAll { .. } => {
|
||||||
|
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
|
||||||
|
}
|
||||||
|
OrderIntent::UpdateUniverse { .. }
|
||||||
|
| OrderIntent::Subscribe { .. }
|
||||||
|
| OrderIntent::Unsubscribe { .. }
|
||||||
|
| OrderIntent::DepositWithdraw { .. }
|
||||||
|
| OrderIntent::FinanceRepay { .. }
|
||||||
|
| OrderIntent::SetManagementFeeRate { .. }
|
||||||
|
| OrderIntent::CancelOrder { .. }
|
||||||
|
| OrderIntent::Futures { .. } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
symbols.retain(|symbol| !symbol.trim().is_empty());
|
||||||
|
symbols
|
||||||
|
}
|
||||||
|
|
||||||
fn collect_scheduled_decisions<S: Strategy>(
|
fn collect_scheduled_decisions<S: Strategy>(
|
||||||
strategy: &mut S,
|
strategy: &mut S,
|
||||||
scheduler: &Scheduler<'_>,
|
scheduler: &Scheduler<'_>,
|
||||||
|
|||||||
@@ -12,13 +12,16 @@ 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;
|
||||||
pub mod strategy_ai;
|
pub mod strategy_ai;
|
||||||
pub mod universe;
|
pub mod universe;
|
||||||
|
|
||||||
pub use broker::{BrokerExecutionReport, BrokerSimulator, MatchingType, SlippageModel};
|
pub use broker::{
|
||||||
|
BrokerExecutionReport, BrokerSimulator, DynamicSlippageConfig, MatchingType, SlippageModel,
|
||||||
|
};
|
||||||
pub use calendar::TradingCalendar;
|
pub use calendar::TradingCalendar;
|
||||||
pub use cost::{ChinaAShareCostModel, CostModel, TradingCost};
|
pub use cost::{ChinaAShareCostModel, CostModel, TradingCost};
|
||||||
pub use data::{
|
pub use data::{
|
||||||
@@ -31,7 +34,7 @@ pub use data::{
|
|||||||
pub use engine::{
|
pub use engine::{
|
||||||
AnalyzerMonthlyReturnRow, AnalyzerPositionRow, AnalyzerReport, AnalyzerRiskSummary,
|
AnalyzerMonthlyReturnRow, AnalyzerPositionRow, AnalyzerReport, AnalyzerRiskSummary,
|
||||||
AnalyzerTradeRow, BacktestConfig, BacktestDayProgress, BacktestEngine, BacktestError,
|
AnalyzerTradeRow, BacktestConfig, BacktestDayProgress, BacktestEngine, BacktestError,
|
||||||
BacktestResult, DailyEquityPoint, FuturesValidationConfig,
|
BacktestResult, DailyEquityPoint, ExecutionQuoteRequest, FuturesValidationConfig,
|
||||||
};
|
};
|
||||||
pub use event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
|
pub use event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
|
||||||
pub use events::{
|
pub use events::{
|
||||||
@@ -48,8 +51,8 @@ pub use metrics::{BacktestMetrics, compute_backtest_metrics};
|
|||||||
pub use platform_expr_strategy::{
|
pub use platform_expr_strategy::{
|
||||||
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
|
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
|
||||||
PlatformExplicitOrderKind, PlatformExprStrategy, PlatformExprStrategyConfig,
|
PlatformExplicitOrderKind, PlatformExprStrategy, PlatformExprStrategyConfig,
|
||||||
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformSelectionQuotePlan,
|
||||||
PlatformUniverseActionKind,
|
PlatformTradeAction, PlatformUniverseActionKind,
|
||||||
};
|
};
|
||||||
pub use platform_runtime_schema::{
|
pub use platform_runtime_schema::{
|
||||||
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
|
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
|
||||||
@@ -66,6 +69,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
@@ -61,6 +61,12 @@ pub struct StrategyExecutionSpec {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub slippage_value: Option<f64>,
|
pub slippage_value: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub slippage_impact_coefficient: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub slippage_volatility_coefficient: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub slippage_max_value: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
pub strict_value_budget: Option<bool>,
|
pub strict_value_budget: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +102,12 @@ pub struct StrategyEngineConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub slippage_value: Option<f64>,
|
pub slippage_value: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub slippage_impact_coefficient: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub slippage_volatility_coefficient: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub slippage_max_value: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
pub strict_value_budget: Option<bool>,
|
pub strict_value_budget: Option<bool>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub dividend_reinvestment: Option<bool>,
|
pub dividend_reinvestment: Option<bool>,
|
||||||
@@ -718,7 +730,6 @@ pub fn platform_expr_config_from_spec(
|
|||||||
.map(|value| value.trim().to_ascii_lowercase())
|
.map(|value| value.trim().to_ascii_lowercase())
|
||||||
.is_some_and(|value| value == "aiquant_rqalpha" || value == "aiquant")
|
.is_some_and(|value| value == "aiquant_rqalpha" || value == "aiquant")
|
||||||
{
|
{
|
||||||
cfg.calendar_rebalance_interval = true;
|
|
||||||
cfg.aiquant_transaction_cost = true;
|
cfg.aiquant_transaction_cost = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1138,7 +1149,7 @@ 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.calendar_rebalance_interval);
|
||||||
assert!(cfg.aiquant_transaction_cost);
|
assert!(cfg.aiquant_transaction_cost);
|
||||||
assert_eq!(cfg.explicit_actions.len(), 1);
|
assert_eq!(cfg.explicit_actions.len(), 1);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1163,7 +1174,7 @@ mod tests {
|
|||||||
cfg.intraday_execution_time,
|
cfg.intraday_execution_time,
|
||||||
Some(NaiveTime::from_hms_opt(9, 33, 0).unwrap())
|
Some(NaiveTime::from_hms_opt(9, 33, 0).unwrap())
|
||||||
);
|
);
|
||||||
assert!(cfg.calendar_rebalance_interval);
|
assert!(!cfg.calendar_rebalance_interval);
|
||||||
assert!(cfg.aiquant_transaction_cost);
|
assert!(cfg.aiquant_transaction_cost);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -270,15 +270,31 @@ impl Position {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn apply_cash_dividend(&mut self, dividend_per_share: f64) -> f64 {
|
pub fn apply_cash_dividend(&mut self, dividend_per_share: f64) -> f64 {
|
||||||
|
self.apply_cash_dividend_internal(dividend_per_share, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_cash_dividend_preserve_cost_basis(&mut self, dividend_per_share: f64) -> f64 {
|
||||||
|
self.apply_cash_dividend_internal(dividend_per_share, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_cash_dividend_internal(
|
||||||
|
&mut self,
|
||||||
|
dividend_per_share: f64,
|
||||||
|
adjust_cost_basis: bool,
|
||||||
|
) -> f64 {
|
||||||
if self.quantity == 0 || !dividend_per_share.is_finite() || dividend_per_share == 0.0 {
|
if self.quantity == 0 || !dividend_per_share.is_finite() || dividend_per_share == 0.0 {
|
||||||
return 0.0;
|
return 0.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
for lot in &mut self.lots {
|
for lot in &mut self.lots {
|
||||||
lot.entry_price -= dividend_per_share;
|
lot.entry_price -= dividend_per_share;
|
||||||
lot.price -= dividend_per_share;
|
if adjust_cost_basis {
|
||||||
|
lot.price -= dividend_per_share;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if adjust_cost_basis {
|
||||||
|
self.average_cost -= dividend_per_share;
|
||||||
}
|
}
|
||||||
self.average_cost -= dividend_per_share;
|
|
||||||
self.last_price -= dividend_per_share;
|
self.last_price -= dividend_per_share;
|
||||||
let cash_delta = self.quantity as f64 * dividend_per_share;
|
let cash_delta = self.quantity as f64 * dividend_per_share;
|
||||||
self.day_dividend_cash += cash_delta;
|
self.day_dividend_cash += cash_delta;
|
||||||
@@ -887,6 +903,23 @@ mod tests {
|
|||||||
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
|
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cash_dividend_can_preserve_avg_cost_for_aiquant_compatibility() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||||
|
let mut position = Position::new("603102.SH");
|
||||||
|
position.buy(date, 1000, 46.45);
|
||||||
|
position.record_buy_trade_cost(1000, 37.16);
|
||||||
|
|
||||||
|
let cost_before = position.average_cost;
|
||||||
|
let entry_before = position.average_entry_price().unwrap();
|
||||||
|
let cash = position.apply_cash_dividend_preserve_cost_basis(0.6);
|
||||||
|
|
||||||
|
assert!((cash - 600.0).abs() < 1e-12);
|
||||||
|
assert!((position.average_cost - cost_before).abs() < 1e-12);
|
||||||
|
assert!((position.average_entry_price().unwrap() - (entry_before - 0.6)).abs() < 1e-12);
|
||||||
|
assert!((position.last_price - 45.85).abs() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn portfolio_tracks_dividend_receivable_and_day_pnl() {
|
fn portfolio_tracks_dividend_receivable_and_day_pnl() {
|
||||||
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||||
|
|||||||
@@ -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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
|||||||
@@ -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,25 +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.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)
|
||||||
|
|||||||
@@ -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),
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
use chrono::{NaiveDate, NaiveTime};
|
use chrono::{NaiveDate, NaiveTime};
|
||||||
use fidc_core::{
|
use fidc_core::{
|
||||||
AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel,
|
AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel,
|
||||||
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, Instrument,
|
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, DynamicSlippageConfig,
|
||||||
IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState, PriceField,
|
Instrument, IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState,
|
||||||
ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
|
PriceField, ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
|
||||||
};
|
};
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
@@ -1485,6 +1485,110 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
|
|||||||
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
|
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_applies_dynamic_slippage_on_snapshot_fills() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
name: "Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: Some("2024-01-10 10:18:00".to_string()),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.1,
|
||||||
|
low: 9.9,
|
||||||
|
close: 10.0,
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 100_000,
|
||||||
|
tick_volume: 100_000,
|
||||||
|
bid1_volume: 80_000,
|
||||||
|
ask1_volume: 80_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 11.0,
|
||||||
|
lower_limit: 9.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
market_cap_bn: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000300.SH".to_string(),
|
||||||
|
open: 100.0,
|
||||||
|
close: 100.0,
|
||||||
|
prev_close: 99.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Open,
|
||||||
|
)
|
||||||
|
.with_slippage_model(SlippageModel::Dynamic(DynamicSlippageConfig::new(
|
||||||
|
0.5, 0.3, 0.1,
|
||||||
|
)));
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::Value {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
value: 100_000.0,
|
||||||
|
reason: "dynamic_slippage".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
let expected_ratio = ((10.0 * report.fill_events[0].quantity as f64) / (100_000.0 * 10.0))
|
||||||
|
* 0.5
|
||||||
|
+ ((10.1 - 9.9) / 10.0) * 0.3;
|
||||||
|
assert!((report.fill_events[0].price - 10.0 * (1.0 + expected_ratio)).abs() < 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user