修复 AiQuant 微盘回测撮合语义

This commit is contained in:
boris
2026-05-13 18:43:02 +08:00
parent 2165831708
commit db72f6f515
8 changed files with 849 additions and 162 deletions

View File

@@ -2918,8 +2918,9 @@ where
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
let order_step_size = self.order_step_size(data, symbol);
let price = self.sizing_price(snapshot);
let snapshot_requested_qty = self.round_buy_quantity(
((value.abs()) / price).floor() as u32,
let snapshot_requested_qty = self.value_buy_quantity(
value.abs(),
price,
minimum_order_quantity,
order_step_size,
);
@@ -3012,8 +3013,9 @@ where
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
let order_step_size = self.order_step_size(data, symbol);
let price = self.sizing_price(snapshot);
let snapshot_requested_qty = self.round_buy_quantity(
((value.abs()) / price).floor() as u32,
let snapshot_requested_qty = self.value_buy_quantity(
value.abs(),
price,
minimum_order_quantity,
order_step_size,
);
@@ -3178,8 +3180,9 @@ where
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
let order_step_size = self.order_step_size(data, symbol);
let price = self.sizing_price(snapshot);
let snapshot_requested_qty = self.round_buy_quantity(
(value.abs() / price).floor() as u32,
let snapshot_requested_qty = self.value_buy_quantity(
value.abs(),
price,
minimum_order_quantity,
order_step_size,
);
@@ -3396,10 +3399,15 @@ where
requested_qty
}
fn value_budget_gross_limit(&self, value_budget: Option<f64>) -> Option<f64> {
fn value_buy_gross_limit(
&self,
value_budget: Option<f64>,
requested_qty: u32,
reference_price: f64,
) -> Option<f64> {
value_budget.map(|budget| {
if self.strict_value_budget {
budget
budget.max(reference_price * requested_qty as f64)
} else {
budget + 400.0
}
@@ -3562,6 +3570,8 @@ where
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(
date,
@@ -3577,7 +3587,7 @@ where
execution_cursors,
None,
Some(portfolio.cash()),
self.value_budget_gross_limit(value_budget),
value_gross_limit,
algo_request,
limit_price,
);
@@ -3608,7 +3618,7 @@ where
let filled_qty = self.affordable_buy_quantity(
date,
portfolio.cash(),
self.value_budget_gross_limit(value_budget),
value_gross_limit,
execution_price,
constrained_qty,
self.minimum_order_quantity(data, symbol),
@@ -3619,7 +3629,7 @@ where
partial_fill_reason,
self.buy_reduction_reason(
portfolio.cash(),
self.value_budget_gross_limit(value_budget),
value_gross_limit,
execution_price,
constrained_qty,
filled_qty,
@@ -4054,6 +4064,26 @@ where
}
}
fn value_buy_quantity(
&self,
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 step = order_step_size.max(1);
if price * minimum as f64 > value_budget + 1e-6 {
return 0;
}
let raw_steps = (value_budget / price / step as f64).round();
let requested = ((raw_steps.max(1.0) as u32) * step).max(minimum);
self.round_buy_quantity(requested, minimum_order_quantity, order_step_size)
}
fn decrement_order_quantity(
&self,
quantity: u32,
@@ -4340,7 +4370,7 @@ where
.filter(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
&& quote.volume_delta != 0
&& self.quote_has_executable_liquidity(quote, side, matching_type)
})
.collect();
let mut filled_qty = 0_u32;
@@ -4466,6 +4496,24 @@ 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 uses_serial_execution_cursor(&self, reason: &str) -> bool {
let _ = reason;
false

View File

@@ -599,6 +599,19 @@ impl SymbolPriceSeries {
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>> {
if lookback == 0 {
return None;
@@ -2065,6 +2078,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(
&self,
date: NaiveDate,

View File

@@ -718,6 +718,7 @@ impl PlatformExprStrategy {
"factor"
| "day_factor"
| "rolling_mean"
| "rolling_mean_current"
| "ma"
| "sma"
| "vma"
@@ -804,6 +805,26 @@ impl PlatformExprStrategy {
}
}
fn value_buy_quantity(
&self,
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 step = order_step_size.max(1);
if price * minimum as f64 > value_budget + 1e-6 {
return 0;
}
let raw_steps = (value_budget / price / step as f64).round();
let requested = ((raw_steps.max(1.0) as u32) * step).max(minimum);
self.round_lot_quantity(requested, minimum_order_quantity, order_step_size)
}
fn decrement_order_quantity(
&self,
quantity: u32,
@@ -1045,15 +1066,16 @@ impl PlatformExprStrategy {
if !sizing_price.is_finite() || sizing_price <= 0.0 {
return 0;
}
let snapshot_requested_qty = self.round_lot_quantity(
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
let snapshot_requested_qty = self.value_buy_quantity(
projected.cash().min(order_value),
sizing_price,
minimum_order_quantity,
order_step_size,
);
let execution_price = self.projected_execution_price(market, OrderSide::Buy);
let mut quantity = snapshot_requested_qty;
let gross_limit = if self.config.strict_value_budget {
order_value
order_value.max(execution_price * quantity as f64)
} else {
order_value + 400.0
};
@@ -1291,9 +1313,19 @@ impl PlatformExprStrategy {
ctx: &StrategyContext<'_>,
date: NaiveDate,
symbol: &str,
) -> Result<StockExpressionState, BacktestError> {
self.stock_state_with_factor_date(ctx, date, date, symbol)
}
fn stock_state_with_factor_date(
&self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
factor_date: NaiveDate,
symbol: &str,
) -> Result<StockExpressionState, BacktestError> {
let market = ctx.data.require_market(date, symbol)?;
let factor = ctx.data.require_factor(date, symbol)?;
let factor = ctx.data.require_factor(factor_date, symbol)?;
let candidate = ctx.data.require_candidate(date, symbol)?;
let instrument = ctx.data.instrument(symbol);
let stock_ma_short = ctx
@@ -2239,6 +2271,17 @@ impl PlatformExprStrategy {
let value = self.resolve_rolling_mean(ctx, day, stock, &field, lookback)?;
Ok(format!("{value:.12}"))
}
"rolling_mean_current" => {
if args.len() != 2 {
return Err(BacktestError::Execution(
"rolling_mean_current expects 2 arguments".to_string(),
));
}
let field = Self::parse_string_or_identifier(&args[0])?;
let lookback = Self::parse_positive_usize(&args[1])?;
let value = self.resolve_current_rolling_mean(ctx, day, stock, &field, lookback)?;
Ok(format!("{value:.12}"))
}
"vma" => {
if args.len() != 1 {
return Err(BacktestError::Execution(
@@ -2785,6 +2828,53 @@ impl PlatformExprStrategy {
})
}
fn resolve_current_rolling_mean(
&self,
ctx: &StrategyContext<'_>,
day: &DayExpressionState,
stock: Option<&StockExpressionState>,
field: &str,
lookback: usize,
) -> Result<f64, BacktestError> {
if lookback == 0 {
return Err(BacktestError::Execution(
"rolling_mean_current lookback must be positive".to_string(),
));
}
let value = match field {
"benchmark_open" => ctx.data.benchmark_open_moving_average(day.date, lookback),
"benchmark_close" => ctx.data.benchmark_moving_average(day.date, lookback),
"signal_open" => {
ctx.data
.market_open_moving_average(day.date, &self.config.signal_symbol, lookback)
}
"signal_close" => ctx.data.market_moving_average(
day.date,
&self.config.signal_symbol,
lookback,
crate::data::PriceField::Close,
),
other => {
let stock = stock.ok_or_else(|| {
BacktestError::Execution(format!(
"rolling_mean_current(\"{other}\", {lookback}) requires stock context"
))
})?;
ctx.data.market_current_numeric_moving_average(
day.date,
&stock.symbol,
other,
lookback,
)
}
};
value.ok_or_else(|| {
BacktestError::Execution(format!(
"missing current rolling mean for field {field} with lookback {lookback}"
))
})
}
fn resolve_rolling_values(
&self,
ctx: &StrategyContext<'_>,
@@ -2844,6 +2934,7 @@ impl PlatformExprStrategy {
error,
BacktestError::Execution(message)
if message.starts_with("missing rolling mean for field ")
|| message.starts_with("missing current rolling mean for field ")
)
}
@@ -4194,9 +4285,10 @@ impl PlatformExprStrategy {
&self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
factor_date: NaiveDate,
) -> Vec<EligibleUniverseSnapshot> {
let mut rows = Vec::new();
for factor in ctx.data.factor_snapshots_on(date) {
for factor in ctx.data.factor_snapshots_on(factor_date) {
if factor.market_cap_bn <= 0.0 || !factor.market_cap_bn.is_finite() {
continue;
}
@@ -4419,16 +4511,18 @@ impl PlatformExprStrategy {
&self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
factor_date: NaiveDate,
day: &DayExpressionState,
band_low: f64,
band_high: f64,
limit: usize,
) -> Result<(Vec<String>, Vec<String>), BacktestError> {
let universe = self.selectable_universe_on(ctx, date);
let universe = self.selectable_universe_on(ctx, date, factor_date);
let mut diagnostics = Vec::new();
let mut candidates = Vec::new();
for candidate in universe {
let stock = self.stock_state(ctx, date, &candidate.symbol)?;
let stock =
self.stock_state_with_factor_date(ctx, date, factor_date, &candidate.symbol)?;
let field_value = self.selection_field_value(&candidate, &stock);
if !field_value.is_finite() {
if diagnostics.len() < 12 {
@@ -4657,6 +4751,10 @@ impl Strategy for PlatformExprStrategy {
}
let day = self.day_state(ctx, decision_date)?;
let selection_factor_date = ctx
.data
.previous_trading_date(decision_date, 1)
.unwrap_or(decision_date);
let (explicit_action_intents, explicit_action_diagnostics) =
if self.config.explicit_action_stage == PlatformExplicitActionStage::OnDay
&& self.explicit_actions_active(ctx.data.calendar(), execution_date)
@@ -4686,6 +4784,7 @@ impl Strategy for PlatformExprStrategy {
let (stock_list, notes) = self.select_symbols(
ctx,
decision_date,
selection_factor_date,
&day,
band_low,
band_high,
@@ -4716,6 +4815,7 @@ impl Strategy for PlatformExprStrategy {
let mut projected_execution_state = ProjectedExecutionState::default();
let mut order_intents = Vec::new();
let mut exit_symbols = BTreeSet::new();
let mut intraday_attempted_buys = BTreeSet::<String>::new();
for position in ctx.portfolio.positions().values() {
if position.quantity == 0 || position.average_cost <= 0.0 {
@@ -4745,54 +4845,52 @@ impl Strategy for PlatformExprStrategy {
&mut projected_execution_state,
);
}
}
if self.config.rotation_enabled && projected.positions().len() < selection_limit {
let remaining_slots = selection_limit - projected.positions().len();
if remaining_slots > 0 {
let replacement_cash =
projected.cash() * trading_ratio / remaining_slots as f64;
for symbol in &stock_list {
if symbol == &position.symbol
|| projected.positions().contains_key(symbol)
{
continue;
}
let decision_stock = self.stock_state(ctx, decision_date, symbol)?;
let execution_stock = self.stock_state(ctx, execution_date, symbol)?;
if self
.buy_rejection_reason(
ctx,
execution_date,
symbol,
&execution_stock,
)?
.is_some()
{
continue;
}
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
continue;
}
let replacement_cash =
replacement_cash * self.buy_scale(ctx, &day, &decision_stock)?;
if replacement_cash <= 0.0 {
continue;
}
order_intents.push(OrderIntent::Value {
symbol: symbol.clone(),
value: replacement_cash,
reason: format!("replacement_after_{}", sell_reason),
});
self.project_order_value(
ctx,
&mut projected,
execution_date,
symbol,
replacement_cash,
&mut projected_execution_state,
);
if self.config.daily_top_up_enabled
&& self.config.rotation_enabled
&& trading_ratio > 0.0
&& projected.positions().len() < selection_limit
{
let fixed_buy_cash =
ctx.portfolio.total_value() * trading_ratio / selection_limit as f64;
let available_buy_cash = fixed_buy_cash.min(projected.cash());
if available_buy_cash >= fixed_buy_cash * 0.5 {
for symbol in &stock_list {
if symbol == &position.symbol
|| projected.positions().contains_key(symbol)
|| intraday_attempted_buys.contains(symbol)
{
continue;
}
let decision_stock = self.stock_state_with_factor_date(
ctx,
decision_date,
selection_factor_date,
symbol,
)?;
let buy_cash =
available_buy_cash * self.buy_scale(ctx, &day, &decision_stock)?;
if buy_cash <= 0.0 {
break;
}
order_intents.push(OrderIntent::Value {
symbol: symbol.clone(),
value: buy_cash,
reason: "daily_top_up_buy".to_string(),
});
let filled_qty = self.project_order_value(
ctx,
&mut projected,
execution_date,
symbol,
buy_cash,
&mut projected_execution_state,
);
if filled_qty > 0 {
intraday_attempted_buys.insert(symbol.clone());
}
break;
}
}
}
@@ -4835,7 +4933,12 @@ impl Strategy for PlatformExprStrategy {
{
continue;
}
let decision_stock = self.stock_state(ctx, decision_date, symbol)?;
let decision_stock = self.stock_state_with_factor_date(
ctx,
decision_date,
selection_factor_date,
symbol,
)?;
let execution_stock = self.stock_state(ctx, execution_date, symbol)?;
if self
.buy_rejection_reason(ctx, execution_date, symbol, &execution_stock)?
@@ -4865,53 +4968,6 @@ impl Strategy for PlatformExprStrategy {
);
}
}
if self.config.daily_top_up_enabled
&& self.config.rotation_enabled
&& !periodic_rebalance
&& !ctx.portfolio.positions().is_empty()
&& projected.positions().len() < selection_limit
{
let fixed_buy_cash = projected.total_value() * trading_ratio / selection_limit as f64;
let available_buy_cash = fixed_buy_cash.min(projected.cash());
if available_buy_cash >= fixed_buy_cash * 0.5 {
for symbol in &stock_list {
if projected.positions().contains_key(symbol) {
continue;
}
let decision_stock = self.stock_state(ctx, decision_date, symbol)?;
let execution_stock = self.stock_state(ctx, execution_date, symbol)?;
if self
.buy_rejection_reason(ctx, execution_date, symbol, &execution_stock)?
.is_some()
{
continue;
}
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
continue;
}
let buy_cash =
available_buy_cash * self.buy_scale(ctx, &day, &decision_stock)?;
if buy_cash <= 0.0 {
continue;
}
order_intents.push(OrderIntent::Value {
symbol: symbol.clone(),
value: buy_cash,
reason: "daily_top_up_buy".to_string(),
});
self.project_order_value(
ctx,
&mut projected,
execution_date,
symbol,
buy_cash,
&mut projected_execution_state,
);
break;
}
}
}
if !explicit_action_intents.is_empty() {
order_intents.extend(explicit_action_intents);
}
@@ -4937,7 +4993,7 @@ impl Strategy for PlatformExprStrategy {
)
},
format!(
"selected={} periodic_rebalance={} exits={} projected_positions={} intents={} limit={} decision_date={} execution_date={}",
"selected={} periodic_rebalance={} exits={} projected_positions={} intents={} limit={} decision_date={} selection_factor_date={} execution_date={}",
stock_list.len(),
periodic_rebalance,
exit_symbols.len(),
@@ -4945,8 +5001,10 @@ impl Strategy for PlatformExprStrategy {
order_intents.len(),
selection_limit,
decision_date,
selection_factor_date,
execution_date
),
format!("selected_symbols={}", stock_list.join(",")),
"platform strategy script executed through expression runtime + bid1/ask1 snapshot execution".to_string(),
];
diagnostics.extend(selection_notes);
@@ -6181,6 +6239,8 @@ mod tests {
concat!(
"ma(\"close\", 2) == 11.5",
" && vma(2) == 150.0",
" && rolling_mean_current(\"close\", 2) == 11.7",
" && rolling_mean_current(\"volume\", 2) == 250.0",
" && rolling_sum(\"volume\", 2) == 300.0",
" && rolling_min(\"close\", 2) == 11.0",
" && rolling_max(\"close\", 2) == 12.0",
@@ -6466,6 +6526,172 @@ mod tests {
);
}
#[test]
fn platform_selection_ranks_with_previous_factor_date() {
let prev = d(2025, 1, 2);
let curr = d(2025, 1, 3);
let symbols = ["300001.SZ", "300002.SZ", "000001.SZ"];
let data = DataSet::from_components(
symbols
.iter()
.map(|symbol| Instrument {
symbol: (*symbol).to_string(),
name: (*symbol).to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: None,
status: "active".to_string(),
})
.collect(),
[prev, curr]
.into_iter()
.flat_map(|date| {
symbols.iter().map(move |symbol| DailyMarketSnapshot {
date,
symbol: (*symbol).to_string(),
timestamp: Some("2025-01-03 09:33:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.5,
low: 9.8,
close: 10.0,
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
prev_close: 9.9,
volume: 1_000_000,
tick_volume: 10_000,
bid1_volume: 2_000,
ask1_volume: 2_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
})
})
.collect(),
vec![
DailyFactorSnapshot {
date: prev,
symbol: "300001.SZ".to_string(),
market_cap_bn: 30.0,
free_float_cap_bn: 30.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
DailyFactorSnapshot {
date: prev,
symbol: "300002.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
DailyFactorSnapshot {
date: curr,
symbol: "300001.SZ".to_string(),
market_cap_bn: 10.0,
free_float_cap_bn: 10.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
DailyFactorSnapshot {
date: curr,
symbol: "300002.SZ".to_string(),
market_cap_bn: 30.0,
free_float_cap_bn: 30.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
],
[prev, curr]
.into_iter()
.flat_map(|date| {
["300001.SZ", "300002.SZ"]
.into_iter()
.map(move |symbol| 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,
})
})
.collect(),
[prev, curr]
.into_iter()
.map(|date| BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1002.0,
prev_close: 998.0,
volume: 1_000_000,
})
.collect(),
)
.expect("dataset");
let portfolio = PortfolioState::new(30_000.0);
let subscriptions = BTreeSet::new();
let ctx = StrategyContext {
execution_date: curr,
decision_date: curr,
decision_index: 1,
data: &data,
portfolio: &portfolio,
futures_account: None,
open_orders: &[],
dynamic_universe: None,
subscriptions: &subscriptions,
process_events: &[],
active_process_event: None,
active_datetime: None,
order_events: &[],
fills: &[],
};
let mut cfg = PlatformExprStrategyConfig::microcap_rotation();
cfg.signal_symbol = "000001.SZ".to_string();
cfg.refresh_rate = 99;
cfg.max_positions = 1;
cfg.benchmark_short_ma_days = 1;
cfg.benchmark_long_ma_days = 1;
cfg.market_cap_lower_expr = "0".to_string();
cfg.market_cap_upper_expr = "100".to_string();
cfg.selection_limit_expr = "1".to_string();
cfg.stock_filter_expr = "close > 0".to_string();
cfg.retry_empty_rebalance = true;
let mut strategy = PlatformExprStrategy::new(cfg);
let decision = strategy.on_day(&ctx).expect("platform decision");
assert!(
decision
.diagnostics
.iter()
.any(|item| item.contains("selection_factor_date=2025-01-02")),
"{:?}",
decision.diagnostics
);
assert!(matches!(
decision.order_intents.first(),
Some(crate::strategy::OrderIntent::Value { symbol, .. }) if symbol == "300002.SZ"
));
}
#[test]
fn platform_strategy_emits_target_shares_explicit_action() {
let date = d(2025, 2, 3);

View File

@@ -223,6 +223,7 @@ const RUNTIME_HELPER_FUNCTIONS: &[&str] = &[
"factor",
"day_factor",
"rolling_mean",
"rolling_mean_current",
"ma",
"sma",
"vma",

View File

@@ -551,6 +551,15 @@ impl PortfolioState {
field: PriceField,
) -> Result<(), DataSetError> {
for position in self.positions.values_mut() {
if field == PriceField::Close
&& position.day_buy_quantity > 0
&& position.sellable_qty(date) == 0
&& position.last_price.is_finite()
&& position.last_price > 0.0
{
position.refresh_day_pnl();
continue;
}
let price = data
.price(date, &position.symbol, field)
.or_else(|| data.price_on_or_before(date, &position.symbol, field))
@@ -1066,6 +1075,111 @@ mod tests {
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(buy_date, &dataset, PriceField::Close)
.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);
}
#[test]
fn position_tracks_day_lifecycle_fields() {
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();

View File

@@ -2151,7 +2151,7 @@ impl OmniMicroCapStrategy {
symbol: self.config.benchmark_signal_symbol.clone(),
field: "decision_close",
})?;
// 前一交易日的指数价格(用于市值区间计算,模拟实盘场景)
let prev_level = if let Some(prev_date) = ctx.data.previous_trading_date(date, 1) {
ctx.data
@@ -2160,7 +2160,7 @@ impl OmniMicroCapStrategy {
} else {
current_level
};
let ma_short = ctx
.data
.market_decision_close_moving_average(
@@ -2200,16 +2200,16 @@ impl OmniMicroCapStrategy {
+ self.config.base_cap_floor;
let start = y.round();
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)
}
@@ -2242,8 +2242,9 @@ impl OmniMicroCapStrategy {
};
// 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;
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();
@@ -2253,39 +2254,48 @@ impl OmniMicroCapStrategy {
*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,
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_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);
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 {
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 {
let Some(volume_ma60) = ctx
.data
.market_decision_volume_moving_average(date, symbol, 60)
else {
return false;
};
if volume_ma5 >= volume_ma60 {
return false;
}
@@ -2662,28 +2672,31 @@ impl Strategy for OmniMicroCapStrategy {
});
}
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
Ok(value) => value,
Err(BacktestError::Execution(message))
if message.contains("insufficient benchmark") =>
{
return Ok(StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: Vec::new(),
notes: vec![format!("warmup: {}", message)],
diagnostics: vec![
"insufficient history; skip trading on warmup dates".to_string(),
],
});
}
Err(err) => return Err(err),
};
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) =
match self.trading_ratio(ctx, date) {
Ok(value) => value,
Err(BacktestError::Execution(message))
if message.contains("insufficient benchmark") =>
{
return Ok(StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: Vec::new(),
notes: vec![format!("warmup: {}", message)],
diagnostics: vec![
"insufficient history; skip trading on warmup dates".to_string(),
],
});
}
Err(err) => return Err(err),
};
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
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);
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 periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
let mut projected = ctx.portfolio.clone();

View File

@@ -124,16 +124,16 @@ impl DynamicMarketCapBandSelector {
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
let low = start.round();
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)
}
}

View File

@@ -7,6 +7,108 @@ use fidc_core::{
};
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]
fn broker_executes_explicit_order_value_buy() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -122,6 +224,31 @@ fn broker_executes_explicit_order_value_buy() {
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, 200);
assert_eq!(portfolio.position(symbol).expect("position").quantity, 200);
}
#[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]
fn broker_executes_order_shares_and_order_lots() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
@@ -1438,6 +1565,121 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
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]
fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();