2 Commits

Author SHA1 Message Date
boris
ce49301b98 修复平台策略次日开盘未来函数 2026-04-30 00:53:45 -07:00
boris
e5439956eb 修复平台表达式嵌套三元执行 2026-04-30 03:57:43 +08:00

View File

@@ -2993,26 +2993,33 @@ impl PlatformExprStrategy {
}
fn rewrite_ternary(expr: &str) -> String {
let Some((question_idx, colon_idx)) = Self::find_top_level_ternary(expr) else {
return expr.trim().to_string();
let trimmed = expr.trim();
let Some((condition_start, question_idx, colon_idx, false_end)) =
Self::find_ternary_span(trimmed)
else {
return trimmed.to_string();
};
let condition = Self::rewrite_ternary(expr[..question_idx].trim());
let when_true = Self::rewrite_ternary(expr[question_idx + 1..colon_idx].trim());
let when_false = Self::rewrite_ternary(expr[colon_idx + 1..].trim());
format!(
"if {} {{ {} }} else {{ {} }}",
let condition = Self::rewrite_ternary(trimmed[condition_start..question_idx].trim());
let when_true = Self::rewrite_ternary(trimmed[question_idx + 1..colon_idx].trim());
let when_false = Self::rewrite_ternary(trimmed[colon_idx + 1..false_end].trim());
let mut rewritten = String::new();
rewritten.push_str(&trimmed[..condition_start]);
rewritten.push_str(&format!(
"(if {} {{ {} }} else {{ {} }})",
condition, when_true, when_false
)
));
rewritten.push_str(&trimmed[false_end..]);
Self::rewrite_ternary(&rewritten)
}
fn find_top_level_ternary(expr: &str) -> Option<(usize, usize)> {
fn find_ternary_span(expr: &str) -> Option<(usize, usize, usize, usize)> {
let mut paren_depth = 0i32;
let mut brace_depth = 0i32;
let mut bracket_depth = 0i32;
let mut in_single_quote = false;
let mut in_double_quote = false;
let mut escaped = false;
let mut question_stack = Vec::new();
let mut question_stack: Vec<(usize, i32, i32, i32)> = Vec::new();
for (idx, ch) in expr.char_indices() {
if escaped {
@@ -3036,13 +3043,25 @@ impl PlatformExprStrategy {
'}' => brace_depth -= 1,
'[' => bracket_depth += 1,
']' => bracket_depth -= 1,
'?' if paren_depth == 0 && brace_depth == 0 && bracket_depth == 0 => {
question_stack.push(idx);
'?' => {
question_stack.push((idx, paren_depth, brace_depth, bracket_depth));
}
':' if paren_depth == 0 && brace_depth == 0 && bracket_depth == 0 => {
if let Some(question_idx) = question_stack.pop() {
if question_stack.is_empty() {
return Some((question_idx, idx));
':' => {
if let Some(&(question_idx, question_paren, question_brace, question_bracket)) =
question_stack.last()
{
if question_paren == paren_depth
&& question_brace == brace_depth
&& question_bracket == bracket_depth
{
question_stack.pop();
let condition_start = Self::find_ternary_condition_start(
expr,
question_idx,
question_paren,
);
let false_end = Self::find_ternary_false_end(expr, idx, paren_depth);
return Some((condition_start, question_idx, idx, false_end));
}
}
}
@@ -3052,6 +3071,96 @@ impl PlatformExprStrategy {
None
}
fn find_ternary_condition_start(
expr: &str,
question_idx: usize,
ternary_paren_depth: i32,
) -> usize {
let mut paren_depth = 0i32;
let mut brace_depth = 0i32;
let mut bracket_depth = 0i32;
let mut in_single_quote = false;
let mut in_double_quote = false;
let mut escaped = false;
let mut start = 0usize;
for (idx, ch) in expr.char_indices() {
if idx >= question_idx {
break;
}
if escaped {
escaped = false;
continue;
}
match ch {
'\\' if in_single_quote || in_double_quote => escaped = true,
'\'' if !in_double_quote => in_single_quote = !in_single_quote,
'"' if !in_single_quote => in_double_quote = !in_double_quote,
_ if in_single_quote || in_double_quote => {}
'(' => {
let next_depth = paren_depth + 1;
paren_depth += 1;
if next_depth == ternary_paren_depth && brace_depth == 0 && bracket_depth == 0 {
start = idx + ch.len_utf8();
}
}
')' => paren_depth -= 1,
'{' => brace_depth += 1,
'}' => brace_depth -= 1,
'[' => bracket_depth += 1,
']' => bracket_depth -= 1,
',' if paren_depth == 0 && brace_depth == 0 && bracket_depth == 0 => {
start = idx + ch.len_utf8();
}
_ => {}
}
}
start
}
fn find_ternary_false_end(expr: &str, colon_idx: usize, ternary_paren_depth: i32) -> usize {
let mut paren_depth = ternary_paren_depth;
let mut brace_depth = 0i32;
let mut bracket_depth = 0i32;
let mut in_single_quote = false;
let mut in_double_quote = false;
let mut escaped = false;
for (idx, ch) in expr[colon_idx + 1..].char_indices() {
let absolute_idx = colon_idx + 1 + idx;
if escaped {
escaped = false;
continue;
}
match ch {
'\\' if in_single_quote || in_double_quote => escaped = true,
'\'' if !in_double_quote => in_single_quote = !in_single_quote,
'"' if !in_single_quote => in_double_quote = !in_double_quote,
_ if in_single_quote || in_double_quote => {}
'(' => paren_depth += 1,
')' => {
if paren_depth == ternary_paren_depth && brace_depth == 0 && bracket_depth == 0
{
return absolute_idx;
}
paren_depth -= 1;
}
'{' => brace_depth += 1,
'}' => brace_depth -= 1,
'[' => bracket_depth += 1,
']' => bracket_depth -= 1,
',' if paren_depth == ternary_paren_depth
&& brace_depth == 0
&& bracket_depth == 0 =>
{
return absolute_idx;
}
_ => {}
}
}
expr.len()
}
fn eval_float(
&self,
ctx: &StrategyContext<'_>,
@@ -4263,7 +4372,8 @@ impl PlatformExprStrategy {
fn stop_take_action(
&self,
ctx: &StrategyContext<'_>,
date: NaiveDate,
signal_date: NaiveDate,
execution_date: NaiveDate,
day: &DayExpressionState,
symbol: &str,
) -> Result<(bool, bool), BacktestError> {
@@ -4278,7 +4388,7 @@ impl PlatformExprStrategy {
if position.quantity == 0 || position.average_cost <= 0.0 {
return Ok((false, false));
}
let stock = match self.stock_state(ctx, date, symbol) {
let stock = match self.stock_state(ctx, signal_date, symbol) {
Ok(stock) => stock,
Err(BacktestError::Data(crate::data::DataSetError::MissingSnapshot { .. })) => {
return Ok((false, false));
@@ -4305,9 +4415,9 @@ impl PlatformExprStrategy {
prev_close: stock.prev_close,
holding_return,
quantity: position.quantity as i64,
sellable_qty: position.sellable_qty(date) as i64,
sellable: position.sellable_qty(date) as i64,
closable: position.sellable_qty(date) as i64,
sellable_qty: position.sellable_qty(execution_date) as i64,
sellable: position.sellable_qty(execution_date) as i64,
closable: position.sellable_qty(execution_date) as i64,
old_quantity: position.day_start_quantity() as i64,
bought_quantity: position.bought_quantity() as i64,
sold_quantity: position.sold_quantity() as i64,
@@ -4361,12 +4471,12 @@ impl PlatformExprStrategy {
boolean
} else if let Some(multiplier) = take_result.clone().try_cast::<f64>() {
!ctx.data
.require_market(date, symbol)?
.require_market(signal_date, symbol)?
.is_at_upper_limit_price(current_price)
&& current_price / position.average_cost > multiplier
} else if let Some(multiplier) = take_result.try_cast::<i64>() {
!ctx.data
.require_market(date, symbol)?
.require_market(signal_date, symbol)?
.is_at_upper_limit_price(current_price)
&& current_price / position.average_cost > multiplier as f64
} else {
@@ -4396,8 +4506,9 @@ impl Strategy for PlatformExprStrategy {
}
fn on_day(&mut self, ctx: &StrategyContext<'_>) -> Result<StrategyDecision, BacktestError> {
let date = ctx.execution_date;
if self.config.in_skip_window(date) {
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(),
@@ -4413,17 +4524,17 @@ impl Strategy for PlatformExprStrategy {
reason: "seasonal_stop_window".to_string(),
})
.collect(),
notes: vec![format!("seasonal stop window on {}", date)],
notes: vec![format!("seasonal stop window on {}", execution_date)],
diagnostics: vec!["platform expr skip window forced all cash".to_string()],
});
}
let day = self.day_state(ctx, date)?;
let day = self.day_state(ctx, decision_date)?;
let (explicit_action_intents, explicit_action_diagnostics) =
if self.config.explicit_action_stage == PlatformExplicitActionStage::OnDay
&& self.explicit_actions_active(ctx.data.calendar(), date)
&& self.explicit_actions_active(ctx.data.calendar(), execution_date)
{
self.explicit_action_intents(ctx, date, &day)?
self.explicit_action_intents(ctx, decision_date, &day)?
} else {
(Vec::new(), Vec::new())
};
@@ -4445,8 +4556,14 @@ impl Strategy for PlatformExprStrategy {
0
};
let stock_list = if self.config.rotation_enabled {
let (stock_list, notes) =
self.select_symbols(ctx, date, &day, band_low, band_high, selection_limit)?;
let (stock_list, notes) = self.select_symbols(
ctx,
decision_date,
&day,
band_low,
band_high,
selection_limit,
)?;
selection_notes = notes;
stock_list
} else {
@@ -4456,7 +4573,7 @@ impl Strategy for PlatformExprStrategy {
if let Some(schedule) = &self.config.rebalance_schedule {
schedule.matches(
ctx.data.calendar(),
date,
execution_date,
ScheduleStage::OnDay,
default_stage_time(ScheduleStage::OnDay),
)
@@ -4476,8 +4593,8 @@ impl Strategy for PlatformExprStrategy {
continue;
}
let (stop_hit, profit_hit) =
self.stop_take_action(ctx, date, &day, &position.symbol)?;
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
self.stop_take_action(ctx, decision_date, execution_date, &day, &position.symbol)?;
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
if stop_hit || profit_hit {
let sell_reason = if stop_hit {
"stop_loss_exit"
@@ -4494,7 +4611,7 @@ impl Strategy for PlatformExprStrategy {
self.project_target_zero(
ctx,
&mut projected,
date,
execution_date,
&position.symbol,
&mut projected_execution_state,
);
@@ -4511,18 +4628,24 @@ impl Strategy for PlatformExprStrategy {
{
continue;
}
let stock = self.stock_state(ctx, date, symbol)?;
let decision_stock = self.stock_state(ctx, decision_date, symbol)?;
let execution_stock = self.stock_state(ctx, execution_date, symbol)?;
if self
.buy_rejection_reason(ctx, date, symbol, &stock)?
.buy_rejection_reason(
ctx,
execution_date,
symbol,
&execution_stock,
)?
.is_some()
{
continue;
}
if !self.stock_passes_expr(ctx, &day, &stock)? {
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
continue;
}
let replacement_cash =
replacement_cash * self.buy_scale(ctx, &day, &stock)?;
replacement_cash * self.buy_scale(ctx, &day, &decision_stock)?;
if replacement_cash <= 0.0 {
continue;
}
@@ -4534,7 +4657,7 @@ impl Strategy for PlatformExprStrategy {
self.project_order_value(
ctx,
&mut projected,
date,
execution_date,
symbol,
replacement_cash,
&mut projected_execution_state,
@@ -4556,7 +4679,7 @@ impl Strategy for PlatformExprStrategy {
if stock_list.iter().any(|candidate| candidate == symbol) {
continue;
}
if !self.can_sell_position(ctx, date, symbol) {
if !self.can_sell_position(ctx, execution_date, symbol) {
continue;
}
order_intents.push(OrderIntent::TargetValue {
@@ -4567,7 +4690,7 @@ impl Strategy for PlatformExprStrategy {
self.project_target_zero(
ctx,
&mut projected,
date,
execution_date,
symbol,
&mut projected_execution_state,
);
@@ -4583,17 +4706,18 @@ impl Strategy for PlatformExprStrategy {
{
continue;
}
let stock = self.stock_state(ctx, date, symbol)?;
let decision_stock = self.stock_state(ctx, decision_date, symbol)?;
let execution_stock = self.stock_state(ctx, execution_date, symbol)?;
if self
.buy_rejection_reason(ctx, date, symbol, &stock)?
.buy_rejection_reason(ctx, execution_date, symbol, &execution_stock)?
.is_some()
{
continue;
}
if !self.stock_passes_expr(ctx, &day, &stock)? {
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
continue;
}
let buy_cash = fixed_buy_cash * self.buy_scale(ctx, &day, &stock)?;
let buy_cash = fixed_buy_cash * self.buy_scale(ctx, &day, &decision_stock)?;
if buy_cash <= 0.0 {
continue;
}
@@ -4605,7 +4729,7 @@ impl Strategy for PlatformExprStrategy {
self.project_order_value(
ctx,
&mut projected,
date,
execution_date,
symbol,
buy_cash,
&mut projected_execution_state,
@@ -4638,13 +4762,15 @@ impl Strategy for PlatformExprStrategy {
)
},
format!(
"selected={} periodic_rebalance={} exits={} projected_positions={} intents={} limit={}",
"selected={} periodic_rebalance={} exits={} projected_positions={} intents={} limit={} decision_date={} execution_date={}",
stock_list.len(),
periodic_rebalance,
exit_symbols.len(),
projected.positions().len(),
order_intents.len(),
selection_limit
selection_limit,
decision_date,
execution_date
),
"platform strategy script executed through expression runtime + bid1/ask1 snapshot execution".to_string(),
];
@@ -4720,6 +4846,14 @@ mod tests {
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
}
#[test]
fn platform_expr_rewrites_nested_ternary() {
let expr = "pct_change(\"close\", 10) + (((close / rolling_mean(\"close\", 20)) - 1) > 0 ? 0.04 : -0.04)";
let rewritten = PlatformExprStrategy::rewrite_ternary(expr);
assert!(rewritten.contains("if ((close / rolling_mean(\"close\", 20)) - 1) > 0"));
assert!(!rewritten.contains('?'));
}
fn sample_calendar() -> TradingCalendar {
TradingCalendar::new(vec![
d(2025, 1, 30),
@@ -5434,6 +5568,179 @@ mod tests {
);
}
#[test]
fn platform_strategy_uses_decision_date_for_next_bar_open_signals() {
let decision_date = d(2025, 2, 3);
let execution_date = d(2025, 2, 4);
let symbol = "000001.SZ";
let data = DataSet::from_components(
vec![Instrument {
symbol: symbol.to_string(),
name: "Decision Date Stock".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: decision_date,
symbol: symbol.to_string(),
timestamp: Some("2025-02-03 10:18:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.5,
low: 9.8,
close: 10.0,
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
prev_close: 9.9,
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,
},
DailyMarketSnapshot {
date: execution_date,
symbol: symbol.to_string(),
timestamp: Some("2025-02-04 10:18:00".to_string()),
day_open: 12.0,
open: 12.0,
high: 101.0,
low: 11.8,
close: 100.0,
last_price: 100.0,
bid1: 99.99,
ask1: 100.01,
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: 110.0,
lower_limit: 9.0,
price_tick: 0.01,
},
],
vec![
DailyFactorSnapshot {
date: decision_date,
symbol: symbol.to_string(),
market_cap_bn: 12.0,
free_float_cap_bn: 10.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
DailyFactorSnapshot {
date: execution_date,
symbol: symbol.to_string(),
market_cap_bn: 12.0,
free_float_cap_bn: 10.0,
pe_ttm: 8.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
],
vec![
CandidateEligibility {
date: decision_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,
},
CandidateEligibility {
date: execution_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: decision_date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1002.0,
prev_close: 998.0,
volume: 1_000_000,
},
BenchmarkSnapshot {
date: execution_date,
benchmark: "000852.SH".to_string(),
open: 1002.0,
close: 1004.0,
prev_close: 1002.0,
volume: 1_000_000,
},
],
)
.expect("dataset");
let portfolio = PortfolioState::new(30_000.0);
let subscriptions = BTreeSet::new();
let ctx = StrategyContext {
execution_date,
decision_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.signal_symbol = symbol.to_string();
cfg.refresh_rate = 1;
cfg.max_positions = 1;
cfg.benchmark_short_ma_days = 1;
cfg.benchmark_long_ma_days = 1;
cfg.stock_short_ma_days = 1;
cfg.stock_mid_ma_days = 1;
cfg.stock_long_ma_days = 1;
cfg.market_cap_lower_expr = "0".to_string();
cfg.market_cap_upper_expr = "100".to_string();
cfg.selection_limit_expr = "1".to_string();
cfg.stock_filter_expr = "close > 50".to_string();
let mut strategy = PlatformExprStrategy::new(cfg);
let decision = strategy.on_day(&ctx).expect("platform decision");
assert!(decision.order_intents.is_empty());
assert!(
decision
.diagnostics
.iter()
.any(|item| item.contains("selected=0"))
);
}
#[test]
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];