修复涨停持仓弱市缩仓保护

This commit is contained in:
boris
2026-06-20 18:01:59 +08:00
parent ecb9a1cfaf
commit 6ddbdac9cd
+192 -21
View File
@@ -2176,6 +2176,28 @@ impl PlatformExprStrategy {
} }
} }
fn regular_sell_should_wait_due_to_highlimit(
&mut self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
symbol: &str,
execution_time: NaiveTime,
) -> Result<bool, BacktestError> {
if !self.config.delayed_limit_open_exit_enabled {
return Ok(false);
}
if self.pending_highlimit_holdings.contains(symbol) {
return self.pending_highlimit_sell_should_wait(ctx, date, symbol, execution_time);
}
match self.stock_is_at_upper_limit_at_time(ctx, date, symbol, execution_time)? {
Some(true) => {
self.pending_highlimit_holdings.insert(symbol.to_string());
Ok(true)
}
Some(false) | None => Ok(false),
}
}
fn stock_state_with_factor_date_and_time( fn stock_state_with_factor_date_and_time(
&self, &self,
ctx: &StrategyContext<'_>, ctx: &StrategyContext<'_>,
@@ -6790,6 +6812,14 @@ impl Strategy for PlatformExprStrategy {
{ {
continue; continue;
} }
if self.regular_sell_should_wait_due_to_highlimit(
ctx,
execution_date,
&position.symbol,
self.intraday_execution_start_time(),
)? {
continue;
}
let (stop_hit, profit_hit) = let (stop_hit, profit_hit) =
self.stop_take_action_for_position(ctx, execution_date, &day, position)?; self.stop_take_action_for_position(ctx, execution_date, &day, position)?;
if stop_hit { if stop_hit {
@@ -6838,7 +6868,7 @@ impl Strategy for PlatformExprStrategy {
if position.quantity == 0 || delayed_sold_symbols.contains(&position.symbol) { if position.quantity == 0 || delayed_sold_symbols.contains(&position.symbol) {
continue; continue;
} }
if self.pending_highlimit_sell_should_wait( if self.regular_sell_should_wait_due_to_highlimit(
ctx, ctx,
execution_date, execution_date,
&position.symbol, &position.symbol,
@@ -6917,6 +6947,14 @@ impl Strategy for PlatformExprStrategy {
if projected_position.quantity == 0 || avg_price <= 0.0 { if projected_position.quantity == 0 || avg_price <= 0.0 {
continue; continue;
} }
if self.regular_sell_should_wait_due_to_highlimit(
ctx,
execution_date,
&position.symbol,
self.intraday_execution_start_time(),
)? {
continue;
}
let (stop_hit, profit_hit) = let (stop_hit, profit_hit) =
self.stop_take_action_for_position(ctx, execution_date, &day, projected_position)?; self.stop_take_action_for_position(ctx, execution_date, &day, projected_position)?;
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol); let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
@@ -6948,26 +6986,6 @@ impl Strategy for PlatformExprStrategy {
continue; continue;
} }
if self.config.delayed_limit_open_exit_enabled {
let stock = match self.stock_state_at_time(
ctx,
execution_date,
&position.symbol,
Some(self.intraday_execution_start_time()),
) {
Ok(stock) => stock,
Err(BacktestError::Data(crate::data::DataSetError::MissingSnapshot {
..
})) => continue,
Err(error) => return Err(error),
};
if stock.upper_limit > 0.0 && stock.last >= stock.upper_limit {
self.pending_highlimit_holdings
.insert(position.symbol.clone());
continue;
}
}
if profit_hit { if profit_hit {
exit_symbols.insert(position.symbol.clone()); exit_symbols.insert(position.symbol.clone());
order_intents.push(OrderIntent::TargetValue { order_intents.push(OrderIntent::TargetValue {
@@ -10976,6 +10994,159 @@ mod tests {
assert!(strategy.pending_highlimit_holdings.contains(symbol)); assert!(strategy.pending_highlimit_holdings.contains(symbol));
} }
#[test]
fn platform_aiquant_weak_market_marks_intraday_highlimit_before_target_adjust() {
let prev_date = d(2023, 5, 4);
let date = d(2023, 5, 5);
let symbol = "600148.SH";
let data = DataSet::from_components_with_actions_and_quotes(
vec![Instrument {
symbol: symbol.to_string(),
name: symbol.to_string(),
board: "SH".to_string(),
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: None,
status: "active".to_string(),
}],
vec![DailyMarketSnapshot {
date,
symbol: symbol.to_string(),
timestamp: Some(format!("{date} 10:18:00")),
day_open: 10.8,
open: 10.8,
high: 11.0,
low: 10.7,
close: 11.0,
last_price: 11.0,
bid1: 11.0,
ask1: 11.0,
prev_close: 10.0,
volume: 1_000_000,
tick_volume: 10_000,
bid1_volume: 10_000,
ask1_volume: 10_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
}],
vec![DailyFactorSnapshot {
date,
symbol: symbol.to_string(),
market_cap_bn: 20.0,
free_float_cap_bn: 20.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
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: "000852.SH".to_string(),
open: 1000.0,
close: 1000.0,
prev_close: 999.0,
volume: 1_000_000,
}],
Vec::new(),
vec![
IntradayExecutionQuote {
date,
symbol: symbol.to_string(),
timestamp: date.and_hms_opt(9, 31, 0).expect("timestamp"),
last_price: 10.8,
bid1: 10.8,
ask1: 10.81,
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 108_000.0,
trading_phase: Some("continuous".to_string()),
},
IntradayExecutionQuote {
date,
symbol: symbol.to_string(),
timestamp: date.and_hms_opt(10, 18, 0).expect("timestamp"),
last_price: 11.0,
bid1: 11.0,
ask1: 11.0,
bid1_volume: 10_000,
ask1_volume: 10_000,
volume_delta: 10_000,
amount_delta: 110_000.0,
trading_phase: Some("continuous".to_string()),
},
],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(100_000.0);
portfolio.position_mut(symbol).buy(prev_date, 3_000, 10.0);
portfolio.apply_cash_delta(-30_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 = symbol.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.delayed_limit_open_exit_enabled = true;
cfg.delayed_limit_open_exit_time = Some(NaiveTime::from_hms_opt(9, 31, 0).expect("time"));
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: intent_symbol,
reason,
..
} if intent_symbol == symbol && reason == "daily_position_target_adjust"
)),
"{:?}",
decision.order_intents
);
assert!(strategy.pending_highlimit_holdings.contains(symbol));
}
#[test] #[test]
fn platform_aiquant_weak_market_allows_pending_highlimit_target_adjust_after_open() { fn platform_aiquant_weak_market_allows_pending_highlimit_target_adjust_after_open() {
let prev_date = d(2023, 5, 4); let prev_date = d(2023, 5, 4);