Compare commits
10 Commits
v2026.05.0
...
v2026.5.18
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f383c1a88 | ||
|
|
4577657c90 | ||
|
|
94662b6e75 | ||
|
|
616cab0e7e | ||
|
|
db72f6f515 | ||
|
|
2165831708 | ||
|
|
1a402f2048 | ||
|
|
bbe60537ff | ||
|
|
3b033fd294 | ||
|
|
d9de9715ef |
@@ -100,6 +100,57 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||||
engine.run()?
|
engine.run()?
|
||||||
}
|
}
|
||||||
|
"aiquant-v104" => {
|
||||||
|
let mut strategy_cfg = OmniMicroCapConfig::aiquant_v104();
|
||||||
|
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||||
|
if !signal_symbol.trim().is_empty() {
|
||||||
|
strategy_cfg.benchmark_signal_symbol = signal_symbol;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(date) = debug_date {
|
||||||
|
let eligible = data.eligible_universe_on(date);
|
||||||
|
eprintln!(
|
||||||
|
"DEBUG eligible_universe_on {} count={}",
|
||||||
|
date,
|
||||||
|
eligible.len()
|
||||||
|
);
|
||||||
|
for row in eligible.iter().take(20) {
|
||||||
|
eprintln!(" {} {:.6}", row.symbol, row.market_cap_bn);
|
||||||
|
}
|
||||||
|
let mut debug_strategy = OmniMicroCapStrategy::new(strategy_cfg.clone());
|
||||||
|
let debug_subscriptions = BTreeSet::new();
|
||||||
|
let decision = debug_strategy.on_day(&StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 1,
|
||||||
|
data: &data,
|
||||||
|
portfolio: &PortfolioState::new(20_000.0),
|
||||||
|
futures_account: None,
|
||||||
|
open_orders: &[],
|
||||||
|
dynamic_universe: None,
|
||||||
|
subscriptions: &debug_subscriptions,
|
||||||
|
process_events: &[],
|
||||||
|
active_process_event: None,
|
||||||
|
active_datetime: None,
|
||||||
|
order_events: &[],
|
||||||
|
fills: &[],
|
||||||
|
})?;
|
||||||
|
eprintln!("DEBUG notes={:?}", decision.notes);
|
||||||
|
eprintln!("DEBUG diagnostics={:?}", decision.diagnostics);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
config.decision_lag_trading_days = decision_lag.unwrap_or(1);
|
||||||
|
config.execution_price_field = execution_price.unwrap_or(PriceField::Close);
|
||||||
|
config.initial_cash = initial_cash.unwrap_or(20_000.0);
|
||||||
|
let strategy = OmniMicroCapStrategy::new(strategy_cfg);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
config.execution_price_field,
|
||||||
|
);
|
||||||
|
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||||
|
engine.run()?
|
||||||
|
}
|
||||||
_ => {
|
_ => {
|
||||||
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
|
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
|
||||||
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||||
|
|||||||
@@ -111,6 +111,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,
|
||||||
|
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>>,
|
||||||
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
||||||
@@ -132,6 +133,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,
|
||||||
|
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),
|
||||||
runtime_intraday_end_time: Cell::new(None),
|
runtime_intraday_end_time: Cell::new(None),
|
||||||
@@ -157,6 +159,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,
|
||||||
|
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),
|
||||||
runtime_intraday_end_time: Cell::new(None),
|
runtime_intraday_end_time: Cell::new(None),
|
||||||
@@ -185,6 +188,15 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
self
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn same_day_buy_close_mark_at_fill(&self) -> bool {
|
||||||
|
self.same_day_buy_close_mark_at_fill
|
||||||
|
}
|
||||||
|
|
||||||
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
|
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
|
||||||
self.volume_percent = volume_percent;
|
self.volume_percent = volume_percent;
|
||||||
self
|
self
|
||||||
@@ -252,6 +264,34 @@ where
|
|||||||
snapshot.price(self.execution_price_field)
|
snapshot.price(self.execution_price_field)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn value_buy_sizing_price(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
data: &DataSet,
|
||||||
|
symbol: &str,
|
||||||
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
|
) -> f64 {
|
||||||
|
let start_cursor = self
|
||||||
|
.runtime_intraday_start_time
|
||||||
|
.get()
|
||||||
|
.or(self.intraday_execution_start_time)
|
||||||
|
.map(|start_time| date.and_time(start_time));
|
||||||
|
data.execution_quotes_on(date, symbol)
|
||||||
|
.iter()
|
||||||
|
.filter(|quote| {
|
||||||
|
start_cursor
|
||||||
|
.map(|cursor| quote.timestamp >= cursor)
|
||||||
|
.unwrap_or(true)
|
||||||
|
})
|
||||||
|
.next()
|
||||||
|
.and_then(|quote| match self.execution_price_field {
|
||||||
|
PriceField::Last => (quote.last_price.is_finite() && quote.last_price > 0.0)
|
||||||
|
.then_some(quote.last_price),
|
||||||
|
_ => quote.buy_price(),
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| self.sizing_price(snapshot))
|
||||||
|
}
|
||||||
|
|
||||||
fn snapshot_execution_price(
|
fn snapshot_execution_price(
|
||||||
&self,
|
&self,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
@@ -2237,7 +2277,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,
|
||||||
@@ -2917,9 +2962,11 @@ where
|
|||||||
let round_lot = self.round_lot(data, symbol);
|
let round_lot = self.round_lot(data, symbol);
|
||||||
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
||||||
let order_step_size = self.order_step_size(data, symbol);
|
let order_step_size = self.order_step_size(data, symbol);
|
||||||
let price = self.sizing_price(snapshot);
|
let price = self.value_buy_sizing_price(date, data, symbol, snapshot);
|
||||||
let snapshot_requested_qty = self.round_buy_quantity(
|
let snapshot_requested_qty = self.value_buy_quantity(
|
||||||
((value.abs()) / price).floor() as u32,
|
date,
|
||||||
|
value.abs(),
|
||||||
|
price,
|
||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
);
|
);
|
||||||
@@ -3012,8 +3059,10 @@ where
|
|||||||
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
||||||
let order_step_size = self.order_step_size(data, symbol);
|
let order_step_size = self.order_step_size(data, symbol);
|
||||||
let price = self.sizing_price(snapshot);
|
let price = self.sizing_price(snapshot);
|
||||||
let snapshot_requested_qty = self.round_buy_quantity(
|
let snapshot_requested_qty = self.value_buy_quantity(
|
||||||
((value.abs()) / price).floor() as u32,
|
date,
|
||||||
|
value.abs(),
|
||||||
|
price,
|
||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
);
|
);
|
||||||
@@ -3178,8 +3227,10 @@ where
|
|||||||
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
||||||
let order_step_size = self.order_step_size(data, symbol);
|
let order_step_size = self.order_step_size(data, symbol);
|
||||||
let price = self.sizing_price(snapshot);
|
let price = self.sizing_price(snapshot);
|
||||||
let snapshot_requested_qty = self.round_buy_quantity(
|
let snapshot_requested_qty = self.value_buy_quantity(
|
||||||
(value.abs() / price).floor() as u32,
|
date,
|
||||||
|
value.abs(),
|
||||||
|
price,
|
||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
);
|
);
|
||||||
@@ -3396,14 +3447,16 @@ where
|
|||||||
requested_qty
|
requested_qty
|
||||||
}
|
}
|
||||||
|
|
||||||
fn value_budget_gross_limit(&self, value_budget: Option<f64>) -> Option<f64> {
|
fn value_buy_gross_limit(
|
||||||
value_budget.map(|budget| {
|
&self,
|
||||||
if self.strict_value_budget {
|
value_budget: Option<f64>,
|
||||||
budget
|
requested_qty: u32,
|
||||||
} else {
|
reference_price: f64,
|
||||||
budget + 400.0
|
) -> Option<f64> {
|
||||||
}
|
if !self.strict_value_budget {
|
||||||
})
|
return None;
|
||||||
|
}
|
||||||
|
value_budget.map(|budget| budget.max(reference_price * requested_qty as f64))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_buy(
|
fn process_buy(
|
||||||
@@ -3562,6 +3615,8 @@ where
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let value_gross_limit =
|
||||||
|
self.value_buy_gross_limit(value_budget, constrained_qty, self.sizing_price(snapshot));
|
||||||
|
|
||||||
let fill = self.resolve_execution_fill(
|
let fill = self.resolve_execution_fill(
|
||||||
date,
|
date,
|
||||||
@@ -3577,7 +3632,7 @@ where
|
|||||||
execution_cursors,
|
execution_cursors,
|
||||||
None,
|
None,
|
||||||
Some(portfolio.cash()),
|
Some(portfolio.cash()),
|
||||||
self.value_budget_gross_limit(value_budget),
|
value_gross_limit,
|
||||||
algo_request,
|
algo_request,
|
||||||
limit_price,
|
limit_price,
|
||||||
);
|
);
|
||||||
@@ -3591,7 +3646,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,
|
||||||
@@ -3608,7 +3668,7 @@ where
|
|||||||
let filled_qty = self.affordable_buy_quantity(
|
let filled_qty = self.affordable_buy_quantity(
|
||||||
date,
|
date,
|
||||||
portfolio.cash(),
|
portfolio.cash(),
|
||||||
self.value_budget_gross_limit(value_budget),
|
value_gross_limit,
|
||||||
execution_price,
|
execution_price,
|
||||||
constrained_qty,
|
constrained_qty,
|
||||||
self.minimum_order_quantity(data, symbol),
|
self.minimum_order_quantity(data, symbol),
|
||||||
@@ -3619,7 +3679,7 @@ where
|
|||||||
partial_fill_reason,
|
partial_fill_reason,
|
||||||
self.buy_reduction_reason(
|
self.buy_reduction_reason(
|
||||||
portfolio.cash(),
|
portfolio.cash(),
|
||||||
self.value_budget_gross_limit(value_budget),
|
value_gross_limit,
|
||||||
execution_price,
|
execution_price,
|
||||||
constrained_qty,
|
constrained_qty,
|
||||||
filled_qty,
|
filled_qty,
|
||||||
@@ -3720,7 +3780,7 @@ where
|
|||||||
.position_mut(symbol)
|
.position_mut(symbol)
|
||||||
.buy(date, leg.quantity, leg.price);
|
.buy(date, leg.quantity, leg.price);
|
||||||
if let Some(position) = portfolio.position_mut_if_exists(symbol) {
|
if let Some(position) = portfolio.position_mut_if_exists(symbol) {
|
||||||
position.record_trade_cost(cost.total());
|
position.record_buy_trade_cost(leg.quantity, cost.total());
|
||||||
}
|
}
|
||||||
|
|
||||||
report.fill_events.push(FillEvent {
|
report.fill_events.push(FillEvent {
|
||||||
@@ -4054,6 +4114,31 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn value_buy_quantity(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
value_budget: f64,
|
||||||
|
price: f64,
|
||||||
|
minimum_order_quantity: u32,
|
||||||
|
order_step_size: u32,
|
||||||
|
) -> u32 {
|
||||||
|
if !value_budget.is_finite() || value_budget <= 0.0 || !price.is_finite() || price <= 0.0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let minimum = minimum_order_quantity.max(1);
|
||||||
|
let raw_quantity = (value_budget / price).floor() as u32;
|
||||||
|
let mut quantity =
|
||||||
|
self.round_buy_quantity(raw_quantity, minimum_order_quantity, order_step_size);
|
||||||
|
while quantity >= minimum {
|
||||||
|
if self.estimated_buy_cash_out(date, price, quantity) <= value_budget + 1e-6 {
|
||||||
|
return quantity;
|
||||||
|
}
|
||||||
|
quantity =
|
||||||
|
self.decrement_order_quantity(quantity, minimum_order_quantity, order_step_size);
|
||||||
|
}
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
fn decrement_order_quantity(
|
fn decrement_order_quantity(
|
||||||
&self,
|
&self,
|
||||||
quantity: u32,
|
quantity: u32,
|
||||||
@@ -4200,6 +4285,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,
|
||||||
@@ -4213,7 +4318,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")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4334,13 +4442,16 @@ where
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let quote_quantity_limited =
|
||||||
|
self.quote_quantity_limited_for_window(matching_type, start_cursor, end_cursor);
|
||||||
let lot = round_lot.max(1);
|
let lot = round_lot.max(1);
|
||||||
let eligible_quotes: Vec<&IntradayExecutionQuote> = quotes
|
let eligible_quotes: Vec<&IntradayExecutionQuote> = quotes
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|quote| {
|
.filter(|quote| {
|
||||||
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
|
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
|
||||||
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
|
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
|
||||||
&& quote.volume_delta != 0
|
&& (!quote_quantity_limited
|
||||||
|
|| self.quote_has_executable_liquidity(quote, side, matching_type))
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let mut filled_qty = 0_u32;
|
let mut filled_qty = 0_u32;
|
||||||
@@ -4348,6 +4459,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() {
|
||||||
@@ -4359,6 +4473,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,
|
||||||
@@ -4368,21 +4489,26 @@ where
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
|
let quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
|
||||||
let top_level_liquidity = match side {
|
|
||||||
OrderSide::Buy => quote.ask1_volume,
|
|
||||||
OrderSide::Sell => quote.bid1_volume,
|
|
||||||
};
|
|
||||||
let available_qty = top_level_liquidity
|
|
||||||
.saturating_mul(lot as u64)
|
|
||||||
.min(u32::MAX as u64) as u32;
|
|
||||||
if available_qty == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
let available_qty = if quote_quantity_limited {
|
||||||
|
let top_level_liquidity = match side {
|
||||||
|
OrderSide::Buy => quote.ask1_volume,
|
||||||
|
OrderSide::Sell => quote.bid1_volume,
|
||||||
|
};
|
||||||
|
top_level_liquidity
|
||||||
|
.saturating_mul(lot as u64)
|
||||||
|
.min(u32::MAX as u64) as u32
|
||||||
|
} else {
|
||||||
|
remaining_qty
|
||||||
|
};
|
||||||
|
if available_qty == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
let mut take_qty = if matching_type == MatchingType::Twap {
|
let mut take_qty = if matching_type == MatchingType::Twap {
|
||||||
let remaining_quotes = (eligible_quotes.len() - quote_index) as u32;
|
let remaining_quotes = (eligible_quotes.len() - quote_index) as u32;
|
||||||
let scheduled_qty =
|
let scheduled_qty =
|
||||||
@@ -4440,6 +4566,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4466,6 +4604,45 @@ where
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn quote_has_executable_liquidity(
|
||||||
|
&self,
|
||||||
|
quote: &IntradayExecutionQuote,
|
||||||
|
side: OrderSide,
|
||||||
|
matching_type: MatchingType,
|
||||||
|
) -> bool {
|
||||||
|
if quote.volume_delta != 0 {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if matches!(matching_type, MatchingType::Vwap | MatchingType::Twap) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match side {
|
||||||
|
OrderSide::Buy => quote.ask1_volume > 0,
|
||||||
|
OrderSide::Sell => quote.bid1_volume > 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote_quantity_limited(&self, matching_type: MatchingType) -> bool {
|
||||||
|
self.volume_limit || self.liquidity_limit || matching_type != MatchingType::NextTickLast
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote_quantity_limited_for_window(
|
||||||
|
&self,
|
||||||
|
matching_type: MatchingType,
|
||||||
|
start_cursor: Option<NaiveDateTime>,
|
||||||
|
end_cursor: Option<NaiveDateTime>,
|
||||||
|
) -> bool {
|
||||||
|
if matching_type == MatchingType::Twap
|
||||||
|
&& !self.volume_limit
|
||||||
|
&& !self.liquidity_limit
|
||||||
|
&& start_cursor.is_some()
|
||||||
|
&& start_cursor == end_cursor
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.quote_quantity_limited(matching_type)
|
||||||
|
}
|
||||||
|
|
||||||
fn uses_serial_execution_cursor(&self, reason: &str) -> bool {
|
fn uses_serial_execution_cursor(&self, reason: &str) -> bool {
|
||||||
let _ = reason;
|
let _ = reason;
|
||||||
false
|
false
|
||||||
@@ -4497,7 +4674,9 @@ 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"
|
||||||
|
| "open at or above upper limit"
|
||||||
|
| "open at or below lower limit" => OrderStatus::Canceled,
|
||||||
_ => OrderStatus::Rejected,
|
_ => OrderStatus::Rejected,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4507,7 +4686,9 @@ 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("open at or above upper limit")
|
||||||
|
|| reason.contains("open at or below lower limit") =>
|
||||||
{
|
{
|
||||||
OrderStatus::Canceled
|
OrderStatus::Canceled
|
||||||
}
|
}
|
||||||
@@ -4531,3 +4712,177 @@ fn sell_reason(decision: &StrategyDecision, symbol: &str) -> &'static str {
|
|||||||
"rebalance_sell"
|
"rebalance_sell"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{BrokerSimulator, MatchingType};
|
||||||
|
use crate::cost::ChinaAShareCostModel;
|
||||||
|
use crate::data::{DailyMarketSnapshot, IntradayExecutionQuote, PriceField};
|
||||||
|
use crate::events::OrderSide;
|
||||||
|
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()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn next_tick_last_without_volume_or_liquidity_limit_does_not_cap_quote_quantity() {
|
||||||
|
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
|
||||||
|
.with_volume_limit(false)
|
||||||
|
.with_liquidity_limit(false);
|
||||||
|
|
||||||
|
assert!(!broker.quote_quantity_limited(MatchingType::NextTickLast));
|
||||||
|
assert!(broker.quote_quantity_limited(MatchingType::CounterpartyOffer));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn next_tick_last_keeps_quote_quantity_cap_when_limits_enabled() {
|
||||||
|
let volume_limited =
|
||||||
|
BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
|
||||||
|
.with_volume_limit(true)
|
||||||
|
.with_liquidity_limit(false);
|
||||||
|
let liquidity_limited =
|
||||||
|
BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
|
||||||
|
.with_volume_limit(false)
|
||||||
|
.with_liquidity_limit(true);
|
||||||
|
|
||||||
|
assert!(volume_limited.quote_quantity_limited(MatchingType::NextTickLast));
|
||||||
|
assert!(liquidity_limited.quote_quantity_limited(MatchingType::NextTickLast));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn instantaneous_twap_without_limits_does_not_cap_quote_quantity() {
|
||||||
|
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
|
||||||
|
.with_volume_limit(false)
|
||||||
|
.with_liquidity_limit(false);
|
||||||
|
let cursor = chrono::NaiveDate::from_ymd_opt(2025, 11, 3)
|
||||||
|
.unwrap()
|
||||||
|
.and_hms_opt(9, 31, 0)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(!broker.quote_quantity_limited_for_window(
|
||||||
|
MatchingType::Twap,
|
||||||
|
Some(cursor),
|
||||||
|
Some(cursor)
|
||||||
|
));
|
||||||
|
assert!(broker.quote_quantity_limited_for_window(
|
||||||
|
MatchingType::Twap,
|
||||||
|
Some(cursor),
|
||||||
|
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 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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ pub struct ChinaAShareCostModel {
|
|||||||
impl Default for ChinaAShareCostModel {
|
impl Default for ChinaAShareCostModel {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
commission_rate: 0.0003,
|
commission_rate: 0.0008,
|
||||||
stamp_tax_rate_before_change: 0.001,
|
stamp_tax_rate_before_change: 0.001,
|
||||||
stamp_tax_rate_after_change: 0.0005,
|
stamp_tax_rate_after_change: 0.0005,
|
||||||
minimum_commission: 5.0,
|
minimum_commission: 5.0,
|
||||||
|
|||||||
@@ -599,6 +599,19 @@ impl SymbolPriceSeries {
|
|||||||
Some(sum / lookback as f64)
|
Some(sum / lookback as f64)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn current_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let end = self.end_index(date)?;
|
||||||
|
if end < lookback {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let start = end - lookback;
|
||||||
|
let sum = self.volume_prefix[end] - self.volume_prefix[start];
|
||||||
|
Some(sum / lookback as f64)
|
||||||
|
}
|
||||||
|
|
||||||
fn decision_volume_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
|
fn decision_volume_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
|
||||||
if lookback == 0 {
|
if lookback == 0 {
|
||||||
return None;
|
return None;
|
||||||
@@ -641,6 +654,14 @@ impl SymbolPriceSeries {
|
|||||||
self.values_for(field).get(end - 1).copied()
|
self.values_for(field).get(end - 1).copied()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn snapshot_before(&self, date: NaiveDate) -> Option<&DailyMarketSnapshot> {
|
||||||
|
let end = self.previous_completed_end_index(date)?;
|
||||||
|
if end == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.snapshots.get(end - 1)
|
||||||
|
}
|
||||||
|
|
||||||
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
||||||
match field {
|
match field {
|
||||||
PriceField::DayOpen => &self.open_prefix,
|
PriceField::DayOpen => &self.open_prefix,
|
||||||
@@ -1815,6 +1836,12 @@ impl DataSet {
|
|||||||
.and_then(|series| series.price_on_or_before(date, field))
|
.and_then(|series| series.price_on_or_before(date, field))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||||
|
self.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.and_then(|series| series.snapshot_before(date))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
||||||
self.factor_by_date
|
self.factor_by_date
|
||||||
.get(&date)
|
.get(&date)
|
||||||
@@ -2065,6 +2092,36 @@ impl DataSet {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn market_current_numeric_moving_average(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
field: &str,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Option<f64> {
|
||||||
|
let field = normalize_field(field);
|
||||||
|
match field.as_str() {
|
||||||
|
"close" | "prev_close" | "stock_close" | "price" => {
|
||||||
|
self.market_moving_average(date, symbol, lookback, PriceField::Close)
|
||||||
|
}
|
||||||
|
"volume" | "stock_volume" => self
|
||||||
|
.factor_moving_average(date, symbol, "daily_volume", lookback)
|
||||||
|
.or_else(|| {
|
||||||
|
self.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.and_then(|series| series.current_volume_moving_average(date, lookback))
|
||||||
|
}),
|
||||||
|
"day_open" | "dayopen" => {
|
||||||
|
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
|
||||||
|
}
|
||||||
|
"open" => self.market_moving_average(date, symbol, lookback, PriceField::Open),
|
||||||
|
"last" | "last_price" => {
|
||||||
|
self.market_moving_average(date, symbol, lookback, PriceField::Last)
|
||||||
|
}
|
||||||
|
other => self.factor_moving_average(date, symbol, other, lookback),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn market_decision_numeric_values(
|
pub fn market_decision_numeric_values(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
|
|||||||
@@ -2127,7 +2127,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
portfolio.update_prices(execution_date, &self.data, PriceField::Close)?;
|
portfolio.update_prices_with_options(
|
||||||
|
execution_date,
|
||||||
|
&self.data,
|
||||||
|
PriceField::Close,
|
||||||
|
self.broker.same_day_buy_close_mark_at_fill(),
|
||||||
|
)?;
|
||||||
|
|
||||||
let post_trade_open_orders = self.open_order_views();
|
let post_trade_open_orders = self.open_order_views();
|
||||||
let visible_order_events = result
|
let visible_order_events = result
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -223,6 +223,7 @@ const RUNTIME_HELPER_FUNCTIONS: &[&str] = &[
|
|||||||
"factor",
|
"factor",
|
||||||
"day_factor",
|
"day_factor",
|
||||||
"rolling_mean",
|
"rolling_mean",
|
||||||
|
"rolling_mean_current",
|
||||||
"ma",
|
"ma",
|
||||||
"sma",
|
"sma",
|
||||||
"vma",
|
"vma",
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ pub struct StrategyRuntimeSpec {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub benchmark: Option<StrategyBenchmarkSpec>,
|
pub benchmark: Option<StrategyBenchmarkSpec>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub universe: Option<StrategyUniverseSpec>,
|
||||||
|
#[serde(default)]
|
||||||
pub signal_symbol: Option<String>,
|
pub signal_symbol: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub execution: Option<StrategyExecutionSpec>,
|
pub execution: Option<StrategyExecutionSpec>,
|
||||||
@@ -40,6 +42,13 @@ pub struct StrategyBenchmarkSpec {
|
|||||||
pub fallback_instrument_id: Option<String>,
|
pub fallback_instrument_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct StrategyUniverseSpec {
|
||||||
|
#[serde(default)]
|
||||||
|
pub exclude: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[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 {
|
||||||
@@ -105,6 +114,15 @@ pub struct DynamicRangeConfig {
|
|||||||
pub cap_span: Option<f64>,
|
pub cap_span: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub xs: Option<f64>,
|
pub xs: Option<f64>,
|
||||||
|
/// Padding ratio to expand the market cap range (e.g., 0.5 means 50% of span)
|
||||||
|
#[serde(default)]
|
||||||
|
pub padding_ratio: Option<f64>,
|
||||||
|
/// Minimum padding in billion yuan
|
||||||
|
#[serde(default)]
|
||||||
|
pub min_padding: Option<f64>,
|
||||||
|
/// Maximum padding in billion yuan
|
||||||
|
#[serde(default)]
|
||||||
|
pub max_padding: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
@@ -138,6 +156,8 @@ pub struct IndexThrottleConfig {
|
|||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct SkipWindowConfig {
|
pub struct SkipWindowConfig {
|
||||||
|
#[serde(default)]
|
||||||
|
pub year: Option<u32>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub month: Option<u32>,
|
pub month: Option<u32>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -373,7 +393,14 @@ pub fn platform_expr_config_from_spec(
|
|||||||
cfg.skip_month_day_ranges = engine
|
cfg.skip_month_day_ranges = engine
|
||||||
.skip_windows
|
.skip_windows
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|window| Some((window.month?, window.start_day?, window.end_day?)))
|
.filter_map(|window| {
|
||||||
|
Some((
|
||||||
|
window.year,
|
||||||
|
window.month?,
|
||||||
|
window.start_day?,
|
||||||
|
window.end_day?,
|
||||||
|
))
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
}
|
}
|
||||||
if let Some(spec_signal_symbol) = engine
|
if let Some(spec_signal_symbol) = engine
|
||||||
@@ -424,6 +451,14 @@ pub fn platform_expr_config_from_spec(
|
|||||||
cfg.signal_symbol = spec_signal_symbol.clone();
|
cfg.signal_symbol = spec_signal_symbol.clone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(universe) = spec.universe.as_ref() {
|
||||||
|
cfg.universe_exclude = universe
|
||||||
|
.exclude
|
||||||
|
.iter()
|
||||||
|
.map(|item| item.trim().to_ascii_lowercase())
|
||||||
|
.filter(|item| !item.is_empty())
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
let mut prelude_parts = Vec::new();
|
let mut prelude_parts = Vec::new();
|
||||||
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
||||||
@@ -619,8 +654,8 @@ pub fn platform_expr_config_from_spec(
|
|||||||
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
||||||
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
||||||
cfg.stock_filter_expr = format!(
|
cfg.stock_filter_expr = format!(
|
||||||
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid > stock_ma_long",
|
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid * {} > stock_ma_long",
|
||||||
ratio
|
ratio, ratio
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
||||||
@@ -1024,6 +1059,7 @@ mod tests {
|
|||||||
"strategyId": "runtime_spec_test",
|
"strategyId": "runtime_spec_test",
|
||||||
"signalSymbol": "000852.SH",
|
"signalSymbol": "000852.SH",
|
||||||
"benchmark": { "instrumentId": "000852.SH" },
|
"benchmark": { "instrumentId": "000852.SH" },
|
||||||
|
"universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] },
|
||||||
"runtimeExpressions": {
|
"runtimeExpressions": {
|
||||||
"prelude": "let stocknum = 8;",
|
"prelude": "let stocknum = 8;",
|
||||||
"selection": {
|
"selection": {
|
||||||
@@ -1054,6 +1090,7 @@ mod tests {
|
|||||||
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
||||||
assert_eq!(cfg.signal_symbol, "000852.SH");
|
assert_eq!(cfg.signal_symbol, "000852.SH");
|
||||||
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
||||||
|
assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]);
|
||||||
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);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
use indexmap::IndexMap;
|
use indexmap::IndexMap;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use crate::data::{DataSet, DataSetError, PriceField};
|
use crate::data::{DataSet, DataSetError, PriceField};
|
||||||
|
|
||||||
@@ -205,6 +205,22 @@ impl Position {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn record_buy_trade_cost(&mut self, quantity: u32, value: f64) {
|
||||||
|
if quantity == 0 || !value.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cost = value.max(0.0);
|
||||||
|
if cost <= 0.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(lot) = self.lots.last_mut() {
|
||||||
|
lot.price += cost / quantity as f64;
|
||||||
|
self.recalculate_average_cost();
|
||||||
|
}
|
||||||
|
self.day_trade_cost += cost;
|
||||||
|
self.refresh_day_pnl();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_dividend_receivable(&mut self, value: f64) {
|
pub fn set_dividend_receivable(&mut self, value: f64) {
|
||||||
self.dividend_receivable = if value.is_finite() {
|
self.dividend_receivable = if value.is_finite() {
|
||||||
value.max(0.0)
|
value.max(0.0)
|
||||||
@@ -316,6 +332,7 @@ pub struct PortfolioState {
|
|||||||
positions: IndexMap<String, Position>,
|
positions: IndexMap<String, Position>,
|
||||||
cash_receivables: Vec<CashReceivable>,
|
cash_receivables: Vec<CashReceivable>,
|
||||||
pending_cash_flows: Vec<PendingCashFlow>,
|
pending_cash_flows: Vec<PendingCashFlow>,
|
||||||
|
day_sold_symbols: BTreeSet<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -348,6 +365,7 @@ impl PortfolioState {
|
|||||||
positions: IndexMap::new(),
|
positions: IndexMap::new(),
|
||||||
cash_receivables: Vec::new(),
|
cash_receivables: Vec::new(),
|
||||||
pending_cash_flows: Vec::new(),
|
pending_cash_flows: Vec::new(),
|
||||||
|
day_sold_symbols: BTreeSet::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,7 +420,18 @@ impl PortfolioState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn prune_flat_positions(&mut self) {
|
pub fn prune_flat_positions(&mut self) {
|
||||||
self.positions.retain(|_, position| !position.is_flat());
|
let mut sold_symbols = Vec::new();
|
||||||
|
self.positions.retain(|symbol, position| {
|
||||||
|
if position.is_flat() {
|
||||||
|
if position.sold_quantity() > 0 {
|
||||||
|
sold_symbols.push(symbol.clone());
|
||||||
|
}
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.day_sold_symbols.extend(sold_symbols);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_cash_receivable(&mut self, receivable: CashReceivable) {
|
pub fn add_cash_receivable(&mut self, receivable: CashReceivable) {
|
||||||
@@ -538,6 +567,7 @@ impl PortfolioState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn begin_trading_day(&mut self) {
|
pub fn begin_trading_day(&mut self) {
|
||||||
|
self.day_sold_symbols.clear();
|
||||||
for position in self.positions.values_mut() {
|
for position in self.positions.values_mut() {
|
||||||
position.begin_trading_day();
|
position.begin_trading_day();
|
||||||
}
|
}
|
||||||
@@ -550,7 +580,31 @@ impl PortfolioState {
|
|||||||
data: &DataSet,
|
data: &DataSet,
|
||||||
field: PriceField,
|
field: PriceField,
|
||||||
) -> Result<(), DataSetError> {
|
) -> Result<(), DataSetError> {
|
||||||
|
self.update_prices_with_options(date, data, field, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_prices_with_options(
|
||||||
|
&mut self,
|
||||||
|
date: NaiveDate,
|
||||||
|
data: &DataSet,
|
||||||
|
field: PriceField,
|
||||||
|
same_day_buy_close_mark_at_fill: bool,
|
||||||
|
) -> Result<(), DataSetError> {
|
||||||
|
let day_sold_symbols = self.day_sold_symbols.clone();
|
||||||
for position in self.positions.values_mut() {
|
for position in self.positions.values_mut() {
|
||||||
|
let sold_today =
|
||||||
|
position.sold_quantity() > 0 || day_sold_symbols.contains(&position.symbol);
|
||||||
|
if same_day_buy_close_mark_at_fill
|
||||||
|
&& field == PriceField::Close
|
||||||
|
&& position.day_buy_quantity > 0
|
||||||
|
&& !sold_today
|
||||||
|
&& position.sellable_qty(date) == 0
|
||||||
|
&& position.last_price.is_finite()
|
||||||
|
&& position.last_price > 0.0
|
||||||
|
{
|
||||||
|
position.refresh_day_pnl();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let price = data
|
let price = data
|
||||||
.price(date, &position.symbol, field)
|
.price(date, &position.symbol, field)
|
||||||
.or_else(|| data.price_on_or_before(date, &position.symbol, field))
|
.or_else(|| data.price_on_or_before(date, &position.symbol, field))
|
||||||
@@ -1066,6 +1120,132 @@ mod tests {
|
|||||||
assert!(position.position_pnl.abs() < 1e-6);
|
assert!(position.position_pnl.abs() < 1e-6);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn portfolio_marks_same_day_buy_at_fill_until_next_trading_day() {
|
||||||
|
let buy_date = NaiveDate::from_ymd_opt(2025, 2, 10).unwrap();
|
||||||
|
let next_date = NaiveDate::from_ymd_opt(2025, 2, 11).unwrap();
|
||||||
|
let symbol = "002652.SZ";
|
||||||
|
let mut portfolio = PortfolioState::new(20_000.0);
|
||||||
|
portfolio.position_mut(symbol).buy(buy_date, 1300, 3.01);
|
||||||
|
|
||||||
|
let dataset = DataSet::from_components(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
name: "Same Day Buy Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![
|
||||||
|
DailyMarketSnapshot {
|
||||||
|
date: buy_date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: None,
|
||||||
|
day_open: 2.99,
|
||||||
|
open: 2.99,
|
||||||
|
high: 3.06,
|
||||||
|
low: 2.98,
|
||||||
|
close: 3.06,
|
||||||
|
last_price: 3.06,
|
||||||
|
bid1: 3.01,
|
||||||
|
ask1: 3.02,
|
||||||
|
prev_close: 2.98,
|
||||||
|
volume: 152_975,
|
||||||
|
tick_volume: 152_975,
|
||||||
|
bid1_volume: 338,
|
||||||
|
ask1_volume: 2476,
|
||||||
|
trading_phase: None,
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 3.28,
|
||||||
|
lower_limit: 2.68,
|
||||||
|
price_tick: 0.01,
|
||||||
|
},
|
||||||
|
DailyMarketSnapshot {
|
||||||
|
date: next_date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: None,
|
||||||
|
day_open: 3.03,
|
||||||
|
open: 3.03,
|
||||||
|
high: 3.08,
|
||||||
|
low: 3.00,
|
||||||
|
close: 3.07,
|
||||||
|
last_price: 3.07,
|
||||||
|
bid1: 3.06,
|
||||||
|
ask1: 3.07,
|
||||||
|
prev_close: 3.06,
|
||||||
|
volume: 160_000,
|
||||||
|
tick_volume: 160_000,
|
||||||
|
bid1_volume: 1000,
|
||||||
|
ask1_volume: 1000,
|
||||||
|
trading_phase: None,
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 3.37,
|
||||||
|
lower_limit: 2.75,
|
||||||
|
price_tick: 0.01,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
Vec::new(),
|
||||||
|
Vec::new(),
|
||||||
|
vec![
|
||||||
|
BenchmarkSnapshot {
|
||||||
|
date: buy_date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1000.0,
|
||||||
|
prev_close: 999.0,
|
||||||
|
volume: 1000,
|
||||||
|
},
|
||||||
|
BenchmarkSnapshot {
|
||||||
|
date: next_date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1001.0,
|
||||||
|
close: 1001.0,
|
||||||
|
prev_close: 1000.0,
|
||||||
|
volume: 1000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
|
||||||
|
portfolio
|
||||||
|
.update_prices_with_options(buy_date, &dataset, PriceField::Close, true)
|
||||||
|
.expect("same day close");
|
||||||
|
let position = portfolio.position(symbol).expect("position");
|
||||||
|
assert!((position.last_price - 3.01).abs() < 1e-9);
|
||||||
|
assert!((position.market_value() - 3913.0).abs() < 1e-6);
|
||||||
|
|
||||||
|
portfolio.begin_trading_day();
|
||||||
|
portfolio
|
||||||
|
.update_prices(next_date, &dataset, PriceField::Close)
|
||||||
|
.expect("next day close");
|
||||||
|
let position = portfolio.position(symbol).expect("position");
|
||||||
|
assert!((position.last_price - 3.07).abs() < 1e-9);
|
||||||
|
assert!((position.market_value() - 3991.0).abs() < 1e-6);
|
||||||
|
|
||||||
|
let prev_date = NaiveDate::from_ymd_opt(2025, 2, 7).unwrap();
|
||||||
|
let mut roundtrip_portfolio = PortfolioState::new(20_000.0);
|
||||||
|
roundtrip_portfolio
|
||||||
|
.position_mut(symbol)
|
||||||
|
.buy(prev_date, 2000, 2.90);
|
||||||
|
roundtrip_portfolio.begin_trading_day();
|
||||||
|
roundtrip_portfolio
|
||||||
|
.position_mut(symbol)
|
||||||
|
.sell(2000, 3.01)
|
||||||
|
.expect("same day sell");
|
||||||
|
roundtrip_portfolio.prune_flat_positions();
|
||||||
|
roundtrip_portfolio
|
||||||
|
.position_mut(symbol)
|
||||||
|
.buy(buy_date, 1800, 3.01);
|
||||||
|
roundtrip_portfolio
|
||||||
|
.update_prices(buy_date, &dataset, PriceField::Close)
|
||||||
|
.expect("same day roundtrip close");
|
||||||
|
let position = roundtrip_portfolio.position(symbol).expect("position");
|
||||||
|
assert!((position.last_price - 3.06).abs() < 1e-9);
|
||||||
|
assert!((position.market_value() - 5508.0).abs() < 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn position_tracks_day_lifecycle_fields() {
|
fn position_tracks_day_lifecycle_fields() {
|
||||||
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||||
|
|||||||
@@ -1090,6 +1090,9 @@ pub struct CnSmallCapRotationConfig {
|
|||||||
pub base_index_level: f64,
|
pub base_index_level: f64,
|
||||||
pub base_cap_floor: f64,
|
pub base_cap_floor: f64,
|
||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
pub short_ma_days: usize,
|
pub short_ma_days: usize,
|
||||||
pub long_ma_days: usize,
|
pub long_ma_days: usize,
|
||||||
pub stock_short_ma_days: usize,
|
pub stock_short_ma_days: usize,
|
||||||
@@ -1101,7 +1104,7 @@ pub struct CnSmallCapRotationConfig {
|
|||||||
pub take_profit_pct: f64,
|
pub take_profit_pct: f64,
|
||||||
pub signal_symbol: Option<String>,
|
pub signal_symbol: Option<String>,
|
||||||
pub skip_months: Vec<u32>,
|
pub skip_months: Vec<u32>,
|
||||||
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
pub skip_month_day_ranges: Vec<(Option<u32>, u32, u32, u32)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CnSmallCapRotationConfig {
|
impl CnSmallCapRotationConfig {
|
||||||
@@ -1114,6 +1117,9 @@ impl CnSmallCapRotationConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
short_ma_days: 3,
|
short_ma_days: 3,
|
||||||
long_ma_days: 5,
|
long_ma_days: 5,
|
||||||
stock_short_ma_days: 3,
|
stock_short_ma_days: 3,
|
||||||
@@ -1138,6 +1144,9 @@ impl CnSmallCapRotationConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
short_ma_days: 5,
|
short_ma_days: 5,
|
||||||
long_ma_days: 10,
|
long_ma_days: 10,
|
||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
@@ -1150,23 +1159,29 @@ impl CnSmallCapRotationConfig {
|
|||||||
signal_symbol: Some("000852.SH".to_string()),
|
signal_symbol: Some("000852.SH".to_string()),
|
||||||
skip_months: vec![],
|
skip_months: vec![],
|
||||||
skip_month_day_ranges: vec![
|
skip_month_day_ranges: vec![
|
||||||
(1, 15, 30),
|
(None, 1, 15, 30),
|
||||||
(4, 15, 29),
|
(None, 4, 15, 29),
|
||||||
(8, 15, 31),
|
(None, 8, 15, 31),
|
||||||
(10, 20, 30),
|
(None, 10, 20, 30),
|
||||||
(12, 20, 30),
|
(None, 12, 20, 30),
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
||||||
|
let year = date.year() as u32;
|
||||||
let month = date.month();
|
let month = date.month();
|
||||||
let day = date.day();
|
let day = date.day();
|
||||||
self.skip_months.contains(&month)
|
self.skip_months.contains(&month)
|
||||||
|| self
|
|| self
|
||||||
.skip_month_day_ranges
|
.skip_month_day_ranges
|
||||||
.iter()
|
.iter()
|
||||||
.any(|(m, start_day, end_day)| month == *m && day >= *start_day && day <= *end_day)
|
.any(|(window_year, m, start_day, end_day)| {
|
||||||
|
window_year.map(|value| value == year).unwrap_or(true)
|
||||||
|
&& month == *m
|
||||||
|
&& day >= *start_day
|
||||||
|
&& day <= *end_day
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1185,6 +1200,9 @@ impl CnSmallCapRotationStrategy {
|
|||||||
config.cap_span,
|
config.cap_span,
|
||||||
config.xs,
|
config.xs,
|
||||||
config.stocknum,
|
config.stocknum,
|
||||||
|
config.padding_ratio,
|
||||||
|
config.min_padding,
|
||||||
|
config.max_padding,
|
||||||
),
|
),
|
||||||
config,
|
config,
|
||||||
last_gross_exposure: None,
|
last_gross_exposure: None,
|
||||||
@@ -1508,6 +1526,9 @@ pub struct OmniMicroCapConfig {
|
|||||||
pub base_index_level: f64,
|
pub base_index_level: f64,
|
||||||
pub base_cap_floor: f64,
|
pub base_cap_floor: f64,
|
||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
pub benchmark_signal_symbol: String,
|
pub benchmark_signal_symbol: String,
|
||||||
pub benchmark_short_ma_days: usize,
|
pub benchmark_short_ma_days: usize,
|
||||||
pub benchmark_long_ma_days: usize,
|
pub benchmark_long_ma_days: usize,
|
||||||
@@ -1518,7 +1539,7 @@ pub struct OmniMicroCapConfig {
|
|||||||
pub trade_rate: f64,
|
pub trade_rate: f64,
|
||||||
pub stop_loss_ratio: f64,
|
pub stop_loss_ratio: f64,
|
||||||
pub take_profit_ratio: f64,
|
pub take_profit_ratio: f64,
|
||||||
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
pub skip_month_day_ranges: Vec<(Option<u32>, u32, u32, u32)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OmniMicroCapConfig {
|
impl OmniMicroCapConfig {
|
||||||
@@ -1531,6 +1552,9 @@ impl OmniMicroCapConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
benchmark_signal_symbol: "000001.SH".to_string(),
|
benchmark_signal_symbol: "000001.SH".to_string(),
|
||||||
benchmark_short_ma_days: 5,
|
benchmark_short_ma_days: 5,
|
||||||
benchmark_long_ma_days: 10,
|
benchmark_long_ma_days: 10,
|
||||||
@@ -1547,12 +1571,44 @@ impl OmniMicroCapConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn aiquant_v104() -> Self {
|
||||||
|
Self {
|
||||||
|
strategy_name: "aiquant-v1.0.4".to_string(),
|
||||||
|
refresh_rate: 120,
|
||||||
|
stocknum: 5,
|
||||||
|
xs: 4.0 / 500.0,
|
||||||
|
base_index_level: 2000.0,
|
||||||
|
base_cap_floor: 7.0,
|
||||||
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 1.2,
|
||||||
|
min_padding: 29.5,
|
||||||
|
max_padding: 50.0,
|
||||||
|
benchmark_signal_symbol: "000852.SH".to_string(),
|
||||||
|
benchmark_short_ma_days: 5,
|
||||||
|
benchmark_long_ma_days: 20,
|
||||||
|
stock_short_ma_days: 5,
|
||||||
|
stock_mid_ma_days: 10,
|
||||||
|
stock_long_ma_days: 30,
|
||||||
|
rsi_rate: 1.0001,
|
||||||
|
trade_rate: 0.5,
|
||||||
|
stop_loss_ratio: 0.92,
|
||||||
|
take_profit_ratio: 1.16,
|
||||||
|
skip_month_day_ranges: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
||||||
|
let year = date.year() as u32;
|
||||||
let month = date.month();
|
let month = date.month();
|
||||||
let day = date.day();
|
let day = date.day();
|
||||||
self.skip_month_day_ranges
|
self.skip_month_day_ranges
|
||||||
.iter()
|
.iter()
|
||||||
.any(|(m, start_day, end_day)| month == *m && day >= *start_day && day <= *end_day)
|
.any(|(window_year, m, start_day, end_day)| {
|
||||||
|
window_year.map(|value| value == year).unwrap_or(true)
|
||||||
|
&& month == *m
|
||||||
|
&& day >= *start_day
|
||||||
|
&& day <= *end_day
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1724,11 +1780,23 @@ impl OmniMicroCapStrategy {
|
|||||||
if !sizing_price.is_finite() || sizing_price <= 0.0 {
|
if !sizing_price.is_finite() || sizing_price <= 0.0 {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
let snapshot_requested_qty = self.round_lot_quantity(
|
let mut snapshot_requested_qty = self.round_lot_quantity(
|
||||||
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
|
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
|
||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
);
|
);
|
||||||
|
while snapshot_requested_qty > 0 {
|
||||||
|
let gross_amount = sizing_price * snapshot_requested_qty as f64;
|
||||||
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
|
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
snapshot_requested_qty = self.decrement_order_quantity(
|
||||||
|
snapshot_requested_qty,
|
||||||
|
minimum_order_quantity,
|
||||||
|
order_step_size,
|
||||||
|
);
|
||||||
|
}
|
||||||
let projected_execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
let projected_execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
||||||
let projected_fill = self.projected_select_execution_fill(
|
let projected_fill = self.projected_select_execution_fill(
|
||||||
ctx,
|
ctx,
|
||||||
@@ -1740,14 +1808,15 @@ impl OmniMicroCapStrategy {
|
|||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
false,
|
false,
|
||||||
Some(projected.cash()),
|
Some(projected.cash().min(order_value)),
|
||||||
Some(order_value + 400.0),
|
Some(order_value),
|
||||||
execution_state,
|
execution_state,
|
||||||
);
|
);
|
||||||
let mut quantity = snapshot_requested_qty;
|
let mut quantity = snapshot_requested_qty;
|
||||||
while quantity > 0 {
|
while quantity > 0 {
|
||||||
let gross_amount = projected_execution_price * quantity as f64;
|
let gross_amount = projected_execution_price * quantity as f64;
|
||||||
if gross_amount <= order_value + 400.0 && gross_amount <= projected.cash() + 1e-6 {
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
|
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
quantity =
|
quantity =
|
||||||
@@ -1762,7 +1831,8 @@ impl OmniMicroCapStrategy {
|
|||||||
.unwrap_or(projected_execution_price);
|
.unwrap_or(projected_execution_price);
|
||||||
while quantity > 0 {
|
while quantity > 0 {
|
||||||
let gross_amount = execution_price * quantity as f64;
|
let gross_amount = execution_price * quantity as f64;
|
||||||
if gross_amount <= projected.cash() + 1e-6 {
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
|
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
quantity =
|
quantity =
|
||||||
@@ -1778,7 +1848,7 @@ impl OmniMicroCapStrategy {
|
|||||||
};
|
};
|
||||||
let gross_amount = fill.price * fill.quantity as f64;
|
let gross_amount = fill.price * fill.quantity as f64;
|
||||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
if gross_amount > projected.cash() + 1e-6 {
|
if cash_out > projected.cash() + 1e-6 || cash_out > order_value + 1e-6 {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
projected.apply_cash_delta(-cash_out);
|
projected.apply_cash_delta(-cash_out);
|
||||||
@@ -2097,7 +2167,8 @@ impl OmniMicroCapStrategy {
|
|||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
) -> Result<(f64, f64, f64, f64), BacktestError> {
|
) -> Result<(f64, f64, f64, f64, f64), BacktestError> {
|
||||||
|
// 当前交易日的指数价格(用于MA计算和仓位控制)
|
||||||
let current_level = ctx
|
let current_level = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
||||||
@@ -2106,6 +2177,16 @@ impl OmniMicroCapStrategy {
|
|||||||
symbol: self.config.benchmark_signal_symbol.clone(),
|
symbol: self.config.benchmark_signal_symbol.clone(),
|
||||||
field: "decision_close",
|
field: "decision_close",
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
// 前一交易日的指数价格(用于市值区间计算,模拟实盘场景)
|
||||||
|
let prev_level = if let Some(prev_date) = ctx.data.previous_trading_date(date, 1) {
|
||||||
|
ctx.data
|
||||||
|
.market_decision_close(prev_date, &self.config.benchmark_signal_symbol)
|
||||||
|
.unwrap_or(current_level)
|
||||||
|
} else {
|
||||||
|
current_level
|
||||||
|
};
|
||||||
|
|
||||||
let ma_short = ctx
|
let ma_short = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(
|
.market_decision_close_moving_average(
|
||||||
@@ -2137,14 +2218,25 @@ impl OmniMicroCapStrategy {
|
|||||||
} else {
|
} else {
|
||||||
1.0
|
1.0
|
||||||
};
|
};
|
||||||
Ok((current_level, ma_short, ma_long, trading_ratio))
|
Ok((current_level, prev_level, ma_short, ma_long, trading_ratio))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
|
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
|
||||||
let y = (index_level - self.config.base_index_level) * self.config.xs
|
let y = (index_level - self.config.base_index_level) * self.config.xs
|
||||||
+ self.config.base_cap_floor;
|
+ self.config.base_cap_floor;
|
||||||
let start = y.round();
|
let start = y.round();
|
||||||
(start, start + self.config.cap_span)
|
let end = start + self.config.cap_span;
|
||||||
|
|
||||||
|
// Apply padding to expand the range
|
||||||
|
let span = end - start;
|
||||||
|
let padding = (span * self.config.padding_ratio)
|
||||||
|
.max(self.config.min_padding)
|
||||||
|
.min(self.config.max_padding);
|
||||||
|
|
||||||
|
let lower_bound = (start - padding).max(0.0);
|
||||||
|
let upper_bound = end + padding;
|
||||||
|
|
||||||
|
(lower_bound, upper_bound)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stock_passes_ma_filter(
|
fn stock_passes_ma_filter(
|
||||||
@@ -2175,7 +2267,67 @@ impl OmniMicroCapStrategy {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid > ma_long
|
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
|
||||||
|
let ma_pass =
|
||||||
|
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
||||||
|
|
||||||
|
// Debug logging for ALL stocks on first decision date
|
||||||
|
static DEBUG_DATE: std::sync::Mutex<Option<NaiveDate>> = std::sync::Mutex::new(None);
|
||||||
|
let mut debug_date = DEBUG_DATE.lock().unwrap();
|
||||||
|
let should_debug = if let Some(d) = *debug_date {
|
||||||
|
d == date
|
||||||
|
} else {
|
||||||
|
*debug_date = Some(date);
|
||||||
|
true
|
||||||
|
};
|
||||||
|
|
||||||
|
if should_debug {
|
||||||
|
eprintln!(
|
||||||
|
"[MA_FILTER] {} cap={:.2} ma5={:.4} ma10={:.4} ma30={:.4} ma10*rsi={:.4} pass={} ({}>{:.4}? {} && {:.4}>{}? {})",
|
||||||
|
symbol,
|
||||||
|
ctx.data.market_decision_close(date, symbol).unwrap_or(0.0),
|
||||||
|
ma_short,
|
||||||
|
ma_mid,
|
||||||
|
ma_long,
|
||||||
|
ma_mid * self.config.rsi_rate,
|
||||||
|
ma_pass,
|
||||||
|
ma_short,
|
||||||
|
ma_mid * self.config.rsi_rate,
|
||||||
|
ma_short > ma_mid * self.config.rsi_rate,
|
||||||
|
ma_mid * self.config.rsi_rate,
|
||||||
|
ma_long,
|
||||||
|
ma_mid * self.config.rsi_rate > ma_long
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ma_pass {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
|
||||||
|
if self.config.strategy_name.contains("aiquant")
|
||||||
|
|| self.config.strategy_name.contains("AiQuant")
|
||||||
|
|| self.config.strategy_name.contains("omni")
|
||||||
|
{
|
||||||
|
let Some(volume_ma5) = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_volume_moving_average(date, symbol, 5)
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(volume_ma60) = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_volume_moving_average(date, symbol, 60)
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
if volume_ma5 >= volume_ma60 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
||||||
@@ -2546,25 +2698,31 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let (index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
|
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) =
|
||||||
Ok(value) => value,
|
match self.trading_ratio(ctx, date) {
|
||||||
Err(BacktestError::Execution(message))
|
Ok(value) => value,
|
||||||
if message.contains("insufficient benchmark") =>
|
Err(BacktestError::Execution(message))
|
||||||
{
|
if message.contains("insufficient benchmark") =>
|
||||||
return Ok(StrategyDecision {
|
{
|
||||||
rebalance: false,
|
return Ok(StrategyDecision {
|
||||||
target_weights: BTreeMap::new(),
|
rebalance: false,
|
||||||
exit_symbols: BTreeSet::new(),
|
target_weights: BTreeMap::new(),
|
||||||
order_intents: Vec::new(),
|
exit_symbols: BTreeSet::new(),
|
||||||
notes: vec![format!("warmup: {}", message)],
|
order_intents: Vec::new(),
|
||||||
diagnostics: vec![
|
notes: vec![format!("warmup: {}", message)],
|
||||||
"insufficient history; skip trading on warmup dates".to_string(),
|
diagnostics: vec![
|
||||||
],
|
"insufficient history; skip trading on warmup dates".to_string(),
|
||||||
});
|
],
|
||||||
}
|
});
|
||||||
Err(err) => return Err(err),
|
}
|
||||||
};
|
Err(err) => return Err(err),
|
||||||
let (band_low, band_high) = self.market_cap_band(index_level);
|
};
|
||||||
|
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||||
|
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
||||||
|
eprintln!(
|
||||||
|
"[DEBUG] date={} current_index={:.2} prev_index={:.2} band=[{:.0}, {:.0}]",
|
||||||
|
date, index_level, prev_index_level, band_low, band_high
|
||||||
|
);
|
||||||
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
||||||
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||||
let mut projected = ctx.portfolio.clone();
|
let mut projected = ctx.portfolio.clone();
|
||||||
|
|||||||
@@ -78,6 +78,9 @@ pub struct DynamicMarketCapBandSelector {
|
|||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
pub xs: f64,
|
pub xs: f64,
|
||||||
pub top_n: usize,
|
pub top_n: usize,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DynamicMarketCapBandSelector {
|
impl DynamicMarketCapBandSelector {
|
||||||
@@ -87,6 +90,9 @@ impl DynamicMarketCapBandSelector {
|
|||||||
cap_span: f64,
|
cap_span: f64,
|
||||||
xs: f64,
|
xs: f64,
|
||||||
top_n: usize,
|
top_n: usize,
|
||||||
|
padding_ratio: f64,
|
||||||
|
min_padding: f64,
|
||||||
|
max_padding: f64,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
base_index_level,
|
base_index_level,
|
||||||
@@ -94,11 +100,14 @@ impl DynamicMarketCapBandSelector {
|
|||||||
cap_span,
|
cap_span,
|
||||||
xs,
|
xs,
|
||||||
top_n,
|
top_n,
|
||||||
|
padding_ratio,
|
||||||
|
min_padding,
|
||||||
|
max_padding,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn demo(top_n: usize) -> Self {
|
pub fn demo(top_n: usize) -> Self {
|
||||||
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n)
|
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n, 0.5, 8.0, 20.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn regime(&self, benchmark_level: f64) -> BandRegime {
|
pub fn regime(&self, benchmark_level: f64) -> BandRegime {
|
||||||
@@ -114,7 +123,18 @@ impl DynamicMarketCapBandSelector {
|
|||||||
pub fn band_for_level(&self, benchmark_level: f64) -> (f64, f64) {
|
pub fn band_for_level(&self, benchmark_level: f64) -> (f64, f64) {
|
||||||
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
|
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
|
||||||
let low = start.round();
|
let low = start.round();
|
||||||
(low, low + self.cap_span)
|
let high = low + self.cap_span;
|
||||||
|
|
||||||
|
// Apply padding to expand the range
|
||||||
|
let span = high - low;
|
||||||
|
let padding = (span * self.padding_ratio)
|
||||||
|
.max(self.min_padding)
|
||||||
|
.min(self.max_padding);
|
||||||
|
|
||||||
|
let lower_bound = (low - padding).max(0.0);
|
||||||
|
let upper_bound = high + padding;
|
||||||
|
|
||||||
|
(lower_bound, upper_bound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ fn china_cost_model_applies_minimum_commission_and_stamp_tax() {
|
|||||||
assert_eq!(buy.stamp_tax, 0.0);
|
assert_eq!(buy.stamp_tax, 0.0);
|
||||||
|
|
||||||
let sell = model.calculate(d(2023, 8, 25), OrderSide::Sell, 100_000.0);
|
let sell = model.calculate(d(2023, 8, 25), OrderSide::Sell, 100_000.0);
|
||||||
assert!((sell.commission - 30.0).abs() < 1e-9);
|
assert!((sell.commission - 80.0).abs() < 1e-9);
|
||||||
assert!((sell.stamp_tax - 100.0).abs() < 1e-9);
|
assert!((sell.stamp_tax - 100.0).abs() < 1e-9);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ fn china_cost_model_tracks_minimum_commission_per_order_id() {
|
|||||||
|
|
||||||
assert!((first.commission - 5.0).abs() < 1e-9);
|
assert!((first.commission - 5.0).abs() < 1e-9);
|
||||||
assert!(second.commission.abs() < 1e-9);
|
assert!(second.commission.abs() < 1e-9);
|
||||||
assert!((third.commission - 1.6).abs() < 1e-9);
|
assert!((third.commission - 12.6).abs() < 1e-9);
|
||||||
assert!((another_order.commission - 5.0).abs() < 1e-9);
|
assert!((another_order.commission - 5.0).abs() < 1e-9);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,108 @@ use fidc_core::{
|
|||||||
};
|
};
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
fn order_value_rounding_data(date: NaiveDate, symbol: &str, price: f64) -> DataSet {
|
||||||
|
DataSet::from_components(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
name: "Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: Some(format!("{date} 09:33:00")),
|
||||||
|
day_open: price,
|
||||||
|
open: price,
|
||||||
|
high: price,
|
||||||
|
low: price,
|
||||||
|
close: price,
|
||||||
|
last_price: price,
|
||||||
|
bid1: price,
|
||||||
|
ask1: price,
|
||||||
|
prev_close: price,
|
||||||
|
volume: 100_000,
|
||||||
|
tick_volume: 100_000,
|
||||||
|
bid1_volume: 80_000,
|
||||||
|
ask1_volume: 80_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: price * 1.1,
|
||||||
|
lower_limit: price * 0.9,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
market_cap_bn: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000300.SH".to_string(),
|
||||||
|
open: 100.0,
|
||||||
|
close: 100.0,
|
||||||
|
prev_close: 99.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute_single_value_order(
|
||||||
|
date: NaiveDate,
|
||||||
|
data: &DataSet,
|
||||||
|
symbol: &str,
|
||||||
|
value: f64,
|
||||||
|
) -> (PortfolioState, fidc_core::BrokerExecutionReport) {
|
||||||
|
let mut portfolio = PortfolioState::new(20_000.0);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Open,
|
||||||
|
)
|
||||||
|
.with_strict_value_budget(true);
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::Value {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
value,
|
||||||
|
reason: "test_order_value_rounding".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
(portfolio, report)
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_executes_explicit_order_value_buy() {
|
fn broker_executes_explicit_order_value_buy() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
@@ -122,6 +224,171 @@ fn broker_executes_explicit_order_value_buy() {
|
|||||||
assert!(portfolio.cash() < 1_000_000.0);
|
assert!(portfolio.cash() < 1_000_000.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_order_value_rounds_to_nearest_lot_when_min_lot_is_affordable() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 1, 24).unwrap();
|
||||||
|
let symbol = "003017.SZ";
|
||||||
|
let data = order_value_rounding_data(date, symbol, 19.97);
|
||||||
|
|
||||||
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 3_938.13);
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 100);
|
||||||
|
assert_eq!(portfolio.position(symbol).expect("position").quantity, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_order_value_budget_includes_buy_commission() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 6, 23).unwrap();
|
||||||
|
let symbol = "605303.SH";
|
||||||
|
let data = order_value_rounding_data(date, symbol, 11.93);
|
||||||
|
|
||||||
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_776.0);
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 300);
|
||||||
|
assert_eq!(portfolio.position(symbol).expect("position").quantity, 300);
|
||||||
|
|
||||||
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_848.0);
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 400);
|
||||||
|
assert_eq!(portfolio.position(symbol).expect("position").quantity, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_delayed_limit_open_sell_uses_tick_price() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 6, 27).unwrap();
|
||||||
|
let prev_date = NaiveDate::from_ymd_opt(2025, 6, 26).unwrap();
|
||||||
|
let symbol = "300635.SZ";
|
||||||
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
name: "Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: Some("2025-06-27 09:31:00".to_string()),
|
||||||
|
day_open: 12.55,
|
||||||
|
open: 12.55,
|
||||||
|
high: 13.16,
|
||||||
|
low: 12.26,
|
||||||
|
close: 12.36,
|
||||||
|
last_price: 12.39,
|
||||||
|
bid1: 12.39,
|
||||||
|
ask1: 12.40,
|
||||||
|
prev_close: 13.24,
|
||||||
|
volume: 329_575,
|
||||||
|
tick_volume: 10_000,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 14.56,
|
||||||
|
lower_limit: 11.92,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
market_cap_bn: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000300.SH".to_string(),
|
||||||
|
open: 100.0,
|
||||||
|
close: 100.0,
|
||||||
|
prev_close: 99.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
vec![IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: date.and_hms_opt(9, 31, 0).unwrap(),
|
||||||
|
last_price: 12.39,
|
||||||
|
bid1: 12.39,
|
||||||
|
ask1: 12.40,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_000,
|
||||||
|
volume_delta: 10_000,
|
||||||
|
amount_delta: 123_900.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(1_000.0);
|
||||||
|
portfolio.position_mut(symbol).buy(prev_date, 800, 10.92);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Last,
|
||||||
|
)
|
||||||
|
.with_matching_type(MatchingType::NextTickLast)
|
||||||
|
.with_intraday_execution_start_time(NaiveTime::from_hms_opt(9, 31, 0).unwrap())
|
||||||
|
.with_volume_limit(false)
|
||||||
|
.with_liquidity_limit(false);
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::TargetValue {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
target_value: 0.0,
|
||||||
|
reason: "delayed_limit_open_sell".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 800);
|
||||||
|
assert_eq!(report.fill_events[0].price, 12.39);
|
||||||
|
assert!(portfolio.position(symbol).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_order_value_skips_when_one_lot_exceeds_budget() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||||
|
let symbol = "300321.SZ";
|
||||||
|
let data = order_value_rounding_data(date, symbol, 20.38);
|
||||||
|
|
||||||
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 2_000.0);
|
||||||
|
|
||||||
|
assert!(report.fill_events.is_empty());
|
||||||
|
assert!(portfolio.position(symbol).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_executes_order_shares_and_order_lots() {
|
fn broker_executes_order_shares_and_order_lots() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
@@ -778,7 +1045,7 @@ fn broker_executes_order_percent_and_target_percent() {
|
|||||||
)
|
)
|
||||||
.expect("percent execution");
|
.expect("percent execution");
|
||||||
assert_eq!(percent_report.fill_events.len(), 1);
|
assert_eq!(percent_report.fill_events.len(), 1);
|
||||||
assert_eq!(percent_report.fill_events[0].quantity, 10_000);
|
assert_eq!(percent_report.fill_events[0].quantity, 9_900);
|
||||||
|
|
||||||
let mut target_percent_portfolio = PortfolioState::new(1_000_000.0);
|
let mut target_percent_portfolio = PortfolioState::new(1_000_000.0);
|
||||||
let target_percent_report = broker
|
let target_percent_report = broker
|
||||||
@@ -1438,6 +1705,121 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
|
|||||||
assert!(portfolio.position("000002.SZ").is_none());
|
assert!(portfolio.position("000002.SZ").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_executes_intraday_last_on_start_quote_without_trade_delta() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
name: "Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: Some("2024-01-10 09:33:00".to_string()),
|
||||||
|
day_open: 15.0,
|
||||||
|
open: 15.0,
|
||||||
|
high: 15.5,
|
||||||
|
low: 14.8,
|
||||||
|
close: 15.2,
|
||||||
|
last_price: 15.2,
|
||||||
|
bid1: 15.19,
|
||||||
|
ask1: 15.21,
|
||||||
|
prev_close: 15.0,
|
||||||
|
volume: 100_000,
|
||||||
|
tick_volume: 100_000,
|
||||||
|
bid1_volume: 80_000,
|
||||||
|
ask1_volume: 80_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 16.5,
|
||||||
|
lower_limit: 13.5,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
market_cap_bn: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000300.SH".to_string(),
|
||||||
|
open: 100.0,
|
||||||
|
close: 100.0,
|
||||||
|
prev_close: 99.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
vec![IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: date.and_hms_opt(9, 33, 0).unwrap(),
|
||||||
|
last_price: 15.2,
|
||||||
|
bid1: 15.19,
|
||||||
|
ask1: 15.21,
|
||||||
|
bid1_volume: 8,
|
||||||
|
ask1_volume: 8,
|
||||||
|
volume_delta: 0,
|
||||||
|
amount_delta: 0.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Last,
|
||||||
|
)
|
||||||
|
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(9, 33, 0).unwrap());
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::Value {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
value: 4_000.0,
|
||||||
|
reason: "start_quote".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 200);
|
||||||
|
assert!((report.fill_events[0].price - 15.2).abs() < 1e-9);
|
||||||
|
assert_eq!(report.order_events[0].status, OrderStatus::Filled);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted() {
|
fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
@@ -2256,7 +2638,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
|
|||||||
exit_symbols: BTreeSet::new(),
|
exit_symbols: BTreeSet::new(),
|
||||||
order_intents: vec![OrderIntent::AlgoPercent {
|
order_intents: vec![OrderIntent::AlgoPercent {
|
||||||
symbol: "000002.SZ".to_string(),
|
symbol: "000002.SZ".to_string(),
|
||||||
percent: 0.0036,
|
percent: 0.0037,
|
||||||
style: AlgoOrderStyle::Twap,
|
style: AlgoOrderStyle::Twap,
|
||||||
start_time: Some(NaiveTime::from_hms_opt(10, 0, 0).unwrap()),
|
start_time: Some(NaiveTime::from_hms_opt(10, 0, 0).unwrap()),
|
||||||
end_time: Some(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
|
end_time: Some(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
|
||||||
|
|||||||
Reference in New Issue
Block a user