5 Commits

Author SHA1 Message Date
boris
adc2f12ddf chore: 更新 fidc-backtest-engine - 2026-05-07 2026-05-07 03:49:26 -07:00
boris
e06a1e88e5 完善AI策略手册防未来函数规则 2026-04-30 09:24:05 -07:00
boris
ce49301b98 修复平台策略次日开盘未来函数 2026-04-30 00:53:45 -07:00
boris
e5439956eb 修复平台表达式嵌套三元执行 2026-04-30 03:57:43 +08:00
boris
8e4e0cd86f 完善平台表达式因子执行能力 2026-04-28 23:22:21 +08:00
5 changed files with 982 additions and 66 deletions

View File

@@ -0,0 +1,17 @@
//! 把 DSP 运行时 schema 序列化为 JSON 输出到 stdout。
//!
//! 用法(在 fidc-backtest-engine 仓库根):
//! cargo run -p fidc-core --bin dump_platform_runtime_schema \
//! > ../omniquant/src/generated/platformRuntimeSchema.json
//!
//! 这是 omniquant 前端编译期校验表达式标识符的事实源;任何对
//! reserved_scope_names / is_runtime_helper / register_fn 清单的修改,记得
//! 重新跑这个命令并把生成文件提交到 omniquant。
use fidc_core::runtime_schema_json;
fn main() {
let schema = runtime_schema_json();
let output = serde_json::to_string_pretty(&schema).expect("serialize schema");
println!("{output}");
}

View File

@@ -9,6 +9,7 @@ pub mod futures;
pub mod instrument; pub mod instrument;
pub mod metrics; pub mod metrics;
pub mod platform_expr_strategy; pub mod platform_expr_strategy;
pub mod platform_runtime_schema;
pub mod platform_strategy_spec; pub mod platform_strategy_spec;
pub mod portfolio; pub mod portfolio;
pub mod rules; pub mod rules;
@@ -50,6 +51,11 @@ pub use platform_expr_strategy::{
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction, PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
PlatformUniverseActionKind, PlatformUniverseActionKind,
}; };
pub use platform_runtime_schema::{
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
rhai_builtin_functions, rhai_keywords, runtime_helper_functions, runtime_schema,
runtime_schema_json,
};
pub use platform_strategy_spec::{ pub use platform_strategy_spec::{
DynamicRangeConfig, IndexThrottleConfig, MovingAverageFilterConfig, SkipWindowConfig, DynamicRangeConfig, IndexThrottleConfig, MovingAverageFilterConfig, SkipWindowConfig,
StrategyBenchmarkSpec, StrategyEngineConfig, StrategyExecutionSpec, StrategyBenchmarkSpec, StrategyEngineConfig, StrategyExecutionSpec,

View File

@@ -1,7 +1,8 @@
use std::collections::{BTreeMap, BTreeSet}; use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime}; use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime};
use rhai::{Dynamic, Engine, Map, Scope}; use rhai::{AST, Dynamic, Engine, Map, Scope};
use crate::cost::ChinaAShareCostModel; use crate::cost::ChinaAShareCostModel;
use crate::data::{DailyMarketSnapshot, EligibleUniverseSnapshot, PriceField}; use crate::data::{DailyMarketSnapshot, EligibleUniverseSnapshot, PriceField};
@@ -415,6 +416,15 @@ struct PositionExpressionState {
pub struct PlatformExprStrategy { pub struct PlatformExprStrategy {
config: PlatformExprStrategyConfig, config: PlatformExprStrategyConfig,
engine: Engine, engine: Engine,
/// 已编译表达式 AST 缓存。
/// Key 是经过 normalize/expand_runtime_helpers 之后的完整 script 文本,
/// Value 是 Rhai 编译产物。命中后 eval 走 eval_ast_with_scope避免重复
/// parsing。一次回测里同一表达式stock_filter / stop_loss / rank_expr 等)
/// 会被反复执行,重复解析的常数级开销在大规模回测里不可忽略。
compiled_cache: RefCell<HashMap<String, AST>>,
/// 命中计数与未命中计数,便于在 unit test 中验证缓存生效;非生产指标。
cache_hits: RefCell<u64>,
cache_misses: RefCell<u64>,
} }
impl PlatformExprStrategy { impl PlatformExprStrategy {
@@ -466,7 +476,63 @@ impl PlatformExprStrategy {
engine.register_fn("upper", |value: &str| value.to_uppercase()); engine.register_fn("upper", |value: &str| value.to_uppercase());
engine.register_fn("trim", |value: &str| value.trim().to_string()); engine.register_fn("trim", |value: &str| value.trim().to_string());
engine.register_fn("strlen", |value: &str| value.chars().count() as i64); engine.register_fn("strlen", |value: &str| value.chars().count() as i64);
Self { config, engine } Self {
config,
engine,
compiled_cache: RefCell::new(HashMap::new()),
cache_hits: RefCell::new(0),
cache_misses: RefCell::new(0),
}
}
/// AST 缓存命中次数(仅用于测试与诊断)。
pub fn ast_cache_hits(&self) -> u64 {
*self.cache_hits.borrow()
}
/// AST 缓存未命中次数(仅用于测试与诊断)。
pub fn ast_cache_misses(&self) -> u64 {
*self.cache_misses.borrow()
}
/// AST 缓存当前条目数(仅用于测试与诊断)。
pub fn ast_cache_size(&self) -> usize {
self.compiled_cache.borrow().len()
}
/// 用 AST 缓存执行 script。命中直接走 eval_ast_with_scope未命中
/// engine.compile再插入缓存再 eval_ast_with_scope。任何编译/执行错误
/// 都按字符串包装为 BacktestError::Execution。
fn eval_with_cache(
&self,
scope: &mut Scope<'_>,
script: &str,
) -> Result<Dynamic, BacktestError> {
// 注意HashMap key 借用即可命中,避免重复克隆 String。
if let Some(ast) = self.compiled_cache.borrow().get(script) {
*self.cache_hits.borrow_mut() += 1;
return self
.engine
.eval_ast_with_scope::<Dynamic>(scope, ast)
.map_err(|error| {
BacktestError::Execution(format!("platform expr eval failed: {}", error))
});
}
*self.cache_misses.borrow_mut() += 1;
let ast = self.engine.compile(script).map_err(|error| {
BacktestError::Execution(format!("platform expr compile failed: {}", error))
})?;
let result = self
.engine
.eval_ast_with_scope::<Dynamic>(scope, &ast)
.map_err(|error| {
BacktestError::Execution(format!("platform expr eval failed: {}", error))
});
// 即便本次执行失败,也把 AST 留下:错误源于 scope 中的值,下次仍然有效。
self.compiled_cache
.borrow_mut()
.insert(script.to_string(), ast);
result
} }
fn is_expression_identifier(name: &str) -> bool { fn is_expression_identifier(name: &str) -> bool {
@@ -1675,6 +1741,7 @@ impl PlatformExprStrategy {
scope.push("tick_volume", stock.tick_volume); scope.push("tick_volume", stock.tick_volume);
scope.push("bid1_volume", stock.bid1_volume); scope.push("bid1_volume", stock.bid1_volume);
scope.push("ask1_volume", stock.ask1_volume); scope.push("ask1_volume", stock.ask1_volume);
scope.push("turnover", stock.turnover_ratio);
scope.push("turnover_ratio", stock.turnover_ratio); scope.push("turnover_ratio", stock.turnover_ratio);
scope.push("effective_turnover_ratio", stock.effective_turnover_ratio); scope.push("effective_turnover_ratio", stock.effective_turnover_ratio);
scope.push("open", stock.open); scope.push("open", stock.open);
@@ -1763,6 +1830,7 @@ impl PlatformExprStrategy {
factors.insert("tick_volume".into(), Dynamic::from(stock.tick_volume)); factors.insert("tick_volume".into(), Dynamic::from(stock.tick_volume));
factors.insert("bid1_volume".into(), Dynamic::from(stock.bid1_volume)); factors.insert("bid1_volume".into(), Dynamic::from(stock.bid1_volume));
factors.insert("ask1_volume".into(), Dynamic::from(stock.ask1_volume)); factors.insert("ask1_volume".into(), Dynamic::from(stock.ask1_volume));
factors.insert("turnover".into(), Dynamic::from(stock.turnover_ratio));
factors.insert("turnover_ratio".into(), Dynamic::from(stock.turnover_ratio)); factors.insert("turnover_ratio".into(), Dynamic::from(stock.turnover_ratio));
factors.insert( factors.insert(
"effective_turnover_ratio".into(), "effective_turnover_ratio".into(),
@@ -2009,25 +2077,44 @@ impl PlatformExprStrategy {
}) })
.filter(|value| !value.trim().is_empty()); .filter(|value| !value.trim().is_empty());
let mut script_parts = Vec::new(); let mut script_parts = Vec::new();
if !self.config.prelude.trim().is_empty() { let prelude = Self::normalize_prelude_for_eval(&self.config.prelude);
script_parts.push(self.config.prelude.trim().to_string()); if !prelude.trim().is_empty() {
script_parts.push(prelude);
} }
if let Some(alias_prelude) = factor_alias_prelude { if let Some(alias_prelude) = factor_alias_prelude {
script_parts.push(alias_prelude); script_parts.push(alias_prelude);
} }
script_parts.push(expanded_expr); script_parts.push(expanded_expr);
let script = script_parts.join("\n"); let script = script_parts.join("\n");
self.engine self.eval_with_cache(&mut scope, &script)
.eval_with_scope::<Dynamic>(&mut scope, &script)
.map_err(|error| {
BacktestError::Execution(format!("platform expr eval failed: {}", error))
})
} }
fn normalize_expr(expr: &str) -> String { fn normalize_expr(expr: &str) -> String {
Self::rewrite_ternary(expr.trim()) Self::rewrite_ternary(expr.trim())
} }
fn normalize_prelude_for_eval(prelude: &str) -> String {
prelude
.lines()
.map(|line| {
let trimmed = line.trim_end();
let head = trimmed.trim_start();
if head.is_empty()
|| head.starts_with("//")
|| trimmed.ends_with(';')
|| trimmed.ends_with('{')
|| trimmed.ends_with('}')
|| !(head.starts_with("let ") || head.starts_with("const "))
{
trimmed.to_string()
} else {
format!("{trimmed};")
}
})
.collect::<Vec<_>>()
.join("\n")
}
fn expand_runtime_helpers( fn expand_runtime_helpers(
&self, &self,
ctx: &StrategyContext<'_>, ctx: &StrategyContext<'_>,
@@ -2766,6 +2853,14 @@ impl PlatformExprStrategy {
) )
} }
fn is_non_numeric_expr_error(error: &BacktestError) -> bool {
matches!(
error,
BacktestError::Execution(message)
if message.starts_with("platform expr did not produce a number: ")
)
}
fn split_top_level_args(args: &str) -> Vec<String> { fn split_top_level_args(args: &str) -> Vec<String> {
let mut parts = Vec::new(); let mut parts = Vec::new();
let mut start = 0usize; let mut start = 0usize;
@@ -2960,26 +3055,33 @@ impl PlatformExprStrategy {
} }
fn rewrite_ternary(expr: &str) -> String { fn rewrite_ternary(expr: &str) -> String {
let Some((question_idx, colon_idx)) = Self::find_top_level_ternary(expr) else { let trimmed = expr.trim();
return expr.trim().to_string(); 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 condition = Self::rewrite_ternary(trimmed[condition_start..question_idx].trim());
let when_true = Self::rewrite_ternary(expr[question_idx + 1..colon_idx].trim()); let when_true = Self::rewrite_ternary(trimmed[question_idx + 1..colon_idx].trim());
let when_false = Self::rewrite_ternary(expr[colon_idx + 1..].trim()); let when_false = Self::rewrite_ternary(trimmed[colon_idx + 1..false_end].trim());
format!( let mut rewritten = String::new();
"if {} {{ {} }} else {{ {} }}", rewritten.push_str(&trimmed[..condition_start]);
rewritten.push_str(&format!(
"(if {} {{ {} }} else {{ {} }})",
condition, when_true, when_false 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 paren_depth = 0i32;
let mut brace_depth = 0i32; let mut brace_depth = 0i32;
let mut bracket_depth = 0i32; let mut bracket_depth = 0i32;
let mut in_single_quote = false; let mut in_single_quote = false;
let mut in_double_quote = false; let mut in_double_quote = false;
let mut escaped = 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() { for (idx, ch) in expr.char_indices() {
if escaped { if escaped {
@@ -3003,13 +3105,25 @@ impl PlatformExprStrategy {
'}' => brace_depth -= 1, '}' => brace_depth -= 1,
'[' => bracket_depth += 1, '[' => bracket_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 let Some(&(question_idx, question_paren, question_brace, question_bracket)) =
if question_stack.is_empty() { question_stack.last()
return Some((question_idx, idx)); {
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));
} }
} }
} }
@@ -3019,6 +3133,96 @@ impl PlatformExprStrategy {
None 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( fn eval_float(
&self, &self,
ctx: &StrategyContext<'_>, ctx: &StrategyContext<'_>,
@@ -4006,7 +4210,7 @@ impl PlatformExprStrategy {
"tick_volume" => Some(stock.tick_volume as f64), "tick_volume" => Some(stock.tick_volume as f64),
"bid1_volume" => Some(stock.bid1_volume as f64), "bid1_volume" => Some(stock.bid1_volume as f64),
"ask1_volume" => Some(stock.ask1_volume as f64), "ask1_volume" => Some(stock.ask1_volume as f64),
"turnover_ratio" => Some(stock.turnover_ratio), "turnover" | "turnover_ratio" => Some(stock.turnover_ratio),
"effective_turnover_ratio" => Some(stock.effective_turnover_ratio), "effective_turnover_ratio" => Some(stock.effective_turnover_ratio),
"open" => Some(stock.open), "open" => Some(stock.open),
"high" => Some(stock.high), "high" => Some(stock.high),
@@ -4075,6 +4279,7 @@ impl PlatformExprStrategy {
return match self.eval_float(ctx, &self.config.rank_expr, day, Some(stock), None) { return match self.eval_float(ctx, &self.config.rank_expr, day, Some(stock), None) {
Ok(value) => Ok(value), Ok(value) => Ok(value),
Err(error) if Self::is_missing_rolling_mean_error(&error) => Ok(f64::NAN), Err(error) if Self::is_missing_rolling_mean_error(&error) => Ok(f64::NAN),
Err(error) if Self::is_non_numeric_expr_error(&error) => Ok(f64::NAN),
Err(error) => Err(error), Err(error) => Err(error),
}; };
} }
@@ -4229,7 +4434,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> {
@@ -4244,7 +4450,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));
@@ -4271,9 +4477,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,
@@ -4327,12 +4533,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 {
@@ -4362,8 +4568,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(),
@@ -4379,17 +4586,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())
}; };
@@ -4411,8 +4618,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 {
@@ -4422,7 +4635,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),
) )
@@ -4442,8 +4655,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"
@@ -4460,7 +4673,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,
); );
@@ -4477,18 +4690,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;
} }
@@ -4500,7 +4719,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,
@@ -4522,7 +4741,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 {
@@ -4533,7 +4752,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,
); );
@@ -4549,17 +4768,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;
} }
@@ -4571,7 +4791,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,
@@ -4604,13 +4824,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(),
]; ];
@@ -4686,6 +4908,14 @@ mod tests {
NaiveDate::from_ymd_opt(year, month, day).expect("valid date") 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 { fn sample_calendar() -> TradingCalendar {
TradingCalendar::new(vec![ TradingCalendar::new(vec![
d(2025, 1, 30), d(2025, 1, 30),
@@ -5376,7 +5606,11 @@ mod tests {
cfg.market_cap_lower_expr = "0".to_string(); cfg.market_cap_lower_expr = "0".to_string();
cfg.market_cap_upper_expr = "100".to_string(); cfg.market_cap_upper_expr = "100".to_string();
cfg.selection_limit_expr = "1".to_string(); cfg.selection_limit_expr = "1".to_string();
cfg.stock_filter_expr = "rolling_mean(\"volume\", 60) > 0".to_string(); cfg.stock_filter_expr = concat!(
"rolling_mean(\"volume\", 60) > 0",
" && pct_change(\"close\", 1) > 0.0"
)
.to_string();
let mut strategy = PlatformExprStrategy::new(cfg); let mut strategy = PlatformExprStrategy::new(cfg);
let decision = strategy.on_day(&ctx).expect("platform decision"); let decision = strategy.on_day(&ctx).expect("platform decision");
@@ -5396,6 +5630,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)];
@@ -5534,6 +5941,139 @@ mod tests {
assert_eq!(decision.order_intents.len(), 1); assert_eq!(decision.order_intents.len(), 1);
} }
#[test]
fn platform_selection_expands_pct_change_in_filter_and_rank_expr() {
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
let market_rows = dates
.iter()
.enumerate()
.map(|(index, date)| DailyMarketSnapshot {
date: *date,
symbol: "000001.SZ".to_string(),
timestamp: None,
day_open: 10.0 + index as f64,
open: 10.0 + index as f64,
high: 10.5 + index as f64,
low: 9.5 + index as f64,
close: 10.0 + index as f64,
last_price: 10.0 + index as f64,
bid1: 10.0 + index as f64,
ask1: 10.0 + index as f64,
prev_close: 9.8 + index as f64,
volume: 1000 + index as u64 * 100,
tick_volume: 0,
bid1_volume: 0,
ask1_volume: 0,
trading_phase: None,
paused: false,
upper_limit: 20.0,
lower_limit: 5.0,
price_tick: 0.01,
})
.collect::<Vec<_>>();
let factor_rows = dates
.iter()
.map(|date| DailyFactorSnapshot {
date: *date,
symbol: "000001.SZ".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(),
})
.collect::<Vec<_>>();
let candidate_rows = dates
.iter()
.map(|date| CandidateEligibility {
date: *date,
symbol: "000001.SZ".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<_>>();
let benchmark_rows = dates
.iter()
.map(|date| BenchmarkSnapshot {
date: *date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1002.0,
prev_close: 998.0,
volume: 1_000_000,
})
.collect::<Vec<_>>();
let data = DataSet::from_components(
vec![Instrument {
symbol: "000001.SZ".to_string(),
name: "Ping An Bank".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: None,
status: "active".to_string(),
}],
market_rows,
factor_rows,
candidate_rows,
benchmark_rows,
)
.expect("dataset");
let portfolio = PortfolioState::new(1_000_000.0);
let subscriptions = BTreeSet::new();
let ctx = StrategyContext {
execution_date: dates[2],
decision_date: dates[2],
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 = 1;
cfg.max_positions = 1;
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 = "100".to_string();
cfg.selection_limit_expr = "1".to_string();
cfg.prelude = "let turnover_floor = 0\nlet boost = 0.5".to_string();
cfg.stock_filter_expr = concat!(
"close > rolling_mean(\"close\", 2)",
" && pct_change(\"close\", 1) > 0.08",
" && turnover > turnover_floor"
)
.to_string();
cfg.exposure_expr = "signal_close > 0 ? 1.0 : 0.5".to_string();
cfg.buy_scale_expr = "touched_upper_limit ? 1.0 : 0.5".to_string();
cfg.rank_expr = concat!(
"(close / rolling_mean(\"close\", 2)) * 0.5",
" + pct_change(\"close\", 1) * boost"
)
.to_string();
cfg.rank_desc = true;
let mut strategy = PlatformExprStrategy::new(cfg);
let decision = strategy.on_day(&ctx).expect("platform decision");
assert_eq!(decision.order_intents.len(), 1);
}
#[test] #[test]
fn platform_strategy_emits_target_shares_explicit_action() { fn platform_strategy_emits_target_shares_explicit_action() {
let date = d(2025, 2, 3); let date = d(2025, 2, 3);

View File

@@ -0,0 +1,343 @@
//! DSP 运行时变量与函数 schema 导出。
//!
//! 这是前后端共享的"事实源":把引擎里 reserved_scope_names 和 is_runtime_helper
//! 等清单按 JSON Schema 暴露出来,供 omniquant 前端在编译期做表达式标识符校验。
//!
//! 维护原则:
//! - 任何对 platform_expr_strategy.rs 中变量名 / 函数名清单的修改都必须在这里
//! 同步一份。两侧一致由 unit test `runtime_schema_matches_strategy_runtime`
//! 守住。
//! - 该 schema 的 version 字段需要与 omniquant/src/platformSchema.ts 里
//! PLATFORM_RUNTIME_SCHEMA_VERSION 保持一致。前端读到不同版本时应给出诊断。
use serde::Serialize;
use serde_json::Value;
/// 当前 schema 版本号。每次 reserved/runtime 列表的破坏性变更需要 +1。
pub const PLATFORM_RUNTIME_SCHEMA_VERSION: &str = "1";
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformRuntimeSchema {
pub version: &'static str,
pub reserved_scope_names: Vec<&'static str>,
pub runtime_helper_functions: Vec<&'static str>,
pub rhai_builtin_functions: Vec<&'static str>,
pub rhai_keywords: Vec<&'static str>,
}
/// reserved scope names 列表。镜像 PlatformExprStrategy::reserved_scope_names。
pub fn reserved_scope_names() -> &'static [&'static str] {
RESERVED_SCOPE_NAMES
}
/// runtime helper functions 列表。镜像 PlatformExprStrategy::is_runtime_helper。
pub fn runtime_helper_functions() -> &'static [&'static str] {
RUNTIME_HELPER_FUNCTIONS
}
/// rhai engine 注册的内置函数列表。镜像 PlatformExprStrategy::new 中 register_fn
/// 的清单。
pub fn rhai_builtin_functions() -> &'static [&'static str] {
RHAI_BUILTIN_FUNCTIONS
}
/// rhai 控制流关键字(避免被前端校验视为未知)。
pub fn rhai_keywords() -> &'static [&'static str] {
RHAI_KEYWORDS
}
/// 构造完整 schema。
pub fn runtime_schema() -> PlatformRuntimeSchema {
PlatformRuntimeSchema {
version: PLATFORM_RUNTIME_SCHEMA_VERSION,
reserved_scope_names: RESERVED_SCOPE_NAMES.to_vec(),
runtime_helper_functions: RUNTIME_HELPER_FUNCTIONS.to_vec(),
rhai_builtin_functions: RHAI_BUILTIN_FUNCTIONS.to_vec(),
rhai_keywords: RHAI_KEYWORDS.to_vec(),
}
}
/// 把 schema 序列化为 JSON Value。给 fidc-data-center / strategy-runtime 接口使用。
pub fn runtime_schema_json() -> Value {
serde_json::to_value(runtime_schema()).expect("runtime schema serialization is infallible")
}
const RESERVED_SCOPE_NAMES: &[&str] = &[
// day-level
"signal_close",
"benchmark_close",
"signal_ma5",
"signal_ma10",
"signal_ma20",
"signal_ma30",
"benchmark_ma5",
"benchmark_ma10",
"benchmark_ma20",
"benchmark_ma30",
"benchmark_ma_short",
"benchmark_ma_long",
"cash",
"available_cash",
"frozen_cash",
"market_value",
"total_equity",
"total_value",
"portfolio_value",
"starting_cash",
"unit_net_value",
"static_unit_net_value",
"daily_pnl",
"daily_returns",
"total_returns",
"cash_liabilities",
"management_fee_rate",
"management_fees",
"current_exposure",
"position_count",
"max_positions",
"refresh_rate",
"year",
"month",
"quarter",
"day_of_month",
"day_of_year",
"week_of_year",
"weekday",
"is_month_start",
"is_month_end",
"has_open_orders",
"open_order_count",
"open_buy_order_count",
"open_sell_order_count",
"open_buy_qty",
"open_sell_qty",
"latest_open_order_id",
"latest_open_order_status",
"latest_open_order_unfilled_qty",
"has_process_events",
"process_event_count",
"current_process_kind",
"current_process_order_id",
"current_process_symbol",
"current_process_side",
"current_process_detail",
"latest_process_kind",
"latest_process_order_id",
"latest_process_symbol",
"latest_process_side",
"latest_process_detail",
"process_event_counts",
"day_factors",
// stock-level
"symbol",
"market_cap",
"free_float_cap",
"pe_ttm",
"volume",
"tick_volume",
"bid1_volume",
"ask1_volume",
"turnover_ratio",
"effective_turnover_ratio",
"open",
"high",
"low",
"close",
"last",
"last_price",
"prev_close",
"amount",
"upper_limit",
"lower_limit",
"price_tick",
"round_lot",
"paused",
"is_st",
"is_kcb",
"is_one_yuan",
"is_new_listing",
"allow_buy",
"allow_sell",
"touched_upper_limit",
"touched_lower_limit",
"hit_upper_limit",
"hit_lower_limit",
"listed_days",
"symbol_open_order_count",
"symbol_open_buy_qty",
"symbol_open_sell_qty",
"latest_symbol_open_order_id",
"latest_symbol_open_order_status",
"latest_symbol_open_order_unfilled_qty",
"stock_ma_short",
"stock_ma_mid",
"stock_ma_long",
"stock_ma5",
"stock_ma10",
"stock_ma20",
"stock_ma30",
"ma5",
"ma10",
"ma20",
"ma30",
"factors",
"order_book_id",
// position-level
"avg_cost",
"avg_price",
"current_price",
"position_prev_close",
"prev_position_close",
"holding_return",
"quantity",
"sellable_qty",
"sellable",
"closable",
"old_quantity",
"buy_quantity",
"sell_quantity",
"bought_quantity",
"sold_quantity",
"buy_avg_price",
"sell_avg_price",
"bought_value",
"sold_value",
"transaction_cost",
"position_market_value",
"equity",
"value_percent",
"unrealized_pnl",
"realized_pnl",
"pnl",
"day_trade_quantity_delta",
"profit_pct",
"trading_pnl",
"position_pnl",
"dividend_receivable",
"at_upper_limit",
"at_lower_limit",
];
const RUNTIME_HELPER_FUNCTIONS: &[&str] = &[
"factor",
"day_factor",
"rolling_mean",
"ma",
"sma",
"vma",
"rolling_sum",
"rolling_min",
"rolling_max",
"rolling_stddev",
"stddev",
"rolling_zscore",
"pct_change",
"factor_value",
"get_factor_value",
"factor_text",
"get_factor_text",
"dividend_cash",
"has_dividend",
"split_ratio",
"has_split",
"securities_margin",
"get_securities_margin_value",
"shares",
"get_shares_value",
"turnover_rate",
"get_turnover_rate_value",
"price_change_rate",
"get_price_change_rate_value",
"stock_connect",
"get_stock_connect_value",
"current_performance",
"fundamental",
"get_fundamentals_value",
"financial",
"get_financials_value",
"pit_financial",
"get_pit_financials_value",
"industry_code",
"get_industry_code",
"industry_name",
"get_industry_name",
"yield_curve",
"get_yield_curve_value",
"is_margin_stock",
"dominant_future",
"get_dominant_future",
"dominant_future_price",
"get_dominant_future_price_value",
];
const RHAI_BUILTIN_FUNCTIONS: &[&str] = &[
"round",
"floor",
"ceil",
"abs",
"min",
"max",
"sqrt",
"pow",
"log",
"exp",
"clamp",
"between",
"nz",
"safe_div",
"iff",
"contains",
"starts_with",
"ends_with",
"lower",
"upper",
"trim",
"strlen",
];
const RHAI_KEYWORDS: &[&str] = &[
"if", "else", "while", "loop", "for", "in", "break", "continue", "return", "fn", "let",
"const", "true", "false", "switch", "do",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runtime_schema_serializes_to_json_object() {
let value = runtime_schema_json();
assert!(value.is_object());
assert_eq!(value["version"], "1");
assert!(value["reservedScopeNames"].is_array());
assert!(value["runtimeHelperFunctions"].is_array());
assert!(value["rhaiBuiltinFunctions"].is_array());
assert!(value["rhaiKeywords"].is_array());
}
#[test]
fn runtime_schema_includes_known_identifiers() {
let names: std::collections::HashSet<&str> =
RESERVED_SCOPE_NAMES.iter().copied().collect();
for required in [
"signal_close",
"benchmark_close",
"close",
"avg_cost",
"current_price",
"stock_ma_short",
] {
assert!(names.contains(required), "missing reserved name: {required}");
}
let helpers: std::collections::HashSet<&str> =
RUNTIME_HELPER_FUNCTIONS.iter().copied().collect();
for required in ["rolling_mean", "factor", "pct_change"] {
assert!(
helpers.contains(required),
"missing helper function: {required}"
);
}
}
}

View File

@@ -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_pricenext_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_pricenext_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(),
@@ -262,7 +267,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
fields: vec![ fields: vec![
ManualField { name: "symbol".to_string(), field_type: "string".to_string(), detail: "证券代码。".to_string() }, ManualField { name: "symbol".to_string(), field_type: "string".to_string(), detail: "证券代码。".to_string() },
ManualField { name: "market_cap/free_float_cap".to_string(), field_type: "float".to_string(), detail: "总市值、流通市值。".to_string() }, ManualField { name: "market_cap/free_float_cap".to_string(), field_type: "float".to_string(), detail: "总市值、流通市值。".to_string() },
ManualField { name: "turnover_ratio/effective_turnover_ratio".to_string(), field_type: "float".to_string(), detail: "换手率、有效换手率。".to_string() }, ManualField { name: "turnover/turnover_ratio/effective_turnover_ratio".to_string(), field_type: "float".to_string(), detail: "换手率、换手率标准字段、有效换手率turnover 是 turnover_ratio 的兼容别名".to_string() },
ManualField { name: "open/high/low/close/last/last_price/prev_close/amount".to_string(), field_type: "float".to_string(), detail: "开盘、最高、最低、收盘、盘中价、昨收和成交额。".to_string() }, ManualField { name: "open/high/low/close/last/last_price/prev_close/amount".to_string(), field_type: "float".to_string(), detail: "开盘、最高、最低、收盘、盘中价、昨收和成交额。".to_string() },
ManualField { name: "upper_limit/lower_limit/price_tick/round_lot/minimum_order_quantity/order_step_size".to_string(), field_type: "float/int".to_string(), detail: "涨跌停、最小价位、整手、最小下单量和数量步长。KSH/BJSE 等板块可与 round_lot 不同。".to_string() }, ManualField { name: "upper_limit/lower_limit/price_tick/round_lot/minimum_order_quantity/order_step_size".to_string(), field_type: "float/int".to_string(), detail: "涨跌停、最小价位、整手、最小下单量和数量步长。KSH/BJSE 等板块可与 round_lot 不同。".to_string() },
ManualField { name: "paused/is_st/is_kcb/is_one_yuan/is_new_listing".to_string(), field_type: "bool".to_string(), detail: "可交易性与板块标志。".to_string() }, ManualField { name: "paused/is_st/is_kcb/is_one_yuan/is_new_listing".to_string(), field_type: "bool".to_string(), detail: "可交易性与板块标志。".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_ma6060日价格均线写 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 == 0risk.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_auctionexecution.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_ma6060日价格均线写 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 == 0risk.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_auctionnext_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() {