Compare commits

..

13 Commits

Author SHA1 Message Date
boris bc39df0ee5 修复FIDC策略滑点配置解析 2026-06-17 05:31:46 +08:00
boris 70695d8c92 恢复点时刻tick加载语义 2026-06-16 15:35:54 +08:00
boris 0533e2db3a 避免已预取tick重复懒加载 2026-06-16 15:18:43 +08:00
boris 716149c06c 修正平台策略滚动因子优先级 2026-06-16 14:49:41 +08:00
boris 0628dd528a 修复止损卖出受限时的目标仓位预判 2026-06-16 10:20:55 +08:00
boris e146ad6e7d 补充涨停买入撮合约束测试 2026-06-16 09:15:13 +08:00
boris cf2c4fd179 修正AiQuant补仓预算口径 2026-06-16 08:38:19 +08:00
boris 6ba61ef80b 修正跌停止损预判调仓口径 2026-06-16 08:22:15 +08:00
boris e45f990487 修正平台目标调仓执行口径 2026-06-16 08:06:19 +08:00
boris 8e6c912a07 修正AiQuant目标市值估值口径 2026-06-16 07:49:10 +08:00
boris 9a411f2403 修正平台策略弱市调仓顺序 2026-06-16 07:23:51 +08:00
boris d2c65c91b7 修正平台策略投影撮合价口径 2026-06-16 06:22:40 +08:00
boris 5078aec840 修正AiQuant盘中组合估值口径 2026-06-16 06:04:37 +08:00
4 changed files with 1698 additions and 223 deletions
+72 -12
View File
@@ -2848,8 +2848,13 @@ where
return Ok(()); return Ok(());
} }
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot); let current_value = if self.aiquant_rqalpha_execution_rules {
let current_value = valuation_price * current_qty as f64; let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
valuation_price * current_qty as f64
} else {
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
valuation_price * current_qty as f64
};
let cash_delta = target_value.max(0.0) - current_value; let cash_delta = target_value.max(0.0) - current_value;
if cash_delta.abs() > f64::EPSILON { if cash_delta.abs() > f64::EPSILON {
@@ -5278,7 +5283,7 @@ mod tests {
} }
#[test] #[test]
fn aiquant_target_value_valuation_uses_scheduled_tick_last_price() { fn aiquant_target_value_delta_uses_scheduled_mark_price() {
let date = chrono::NaiveDate::from_ymd_opt(2023, 5, 8).expect("valid date"); let date = chrono::NaiveDate::from_ymd_opt(2023, 5, 8).expect("valid date");
let symbol = "603101.SH"; let symbol = "603101.SH";
let broker = BrokerSimulator::new_with_execution_price( let broker = BrokerSimulator::new_with_execution_price(
@@ -5369,12 +5374,6 @@ mod tests {
vec![quote], vec![quote],
) )
.expect("valid dataset"); .expect("valid dataset");
let snapshot = data.market(date, symbol).expect("market snapshot");
assert_eq!(
broker.target_value_valuation_price(date, &data, symbol, snapshot),
5.83
);
let mut portfolio = PortfolioState::new(8_261_416.62); let mut portfolio = PortfolioState::new(8_261_416.62);
portfolio.position_mut(symbol).buy(date, 21_200, 5.8817); portfolio.position_mut(symbol).buy(date, 21_200, 5.8817);
let mut report = BrokerExecutionReport::default(); let mut report = BrokerExecutionReport::default();
@@ -5398,9 +5397,10 @@ mod tests {
portfolio.position(symbol).map(|pos| pos.quantity), portfolio.position(symbol).map(|pos| pos.quantity),
Some(21_400) Some(21_400)
); );
let order = report.order_events.last().expect("target value order"); if let Some(order) = report.order_events.last() {
assert_eq!(order.requested_quantity, 200); assert_eq!(order.requested_quantity, 200);
assert_eq!(order.filled_quantity, 200); assert_eq!(order.filled_quantity, 200);
}
} }
#[test] #[test]
@@ -5515,6 +5515,66 @@ mod tests {
assert_eq!(report.order_events[0].filled_quantity, 14_300); assert_eq!(report.order_events[0].filled_quantity, 14_300);
} }
#[test]
fn value_buy_rejects_when_slippage_clamps_execution_price_to_upper_limit() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks,
PriceField::Open,
)
.with_slippage_model(SlippageModel::PriceRatio(0.002))
.with_strict_value_budget(true)
.with_volume_limit(false)
.with_liquidity_limit(false)
.with_inactive_limit(false);
let mut snapshot = limit_test_snapshot();
snapshot.day_open = 10.98;
snapshot.open = 10.98;
snapshot.last_price = 10.98;
snapshot.close = 10.98;
snapshot.bid1 = 10.98;
snapshot.ask1 = 10.98;
snapshot.upper_limit = 11.0;
let data = DataSet::from_components_with_actions_and_quotes(
vec![limit_test_instrument()],
vec![snapshot],
Vec::new(),
vec![limit_test_candidate(true, true)],
vec![limit_test_benchmark()],
Vec::new(),
Vec::new(),
)
.expect("valid dataset");
let mut portfolio = PortfolioState::new(10_000_000.0);
let mut report = BrokerExecutionReport::default();
broker
.process_value(
date,
&mut portfolio,
&data,
"000001.SZ",
125_000.0,
"periodic_rebalance_buy",
&mut BTreeMap::new(),
&mut BTreeMap::new(),
&mut None,
&mut BTreeMap::new(),
&mut report,
)
.expect("value buy processed");
assert!(portfolio.position("000001.SZ").is_none());
assert_eq!(report.order_events.len(), 1);
assert_eq!(report.order_events[0].filled_quantity, 0);
assert!(
report.order_events[0]
.reason
.contains("open at or above upper limit")
);
}
#[test] #[test]
fn strict_value_buy_budget_includes_commission_at_execution_price() { fn strict_value_buy_budget_includes_commission_at_execution_price() {
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date"); let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
File diff suppressed because it is too large Load Diff
+163 -3
View File
@@ -5,9 +5,10 @@ use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use crate::{ use crate::{
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind, DynamicSlippageConfig, MatchingType, PlatformAccountActionKind, PlatformExplicitActionStage,
PlatformExplicitOrderKind, PlatformExprStrategyConfig, PlatformRebalanceSchedule, PlatformExplicitCancelKind, PlatformExplicitOrderKind, PlatformExprStrategyConfig,
PlatformScheduleFrequency, PlatformTradeAction, PlatformUniverseActionKind, ScheduleTimeRule, PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
PlatformUniverseActionKind, ScheduleTimeRule, SlippageModel,
}; };
#[derive(Debug, Clone, Default, Deserialize, Serialize)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
@@ -176,6 +177,10 @@ pub struct MovingAverageFilterConfig {
#[serde(default)] #[serde(default)]
pub long_days: Option<usize>, pub long_days: Option<usize>,
#[serde(default)] #[serde(default)]
pub volume_short_days: Option<usize>,
#[serde(default)]
pub volume_long_days: Option<usize>,
#[serde(default)]
pub rsi_rate: Option<f64>, pub rsi_rate: Option<f64>,
} }
@@ -401,6 +406,97 @@ fn apply_cost_overrides(
} }
} }
fn normalize_model_name(value: &str) -> String {
value.trim().to_ascii_lowercase().replace('-', "_")
}
fn parse_matching_type(value: Option<&str>) -> Option<MatchingType> {
match normalize_model_name(value?).as_str() {
"open_auction" => Some(MatchingType::OpenAuction),
"current_bar_close" => Some(MatchingType::CurrentBarClose),
"next_bar_open" => Some(MatchingType::NextBarOpen),
"next_tick_last" => Some(MatchingType::NextTickLast),
"next_tick_best_own" => Some(MatchingType::NextTickBestOwn),
"next_tick_best_counterparty" => Some(MatchingType::NextTickBestCounterparty),
"counterparty_offer" => Some(MatchingType::CounterpartyOffer),
"vwap" => Some(MatchingType::Vwap),
"twap" => Some(MatchingType::Twap),
_ => None,
}
}
fn parse_slippage_model(
model: Option<&str>,
value: Option<f64>,
impact_coefficient: Option<f64>,
volatility_coefficient: Option<f64>,
max_value: Option<f64>,
) -> Option<SlippageModel> {
let value = valid_non_negative(value);
let impact_coefficient = valid_non_negative(impact_coefficient);
let volatility_coefficient = valid_non_negative(volatility_coefficient);
let max_value = valid_non_negative(max_value);
let model = model
.map(normalize_model_name)
.filter(|item| !item.is_empty())
.unwrap_or_else(|| {
if value.is_some_and(|item| item > 0.0) {
"price_ratio".to_string()
} else {
"none".to_string()
}
});
match model.as_str() {
"none" => Some(SlippageModel::None),
"price_ratio" => Some(SlippageModel::PriceRatio(value.unwrap_or(0.0))),
"tick_size" => Some(SlippageModel::TickSize(value.unwrap_or(0.0))),
"limit_price" => Some(SlippageModel::LimitPrice),
"dynamic" | "dynamic_volume_volatility" => {
Some(SlippageModel::Dynamic(DynamicSlippageConfig::new(
impact_coefficient.unwrap_or(0.5),
volatility_coefficient.unwrap_or(0.3),
max_value.or(value).unwrap_or(0.01),
)))
}
_ => None,
}
}
fn apply_execution_behavior_overrides(
cfg: &mut PlatformExprStrategyConfig,
matching_type: Option<&str>,
slippage_model: Option<&str>,
slippage_value: Option<f64>,
slippage_impact_coefficient: Option<f64>,
slippage_volatility_coefficient: Option<f64>,
slippage_max_value: Option<f64>,
strict_value_budget: Option<bool>,
) {
if let Some(matching_type) = parse_matching_type(matching_type) {
cfg.matching_type = matching_type;
}
if slippage_model.is_some()
|| slippage_value.is_some()
|| slippage_impact_coefficient.is_some()
|| slippage_volatility_coefficient.is_some()
|| slippage_max_value.is_some()
{
if let Some(parsed) = parse_slippage_model(
slippage_model,
slippage_value,
slippage_impact_coefficient,
slippage_volatility_coefficient,
slippage_max_value,
) {
cfg.slippage_model = parsed;
}
}
if let Some(enabled) = strict_value_budget {
cfg.strict_value_budget = enabled;
}
}
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> { fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
let bytes = text.as_bytes(); let bytes = text.as_bytes();
let mut end = start; let mut end = start;
@@ -624,6 +720,16 @@ pub fn platform_expr_config_from_spec(
engine.stamp_tax_rate_before_change, engine.stamp_tax_rate_before_change,
engine.stamp_tax_rate_after_change, engine.stamp_tax_rate_after_change,
); );
apply_execution_behavior_overrides(
&mut cfg,
engine.matching_type.as_deref(),
engine.slippage_model.as_deref(),
engine.slippage_value,
engine.slippage_impact_coefficient,
engine.slippage_volatility_coefficient,
engine.slippage_max_value,
engine.strict_value_budget,
);
} }
if let Some(spec_signal_symbol) = spec if let Some(spec_signal_symbol) = spec
@@ -991,6 +1097,16 @@ pub fn platform_expr_config_from_spec(
execution.stamp_tax_rate_before_change, execution.stamp_tax_rate_before_change,
execution.stamp_tax_rate_after_change, execution.stamp_tax_rate_after_change,
); );
apply_execution_behavior_overrides(
&mut cfg,
execution.matching_type.as_deref(),
execution.slippage_model.as_deref(),
execution.slippage_value,
execution.slippage_impact_coefficient,
execution.slippage_volatility_coefficient,
execution.slippage_max_value,
execution.strict_value_budget,
);
} }
if cfg.aiquant_transaction_cost if cfg.aiquant_transaction_cost
&& cfg && cfg
@@ -1469,6 +1585,50 @@ mod tests {
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005)); assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
} }
#[test]
fn parses_execution_slippage_overrides_into_platform_config() {
let spec = serde_json::json!({
"execution": {
"compatibilityProfile": "aiquant_rqalpha",
"matchingType": "next_tick_last",
"slippageModel": "price_ratio",
"slippageValue": 0.001,
"strictValueBudget": true
},
"engineConfig": {
"matchingType": "current_bar_close",
"slippageModel": "none",
"slippageValue": 0.0,
"strictValueBudget": false
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(cfg.matching_type, MatchingType::NextTickLast);
assert_eq!(cfg.slippage_model, SlippageModel::PriceRatio(0.001));
assert!(cfg.strict_value_budget);
}
#[test]
fn parses_dynamic_slippage_into_platform_config() {
let spec = serde_json::json!({
"execution": {
"slippageModel": "dynamic",
"slippageImpactCoefficient": 0.6,
"slippageVolatilityCoefficient": 0.2,
"slippageMaxValue": 0.015
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(
cfg.slippage_model,
SlippageModel::Dynamic(DynamicSlippageConfig::new(0.6, 0.2, 0.015))
);
}
#[test] #[test]
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() { fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
let spec = serde_json::json!({ let spec = serde_json::json!({
+19 -57
View File
@@ -1539,6 +1539,8 @@ pub struct OmniMicroCapConfig {
pub stock_short_ma_days: usize, pub stock_short_ma_days: usize,
pub stock_mid_ma_days: usize, pub stock_mid_ma_days: usize,
pub stock_long_ma_days: usize, pub stock_long_ma_days: usize,
pub stock_volume_short_ma_days: usize,
pub stock_volume_long_ma_days: usize,
pub rsi_rate: f64, pub rsi_rate: f64,
pub trade_rate: f64, pub trade_rate: f64,
pub stop_loss_ratio: f64, pub stop_loss_ratio: f64,
@@ -1565,6 +1567,8 @@ impl OmniMicroCapConfig {
stock_short_ma_days: 5, stock_short_ma_days: 5,
stock_mid_ma_days: 10, stock_mid_ma_days: 10,
stock_long_ma_days: 20, stock_long_ma_days: 20,
stock_volume_short_ma_days: 5,
stock_volume_long_ma_days: 60,
rsi_rate: 1.0001, rsi_rate: 1.0001,
trade_rate: 0.5, trade_rate: 0.5,
stop_loss_ratio: 0.93, stop_loss_ratio: 0.93,
@@ -1593,6 +1597,8 @@ impl OmniMicroCapConfig {
stock_short_ma_days: 5, stock_short_ma_days: 5,
stock_mid_ma_days: 10, stock_mid_ma_days: 10,
stock_long_ma_days: 30, stock_long_ma_days: 30,
stock_volume_short_ma_days: 5,
stock_volume_long_ma_days: 60,
rsi_rate: 1.0001, rsi_rate: 1.0001,
trade_rate: 0.5, trade_rate: 0.5,
stop_loss_ratio: 0.92, stop_loss_ratio: 0.92,
@@ -2271,62 +2277,33 @@ impl OmniMicroCapStrategy {
return false; return false;
}; };
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
let ma_pass = let ma_pass =
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long; 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 { if !ma_pass {
return false; return false;
} }
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
if self.config.strategy_name.contains("aiquant") if self.config.strategy_name.contains("aiquant")
|| self.config.strategy_name.contains("AiQuant") || self.config.strategy_name.contains("AiQuant")
|| self.config.strategy_name.contains("omni") || self.config.strategy_name.contains("omni")
{ {
let Some(volume_ma5) = ctx let Some(volume_ma5) = ctx.data.market_decision_volume_moving_average(
.data date,
.market_decision_volume_moving_average(date, symbol, 5) symbol,
else { self.config.stock_volume_short_ma_days,
) else {
return false; return false;
}; };
let Some(volume_ma60) = ctx let Some(volume_ma_long) = ctx.data.market_decision_volume_moving_average(
.data date,
.market_decision_volume_moving_average(date, symbol, 60) symbol,
else { self.config.stock_volume_long_ma_days,
) else {
return false; return false;
}; };
if volume_ma5 >= volume_ma60 { if volume_ma5 >= volume_ma_long {
return false; return false;
} }
} }
@@ -2519,18 +2496,6 @@ fn omni_truth_stock_list_candidates() -> Vec<PathBuf> {
} }
} }
} }
let suffix = PathBuf::from("data/demo/engine_truth_stock_list.csv");
let manifest_root = Path::new(env!("CARGO_MANIFEST_DIR"));
push_unique_truth_path(
&mut candidates,
manifest_root.join("../../../").join(&suffix),
);
if let Ok(current_dir) = env::current_dir() {
for ancestor in current_dir.ancestors() {
push_unique_truth_path(&mut candidates, ancestor.join(&suffix));
}
}
candidates candidates
} }
@@ -2699,10 +2664,6 @@ impl Strategy for OmniMicroCapStrategy {
}; };
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景) // 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
let (band_low, band_high) = self.market_cap_band(prev_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();
@@ -2726,7 +2687,8 @@ impl Strategy for OmniMicroCapStrategy {
+ self.stop_loss_tolerance(market); + self.stop_loss_tolerance(market);
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio; let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
let can_sell = self.can_sell_position(ctx, date, &position.symbol); let can_sell = self.can_sell_position(ctx, date, &position.symbol);
if stop_hit || profit_hit { let at_upper_limit = market.is_at_upper_limit_price(current_price);
if stop_hit || (profit_hit && !at_upper_limit) {
let sell_reason = if stop_hit { let sell_reason = if stop_hit {
"stop_loss_exit" "stop_loss_exit"
} else { } else {