修复止损卖出受限时的目标仓位预判

This commit is contained in:
boris
2026-06-16 10:20:55 +08:00
parent e146ad6e7d
commit 0628dd528a
+202 -4
View File
@@ -312,7 +312,7 @@ fn band_low(index_close) {
} }
} }
#[derive(Default)] #[derive(Default, Clone)]
struct ProjectedExecutionState { struct ProjectedExecutionState {
execution_cursors: BTreeMap<String, NaiveDateTime>, execution_cursors: BTreeMap<String, NaiveDateTime>,
intraday_turnover: BTreeMap<String, u32>, intraday_turnover: BTreeMap<String, u32>,
@@ -1678,6 +1678,27 @@ impl PlatformExprStrategy {
.unwrap_or(true) .unwrap_or(true)
} }
fn projected_target_zero_would_fill(
&self,
ctx: &StrategyContext<'_>,
projected: &PortfolioState,
date: NaiveDate,
symbol: &str,
execution_state: &ProjectedExecutionState,
) -> bool {
let mut trial_projected = projected.clone();
let mut trial_execution_state = execution_state.clone();
self.project_target_zero(
ctx,
&mut trial_projected,
date,
symbol,
&mut trial_execution_state,
)
.is_some()
&& Self::projected_position_is_flat(&trial_projected, symbol)
}
fn projected_position_value_at_execution_price( fn projected_position_value_at_execution_price(
&self, &self,
ctx: &StrategyContext<'_>, ctx: &StrategyContext<'_>,
@@ -6490,13 +6511,19 @@ impl Strategy for PlatformExprStrategy {
} }
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)?;
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
if stop_hit { if stop_hit {
if can_sell { if self.projected_target_zero_would_fill(
ctx,
&projected,
execution_date,
&position.symbol,
&projected_execution_state,
) {
pending_full_close_symbols.insert(position.symbol.clone()); pending_full_close_symbols.insert(position.symbol.clone());
} }
continue; continue;
} }
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
if !can_sell { if !can_sell {
continue; continue;
} }
@@ -6518,7 +6545,15 @@ impl Strategy for PlatformExprStrategy {
} }
} }
if profit_hit { if profit_hit {
pending_full_close_symbols.insert(position.symbol.clone()); if self.projected_target_zero_would_fill(
ctx,
&projected,
execution_date,
&position.symbol,
&projected_execution_state,
) {
pending_full_close_symbols.insert(position.symbol.clone());
}
} }
} }
} }
@@ -12502,6 +12537,169 @@ mod tests {
))); )));
} }
#[test]
fn platform_weak_market_keeps_positive_adjust_when_intraday_stop_loss_sell_blocked() {
let prev_date = d(2025, 2, 2);
let date = d(2025, 2, 3);
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("2025-02-03 10:40:00".to_string()),
day_open: 9.6,
open: 9.6,
high: 9.7,
low: 9.0,
close: 9.5,
last_price: 9.5,
bid1: 9.5,
ask1: 9.51,
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: 1000.0,
volume: 1_000_000,
}],
Vec::new(),
symbols
.iter()
.map(|symbol| IntradayExecutionQuote {
date,
symbol: (*symbol).to_string(),
timestamp: date.and_hms_opt(10, 40, 0).expect("timestamp"),
last_price: 9.0,
bid1: 9.0,
ask1: 9.01,
bid1_volume: 2_000,
ask1_volume: 2_000,
volume_delta: 10_000,
amount_delta: 90_000.0,
trading_phase: Some("continuous".to_string()),
})
.collect(),
)
.expect("dataset");
let mut portfolio = PortfolioState::new(40_000.0);
portfolio
.position_mut("000001.SZ")
.buy(prev_date, 800, 11.0);
let subscriptions = BTreeSet::new();
let ctx = StrategyContext {
execution_date: date,
decision_date: date,
decision_index: 2,
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 = "000001.SZ".to_string();
cfg.refresh_rate = 99;
cfg.max_positions = 2;
cfg.benchmark_short_ma_days = 1;
cfg.benchmark_long_ma_days = 1;
cfg.market_cap_lower_expr = "0".to_string();
cfg.market_cap_upper_expr = "1000".to_string();
cfg.selection_limit_expr = "2".to_string();
cfg.stock_filter_expr = "close > 0".to_string();
cfg.exposure_expr = "0.5".to_string();
cfg.stop_loss_expr = "0.92".to_string();
cfg.take_profit_expr.clear();
cfg.daily_top_up_enabled = true;
cfg.aiquant_transaction_cost = true;
cfg.slippage_model = SlippageModel::PriceRatio(0.002);
cfg.intraday_execution_time = Some(NaiveTime::from_hms_opt(10, 40, 0).expect("time"));
let mut strategy = PlatformExprStrategy::new(cfg);
strategy.rebalance_day_counter = 2;
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
)));
assert!(decision.order_intents.iter().any(|intent| matches!(
intent,
OrderIntent::TargetValue {
symbol,
target_value,
reason,
} if symbol == "000001.SZ" && *target_value == 0.0 && reason == "stop_loss_exit"
)));
}
#[test] #[test]
fn platform_refresh_rate_uses_stateful_aiquant_day_counter() { fn platform_refresh_rate_uses_stateful_aiquant_day_counter() {
let dates = [d(2025, 2, 5), d(2025, 2, 6), d(2025, 2, 7)]; let dates = [d(2025, 2, 5), d(2025, 2, 6), d(2025, 2, 7)];