Compare commits

...

3 Commits

Author SHA1 Message Date
boris 27e523a1dc 仅在成功清仓后释放目标权重 2026-09-07 04:01:25 +08:00
boris f9d9f06d3f 统一每日目标组合执行路径 2026-09-07 04:01:25 +08:00
boris d45f39f1bf 统一止盈退出后的目标权重重分配 2026-09-07 04:01:25 +08:00
+263 -86
View File
@@ -178,6 +178,121 @@ impl PlatformPortfolioDrawdownController {
}
}
fn ordered_weight_bps_from_scales(
scales: &[(String, f64)],
) -> Result<Vec<(String, u32)>, BacktestError> {
if scales.is_empty() {
return Ok(Vec::new());
}
if scales
.iter()
.any(|(_, scale)| !scale.is_finite() || *scale < 0.0)
{
return Err(BacktestError::Execution(
"target portfolio buy scale must be finite and non-negative".to_string(),
));
}
let scale_total = scales.iter().map(|(_, scale)| *scale).sum::<f64>();
if !scale_total.is_finite() || scale_total <= 0.0 {
return Err(BacktestError::Execution(
"target portfolio buy scale total must be positive".to_string(),
));
}
let mut weights = scales
.iter()
.map(|(symbol, scale)| {
(
symbol.clone(),
((*scale / scale_total * 10_000.0) + 1e-9).floor() as u32,
)
})
.collect::<Vec<_>>();
let assigned = weights.iter().map(|(_, weight)| *weight).sum::<u32>();
let remainder = 10_000_u32.saturating_sub(assigned);
let weight_count = weights.len();
for index in 0..remainder as usize {
weights[index % weight_count].1 += 1;
}
Ok(weights)
}
fn replenish_target_weight_bps(
original_weights: &[(String, u32)],
candidate_symbols: &[String],
excluded_symbols: &BTreeSet<String>,
target_count: usize,
) -> Vec<(String, u32)> {
let original_by_symbol = original_weights.iter().cloned().collect::<BTreeMap<_, _>>();
let mut active = original_weights
.iter()
.filter(|(symbol, weight)| *weight > 0 && !excluded_symbols.contains(symbol))
.map(|(symbol, _)| symbol.clone())
.collect::<Vec<_>>();
let mut seen = active.iter().cloned().collect::<BTreeSet<_>>();
let mut promoted = Vec::new();
for symbol in candidate_symbols {
if active.len() >= target_count {
break;
}
if excluded_symbols.contains(symbol) || !seen.insert(symbol.clone()) {
continue;
}
active.push(symbol.clone());
promoted.push(symbol.clone());
}
if active.is_empty() {
return Vec::new();
}
let mut result = active
.iter()
.map(|symbol| {
(
symbol.clone(),
*original_by_symbol.get(symbol).unwrap_or(&0),
)
})
.collect::<Vec<_>>();
let assigned = result.iter().map(|(_, weight)| *weight).sum::<u32>();
let missing = 10_000_u32.saturating_sub(assigned);
if missing == 0 {
return result;
}
let recipients = if promoted.is_empty() {
active
} else {
promoted
};
let base_total = recipients
.iter()
.map(|symbol| *original_by_symbol.get(symbol).unwrap_or(&0))
.sum::<u32>();
let mut allocated = recipients
.iter()
.map(|symbol| {
if base_total > 0 {
(u64::from(missing) * u64::from(*original_by_symbol.get(symbol).unwrap_or(&0))
/ u64::from(base_total)) as u32
} else {
missing / recipients.len() as u32
}
})
.collect::<Vec<_>>();
let allocated_total = allocated.iter().sum::<u32>();
let recipient_count = allocated.len();
for index in 0..missing.saturating_sub(allocated_total) as usize {
allocated[index % recipient_count] += 1;
}
let additions = recipients
.into_iter()
.zip(allocated)
.collect::<BTreeMap<_, _>>();
for (symbol, weight) in &mut result {
*weight += additions.get(symbol).copied().unwrap_or(0);
}
result
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SelectionRiskDeferral {
None,
@@ -1110,6 +1225,7 @@ pub struct PlatformExprStrategy {
rebalance_day_counter: usize,
last_rebalance_date: Option<NaiveDate>,
last_target_selection: Option<BTreeSet<String>>,
last_target_order: Option<Vec<String>>,
last_trading_ratio: Option<f64>,
portfolio_drawdown_controller: Option<PlatformPortfolioDrawdownController>,
pending_highlimit_holdings: BTreeSet<String>,
@@ -1444,6 +1560,7 @@ impl PlatformExprStrategy {
rebalance_day_counter: 0,
last_rebalance_date: None,
last_target_selection: None,
last_target_order: None,
last_trading_ratio: None,
portfolio_drawdown_controller,
pending_highlimit_holdings: BTreeSet::new(),
@@ -12416,15 +12533,51 @@ impl Strategy for PlatformExprStrategy {
}
let stop_take_exit_signal_symbols = current_stop_take_exit_symbols.clone();
let original_target_weights =
if self.config.target_portfolio_daily_enabled && selection_limit > 0 {
let mut scales = Vec::new();
let original_target_symbols = self
.last_target_order
.as_ref()
.filter(|symbols| !symbols.is_empty())
.cloned()
.or_else(|| {
self.last_target_selection
.as_ref()
.filter(|symbols| !symbols.is_empty())
.map(|symbols| symbols.iter().cloned().collect())
})
.unwrap_or_else(|| stock_list.iter().take(selection_limit).cloned().collect());
for symbol in original_target_symbols.iter().take(selection_limit) {
let decision_stock = self.stock_state_with_factor_date(
ctx,
decision_date,
selection_factor_date,
symbol,
)?;
scales.push((symbol.clone(), self.buy_scale(ctx, &day, &decision_stock)?));
}
ordered_weight_bps_from_scales(&scales)?
} else {
Vec::new()
};
let target_portfolio_weights = replenish_target_weight_bps(
&original_target_weights,
&stock_list,
&exit_symbols,
selection_limit,
);
let target_portfolio_weight_bps = target_portfolio_weights
.iter()
.cloned()
.collect::<BTreeMap<_, _>>();
if self.config.rotation_enabled
&& self.config.daily_position_target_adjust_enabled
&& trading_ratio > 0.0
&& (self.config.target_portfolio_daily_enabled || trading_ratio < 1.0)
&& selection_limit > 0
&& !(persistent_model_lifecycle
&& self.config.target_portfolio_daily_enabled
&& daily_top_up_active)
&& !(self.config.target_portfolio_daily_enabled && daily_top_up_active)
&& (!ctx.portfolio.positions().is_empty()
|| (persistent_model_lifecycle && !self.position_entry_dates.is_empty()))
{
@@ -12457,9 +12610,24 @@ impl Strategy for PlatformExprStrategy {
&position.symbol,
)?;
let stock_scale = self.buy_scale(ctx, &day, &decision_stock)?;
let target_value = strategy_visible_total_value * trading_ratio
/ selection_limit as f64
* stock_scale;
let target_value = if self.config.target_portfolio_daily_enabled {
target_portfolio_weight_bps
.get(&position.symbol)
.map(|weight_bps| {
strategy_visible_total_value
* trading_ratio
* f64::from(*weight_bps)
/ 10_000.0
})
.unwrap_or(
strategy_visible_total_value * trading_ratio
/ selection_limit as f64
* stock_scale,
)
} else {
strategy_visible_total_value * trading_ratio / selection_limit as f64
* stock_scale
};
if !target_value.is_finite() || target_value <= 0.0 {
continue;
}
@@ -12558,9 +12726,24 @@ impl Strategy for PlatformExprStrategy {
&symbol,
)?;
let stock_scale = self.buy_scale(ctx, &day, &decision_stock)?;
let target_value = strategy_visible_total_value * trading_ratio
/ selection_limit as f64
* stock_scale;
let target_value = if self.config.target_portfolio_daily_enabled {
target_portfolio_weight_bps
.get(&symbol)
.map(|weight_bps| {
strategy_visible_total_value
* trading_ratio
* f64::from(*weight_bps)
/ 10_000.0
})
.unwrap_or(
strategy_visible_total_value * trading_ratio
/ selection_limit as f64
* stock_scale,
)
} else {
strategy_visible_total_value * trading_ratio / selection_limit as f64
* stock_scale
};
if !target_value.is_finite() || target_value <= 0.0 {
continue;
}
@@ -12962,46 +13145,17 @@ impl Strategy for PlatformExprStrategy {
}
}
if daily_top_up_active
&& self.config.target_portfolio_daily_enabled
&& persistent_model_lifecycle
{
let mut target_symbols = self
.position_entry_dates
.keys()
.filter(|symbol| !exit_symbols.contains(*symbol))
.filter(|symbol| !factor_position_action_symbols.contains(*symbol))
.cloned()
.collect::<BTreeSet<_>>();
for symbol in &stock_list {
if target_symbols.len() >= selection_limit {
break;
}
if target_symbols.contains(symbol) || exit_symbols.contains(symbol) {
continue;
}
if ctx
.data
.market_latest_back_adjusted_close(signal_date, symbol)
.is_none()
{
continue;
}
self.remember_position_entry_date(symbol, signal_date);
target_symbols.insert(symbol.clone());
}
for symbol in target_symbols {
let decision_stock = self.stock_state_with_factor_date(
ctx,
decision_date,
selection_factor_date,
&symbol,
)?;
let stock_scale = self.buy_scale(ctx, &day, &decision_stock)?;
let target_value = strategy_visible_total_value * trading_ratio
/ selection_limit as f64
* stock_scale;
let daily_target_portfolio_weights = replenish_target_weight_bps(
&original_target_weights,
&stock_list,
&same_day_sold_symbols,
selection_limit,
);
if daily_top_up_active && self.config.target_portfolio_daily_enabled {
for (symbol, weight_bps) in &daily_target_portfolio_weights {
let target_value =
strategy_visible_total_value * trading_ratio * f64::from(*weight_bps)
/ 10_000.0;
if !target_value.is_finite() || target_value <= 0.0 {
continue;
}
@@ -13029,6 +13183,7 @@ impl Strategy for PlatformExprStrategy {
&mut projected_execution_state,
);
intraday_attempted_buys.insert(symbol.clone());
self.remember_position_entry_date(symbol, signal_date);
}
let after_qty = projected
.position(&symbol)
@@ -13043,40 +13198,9 @@ impl Strategy for PlatformExprStrategy {
deferred_daily_target_values.insert(symbol.clone(), target_value);
}
if after_qty > before_qty {
same_bar_buy_symbols.insert(symbol);
same_bar_buy_symbols.insert(symbol.clone());
}
}
} else if daily_top_up_active && self.config.target_portfolio_daily_enabled {
self.try_daily_top_up_at_position(
ctx,
&day,
&stock_list,
decision_date,
execution_date,
projection_date,
selection_factor_date,
signal_date,
daily_top_up_target_budget,
selection_limit,
defer_execution_risk,
None,
&mut projected,
&mut projected_execution_state,
&mut order_intents,
&mut available_cash,
&mut slot_working_symbols,
&mut same_bar_buy_symbols,
&pending_full_close_symbols,
&slot_blocking_symbols,
&same_day_sold_symbols,
&exit_symbols,
&delayed_sold_symbols,
&mut intraday_attempted_buys,
&mut daily_top_up_pending_buy_value,
&deferred_daily_target_values,
debug_daily_top_up,
&mut daily_top_up_debug_notes,
)?;
}
if periodic_rebalance {
@@ -13166,7 +13290,10 @@ impl Strategy for PlatformExprStrategy {
if !rebalance_existing_positions {
continue;
}
let target_value = target_budget / selection_limit as f64 * stock_scale;
let target_value = target_portfolio_weight_bps
.get(symbol)
.map(|weight_bps| target_budget * f64::from(*weight_bps) / 10_000.0)
.unwrap_or(target_budget / selection_limit as f64 * stock_scale);
let before_qty = projected
.position(symbol)
.map(|position| position.quantity)
@@ -13218,7 +13345,10 @@ impl Strategy for PlatformExprStrategy {
{
continue;
}
let target_value = fixed_buy_cash * stock_scale;
let target_value = target_portfolio_weight_bps
.get(symbol)
.map(|weight_bps| target_budget * f64::from(*weight_bps) / 10_000.0)
.unwrap_or(fixed_buy_cash * stock_scale);
if target_value <= 0.0 {
continue;
}
@@ -13271,8 +13401,13 @@ impl Strategy for PlatformExprStrategy {
}
}
if self.config.rotation_enabled && periodic_rebalance {
self.last_target_selection =
Some(stock_list.iter().take(selection_limit).cloned().collect());
let target_order = stock_list
.iter()
.take(selection_limit)
.cloned()
.collect::<Vec<_>>();
self.last_target_selection = Some(target_order.iter().cloned().collect());
self.last_target_order = Some(target_order);
}
if self.config.rotation_enabled && trading_ratio.is_finite() {
self.last_trading_ratio = Some(trading_ratio);
@@ -13444,7 +13579,8 @@ mod tests {
PlatformScheduleFrequency, PlatformStopTakeReferencePriceMode, PlatformTradeAction,
PlatformUniverseActionKind, RuntimeHelperResolution, SelectionRiskDeferral,
StockFilterQuoteUsage, StockRollingField, StockSnapshotFieldRequirements,
framework_stock_rolling_factor_requirement, scheduled_position_exposure,
framework_stock_rolling_factor_requirement, ordered_weight_bps_from_scales,
replenish_target_weight_bps, scheduled_position_exposure,
};
use crate::{
AlgoOrderStyle, BenchmarkSnapshot, CandidateEligibility, CorporateAction,
@@ -13460,6 +13596,39 @@ mod tests {
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
}
#[test]
fn target_weight_replenishment_matches_integer_bps_pool_contract() {
let scales = (0..24)
.map(|index| {
(
format!("S{index:02}"),
if index < 16 { 1.0008 } else { 0.9984 },
)
})
.collect::<Vec<_>>();
let original = ordered_weight_bps_from_scales(&scales).expect("weights");
let excluded = BTreeSet::from(["S01".to_string()]);
let candidates = scales
.iter()
.map(|(symbol, _)| symbol.clone())
.collect::<Vec<_>>();
let replenished = replenish_target_weight_bps(&original, &candidates, &excluded, 24);
let by_symbol = replenished.iter().cloned().collect::<BTreeMap<_, _>>();
assert_eq!(replenished.len(), 23);
assert_eq!(
replenished.iter().map(|(_, weight)| *weight).sum::<u32>(),
10_000
);
assert_eq!(by_symbol.get("S00"), Some(&436));
assert_eq!(by_symbol.get("S02"), Some(&436));
assert_eq!(by_symbol.get("S03"), Some(&436));
assert_eq!(by_symbol.get("S04"), Some(&435));
assert_eq!(by_symbol.get("S16"), Some(&434));
assert!(!by_symbol.contains_key("S01"));
}
fn single_symbol_platform_data(dates: &[NaiveDate], symbol: &str) -> DataSet {
DataSet::from_components(
vec![Instrument {
@@ -27557,6 +27726,14 @@ mod tests {
let mut strategy = PlatformExprStrategy::new(cfg);
strategy.rebalance_day_counter = 2;
strategy.last_rebalance_date = Some(prev_date);
let target_order = vec![
buy_first.to_string(),
buy_second.to_string(),
keep_first.to_string(),
keep_second.to_string(),
];
strategy.last_target_selection = Some(target_order.iter().cloned().collect());
strategy.last_target_order = Some(target_order);
strategy
.position_entry_dates
.insert(take_profit.to_string(), prev_date);