修复FiRisk禁持清仓判定

This commit is contained in:
boris
2026-06-20 19:51:38 +08:00
parent 144483be4c
commit 816fc48077
+188 -2
View File
@@ -5937,6 +5937,35 @@ impl PlatformExprStrategy {
self.can_sell_position_at_time(ctx, date, symbol, None)
}
fn candidate_requires_firisk_forced_exit(
&self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
symbol: &str,
execution_time: NaiveTime,
) -> Result<bool, BacktestError> {
let Ok(candidate) = ctx.data.require_candidate(date, symbol) else {
return Ok(false);
};
if candidate.allow_buy || !candidate.allow_sell || candidate.is_paused {
return Ok(false);
}
if !self.can_sell_position(ctx, date, symbol) {
return Ok(false);
}
let stock = match self.stock_state_at_time(ctx, date, symbol, Some(execution_time)) {
Ok(stock) => stock,
Err(BacktestError::Data(crate::data::DataSetError::MissingSnapshot { .. })) => {
return Ok(false);
}
Err(error) => return Err(error),
};
if stock.upper_limit > 0.0 && stock.last >= stock.upper_limit {
return Ok(false);
}
Ok(true)
}
fn can_sell_position_at_time(
&self,
ctx: &StrategyContext<'_>,
@@ -6633,6 +6662,7 @@ impl Strategy for PlatformExprStrategy {
let mut intraday_attempted_buys = BTreeSet::<String>::new();
let mut delayed_sold_symbols = BTreeSet::<String>::new();
let mut unresolved_stop_loss_symbols = BTreeSet::<String>::new();
let mut pending_firisk_forced_exit_symbols = BTreeSet::<String>::new();
let delayed_limit_exit_time = self
.config
.delayed_limit_open_exit_time
@@ -6820,6 +6850,16 @@ impl Strategy for PlatformExprStrategy {
)? {
continue;
}
if self.candidate_requires_firisk_forced_exit(
ctx,
execution_date,
&position.symbol,
self.intraday_execution_start_time(),
)? {
pending_full_close_symbols.insert(position.symbol.clone());
pending_firisk_forced_exit_symbols.insert(position.symbol.clone());
continue;
}
let (stop_hit, profit_hit) =
self.stop_take_action_for_position(ctx, execution_date, &day, position)?;
if stop_hit {
@@ -6854,6 +6894,32 @@ impl Strategy for PlatformExprStrategy {
}
}
for symbol in pending_firisk_forced_exit_symbols {
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: "risk_forced_exit".to_string(),
});
if self
.project_target_zero(
ctx,
&mut projected,
execution_date,
&symbol,
&mut projected_execution_state,
)
.is_some()
&& Self::projected_position_is_flat(&projected, &symbol)
{
same_day_sold_symbols.insert(symbol.clone());
slot_working_symbols.remove(&symbol);
}
}
if self.config.aiquant_transaction_cost
&& self.config.rotation_enabled
&& trading_ratio > 0.0
@@ -10676,7 +10742,119 @@ mod tests {
}
#[test]
fn platform_aiquant_buy_disabled_does_not_force_exit_existing_position() {
fn platform_aiquant_upper_limit_buy_disabled_does_not_force_exit_existing_position() {
let date = d(2023, 5, 5);
let symbol = "300621.SZ";
let data = DataSet::from_components(
vec![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(),
}],
vec![DailyMarketSnapshot {
date,
symbol: symbol.to_string(),
timestamp: Some(format!("{date} 10:18:00")),
day_open: 10.0,
open: 10.0,
high: 11.44,
low: 9.8,
close: 11.44,
last_price: 11.44,
bid1: 11.44,
ask1: 0.0,
prev_close: 10.4,
volume: 200_000,
tick_volume: 1_000,
bid1_volume: 2_000,
ask1_volume: 2_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.44,
lower_limit: 9.36,
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: false,
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,
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000_000.0);
portfolio
.position_mut(symbol)
.buy(d(2023, 5, 4), 30_000, 10.0);
portfolio.apply_cash_delta(-300_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.exposure_expr = "1.0".to_string();
cfg.selection_limit_expr = "40".to_string();
cfg.stock_filter_expr = "true".to_string();
cfg.stop_loss_expr.clear();
cfg.take_profit_expr.clear();
let mut strategy = PlatformExprStrategy::new(cfg);
let decision = strategy.on_day(&ctx).expect("platform decision");
assert!(!decision.order_intents.iter().any(|intent| matches!(
intent,
OrderIntent::TargetValue {
symbol: intent_symbol,
target_value,
reason,
} if intent_symbol == symbol && *target_value == 0.0 && reason == "risk_forced_exit"
)));
}
#[test]
fn platform_aiquant_firisk_buy_disabled_forces_existing_position_exit() {
let date = d(2023, 5, 5);
let symbol = "300621.SZ";
let data = DataSet::from_components(
@@ -10777,7 +10955,7 @@ mod tests {
let decision = strategy.on_day(&ctx).expect("platform decision");
assert!(!decision.order_intents.iter().any(|intent| matches!(
assert!(decision.order_intents.iter().any(|intent| matches!(
intent,
OrderIntent::TargetValue {
symbol: intent_symbol,
@@ -10785,6 +10963,14 @@ mod tests {
reason,
} if intent_symbol == symbol && *target_value == 0.0 && reason == "risk_forced_exit"
)));
assert!(!decision.order_intents.iter().any(|intent| matches!(
intent,
OrderIntent::Shares {
symbol: intent_symbol,
reason,
..
} if intent_symbol == symbol && reason == "daily_position_target_adjust"
)));
}
#[test]