完善平台表达式因子执行能力
This commit is contained in:
@@ -1675,6 +1675,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 +1764,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,8 +2011,9 @@ 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);
|
||||||
@@ -2028,6 +2031,28 @@ impl PlatformExprStrategy {
|
|||||||
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 +2791,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;
|
||||||
@@ -4006,7 +4039,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 +4108,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),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -5376,7 +5410,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");
|
||||||
@@ -5534,6 +5572,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);
|
||||||
|
|||||||
@@ -262,7 +262,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() },
|
||||||
|
|||||||
Reference in New Issue
Block a user