diff --git a/crates/fidc-core/src/platform_expr_strategy.rs b/crates/fidc-core/src/platform_expr_strategy.rs index abb1267..ae754e9 100644 --- a/crates/fidc-core/src/platform_expr_strategy.rs +++ b/crates/fidc-core/src/platform_expr_strategy.rs @@ -6407,40 +6407,21 @@ impl Strategy for PlatformExprStrategy { fn on_day(&mut self, ctx: &StrategyContext<'_>) -> Result { let execution_date = ctx.execution_date; let decision_date = ctx.decision_date; - if self.config.in_skip_window(execution_date) { - return Ok(StrategyDecision { - rebalance: false, - target_weights: BTreeMap::new(), - exit_symbols: ctx.portfolio.positions().keys().cloned().collect(), - order_intents: ctx - .portfolio - .positions() - .keys() - .cloned() - .map(|symbol| OrderIntent::TargetValue { - symbol, - target_value: 0.0, - reason: "seasonal_stop_window".to_string(), - }) - .collect(), - notes: vec![format!("seasonal stop window on {}", execution_date)], - diagnostics: vec!["platform expr skip window forced all cash".to_string()], - }); - } + let in_skip_window = self.config.in_skip_window(execution_date); let day = self.day_state(ctx, decision_date)?; let (selection_market_date, selection_universe_factor_date, selection_factor_date) = self.selection_dates(ctx); - let (explicit_action_intents, explicit_action_diagnostics) = - if self.config.explicit_action_stage == PlatformExplicitActionStage::OnDay - && self.explicit_actions_active(ctx.data.calendar(), execution_date) - { - self.explicit_action_intents(ctx, decision_date, &day)? - } else { - (Vec::new(), Vec::new()) - }; + let (explicit_action_intents, explicit_action_diagnostics) = if !in_skip_window + && self.config.explicit_action_stage == PlatformExplicitActionStage::OnDay + && self.explicit_actions_active(ctx.data.calendar(), execution_date) + { + self.explicit_action_intents(ctx, decision_date, &day)? + } else { + (Vec::new(), Vec::new()) + }; let mut selection_notes = Vec::new(); - let trading_ratio = if self.config.rotation_enabled { + let trading_ratio = if self.config.rotation_enabled && !in_skip_window { self.trading_ratio(ctx, &day)? } else { 0.0 @@ -6457,18 +6438,18 @@ impl Strategy for PlatformExprStrategy { } else { ctx.portfolio.total_value() }; - let (band_low, band_high) = if self.config.rotation_enabled { + let (band_low, band_high) = if self.config.rotation_enabled && !in_skip_window { self.market_cap_band(ctx, &day)? } else { (0.0, 0.0) }; - let selection_limit = if self.config.rotation_enabled { + let selection_limit = if self.config.rotation_enabled && !in_skip_window { self.selection_limit(ctx, &day)? .min(self.config.max_positions.max(1)) } else { 0 }; - let stock_list = if self.config.rotation_enabled { + let stock_list = if self.config.rotation_enabled && !in_skip_window { let (stock_list, notes) = self.select_symbols( ctx, selection_market_date, @@ -6487,7 +6468,7 @@ impl Strategy for PlatformExprStrategy { let empty_rebalance_retry = self.config.retry_empty_rebalance && ctx.portfolio.positions().is_empty(); let effective_refresh_rate = self.effective_refresh_rate(ctx, &day)?; - let periodic_rebalance = if self.config.rotation_enabled { + let periodic_rebalance = if self.config.rotation_enabled && !in_skip_window { if let Some(schedule) = &self.config.rebalance_schedule { schedule.matches( ctx.data.calendar(), @@ -6630,6 +6611,38 @@ impl Strategy for PlatformExprStrategy { } } + if in_skip_window { + for symbol in ctx.portfolio.positions().keys() { + if delayed_sold_symbols.contains(symbol) { + continue; + } + exit_symbols.insert(symbol.clone()); + order_intents.push(OrderIntent::TargetValue { + symbol: symbol.clone(), + target_value: 0.0, + reason: "seasonal_stop_window".to_string(), + }); + } + let mut notes = vec![format!("seasonal stop window on {}", execution_date)]; + if !delayed_sold_symbols.is_empty() { + notes.push(format!( + "delayed limit open sells before seasonal stop: {}", + delayed_sold_symbols.len() + )); + } + return Ok(StrategyDecision { + rebalance: false, + target_weights: BTreeMap::new(), + exit_symbols, + order_intents, + notes, + diagnostics: vec![ + "platform expr skip window forced all cash after delayed open exits" + .to_string(), + ], + }); + } + let mut aiquant_available_cash = if delayed_sold_symbols.is_empty() { ctx.portfolio.cash() } else { @@ -8498,6 +8511,295 @@ mod tests { assert!(strategy.pending_highlimit_holdings.is_empty()); } + #[test] + fn platform_skip_window_runs_delayed_open_exit_before_seasonal_liquidation() { + let prev_date = d(2024, 1, 12); + let date = d(2024, 1, 15); + let delayed_symbol = "605081.SH"; + let other_symbol = "002001.SZ"; + let signal_symbol = "000001.SH"; + let data = DataSet::from_components_with_actions_and_quotes( + vec![ + Instrument { + symbol: delayed_symbol.to_string(), + name: delayed_symbol.to_string(), + board: "SH".to_string(), + round_lot: 100, + listed_at: Some(d(2020, 1, 1)), + delisted_at: None, + status: "active".to_string(), + }, + Instrument { + symbol: other_symbol.to_string(), + name: other_symbol.to_string(), + board: "SZ".to_string(), + round_lot: 100, + listed_at: Some(d(2020, 1, 1)), + delisted_at: None, + status: "active".to_string(), + }, + Instrument { + symbol: signal_symbol.to_string(), + name: signal_symbol.to_string(), + board: "SH".to_string(), + round_lot: 100, + listed_at: Some(d(1990, 12, 19)), + delisted_at: None, + status: "active".to_string(), + }, + ], + vec![ + DailyMarketSnapshot { + date, + symbol: delayed_symbol.to_string(), + timestamp: Some("2024-01-15 10:18:00".to_string()), + day_open: 14.63, + open: 14.63, + high: 14.70, + low: 14.42, + close: 14.50, + last_price: 14.50, + bid1: 14.50, + ask1: 14.51, + prev_close: 13.30, + volume: 200_000, + tick_volume: 1_000, + bid1_volume: 1_000, + ask1_volume: 1_000, + trading_phase: Some("continuous".to_string()), + paused: false, + upper_limit: 14.63, + lower_limit: 11.97, + price_tick: 0.01, + }, + DailyMarketSnapshot { + date, + symbol: other_symbol.to_string(), + timestamp: Some("2024-01-15 10:18:00".to_string()), + day_open: 8.00, + open: 8.00, + high: 8.10, + low: 7.90, + close: 8.02, + last_price: 8.02, + bid1: 8.01, + ask1: 8.02, + prev_close: 7.95, + volume: 200_000, + tick_volume: 1_000, + bid1_volume: 1_000, + ask1_volume: 1_000, + trading_phase: Some("continuous".to_string()), + paused: false, + upper_limit: 8.75, + lower_limit: 7.16, + price_tick: 0.01, + }, + DailyMarketSnapshot { + date, + symbol: signal_symbol.to_string(), + timestamp: Some("2024-01-15 10:18:00".to_string()), + day_open: 2900.0, + open: 2900.0, + high: 2910.0, + low: 2890.0, + close: 2905.0, + last_price: 2905.0, + bid1: 2905.0, + ask1: 2905.1, + prev_close: 2898.0, + volume: 1_000_000, + tick_volume: 1_000, + bid1_volume: 1_000, + ask1_volume: 1_000, + trading_phase: Some("continuous".to_string()), + paused: false, + upper_limit: 0.0, + lower_limit: 0.0, + price_tick: 0.01, + }, + ], + vec![ + DailyFactorSnapshot { + date, + symbol: delayed_symbol.to_string(), + market_cap_bn: 24.0, + free_float_cap_bn: 6.0, + pe_ttm: 8.0, + turnover_ratio: Some(20.0), + effective_turnover_ratio: Some(20.0), + extra_factors: BTreeMap::new(), + }, + DailyFactorSnapshot { + date, + symbol: other_symbol.to_string(), + market_cap_bn: 23.0, + free_float_cap_bn: 5.0, + pe_ttm: 8.0, + turnover_ratio: Some(20.0), + effective_turnover_ratio: Some(20.0), + extra_factors: BTreeMap::new(), + }, + ], + vec![ + CandidateEligibility { + date, + symbol: delayed_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, + }, + CandidateEligibility { + date, + symbol: other_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: "932000.CSI".to_string(), + open: 1000.0, + close: 1002.0, + prev_close: 998.0, + volume: 1_000_000, + }], + Vec::new(), + vec![ + IntradayExecutionQuote { + date, + symbol: delayed_symbol.to_string(), + timestamp: date.and_hms_opt(9, 31, 0).expect("valid timestamp"), + last_price: 14.62, + bid1: 14.61, + ask1: 14.62, + bid1_volume: 1_000, + ask1_volume: 1_000, + volume_delta: 10_000, + amount_delta: 146_200.0, + trading_phase: Some("continuous".to_string()), + }, + IntradayExecutionQuote { + date, + symbol: delayed_symbol.to_string(), + timestamp: date.and_hms_opt(10, 18, 0).expect("valid timestamp"), + last_price: 14.50, + bid1: 14.50, + ask1: 14.51, + bid1_volume: 1_000, + ask1_volume: 1_000, + volume_delta: 10_000, + amount_delta: 145_000.0, + trading_phase: Some("continuous".to_string()), + }, + IntradayExecutionQuote { + date, + symbol: other_symbol.to_string(), + timestamp: date.and_hms_opt(10, 18, 0).expect("valid timestamp"), + last_price: 8.02, + bid1: 8.01, + ask1: 8.02, + bid1_volume: 1_000, + ask1_volume: 1_000, + volume_delta: 10_000, + amount_delta: 80_200.0, + trading_phase: Some("continuous".to_string()), + }, + ], + ) + .expect("dataset"); + let mut portfolio = PortfolioState::new(1_000_000.0); + portfolio + .position_mut(delayed_symbol) + .buy(prev_date, 3_800, 13.30); + portfolio + .position_mut(other_symbol) + .buy(prev_date, 5_000, 7.95); + let subscriptions = BTreeSet::new(); + let ctx = StrategyContext { + execution_date: date, + decision_date: date, + decision_index: 20, + 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 = signal_symbol.to_string(); + cfg.benchmark_symbol = "932000.CSI".to_string(); + cfg.aiquant_transaction_cost = true; + cfg.intraday_execution_time = Some(NaiveTime::from_hms_opt(10, 18, 0).unwrap()); + cfg.delayed_limit_open_exit_enabled = true; + cfg.delayed_limit_open_exit_time = Some(NaiveTime::from_hms_opt(9, 31, 0).unwrap()); + cfg.skip_month_day_ranges = vec![(Some(2024), 1, 15, 31)]; + let mut strategy = PlatformExprStrategy::new(cfg); + strategy + .pending_highlimit_holdings + .insert(delayed_symbol.to_string()); + + let decision = strategy.on_day(&ctx).expect("platform decision"); + + assert!( + decision.order_intents.iter().any(|intent| matches!( + intent, + OrderIntent::AlgoValue { + symbol, + reason, + start_time, + .. + } if symbol == delayed_symbol + && reason == "delayed_limit_open_sell" + && *start_time == Some(NaiveTime::from_hms_opt(9, 31, 0).unwrap()) + )), + "{:?}", + decision.order_intents + ); + assert!( + decision.order_intents.iter().any(|intent| matches!( + intent, + OrderIntent::TargetValue { + symbol, + target_value, + reason, + } if symbol == other_symbol + && *target_value == 0.0 + && reason == "seasonal_stop_window" + )), + "{:?}", + decision.order_intents + ); + assert!( + !decision.order_intents.iter().any(|intent| matches!( + intent, + OrderIntent::TargetValue { + symbol, + reason, + .. + } if symbol == delayed_symbol && reason == "seasonal_stop_window" + )), + "{:?}", + decision.order_intents + ); + assert!(!strategy.pending_highlimit_holdings.contains(delayed_symbol)); + } + #[test] fn platform_aiquant_marks_highlimit_before_cptrade_time() { let prev_date = d(2024, 3, 1); @@ -8947,7 +9249,9 @@ mod tests { .expect("dataset"); let mut portfolio = PortfolioState::new(1_000_000.0); portfolio.position_mut(symbol).buy(prev_date, 100, 10.0); - portfolio.position_mut(symbol).record_buy_trade_cost(100, 1.0); + portfolio + .position_mut(symbol) + .record_buy_trade_cost(100, 1.0); let position = portfolio.position(symbol).expect("position"); assert!((position.average_entry_price().unwrap() - 10.0).abs() < 1e-12); assert!((position.average_cost - 10.01).abs() < 1e-12);