Compare commits
2 Commits
v2026.4.29
...
v2026.4.30
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e06a1e88e5 | ||
|
|
ce49301b98 |
@@ -3100,8 +3100,7 @@ impl PlatformExprStrategy {
|
|||||||
'(' => {
|
'(' => {
|
||||||
let next_depth = paren_depth + 1;
|
let next_depth = paren_depth + 1;
|
||||||
paren_depth += 1;
|
paren_depth += 1;
|
||||||
if next_depth == ternary_paren_depth && brace_depth == 0 && bracket_depth == 0
|
if next_depth == ternary_paren_depth && brace_depth == 0 && bracket_depth == 0 {
|
||||||
{
|
|
||||||
start = idx + ch.len_utf8();
|
start = idx + ch.len_utf8();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4373,7 +4372,8 @@ impl PlatformExprStrategy {
|
|||||||
fn stop_take_action(
|
fn stop_take_action(
|
||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
date: NaiveDate,
|
signal_date: NaiveDate,
|
||||||
|
execution_date: NaiveDate,
|
||||||
day: &DayExpressionState,
|
day: &DayExpressionState,
|
||||||
symbol: &str,
|
symbol: &str,
|
||||||
) -> Result<(bool, bool), BacktestError> {
|
) -> Result<(bool, bool), BacktestError> {
|
||||||
@@ -4388,7 +4388,7 @@ impl PlatformExprStrategy {
|
|||||||
if position.quantity == 0 || position.average_cost <= 0.0 {
|
if position.quantity == 0 || position.average_cost <= 0.0 {
|
||||||
return Ok((false, false));
|
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,
|
Ok(stock) => stock,
|
||||||
Err(BacktestError::Data(crate::data::DataSetError::MissingSnapshot { .. })) => {
|
Err(BacktestError::Data(crate::data::DataSetError::MissingSnapshot { .. })) => {
|
||||||
return Ok((false, false));
|
return Ok((false, false));
|
||||||
@@ -4415,9 +4415,9 @@ impl PlatformExprStrategy {
|
|||||||
prev_close: stock.prev_close,
|
prev_close: stock.prev_close,
|
||||||
holding_return,
|
holding_return,
|
||||||
quantity: position.quantity as i64,
|
quantity: position.quantity as i64,
|
||||||
sellable_qty: position.sellable_qty(date) as i64,
|
sellable_qty: position.sellable_qty(execution_date) as i64,
|
||||||
sellable: position.sellable_qty(date) as i64,
|
sellable: position.sellable_qty(execution_date) as i64,
|
||||||
closable: position.sellable_qty(date) as i64,
|
closable: position.sellable_qty(execution_date) as i64,
|
||||||
old_quantity: position.day_start_quantity() as i64,
|
old_quantity: position.day_start_quantity() as i64,
|
||||||
bought_quantity: position.bought_quantity() as i64,
|
bought_quantity: position.bought_quantity() as i64,
|
||||||
sold_quantity: position.sold_quantity() as i64,
|
sold_quantity: position.sold_quantity() as i64,
|
||||||
@@ -4471,12 +4471,12 @@ impl PlatformExprStrategy {
|
|||||||
boolean
|
boolean
|
||||||
} else if let Some(multiplier) = take_result.clone().try_cast::<f64>() {
|
} else if let Some(multiplier) = take_result.clone().try_cast::<f64>() {
|
||||||
!ctx.data
|
!ctx.data
|
||||||
.require_market(date, symbol)?
|
.require_market(signal_date, symbol)?
|
||||||
.is_at_upper_limit_price(current_price)
|
.is_at_upper_limit_price(current_price)
|
||||||
&& current_price / position.average_cost > multiplier
|
&& current_price / position.average_cost > multiplier
|
||||||
} else if let Some(multiplier) = take_result.try_cast::<i64>() {
|
} else if let Some(multiplier) = take_result.try_cast::<i64>() {
|
||||||
!ctx.data
|
!ctx.data
|
||||||
.require_market(date, symbol)?
|
.require_market(signal_date, symbol)?
|
||||||
.is_at_upper_limit_price(current_price)
|
.is_at_upper_limit_price(current_price)
|
||||||
&& current_price / position.average_cost > multiplier as f64
|
&& current_price / position.average_cost > multiplier as f64
|
||||||
} else {
|
} else {
|
||||||
@@ -4506,8 +4506,9 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn on_day(&mut self, ctx: &StrategyContext<'_>) -> Result<StrategyDecision, BacktestError> {
|
fn on_day(&mut self, ctx: &StrategyContext<'_>) -> Result<StrategyDecision, BacktestError> {
|
||||||
let date = ctx.execution_date;
|
let execution_date = ctx.execution_date;
|
||||||
if self.config.in_skip_window(date) {
|
let decision_date = ctx.decision_date;
|
||||||
|
if self.config.in_skip_window(execution_date) {
|
||||||
return Ok(StrategyDecision {
|
return Ok(StrategyDecision {
|
||||||
rebalance: false,
|
rebalance: false,
|
||||||
target_weights: BTreeMap::new(),
|
target_weights: BTreeMap::new(),
|
||||||
@@ -4523,17 +4524,17 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
reason: "seasonal_stop_window".to_string(),
|
reason: "seasonal_stop_window".to_string(),
|
||||||
})
|
})
|
||||||
.collect(),
|
.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()],
|
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) =
|
let (explicit_action_intents, explicit_action_diagnostics) =
|
||||||
if self.config.explicit_action_stage == PlatformExplicitActionStage::OnDay
|
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 {
|
} else {
|
||||||
(Vec::new(), Vec::new())
|
(Vec::new(), Vec::new())
|
||||||
};
|
};
|
||||||
@@ -4555,8 +4556,14 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
0
|
0
|
||||||
};
|
};
|
||||||
let stock_list = if self.config.rotation_enabled {
|
let stock_list = if self.config.rotation_enabled {
|
||||||
let (stock_list, notes) =
|
let (stock_list, notes) = self.select_symbols(
|
||||||
self.select_symbols(ctx, date, &day, band_low, band_high, selection_limit)?;
|
ctx,
|
||||||
|
decision_date,
|
||||||
|
&day,
|
||||||
|
band_low,
|
||||||
|
band_high,
|
||||||
|
selection_limit,
|
||||||
|
)?;
|
||||||
selection_notes = notes;
|
selection_notes = notes;
|
||||||
stock_list
|
stock_list
|
||||||
} else {
|
} else {
|
||||||
@@ -4566,7 +4573,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
if let Some(schedule) = &self.config.rebalance_schedule {
|
if let Some(schedule) = &self.config.rebalance_schedule {
|
||||||
schedule.matches(
|
schedule.matches(
|
||||||
ctx.data.calendar(),
|
ctx.data.calendar(),
|
||||||
date,
|
execution_date,
|
||||||
ScheduleStage::OnDay,
|
ScheduleStage::OnDay,
|
||||||
default_stage_time(ScheduleStage::OnDay),
|
default_stage_time(ScheduleStage::OnDay),
|
||||||
)
|
)
|
||||||
@@ -4586,8 +4593,8 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let (stop_hit, profit_hit) =
|
let (stop_hit, profit_hit) =
|
||||||
self.stop_take_action(ctx, date, &day, &position.symbol)?;
|
self.stop_take_action(ctx, decision_date, execution_date, &day, &position.symbol)?;
|
||||||
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
|
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
|
||||||
if stop_hit || profit_hit {
|
if stop_hit || profit_hit {
|
||||||
let sell_reason = if stop_hit {
|
let sell_reason = if stop_hit {
|
||||||
"stop_loss_exit"
|
"stop_loss_exit"
|
||||||
@@ -4604,7 +4611,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
self.project_target_zero(
|
self.project_target_zero(
|
||||||
ctx,
|
ctx,
|
||||||
&mut projected,
|
&mut projected,
|
||||||
date,
|
execution_date,
|
||||||
&position.symbol,
|
&position.symbol,
|
||||||
&mut projected_execution_state,
|
&mut projected_execution_state,
|
||||||
);
|
);
|
||||||
@@ -4621,18 +4628,24 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
{
|
{
|
||||||
continue;
|
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
|
if self
|
||||||
.buy_rejection_reason(ctx, date, symbol, &stock)?
|
.buy_rejection_reason(
|
||||||
|
ctx,
|
||||||
|
execution_date,
|
||||||
|
symbol,
|
||||||
|
&execution_stock,
|
||||||
|
)?
|
||||||
.is_some()
|
.is_some()
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if !self.stock_passes_expr(ctx, &day, &stock)? {
|
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let replacement_cash =
|
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 {
|
if replacement_cash <= 0.0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -4644,7 +4657,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
self.project_order_value(
|
self.project_order_value(
|
||||||
ctx,
|
ctx,
|
||||||
&mut projected,
|
&mut projected,
|
||||||
date,
|
execution_date,
|
||||||
symbol,
|
symbol,
|
||||||
replacement_cash,
|
replacement_cash,
|
||||||
&mut projected_execution_state,
|
&mut projected_execution_state,
|
||||||
@@ -4666,7 +4679,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
if stock_list.iter().any(|candidate| candidate == symbol) {
|
if stock_list.iter().any(|candidate| candidate == symbol) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if !self.can_sell_position(ctx, date, symbol) {
|
if !self.can_sell_position(ctx, execution_date, symbol) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
order_intents.push(OrderIntent::TargetValue {
|
order_intents.push(OrderIntent::TargetValue {
|
||||||
@@ -4677,7 +4690,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
self.project_target_zero(
|
self.project_target_zero(
|
||||||
ctx,
|
ctx,
|
||||||
&mut projected,
|
&mut projected,
|
||||||
date,
|
execution_date,
|
||||||
symbol,
|
symbol,
|
||||||
&mut projected_execution_state,
|
&mut projected_execution_state,
|
||||||
);
|
);
|
||||||
@@ -4693,17 +4706,18 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
{
|
{
|
||||||
continue;
|
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
|
if self
|
||||||
.buy_rejection_reason(ctx, date, symbol, &stock)?
|
.buy_rejection_reason(ctx, execution_date, symbol, &execution_stock)?
|
||||||
.is_some()
|
.is_some()
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if !self.stock_passes_expr(ctx, &day, &stock)? {
|
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
|
||||||
continue;
|
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 {
|
if buy_cash <= 0.0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -4715,7 +4729,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
self.project_order_value(
|
self.project_order_value(
|
||||||
ctx,
|
ctx,
|
||||||
&mut projected,
|
&mut projected,
|
||||||
date,
|
execution_date,
|
||||||
symbol,
|
symbol,
|
||||||
buy_cash,
|
buy_cash,
|
||||||
&mut projected_execution_state,
|
&mut projected_execution_state,
|
||||||
@@ -4748,13 +4762,15 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
format!(
|
format!(
|
||||||
"selected={} periodic_rebalance={} exits={} projected_positions={} intents={} limit={}",
|
"selected={} periodic_rebalance={} exits={} projected_positions={} intents={} limit={} decision_date={} execution_date={}",
|
||||||
stock_list.len(),
|
stock_list.len(),
|
||||||
periodic_rebalance,
|
periodic_rebalance,
|
||||||
exit_symbols.len(),
|
exit_symbols.len(),
|
||||||
projected.positions().len(),
|
projected.positions().len(),
|
||||||
order_intents.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(),
|
"platform strategy script executed through expression runtime + bid1/ask1 snapshot execution".to_string(),
|
||||||
];
|
];
|
||||||
@@ -5552,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]
|
#[test]
|
||||||
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
|
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
|
||||||
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
||||||
|
|||||||
@@ -101,6 +101,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
|||||||
"AI 生成策略时只能输出完整 engine-script 代码,不输出 Markdown、解释、推理过程、JSON 包装或手册复述。".to_string(),
|
"AI 生成策略时只能输出完整 engine-script 代码,不输出 Markdown、解释、推理过程、JSON 包装或手册复述。".to_string(),
|
||||||
"表达式字段以运行时字段为准:市值使用 market_cap,流通市值使用 free_float_cap;不要在策略表达式中使用数据库原始字段 float_market_cap。".to_string(),
|
"表达式字段以运行时字段为准:市值使用 market_cap,流通市值使用 free_float_cap;不要在策略表达式中使用数据库原始字段 float_market_cap。".to_string(),
|
||||||
"任意窗口价格均线使用 rolling_mean(\"close\", n) 或 ma(\"close\", n),任意窗口均量使用 rolling_mean(\"volume\", n) 或 vma(n);不要使用未列出的 ma60、stock_ma60、signal_ma60 或 benchmark_ma60 变量。".to_string(),
|
"任意窗口价格均线使用 rolling_mean(\"close\", n) 或 ma(\"close\", n),任意窗口均量使用 rolling_mean(\"volume\", n) 或 vma(n);不要使用未列出的 ma60、stock_ma60、signal_ma60 或 benchmark_ma60 变量。".to_string(),
|
||||||
|
"next_bar_open 会用决策日信号生成订单,并在下一可交易开盘撮合;不得把执行日 open/high/low/close 当成下单前已知信息。".to_string(),
|
||||||
"自定义 fn 必须通过参数传入运行时字段;不要用 fn score() 这类零参数函数直接引用 market_cap、close、ma5 等股票字段。".to_string(),
|
"自定义 fn 必须通过参数传入运行时字段;不要用 fn score() 这类零参数函数直接引用 market_cap、close、ma5 等股票字段。".to_string(),
|
||||||
"禁止自由 Python/JavaScript 命令式语句,最终必须输出平台 DSL。".to_string(),
|
"禁止自由 Python/JavaScript 命令式语句,最终必须输出平台 DSL。".to_string(),
|
||||||
],
|
],
|
||||||
@@ -165,6 +166,10 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
|||||||
title: "诊断解释".to_string(),
|
title: "诊断解释".to_string(),
|
||||||
detail: "结果为空或收益异常时优先展示 diagnostics、选股数量、过滤原因、缺失字段、窗口不足、涨跌停/停牌拒单、快照缓存命中情况。不要只返回 JSON;要给用户自然语言结论和下一步优化建议。".to_string(),
|
detail: "结果为空或收益异常时优先展示 diagnostics、选股数量、过滤原因、缺失字段、窗口不足、涨跌停/停牌拒单、快照缓存命中情况。不要只返回 JSON;要给用户自然语言结论和下一步优化建议。".to_string(),
|
||||||
},
|
},
|
||||||
|
ManualSection {
|
||||||
|
title: "收益合理性复核".to_string(),
|
||||||
|
detail: "展示或用于优化前,应按 finalEquity / initialCash - 1 复算总收益。若小资金回测出现极端收益、指标与资金不一致、或历史 run 来自旧引擎,应检查交易明细并用当前编译后的回测引擎重新回测,不要把异常 run 当成成功样本。".to_string(),
|
||||||
|
},
|
||||||
],
|
],
|
||||||
optimization_playbook: vec![
|
optimization_playbook: vec![
|
||||||
ManualSection {
|
ManualSection {
|
||||||
@@ -215,7 +220,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
|||||||
},
|
},
|
||||||
ManualSection {
|
ManualSection {
|
||||||
title: "execution.matching_type / execution.slippage".to_string(),
|
title: "execution.matching_type / execution.slippage".to_string(),
|
||||||
detail: "设置撮合模式和滑点。支持 execution.matching_type(\"next_tick_last\" | \"next_tick_best_own\" | \"next_tick_best_counterparty\" | \"counterparty_offer\" | \"vwap\" | \"current_bar_close\" | \"next_bar_open\" | \"open_auction\")。其中 next_tick_last 使用 tick 的 last_price;next_tick_best_own / next_tick_best_counterparty 会按 L1 买一卖一近似 平台内核 的 tick 最优价语义;counterparty_offer 在存在 order_book_depth 多档盘口数据时会按真实档位逐档扫单并计算加权成交价,不存在 depth 时回退 L1 对手方报价;vwap 会在盘中执行价链路上聚合多笔成交为单条 VWAP 成交;open_auction 使用当日集合竞价开盘价 day_open 进行撮合,且不额外施加滑点,并按竞价成交量而不是盘口一档流动性限制成交;滑点支持 execution.slippage(\"none\") / execution.slippage(\"price_ratio\", 0.001) / execution.slippage(\"tick_size\", 1) / execution.slippage(\"limit_price\"),其中 limit_price 会在限价单成交时按挂单价模拟 平台内核 的最坏成交价。".to_string(),
|
detail: "设置撮合模式和滑点。支持 execution.matching_type(\"next_tick_last\" | \"next_tick_best_own\" | \"next_tick_best_counterparty\" | \"counterparty_offer\" | \"vwap\" | \"current_bar_close\" | \"next_bar_open\" | \"open_auction\")。其中 next_tick_last 使用 tick 的 last_price;next_tick_best_own / next_tick_best_counterparty 会按 L1 买一卖一近似 平台内核 的 tick 最优价语义;counterparty_offer 在存在 order_book_depth 多档盘口数据时会按真实档位逐档扫单并计算加权成交价,不存在 depth 时回退 L1 对手方报价;vwap 会在盘中执行价链路上聚合多笔成交为单条 VWAP 成交;next_bar_open 使用决策日信号并在下一可交易日开盘撮合,禁止把执行日 open/high/low/close 解释为下单前已知数据;open_auction 使用当日集合竞价开盘价 day_open 进行撮合,且不额外施加滑点,并按竞价成交量而不是盘口一档流动性限制成交;滑点支持 execution.slippage(\"none\") / execution.slippage(\"price_ratio\", 0.001) / execution.slippage(\"tick_size\", 1) / execution.slippage(\"limit_price\"),其中 limit_price 会在限价单成交时按挂单价模拟 平台内核 的最坏成交价。".to_string(),
|
||||||
},
|
},
|
||||||
ManualSection {
|
ManualSection {
|
||||||
title: "期货提交校验".to_string(),
|
title: "期货提交校验".to_string(),
|
||||||
@@ -433,7 +438,12 @@ pub fn render_manual_markdown(manual: &StrategyAiManual) -> String {
|
|||||||
out.push_str("- 任意窗口价格均线使用 `rolling_mean(\"close\", n)` 或 `ma(\"close\", n)`;任意窗口均量使用 `rolling_mean(\"volume\", n)` 或 `vma(n)`;不要使用未列出的 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60` 变量。\n");
|
out.push_str("- 任意窗口价格均线使用 `rolling_mean(\"close\", n)` 或 `ma(\"close\", n)`;任意窗口均量使用 `rolling_mean(\"volume\", n)` 或 `vma(n)`;不要使用未列出的 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60` 变量。\n");
|
||||||
out.push_str("- 自定义 `fn` 必须通过参数传入运行时字段;不要用 `fn score()` 这类零参数函数直接引用 `market_cap`、`close`、`ma5` 等股票字段。\n");
|
out.push_str("- 自定义 `fn` 必须通过参数传入运行时字段;不要用 `fn score()` 这类零参数函数直接引用 `market_cap`、`close`、`ma5` 等股票字段。\n");
|
||||||
out.push_str("- `selection.market_cap_band` 必须写命名参数:`field=\"market_cap\"` 或 `field=\"free_float_cap\"`,并包含 `lower=...` 与 `upper=...`。\n");
|
out.push_str("- `selection.market_cap_band` 必须写命名参数:`field=\"market_cap\"` 或 `field=\"free_float_cap\"`,并包含 `lower=...` 与 `upper=...`。\n");
|
||||||
out.push_str("- `risk.index_exposure(...)` 只能传一个表达式;`execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
|
out.push_str(
|
||||||
|
"- `risk.index_exposure(...)` 只能传一个表达式;不要生成 `risk.exposure(...)`。\n",
|
||||||
|
);
|
||||||
|
out.push_str("- 完整三元表达式 `cond ? a : b` 可在表达式参数中使用;若当前运行环境报 `Unknown operator: '?'`,先重编译并重启回测服务,不要改写策略语义掩盖运行时漂移。\n");
|
||||||
|
out.push_str("- `next_bar_open` 的选股、排序和仓位信号来自决策日,订单在下一可交易开盘撮合;不要使用执行日价格作为下单前信号。\n");
|
||||||
|
out.push_str("- `execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
|
||||||
out.push_str("## 语句块\n");
|
out.push_str("## 语句块\n");
|
||||||
for item in &manual.statement_blocks {
|
for item in &manual.statement_blocks {
|
||||||
out.push_str(&format!("- `{}`: {}\n", item.title, item.detail));
|
out.push_str(&format!("- `{}`: {}\n", item.title, item.detail));
|
||||||
@@ -508,9 +518,9 @@ pub fn build_generation_prompt(
|
|||||||
prompt.push_str("- 生成的代码必须能转换为 strategy_spec 并提交 POST /v1/backtests。\n");
|
prompt.push_str("- 生成的代码必须能转换为 strategy_spec 并提交 POST /v1/backtests。\n");
|
||||||
prompt.push_str("- 不要使用手册未列出的字段、函数或外部平台 API 名称。\n\n");
|
prompt.push_str("- 不要使用手册未列出的字段、函数或外部平台 API 名称。\n\n");
|
||||||
prompt.push_str("只允许使用这些可编译语句:market、benchmark、signal、rebalance.every_days(...).at([...])、selection.limit、selection.market_cap_band、filter.stock_ma、filter.stock_expr、ordering.rank_by、ordering.rank_expr、allocation.buy_scale、risk.stop_loss、risk.take_profit、risk.index_exposure、execution.matching_type、execution.slippage、universe.exclude。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
|
prompt.push_str("只允许使用这些可编译语句:market、benchmark、signal、rebalance.every_days(...).at([...])、selection.limit、selection.market_cap_band、filter.stock_ma、filter.stock_expr、ordering.rank_by、ordering.rank_expr、allocation.buy_scale、risk.stop_loss、risk.take_profit、risk.index_exposure、execution.matching_type、execution.slippage、universe.exclude。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
|
||||||
prompt.push_str("参数形态必须严格:selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap;禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma60,60日价格均线写 rolling_mean(\"close\", 60) 或 ma(\"close\", 60),任意窗口均量写 rolling_mean(\"volume\", n) 或 vma(n);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit,不要写 is_st == 0;risk.index_exposure 只能传一个数值表达式,例如 ((signal_close < signal_ma20) ? 0.35 : 1.0);execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auction;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
|
prompt.push_str("参数形态必须严格:selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap;禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma60,60日价格均线写 rolling_mean(\"close\", 60) 或 ma(\"close\", 60),任意窗口均量写 rolling_mean(\"volume\", n) 或 vma(n);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit,不要写 is_st == 0;risk.index_exposure 只能传一个数值表达式,不要使用 risk.exposure;完整三元表达式 cond ? a : b 可以使用,但不得输出残缺问号/冒号片段;execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auction;next_bar_open 只能使用决策日信号,不能把执行日价格当作下单前信息;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
|
||||||
prompt.push_str("回测成功但 tradeCount=0 或 holdingCount=0 是无效策略;第一版必须保持稳定买入覆盖率,复杂因子只能在后续优化中逐步加严。\n");
|
prompt.push_str("回测成功但 tradeCount=0 或 holdingCount=0 是无效策略;第一版必须保持稳定买入覆盖率,复杂因子只能在后续优化中逐步加严。\n");
|
||||||
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure((signal_close < signal_ma20) ? 0.35 : 1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
|
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure(1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
|
||||||
prompt.push_str("用户目标:\n");
|
prompt.push_str("用户目标:\n");
|
||||||
prompt.push_str(&format!("- {}\n", request.user_goal));
|
prompt.push_str(&format!("- {}\n", request.user_goal));
|
||||||
if !request.constraints.is_empty() {
|
if !request.constraints.is_empty() {
|
||||||
|
|||||||
Reference in New Issue
Block a user