修正弱市缩仓阈值语义

This commit is contained in:
boris
2026-06-18 11:39:13 +08:00
parent 4f39ac7dfe
commit d7c1674c6c
2 changed files with 224 additions and 6 deletions
+193 -6
View File
@@ -208,6 +208,7 @@ pub struct PlatformExprStrategyConfig {
pub daily_top_up_enabled: bool,
pub retry_empty_rebalance: bool,
pub calendar_rebalance_interval: bool,
pub weak_market_shrink_overweight_threshold: Option<f64>,
pub aiquant_transaction_cost: bool,
pub commission_rate: Option<f64>,
pub minimum_commission: Option<f64>,
@@ -277,6 +278,7 @@ fn band_low(index_close) {
daily_top_up_enabled: false,
retry_empty_rebalance: false,
calendar_rebalance_interval: false,
weak_market_shrink_overweight_threshold: None,
aiquant_transaction_cost: false,
commission_rate: None,
minimum_commission: None,
@@ -6659,34 +6661,53 @@ impl Strategy for PlatformExprStrategy {
if position.quantity == 0 || delayed_sold_symbols.contains(&position.symbol) {
continue;
}
if pending_full_close_symbols.contains(&position.symbol) {
continue;
}
let current_value = self.projected_position_value_at_execution_price(
ctx,
&projected,
execution_date,
&position.symbol,
);
if pending_full_close_symbols.contains(&position.symbol)
&& target_value > current_value + f64::EPSILON
if let Some(threshold) = self
.config
.weak_market_shrink_overweight_threshold
.filter(|value| value.is_finite() && *value > 0.0)
{
continue;
if current_value <= target_value * threshold {
continue;
}
}
let before_qty = projected
.position(&position.symbol)
.map(|projected_position| projected_position.quantity)
.unwrap_or(0);
let mut trial_projected = projected.clone();
let mut trial_execution_state = projected_execution_state.clone();
self.project_target_value(
ctx,
&mut projected,
&mut trial_projected,
execution_date,
&position.symbol,
target_value,
&mut projected_execution_state,
&mut trial_execution_state,
);
let after_qty = projected
let after_qty = trial_projected
.position(&position.symbol)
.map(|projected_position| projected_position.quantity)
.unwrap_or(0);
let quantity_delta = after_qty as i32 - before_qty as i32;
if self
.config
.weak_market_shrink_overweight_threshold
.is_some()
&& quantity_delta >= 0
{
continue;
}
projected = trial_projected;
projected_execution_state = trial_execution_state;
if quantity_delta != 0 {
order_intents.push(OrderIntent::Shares {
symbol: position.symbol.clone(),
@@ -9615,6 +9636,172 @@ mod tests {
)));
}
#[test]
fn platform_aiquant_weak_market_threshold_only_sells_overweight_positions() {
let prev_date = d(2023, 5, 4);
let date = d(2023, 5, 5);
let symbols = ["000001.SZ", "000002.SZ"];
let data = DataSet::from_components_with_actions_and_quotes(
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(),
symbols
.iter()
.map(|symbol| DailyMarketSnapshot {
date,
symbol: (*symbol).to_string(),
timestamp: Some(format!("{date} 10:18:00")),
day_open: 10.0,
open: 10.0,
high: 10.2,
low: 9.8,
close: 10.0,
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
prev_close: 10.0,
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(),
symbols
.iter()
.enumerate()
.map(|(index, symbol)| DailyFactorSnapshot {
date,
symbol: (*symbol).to_string(),
market_cap_bn: 10.0 + index as f64,
free_float_cap_bn: 10.0 + index as f64,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
})
.collect(),
symbols
.iter()
.map(|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(),
vec![BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 999.0,
volume: 1_000_000,
}],
Vec::new(),
symbols
.iter()
.map(|symbol| IntradayExecutionQuote {
date,
symbol: (*symbol).to_string(),
timestamp: date.and_hms_opt(10, 18, 0).expect("timestamp"),
last_price: 10.0,
bid1: 10.0,
ask1: 10.01,
bid1_volume: 10,
ask1_volume: 10,
volume_delta: 10_000,
amount_delta: 100_000.0,
trading_phase: Some("continuous".to_string()),
})
.collect(),
)
.expect("dataset");
let mut portfolio = PortfolioState::new(100_000.0);
portfolio
.position_mut("000001.SZ")
.buy(prev_date, 3_000, 10.0);
portfolio
.position_mut("000002.SZ")
.buy(prev_date, 2_400, 10.0);
portfolio.apply_cash_delta(-54_000.0);
let subscriptions = BTreeSet::new();
let ctx = StrategyContext {
execution_date: date,
decision_date: date,
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.aiquant_transaction_cost = true;
cfg.signal_symbol = "000001.SZ".to_string();
cfg.max_positions = 2;
cfg.selection_limit_expr = "2".to_string();
cfg.market_cap_lower_expr = "0".to_string();
cfg.market_cap_upper_expr = "1000".to_string();
cfg.stock_filter_expr = "false".to_string();
cfg.exposure_expr = "0.5".to_string();
cfg.stop_loss_expr.clear();
cfg.take_profit_expr.clear();
cfg.weak_market_shrink_overweight_threshold = Some(1.10);
cfg.intraday_execution_time = Some(NaiveTime::from_hms_opt(10, 18, 0).expect("time"));
let mut strategy = PlatformExprStrategy::new(cfg);
strategy.rebalance_day_counter = 1;
let decision = strategy.on_day(&ctx).expect("platform decision");
assert!(
decision.order_intents.iter().any(|intent| matches!(
intent,
OrderIntent::Shares {
symbol,
quantity,
reason,
} if symbol == "000001.SZ"
&& reason == "daily_position_target_adjust"
&& *quantity < 0
)),
"{:?}",
decision.order_intents
);
assert!(!decision.order_intents.iter().any(|intent| matches!(
intent,
OrderIntent::Shares {
symbol,
reason,
..
} if symbol == "000002.SZ" && reason == "daily_position_target_adjust"
)));
}
#[test]
fn platform_aiquant_weak_market_does_not_retarget_same_ratio_every_day() {
let first_date = d(2023, 5, 4);
@@ -140,6 +140,8 @@ pub struct StrategyEngineConfig {
#[serde(default)]
pub dividend_reinvestment: Option<bool>,
#[serde(default)]
pub weak_market_shrink_overweight_threshold: Option<f64>,
#[serde(default)]
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
#[serde(default)]
pub skip_windows: Vec<SkipWindowConfig>,
@@ -300,6 +302,8 @@ pub struct StrategyExpressionTradingConfig {
#[serde(default)]
pub retry_empty_rebalance: Option<bool>,
#[serde(default)]
pub weak_market_shrink_overweight_threshold: Option<f64>,
#[serde(default)]
pub delayed_limit_open_exit: Option<bool>,
#[serde(default)]
pub delayed_limit_open_exit_time: Option<String>,
@@ -661,6 +665,12 @@ pub fn platform_expr_config_from_spec(
if let Some(refresh_rate) = engine.refresh_rate.filter(|value| *value > 0) {
cfg.refresh_rate = refresh_rate;
}
if let Some(threshold) = engine
.weak_market_shrink_overweight_threshold
.filter(|value| value.is_finite() && *value > 0.0)
{
cfg.weak_market_shrink_overweight_threshold = Some(threshold);
}
if let Some(schedule) = engine
.rebalance_schedule
.as_ref()
@@ -941,6 +951,12 @@ pub fn platform_expr_config_from_spec(
if let Some(enabled) = trading.retry_empty_rebalance {
cfg.retry_empty_rebalance = enabled;
}
if let Some(threshold) = trading
.weak_market_shrink_overweight_threshold
.filter(|value| value.is_finite() && *value > 0.0)
{
cfg.weak_market_shrink_overweight_threshold = Some(threshold);
}
if let Some(enabled) = trading.release_slot_on_exit_signal {
cfg.release_slot_on_exit_signal = enabled;
}
@@ -1569,6 +1585,7 @@ mod tests {
"rotationEnabled": false,
"dailyTopUp": true,
"retryEmptyRebalance": true,
"weakMarketShrinkOverweightThreshold": 1.1,
"stage": "open_auction",
"actions": [
{
@@ -1592,6 +1609,7 @@ mod tests {
assert!(!cfg.rotation_enabled);
assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance);
assert_eq!(cfg.weak_market_shrink_overweight_threshold, Some(1.1));
assert!(!cfg.calendar_rebalance_interval);
assert!(cfg.aiquant_transaction_cost);
assert_eq!(cfg.explicit_actions.len(), 1);
@@ -1601,6 +1619,19 @@ mod tests {
);
}
#[test]
fn engine_config_parses_weak_market_shrink_overweight_threshold() {
let spec = serde_json::json!({
"engineConfig": {
"weakMarketShrinkOverweightThreshold": 1.2
}
});
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
assert_eq!(cfg.weak_market_shrink_overweight_threshold, Some(1.2));
}
#[test]
fn parses_execution_cost_overrides_into_platform_config() {
let spec = serde_json::json!({