Compare commits
9 Commits
v2026.4.30
...
v2026.5.12
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2165831708 | ||
|
|
1a402f2048 | ||
|
|
bbe60537ff | ||
|
|
3b033fd294 | ||
|
|
d9de9715ef | ||
|
|
65742d4d5e | ||
|
|
a47c7c3e49 | ||
|
|
adc2f12ddf | ||
|
|
e06a1e88e5 |
@@ -100,6 +100,57 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||||
engine.run()?
|
engine.run()?
|
||||||
}
|
}
|
||||||
|
"aiquant-v104" => {
|
||||||
|
let mut strategy_cfg = OmniMicroCapConfig::aiquant_v104();
|
||||||
|
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||||
|
if !signal_symbol.trim().is_empty() {
|
||||||
|
strategy_cfg.benchmark_signal_symbol = signal_symbol;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(date) = debug_date {
|
||||||
|
let eligible = data.eligible_universe_on(date);
|
||||||
|
eprintln!(
|
||||||
|
"DEBUG eligible_universe_on {} count={}",
|
||||||
|
date,
|
||||||
|
eligible.len()
|
||||||
|
);
|
||||||
|
for row in eligible.iter().take(20) {
|
||||||
|
eprintln!(" {} {:.6}", row.symbol, row.market_cap_bn);
|
||||||
|
}
|
||||||
|
let mut debug_strategy = OmniMicroCapStrategy::new(strategy_cfg.clone());
|
||||||
|
let debug_subscriptions = BTreeSet::new();
|
||||||
|
let decision = debug_strategy.on_day(&StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 1,
|
||||||
|
data: &data,
|
||||||
|
portfolio: &PortfolioState::new(20_000.0),
|
||||||
|
futures_account: None,
|
||||||
|
open_orders: &[],
|
||||||
|
dynamic_universe: None,
|
||||||
|
subscriptions: &debug_subscriptions,
|
||||||
|
process_events: &[],
|
||||||
|
active_process_event: None,
|
||||||
|
active_datetime: None,
|
||||||
|
order_events: &[],
|
||||||
|
fills: &[],
|
||||||
|
})?;
|
||||||
|
eprintln!("DEBUG notes={:?}", decision.notes);
|
||||||
|
eprintln!("DEBUG diagnostics={:?}", decision.diagnostics);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
config.decision_lag_trading_days = decision_lag.unwrap_or(1);
|
||||||
|
config.execution_price_field = execution_price.unwrap_or(PriceField::Close);
|
||||||
|
config.initial_cash = initial_cash.unwrap_or(20_000.0);
|
||||||
|
let strategy = OmniMicroCapStrategy::new(strategy_cfg);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
config.execution_price_field,
|
||||||
|
);
|
||||||
|
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||||
|
engine.run()?
|
||||||
|
}
|
||||||
_ => {
|
_ => {
|
||||||
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
|
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
|
||||||
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||||
|
|||||||
17
crates/fidc-core/src/bin/dump_platform_runtime_schema.rs
Normal file
17
crates/fidc-core/src/bin/dump_platform_runtime_schema.rs
Normal 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}");
|
||||||
|
}
|
||||||
@@ -110,6 +110,7 @@ pub struct BrokerSimulator<C, R> {
|
|||||||
volume_limit: bool,
|
volume_limit: bool,
|
||||||
inactive_limit: bool,
|
inactive_limit: bool,
|
||||||
liquidity_limit: bool,
|
liquidity_limit: bool,
|
||||||
|
strict_value_budget: bool,
|
||||||
intraday_execution_start_time: Option<NaiveTime>,
|
intraday_execution_start_time: Option<NaiveTime>,
|
||||||
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
|
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
|
||||||
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
||||||
@@ -130,6 +131,7 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
volume_limit: true,
|
volume_limit: true,
|
||||||
inactive_limit: true,
|
inactive_limit: true,
|
||||||
liquidity_limit: true,
|
liquidity_limit: true,
|
||||||
|
strict_value_budget: false,
|
||||||
intraday_execution_start_time: None,
|
intraday_execution_start_time: None,
|
||||||
runtime_intraday_start_time: Cell::new(None),
|
runtime_intraday_start_time: Cell::new(None),
|
||||||
runtime_intraday_end_time: Cell::new(None),
|
runtime_intraday_end_time: Cell::new(None),
|
||||||
@@ -154,6 +156,7 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
volume_limit: true,
|
volume_limit: true,
|
||||||
inactive_limit: true,
|
inactive_limit: true,
|
||||||
liquidity_limit: true,
|
liquidity_limit: true,
|
||||||
|
strict_value_budget: false,
|
||||||
intraday_execution_start_time: None,
|
intraday_execution_start_time: None,
|
||||||
runtime_intraday_start_time: Cell::new(None),
|
runtime_intraday_start_time: Cell::new(None),
|
||||||
runtime_intraday_end_time: Cell::new(None),
|
runtime_intraday_end_time: Cell::new(None),
|
||||||
@@ -177,6 +180,11 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_strict_value_budget(mut self, enabled: bool) -> Self {
|
||||||
|
self.strict_value_budget = enabled;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
|
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
|
||||||
self.volume_percent = volume_percent;
|
self.volume_percent = volume_percent;
|
||||||
self
|
self
|
||||||
@@ -3388,6 +3396,16 @@ where
|
|||||||
requested_qty
|
requested_qty
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn value_budget_gross_limit(&self, value_budget: Option<f64>) -> Option<f64> {
|
||||||
|
value_budget.map(|budget| {
|
||||||
|
if self.strict_value_budget {
|
||||||
|
budget
|
||||||
|
} else {
|
||||||
|
budget + 400.0
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn process_buy(
|
fn process_buy(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
@@ -3559,7 +3577,7 @@ where
|
|||||||
execution_cursors,
|
execution_cursors,
|
||||||
None,
|
None,
|
||||||
Some(portfolio.cash()),
|
Some(portfolio.cash()),
|
||||||
value_budget.map(|budget| budget + 400.0),
|
self.value_budget_gross_limit(value_budget),
|
||||||
algo_request,
|
algo_request,
|
||||||
limit_price,
|
limit_price,
|
||||||
);
|
);
|
||||||
@@ -3590,7 +3608,7 @@ where
|
|||||||
let filled_qty = self.affordable_buy_quantity(
|
let filled_qty = self.affordable_buy_quantity(
|
||||||
date,
|
date,
|
||||||
portfolio.cash(),
|
portfolio.cash(),
|
||||||
value_budget.map(|budget| budget + 400.0),
|
self.value_budget_gross_limit(value_budget),
|
||||||
execution_price,
|
execution_price,
|
||||||
constrained_qty,
|
constrained_qty,
|
||||||
self.minimum_order_quantity(data, symbol),
|
self.minimum_order_quantity(data, symbol),
|
||||||
@@ -3601,7 +3619,7 @@ where
|
|||||||
partial_fill_reason,
|
partial_fill_reason,
|
||||||
self.buy_reduction_reason(
|
self.buy_reduction_reason(
|
||||||
portfolio.cash(),
|
portfolio.cash(),
|
||||||
value_budget.map(|budget| budget + 400.0),
|
self.value_budget_gross_limit(value_budget),
|
||||||
execution_price,
|
execution_price,
|
||||||
constrained_qty,
|
constrained_qty,
|
||||||
filled_qty,
|
filled_qty,
|
||||||
@@ -3660,7 +3678,7 @@ where
|
|||||||
side: OrderSide::Buy,
|
side: OrderSide::Buy,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
filled_quantity: 0,
|
filled_quantity: 0,
|
||||||
status: OrderStatus::Rejected,
|
status: zero_fill_status_for_reason(detail),
|
||||||
reason: format!("{reason}: {detail}"),
|
reason: format!("{reason}: {detail}"),
|
||||||
});
|
});
|
||||||
Self::emit_order_process_event(
|
Self::emit_order_process_event(
|
||||||
@@ -3670,7 +3688,10 @@ where
|
|||||||
order_id,
|
order_id,
|
||||||
symbol,
|
symbol,
|
||||||
OrderSide::Buy,
|
OrderSide::Buy,
|
||||||
format!("status=Rejected reason={detail}"),
|
format!(
|
||||||
|
"status={:?} reason={detail}",
|
||||||
|
zero_fill_status_for_reason(detail)
|
||||||
|
),
|
||||||
);
|
);
|
||||||
self.clear_open_order(order_id);
|
self.clear_open_order(order_id);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -4255,57 +4276,43 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
if algo_request.is_some() || self.intraday_execution_start_time.is_some() {
|
if algo_request.is_some() || self.intraday_execution_start_time.is_some() {
|
||||||
let execution_price = self.snapshot_execution_price(snapshot, side);
|
|
||||||
if !self.price_satisfies_limit(
|
|
||||||
side,
|
|
||||||
execution_price,
|
|
||||||
limit_price,
|
|
||||||
snapshot.effective_price_tick(),
|
|
||||||
) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let execution_price =
|
|
||||||
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
|
||||||
let quantity = match side {
|
|
||||||
OrderSide::Buy => self.affordable_buy_quantity(
|
|
||||||
date,
|
|
||||||
cash_limit.unwrap_or(f64::INFINITY),
|
|
||||||
gross_limit,
|
|
||||||
execution_price,
|
|
||||||
requested_qty,
|
|
||||||
minimum_order_quantity,
|
|
||||||
order_step_size,
|
|
||||||
),
|
|
||||||
OrderSide::Sell => requested_qty,
|
|
||||||
};
|
|
||||||
if quantity == 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let next_cursor = algo_request
|
let next_cursor = algo_request
|
||||||
.and_then(|request| request.start_time)
|
.and_then(|request| request.start_time)
|
||||||
.or(self.intraday_execution_start_time)
|
.or(self.intraday_execution_start_time)
|
||||||
.map(|start_time| date.and_time(start_time) + Duration::seconds(1))
|
.map(|start_time| date.and_time(start_time) + Duration::seconds(1))
|
||||||
.unwrap_or_else(|| date.and_hms_opt(0, 0, 1).expect("valid midnight"));
|
.unwrap_or_else(|| date.and_hms_opt(0, 0, 1).expect("valid midnight"));
|
||||||
return Some(ExecutionFill {
|
return Some(ExecutionFill {
|
||||||
quantity,
|
quantity: 0,
|
||||||
next_cursor,
|
next_cursor,
|
||||||
legs: vec![ExecutionLeg {
|
legs: Vec::new(),
|
||||||
price: execution_price,
|
unfilled_reason: Some(self.empty_intraday_quote_reason(
|
||||||
quantity,
|
quotes,
|
||||||
}],
|
start_cursor,
|
||||||
unfilled_reason: self.buy_reduction_reason(
|
end_cursor,
|
||||||
cash_limit.unwrap_or(f64::INFINITY),
|
)),
|
||||||
gross_limit,
|
|
||||||
execution_price,
|
|
||||||
requested_qty,
|
|
||||||
quantity,
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn empty_intraday_quote_reason(
|
||||||
|
&self,
|
||||||
|
quotes: &[IntradayExecutionQuote],
|
||||||
|
start_cursor: Option<NaiveDateTime>,
|
||||||
|
end_cursor: Option<NaiveDateTime>,
|
||||||
|
) -> &'static str {
|
||||||
|
let saw_quote_in_window = quotes.iter().any(|quote| {
|
||||||
|
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
|
||||||
|
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
|
||||||
|
});
|
||||||
|
if saw_quote_in_window {
|
||||||
|
"intraday quote liquidity exhausted"
|
||||||
|
} else {
|
||||||
|
"no execution quotes after start"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn select_execution_fill(
|
fn select_execution_fill(
|
||||||
&self,
|
&self,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
@@ -4487,7 +4494,10 @@ fn merge_partial_fill_reason(current: Option<String>, next: Option<&str>) -> Opt
|
|||||||
|
|
||||||
fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
|
fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
|
||||||
match reason {
|
match reason {
|
||||||
"tick no volume" | "tick volume limit" => OrderStatus::Canceled,
|
"tick no volume"
|
||||||
|
| "tick volume limit"
|
||||||
|
| "intraday quote liquidity exhausted"
|
||||||
|
| "no execution quotes after start" => OrderStatus::Canceled,
|
||||||
_ => OrderStatus::Rejected,
|
_ => OrderStatus::Rejected,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -682,6 +682,23 @@ impl BenchmarkPriceSeries {
|
|||||||
self.moving_average_for(date, lookback, PriceField::Close)
|
self.moving_average_for(date, lookback, PriceField::Close)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn decision_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let end = match self.dates.binary_search(&date) {
|
||||||
|
Ok(idx) => idx,
|
||||||
|
Err(0) => return None,
|
||||||
|
Err(idx) => idx,
|
||||||
|
};
|
||||||
|
if end < lookback {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let start = end - lookback;
|
||||||
|
let sum = self.close_prefix[end] - self.close_prefix[start];
|
||||||
|
Some(sum / lookback as f64)
|
||||||
|
}
|
||||||
|
|
||||||
fn moving_average_for(
|
fn moving_average_for(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
@@ -2123,6 +2140,15 @@ impl DataSet {
|
|||||||
self.benchmark_series_cache.moving_average(date, lookback)
|
self.benchmark_series_cache.moving_average(date, lookback)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn benchmark_decision_moving_average(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Option<f64> {
|
||||||
|
self.benchmark_series_cache
|
||||||
|
.decision_moving_average(date, lookback)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn benchmark_open_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
pub fn benchmark_open_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||||
self.benchmark_series_cache
|
self.benchmark_series_cache
|
||||||
.moving_average_for(date, lookback, PriceField::Open)
|
.moving_average_for(date, lookback, PriceField::Open)
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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};
|
||||||
@@ -198,6 +199,9 @@ pub struct PlatformExprStrategyConfig {
|
|||||||
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
||||||
pub rebalance_schedule: Option<PlatformRebalanceSchedule>,
|
pub rebalance_schedule: Option<PlatformRebalanceSchedule>,
|
||||||
pub rotation_enabled: bool,
|
pub rotation_enabled: bool,
|
||||||
|
pub daily_top_up_enabled: bool,
|
||||||
|
pub retry_empty_rebalance: bool,
|
||||||
|
pub strict_value_budget: bool,
|
||||||
pub explicit_action_stage: PlatformExplicitActionStage,
|
pub explicit_action_stage: PlatformExplicitActionStage,
|
||||||
pub explicit_action_schedule: Option<PlatformRebalanceSchedule>,
|
pub explicit_action_schedule: Option<PlatformRebalanceSchedule>,
|
||||||
pub subscription_guard_required: bool,
|
pub subscription_guard_required: bool,
|
||||||
@@ -248,6 +252,9 @@ fn band_low(index_close) {
|
|||||||
skip_month_day_ranges: Vec::new(),
|
skip_month_day_ranges: Vec::new(),
|
||||||
rebalance_schedule: None,
|
rebalance_schedule: None,
|
||||||
rotation_enabled: true,
|
rotation_enabled: true,
|
||||||
|
daily_top_up_enabled: false,
|
||||||
|
retry_empty_rebalance: false,
|
||||||
|
strict_value_budget: false,
|
||||||
explicit_action_stage: PlatformExplicitActionStage::OnDay,
|
explicit_action_stage: PlatformExplicitActionStage::OnDay,
|
||||||
explicit_action_schedule: None,
|
explicit_action_schedule: None,
|
||||||
subscription_guard_required: false,
|
subscription_guard_required: false,
|
||||||
@@ -415,6 +422,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 +482,68 @@ 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> {
|
||||||
|
// 命中分支:先借用 cache 拿到 AST,做完 eval 再 drop borrow,避免与
|
||||||
|
// cache_hits 的 borrow_mut 冲突(虽然是不同 RefCell,但显式作用域更清晰)。
|
||||||
|
{
|
||||||
|
let cache = self.compiled_cache.borrow();
|
||||||
|
if let Some(ast) = cache.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 {
|
||||||
@@ -801,53 +878,6 @@ impl PlatformExprStrategy {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(market) = ctx.data.market(date, symbol) {
|
|
||||||
let execution_price = self.projected_execution_price(market, side);
|
|
||||||
if execution_price.is_finite() && execution_price > 0.0 {
|
|
||||||
let quantity = match side {
|
|
||||||
OrderSide::Buy => {
|
|
||||||
let cash = cash_limit.unwrap_or(f64::INFINITY);
|
|
||||||
let mut take_qty = self.round_lot_quantity(
|
|
||||||
requested_qty,
|
|
||||||
minimum_order_quantity,
|
|
||||||
order_step_size,
|
|
||||||
);
|
|
||||||
while take_qty > 0 {
|
|
||||||
let candidate_gross = execution_price * take_qty as f64;
|
|
||||||
if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) {
|
|
||||||
take_qty = self.decrement_order_quantity(
|
|
||||||
take_qty,
|
|
||||||
minimum_order_quantity,
|
|
||||||
order_step_size,
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let candidate_cash =
|
|
||||||
candidate_gross + self.buy_commission(candidate_gross);
|
|
||||||
if candidate_cash <= cash + 1e-6 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
take_qty = self.decrement_order_quantity(
|
|
||||||
take_qty,
|
|
||||||
minimum_order_quantity,
|
|
||||||
order_step_size,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
take_qty
|
|
||||||
}
|
|
||||||
OrderSide::Sell => requested_qty,
|
|
||||||
};
|
|
||||||
if quantity > 0 {
|
|
||||||
return Some(ProjectedExecutionFill {
|
|
||||||
price: execution_price,
|
|
||||||
quantity,
|
|
||||||
next_cursor: date.and_time(self.intraday_execution_start_time())
|
|
||||||
+ Duration::seconds(1),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let start_cursor = self.projected_execution_start_cursor(date, symbol, execution_state);
|
let start_cursor = self.projected_execution_start_cursor(date, symbol, execution_state);
|
||||||
let quotes = ctx.data.execution_quotes_on(date, symbol);
|
let quotes = ctx.data.execution_quotes_on(date, symbol);
|
||||||
let mut filled_qty = 0_u32;
|
let mut filled_qty = 0_u32;
|
||||||
@@ -962,12 +992,18 @@ impl PlatformExprStrategy {
|
|||||||
None,
|
None,
|
||||||
execution_state,
|
execution_state,
|
||||||
)
|
)
|
||||||
.unwrap_or(ProjectedExecutionFill {
|
.or_else(|| {
|
||||||
price: self.projected_execution_price(market, OrderSide::Sell),
|
if ctx.data.execution_quotes_on(date, symbol).is_empty() {
|
||||||
quantity,
|
None
|
||||||
next_cursor: date.and_time(self.intraday_execution_start_time())
|
} else {
|
||||||
+ Duration::seconds(1),
|
Some(ProjectedExecutionFill {
|
||||||
});
|
price: self.projected_execution_price(market, OrderSide::Sell),
|
||||||
|
quantity,
|
||||||
|
next_cursor: date.and_time(self.intraday_execution_start_time())
|
||||||
|
+ Duration::seconds(1),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})?;
|
||||||
let gross_amount = fill.price * fill.quantity as f64;
|
let gross_amount = fill.price * fill.quantity as f64;
|
||||||
let net_cash = gross_amount - self.sell_cost(date, gross_amount);
|
let net_cash = gross_amount - self.sell_cost(date, gross_amount);
|
||||||
projected
|
projected
|
||||||
@@ -1016,9 +1052,14 @@ impl PlatformExprStrategy {
|
|||||||
);
|
);
|
||||||
let execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
let execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
||||||
let mut quantity = snapshot_requested_qty;
|
let mut quantity = snapshot_requested_qty;
|
||||||
|
let gross_limit = if self.config.strict_value_budget {
|
||||||
|
order_value
|
||||||
|
} else {
|
||||||
|
order_value + 400.0
|
||||||
|
};
|
||||||
while quantity > 0 {
|
while quantity > 0 {
|
||||||
let gross_amount = execution_price * quantity as f64;
|
let gross_amount = execution_price * quantity as f64;
|
||||||
if gross_amount <= order_value + 400.0
|
if gross_amount <= gross_limit
|
||||||
&& gross_amount + self.buy_commission(gross_amount) <= projected.cash() + 1e-6
|
&& gross_amount + self.buy_commission(gross_amount) <= projected.cash() + 1e-6
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -1041,15 +1082,24 @@ impl PlatformExprStrategy {
|
|||||||
order_step_size,
|
order_step_size,
|
||||||
false,
|
false,
|
||||||
Some(projected.cash()),
|
Some(projected.cash()),
|
||||||
Some(order_value + 400.0),
|
Some(gross_limit),
|
||||||
execution_state,
|
execution_state,
|
||||||
)
|
)
|
||||||
.unwrap_or(ProjectedExecutionFill {
|
.or_else(|| {
|
||||||
price: execution_price,
|
if ctx.data.execution_quotes_on(date, symbol).is_empty() {
|
||||||
quantity,
|
None
|
||||||
next_cursor: date.and_time(self.intraday_execution_start_time())
|
} else {
|
||||||
+ Duration::seconds(1),
|
Some(ProjectedExecutionFill {
|
||||||
|
price: execution_price,
|
||||||
|
quantity,
|
||||||
|
next_cursor: date.and_time(self.intraday_execution_start_time())
|
||||||
|
+ Duration::seconds(1),
|
||||||
|
})
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
let Some(fill) = fill else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
let gross_amount = fill.price * fill.quantity as f64;
|
let gross_amount = fill.price * fill.quantity as f64;
|
||||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
if cash_out > projected.cash() + 1e-6 {
|
if cash_out > projected.cash() + 1e-6 {
|
||||||
@@ -1111,46 +1161,56 @@ impl PlatformExprStrategy {
|
|||||||
let benchmark_close = benchmark.close;
|
let benchmark_close = benchmark.close;
|
||||||
let benchmark_ma_short = ctx
|
let benchmark_ma_short = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(
|
.benchmark_decision_moving_average(date, self.config.benchmark_short_ma_days)
|
||||||
date,
|
.or_else(|| {
|
||||||
&self.config.signal_symbol,
|
ctx.data
|
||||||
self.config.benchmark_short_ma_days,
|
.benchmark_moving_average(date, self.config.benchmark_short_ma_days)
|
||||||
)
|
})
|
||||||
.ok_or_else(|| {
|
.unwrap_or(benchmark_close);
|
||||||
BacktestError::Execution(format!(
|
|
||||||
"insufficient benchmark short MA history for {} on {}",
|
|
||||||
self.config.signal_symbol, date
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
let benchmark_ma_long = ctx
|
let benchmark_ma_long = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(
|
.benchmark_decision_moving_average(date, self.config.benchmark_long_ma_days)
|
||||||
date,
|
.or_else(|| {
|
||||||
&self.config.signal_symbol,
|
ctx.data
|
||||||
self.config.benchmark_long_ma_days,
|
.benchmark_moving_average(date, self.config.benchmark_long_ma_days)
|
||||||
)
|
})
|
||||||
.ok_or_else(|| {
|
.unwrap_or(benchmark_ma_short);
|
||||||
BacktestError::Execution(format!(
|
|
||||||
"insufficient benchmark long MA history for {} on {}",
|
|
||||||
self.config.signal_symbol, date
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
let benchmark_ma5 = ctx
|
let benchmark_ma5 = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(date, &self.config.signal_symbol, 5)
|
.benchmark_decision_moving_average(date, 5)
|
||||||
|
.or_else(|| ctx.data.benchmark_moving_average(date, 5))
|
||||||
.unwrap_or(benchmark_ma_short);
|
.unwrap_or(benchmark_ma_short);
|
||||||
let benchmark_ma10 = ctx
|
let benchmark_ma10 = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(date, &self.config.signal_symbol, 10)
|
.benchmark_decision_moving_average(date, 10)
|
||||||
|
.or_else(|| ctx.data.benchmark_moving_average(date, 10))
|
||||||
.unwrap_or(benchmark_ma_long);
|
.unwrap_or(benchmark_ma_long);
|
||||||
let benchmark_ma20 = ctx
|
let benchmark_ma20 = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(date, &self.config.signal_symbol, 20)
|
.benchmark_decision_moving_average(date, 20)
|
||||||
|
.or_else(|| ctx.data.benchmark_moving_average(date, 20))
|
||||||
.unwrap_or(benchmark_ma10);
|
.unwrap_or(benchmark_ma10);
|
||||||
let benchmark_ma30 = ctx
|
let benchmark_ma30 = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(date, &self.config.signal_symbol, 30)
|
.benchmark_decision_moving_average(date, 30)
|
||||||
|
.or_else(|| ctx.data.benchmark_moving_average(date, 30))
|
||||||
.unwrap_or(benchmark_ma20);
|
.unwrap_or(benchmark_ma20);
|
||||||
|
let signal_ma5 = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_close_moving_average(date, &self.config.signal_symbol, 5)
|
||||||
|
.unwrap_or(benchmark_ma5);
|
||||||
|
let signal_ma10 = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_close_moving_average(date, &self.config.signal_symbol, 10)
|
||||||
|
.unwrap_or(benchmark_ma10);
|
||||||
|
let signal_ma20 = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_close_moving_average(date, &self.config.signal_symbol, 20)
|
||||||
|
.unwrap_or(benchmark_ma20);
|
||||||
|
let signal_ma30 = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_close_moving_average(date, &self.config.signal_symbol, 30)
|
||||||
|
.unwrap_or(benchmark_ma30);
|
||||||
let account = ctx.account();
|
let account = ctx.account();
|
||||||
let cash = account.cash;
|
let cash = account.cash;
|
||||||
let market_value = account.market_value;
|
let market_value = account.market_value;
|
||||||
@@ -1175,10 +1235,10 @@ impl PlatformExprStrategy {
|
|||||||
benchmark_ma10,
|
benchmark_ma10,
|
||||||
benchmark_ma20,
|
benchmark_ma20,
|
||||||
benchmark_ma30,
|
benchmark_ma30,
|
||||||
signal_ma5: benchmark_ma5,
|
signal_ma5,
|
||||||
signal_ma10: benchmark_ma10,
|
signal_ma10,
|
||||||
signal_ma20: benchmark_ma20,
|
signal_ma20,
|
||||||
signal_ma30: benchmark_ma30,
|
signal_ma30,
|
||||||
cash,
|
cash,
|
||||||
available_cash: account.available_cash,
|
available_cash: account.available_cash,
|
||||||
frozen_cash: account.frozen_cash,
|
frozen_cash: account.frozen_cash,
|
||||||
@@ -2020,11 +2080,7 @@ impl PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
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 {
|
||||||
@@ -4134,6 +4190,77 @@ impl PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn selectable_universe_on(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
date: NaiveDate,
|
||||||
|
) -> Vec<EligibleUniverseSnapshot> {
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for factor in ctx.data.factor_snapshots_on(date) {
|
||||||
|
if factor.market_cap_bn <= 0.0 || !factor.market_cap_bn.is_finite() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ctx.has_dynamic_universe() && !ctx.dynamic_universe_contains(&factor.symbol) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(candidate) = ctx.data.candidate(date, &factor.symbol) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(market) = ctx.data.market(date, &factor.symbol) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if market.paused {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !self.stock_passes_universe_exclude(
|
||||||
|
candidate,
|
||||||
|
market,
|
||||||
|
self.special_name(ctx, &factor.symbol),
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rows.push(EligibleUniverseSnapshot {
|
||||||
|
symbol: factor.symbol.clone(),
|
||||||
|
market_cap_bn: factor.market_cap_bn,
|
||||||
|
free_float_cap_bn: factor.free_float_cap_bn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
rows.sort_by(|left, right| {
|
||||||
|
left.market_cap_bn
|
||||||
|
.partial_cmp(&right.market_cap_bn)
|
||||||
|
.unwrap_or(std::cmp::Ordering::Equal)
|
||||||
|
.then_with(|| left.symbol.cmp(&right.symbol))
|
||||||
|
});
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stock_passes_universe_exclude(
|
||||||
|
&self,
|
||||||
|
candidate: &crate::data::CandidateEligibility,
|
||||||
|
market: &DailyMarketSnapshot,
|
||||||
|
has_special_name: bool,
|
||||||
|
) -> bool {
|
||||||
|
let excludes = &self.config.universe_exclude;
|
||||||
|
if excludes.iter().any(|item| item == "paused") && (market.paused || candidate.is_paused) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "st") && (candidate.is_st || has_special_name) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "kcb") && candidate.is_kcb {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "new_listing") && candidate.is_new_listing {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "one_yuan")
|
||||||
|
&& (candidate.is_one_yuan || market.day_open <= 1.0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
candidate.allow_buy && candidate.allow_sell
|
||||||
|
}
|
||||||
|
|
||||||
fn stock_numeric_field_value(
|
fn stock_numeric_field_value(
|
||||||
&self,
|
&self,
|
||||||
candidate: &EligibleUniverseSnapshot,
|
candidate: &EligibleUniverseSnapshot,
|
||||||
@@ -4297,7 +4424,7 @@ impl PlatformExprStrategy {
|
|||||||
band_high: f64,
|
band_high: f64,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
) -> Result<(Vec<String>, Vec<String>), BacktestError> {
|
) -> Result<(Vec<String>, Vec<String>), BacktestError> {
|
||||||
let universe = ctx.eligible_universe_on(date);
|
let universe = self.selectable_universe_on(ctx, date);
|
||||||
let mut diagnostics = Vec::new();
|
let mut diagnostics = Vec::new();
|
||||||
let mut candidates = Vec::new();
|
let mut candidates = Vec::new();
|
||||||
for candidate in universe {
|
for candidate in universe {
|
||||||
@@ -4569,6 +4696,8 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
|
let empty_rebalance_retry =
|
||||||
|
self.config.retry_empty_rebalance && ctx.portfolio.positions().is_empty();
|
||||||
let periodic_rebalance = if self.config.rotation_enabled {
|
let periodic_rebalance = if self.config.rotation_enabled {
|
||||||
if let Some(schedule) = &self.config.rebalance_schedule {
|
if let Some(schedule) = &self.config.rebalance_schedule {
|
||||||
schedule.matches(
|
schedule.matches(
|
||||||
@@ -4576,9 +4705,9 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
execution_date,
|
execution_date,
|
||||||
ScheduleStage::OnDay,
|
ScheduleStage::OnDay,
|
||||||
default_stage_time(ScheduleStage::OnDay),
|
default_stage_time(ScheduleStage::OnDay),
|
||||||
)
|
) || empty_rebalance_retry
|
||||||
} else {
|
} else {
|
||||||
ctx.decision_index % self.config.refresh_rate == 0
|
ctx.decision_index % self.config.refresh_rate == 0 || empty_rebalance_retry
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
@@ -4697,7 +4826,7 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let fixed_buy_cash = projected.cash() * trading_ratio / selection_limit as f64;
|
let fixed_buy_cash = projected.cash() * trading_ratio / selection_limit as f64;
|
||||||
for symbol in &stock_list {
|
for symbol in stock_list.iter().take(selection_limit) {
|
||||||
if projected.positions().len() >= selection_limit {
|
if projected.positions().len() >= selection_limit {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -4736,6 +4865,52 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if self.config.daily_top_up_enabled
|
||||||
|
&& self.config.rotation_enabled
|
||||||
|
&& !periodic_rebalance
|
||||||
|
&& !ctx.portfolio.positions().is_empty()
|
||||||
|
&& projected.positions().len() < selection_limit
|
||||||
|
{
|
||||||
|
let fixed_buy_cash = projected.total_value() * trading_ratio / selection_limit as f64;
|
||||||
|
let available_buy_cash = fixed_buy_cash.min(projected.cash());
|
||||||
|
if available_buy_cash >= fixed_buy_cash * 0.5 {
|
||||||
|
for symbol in &stock_list {
|
||||||
|
if projected.positions().contains_key(symbol) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let decision_stock = self.stock_state(ctx, decision_date, symbol)?;
|
||||||
|
let execution_stock = self.stock_state(ctx, execution_date, symbol)?;
|
||||||
|
if self
|
||||||
|
.buy_rejection_reason(ctx, execution_date, symbol, &execution_stock)?
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !self.stock_passes_expr(ctx, &day, &decision_stock)? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let buy_cash =
|
||||||
|
available_buy_cash * self.buy_scale(ctx, &day, &decision_stock)?;
|
||||||
|
if buy_cash <= 0.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
order_intents.push(OrderIntent::Value {
|
||||||
|
symbol: symbol.clone(),
|
||||||
|
value: buy_cash,
|
||||||
|
reason: "daily_top_up_buy".to_string(),
|
||||||
|
});
|
||||||
|
self.project_order_value(
|
||||||
|
ctx,
|
||||||
|
&mut projected,
|
||||||
|
execution_date,
|
||||||
|
symbol,
|
||||||
|
buy_cash,
|
||||||
|
&mut projected_execution_state,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !explicit_action_intents.is_empty() {
|
if !explicit_action_intents.is_empty() {
|
||||||
order_intents.extend(explicit_action_intents);
|
order_intents.extend(explicit_action_intents);
|
||||||
@@ -5741,6 +5916,152 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_strategy_honors_configured_universe_excludes_for_new_listings() {
|
||||||
|
let date = d(2025, 2, 3);
|
||||||
|
let symbols = ["301001.SZ", "000001.SZ"];
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| Instrument {
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
name: (*symbol).to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2025, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
timestamp: Some("2025-02-03 09:33: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,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![
|
||||||
|
DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "301001.SZ".to_string(),
|
||||||
|
market_cap_bn: 8.0,
|
||||||
|
free_float_cap_bn: 7.0,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
DailyFactorSnapshot {
|
||||||
|
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(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "301001.SZ".to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: true,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
},
|
||||||
|
CandidateEligibility {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1002.0,
|
||||||
|
prev_close: 998.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 0,
|
||||||
|
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.stock_short_ma_days = 1;
|
||||||
|
cfg.stock_mid_ma_days = 1;
|
||||||
|
cfg.stock_long_ma_days = 1;
|
||||||
|
cfg.universe_exclude = vec![
|
||||||
|
"paused".to_string(),
|
||||||
|
"st".to_string(),
|
||||||
|
"kcb".to_string(),
|
||||||
|
"one_yuan".to_string(),
|
||||||
|
];
|
||||||
|
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 = "true".to_string();
|
||||||
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||||
|
|
||||||
|
assert!(decision.order_intents.iter().any(|intent| matches!(
|
||||||
|
intent,
|
||||||
|
crate::strategy::OrderIntent::Value { symbol, .. } if symbol == "301001.SZ"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
#[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)];
|
||||||
@@ -6012,6 +6333,139 @@ mod tests {
|
|||||||
assert_eq!(decision.order_intents.len(), 1);
|
assert_eq!(decision.order_intents.len(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_daily_top_up_keeps_selection_limited_to_target_count() {
|
||||||
|
let date = d(2025, 2, 3);
|
||||||
|
let symbols = ["000001.SZ", "000002.SZ", "000003.SZ"];
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| Instrument {
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
name: (*symbol).to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2020, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
timestamp: Some("2025-02-03 09:33: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,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, symbol)| DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
market_cap_bn: 10.0 + index as f64,
|
||||||
|
free_float_cap_bn: 10.0 + index as f64,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| CandidateEligibility {
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1002.0,
|
||||||
|
prev_close: 998.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(30_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: 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 = "000001.SZ".to_string();
|
||||||
|
cfg.refresh_rate = 99;
|
||||||
|
cfg.max_positions = 2;
|
||||||
|
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 = "2".to_string();
|
||||||
|
cfg.stock_filter_expr = "close > 0".to_string();
|
||||||
|
cfg.daily_top_up_enabled = true;
|
||||||
|
cfg.retry_empty_rebalance = true;
|
||||||
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
decision
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|item| item.contains("selected=2")),
|
||||||
|
"{:?}",
|
||||||
|
decision.diagnostics
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!decision
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|item| item.contains("selected=3")),
|
||||||
|
"{:?}",
|
||||||
|
decision.diagnostics
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[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);
|
||||||
@@ -7447,4 +7901,133 @@ mod tests {
|
|||||||
let decision = strategy.on_day(&ctx).expect("platform decision");
|
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||||
assert_eq!(decision.order_intents.len(), 1);
|
assert_eq!(decision.order_intents.len(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ast_cache_reuses_compiled_ast_across_invocations() {
|
||||||
|
let date = d(2025, 2, 3);
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
name: "Ping An Bank".to_string(),
|
||||||
|
board: "SZSE".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2010, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
timestamp: Some("10:18:00".to_string()),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.2,
|
||||||
|
low: 9.9,
|
||||||
|
close: 10.1,
|
||||||
|
last_price: 10.05,
|
||||||
|
bid1: 10.04,
|
||||||
|
ask1: 10.05,
|
||||||
|
prev_close: 9.95,
|
||||||
|
volume: 1_000_000,
|
||||||
|
tick_volume: 5_000,
|
||||||
|
bid1_volume: 1_000,
|
||||||
|
ask1_volume: 1_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 10.94,
|
||||||
|
lower_limit: 8.96,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
market_cap_bn: 12.0,
|
||||||
|
free_float_cap_bn: 10.0,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(22.0),
|
||||||
|
effective_turnover_ratio: Some(18.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
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,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1002.0,
|
||||||
|
prev_close: 998.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 0,
|
||||||
|
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.rotation_enabled = false;
|
||||||
|
cfg.benchmark_short_ma_days = 1;
|
||||||
|
cfg.benchmark_long_ma_days = 1;
|
||||||
|
cfg.explicit_actions = vec![PlatformTradeAction::Order {
|
||||||
|
kind: PlatformExplicitOrderKind::Value,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
amount_expr: "cash * 0.1".to_string(),
|
||||||
|
limit_price_expr: None,
|
||||||
|
start_time_expr: None,
|
||||||
|
end_time_expr: None,
|
||||||
|
when_expr: Some("allow_buy".to_string()),
|
||||||
|
reason: "ast_cache_reuse".to_string(),
|
||||||
|
}];
|
||||||
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
// 第一次调用:所有表达式 cache miss。
|
||||||
|
let _ = strategy.on_day(&ctx).expect("first decision");
|
||||||
|
let misses_after_first = strategy.ast_cache_misses();
|
||||||
|
let hits_after_first = strategy.ast_cache_hits();
|
||||||
|
assert!(
|
||||||
|
misses_after_first > 0,
|
||||||
|
"first run should populate cache, misses={}",
|
||||||
|
misses_after_first
|
||||||
|
);
|
||||||
|
|
||||||
|
// 第二次调用:相同表达式,cache hit 数应当 > 第一次。
|
||||||
|
let _ = strategy.on_day(&ctx).expect("second decision");
|
||||||
|
let misses_after_second = strategy.ast_cache_misses();
|
||||||
|
let hits_after_second = strategy.ast_cache_hits();
|
||||||
|
assert!(
|
||||||
|
hits_after_second > hits_after_first,
|
||||||
|
"second run should reuse cached AST, hits {} -> {}",
|
||||||
|
hits_after_first,
|
||||||
|
hits_after_second
|
||||||
|
);
|
||||||
|
// 缓存条目数不应该再增长(相同 script):misses 不再增加。
|
||||||
|
assert_eq!(
|
||||||
|
misses_after_second, misses_after_first,
|
||||||
|
"second run should not introduce new misses for same scripts"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
345
crates/fidc-core/src/platform_runtime_schema.rs
Normal file
345
crates/fidc-core/src/platform_runtime_schema.rs
Normal file
@@ -0,0 +1,345 @@
|
|||||||
|
//! 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}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@ pub struct StrategyRuntimeSpec {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub benchmark: Option<StrategyBenchmarkSpec>,
|
pub benchmark: Option<StrategyBenchmarkSpec>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub universe: Option<StrategyUniverseSpec>,
|
||||||
|
#[serde(default)]
|
||||||
pub signal_symbol: Option<String>,
|
pub signal_symbol: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub execution: Option<StrategyExecutionSpec>,
|
pub execution: Option<StrategyExecutionSpec>,
|
||||||
@@ -40,6 +42,13 @@ pub struct StrategyBenchmarkSpec {
|
|||||||
pub fallback_instrument_id: Option<String>,
|
pub fallback_instrument_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct StrategyUniverseSpec {
|
||||||
|
#[serde(default)]
|
||||||
|
pub exclude: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct StrategyExecutionSpec {
|
pub struct StrategyExecutionSpec {
|
||||||
@@ -49,6 +58,8 @@ pub struct StrategyExecutionSpec {
|
|||||||
pub slippage_model: Option<String>,
|
pub slippage_model: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub slippage_value: Option<f64>,
|
pub slippage_value: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub strict_value_budget: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
@@ -83,6 +94,8 @@ pub struct StrategyEngineConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub slippage_value: Option<f64>,
|
pub slippage_value: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub strict_value_budget: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
pub dividend_reinvestment: Option<bool>,
|
pub dividend_reinvestment: Option<bool>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
|
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
|
||||||
@@ -101,6 +114,15 @@ pub struct DynamicRangeConfig {
|
|||||||
pub cap_span: Option<f64>,
|
pub cap_span: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub xs: Option<f64>,
|
pub xs: Option<f64>,
|
||||||
|
/// Padding ratio to expand the market cap range (e.g., 0.5 means 50% of span)
|
||||||
|
#[serde(default)]
|
||||||
|
pub padding_ratio: Option<f64>,
|
||||||
|
/// Minimum padding in billion yuan
|
||||||
|
#[serde(default)]
|
||||||
|
pub min_padding: Option<f64>,
|
||||||
|
/// Maximum padding in billion yuan
|
||||||
|
#[serde(default)]
|
||||||
|
pub max_padding: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
@@ -224,6 +246,10 @@ pub struct StrategyExpressionTradingConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub rotation_enabled: Option<bool>,
|
pub rotation_enabled: Option<bool>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub daily_top_up: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub retry_empty_rebalance: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
pub subscription_guard_required: Option<bool>,
|
pub subscription_guard_required: Option<bool>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub actions: Vec<StrategyExpressionActionConfig>,
|
pub actions: Vec<StrategyExpressionActionConfig>,
|
||||||
@@ -416,6 +442,14 @@ pub fn platform_expr_config_from_spec(
|
|||||||
cfg.signal_symbol = spec_signal_symbol.clone();
|
cfg.signal_symbol = spec_signal_symbol.clone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(universe) = spec.universe.as_ref() {
|
||||||
|
cfg.universe_exclude = universe
|
||||||
|
.exclude
|
||||||
|
.iter()
|
||||||
|
.map(|item| item.trim().to_ascii_lowercase())
|
||||||
|
.filter(|item| !item.is_empty())
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
let mut prelude_parts = Vec::new();
|
let mut prelude_parts = Vec::new();
|
||||||
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
||||||
@@ -551,6 +585,24 @@ pub fn platform_expr_config_from_spec(
|
|||||||
if let Some(enabled) = trading.rotation_enabled {
|
if let Some(enabled) = trading.rotation_enabled {
|
||||||
cfg.rotation_enabled = enabled;
|
cfg.rotation_enabled = enabled;
|
||||||
}
|
}
|
||||||
|
if let Some(enabled) = trading.daily_top_up {
|
||||||
|
cfg.daily_top_up_enabled = enabled;
|
||||||
|
}
|
||||||
|
if let Some(enabled) = trading.retry_empty_rebalance {
|
||||||
|
cfg.retry_empty_rebalance = enabled;
|
||||||
|
}
|
||||||
|
if let Some(enabled) = spec
|
||||||
|
.engine_config
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|engine| engine.strict_value_budget)
|
||||||
|
.or_else(|| {
|
||||||
|
spec.execution
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|execution| execution.strict_value_budget)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
cfg.strict_value_budget = enabled;
|
||||||
|
}
|
||||||
if let Some(required) = trading.subscription_guard_required {
|
if let Some(required) = trading.subscription_guard_required {
|
||||||
cfg.subscription_guard_required = required;
|
cfg.subscription_guard_required = required;
|
||||||
}
|
}
|
||||||
@@ -593,8 +645,8 @@ pub fn platform_expr_config_from_spec(
|
|||||||
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
||||||
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
||||||
cfg.stock_filter_expr = format!(
|
cfg.stock_filter_expr = format!(
|
||||||
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid > stock_ma_long",
|
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid * {} > stock_ma_long",
|
||||||
ratio
|
ratio, ratio
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
||||||
@@ -998,6 +1050,7 @@ mod tests {
|
|||||||
"strategyId": "runtime_spec_test",
|
"strategyId": "runtime_spec_test",
|
||||||
"signalSymbol": "000852.SH",
|
"signalSymbol": "000852.SH",
|
||||||
"benchmark": { "instrumentId": "000852.SH" },
|
"benchmark": { "instrumentId": "000852.SH" },
|
||||||
|
"universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] },
|
||||||
"runtimeExpressions": {
|
"runtimeExpressions": {
|
||||||
"prelude": "let stocknum = 8;",
|
"prelude": "let stocknum = 8;",
|
||||||
"selection": {
|
"selection": {
|
||||||
@@ -1008,6 +1061,8 @@ mod tests {
|
|||||||
},
|
},
|
||||||
"trading": {
|
"trading": {
|
||||||
"rotationEnabled": false,
|
"rotationEnabled": false,
|
||||||
|
"dailyTopUp": true,
|
||||||
|
"retryEmptyRebalance": true,
|
||||||
"stage": "open_auction",
|
"stage": "open_auction",
|
||||||
"actions": [
|
"actions": [
|
||||||
{
|
{
|
||||||
@@ -1026,7 +1081,10 @@ mod tests {
|
|||||||
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
||||||
assert_eq!(cfg.signal_symbol, "000852.SH");
|
assert_eq!(cfg.signal_symbol, "000852.SH");
|
||||||
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
||||||
|
assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]);
|
||||||
assert!(!cfg.rotation_enabled);
|
assert!(!cfg.rotation_enabled);
|
||||||
|
assert!(cfg.daily_top_up_enabled);
|
||||||
|
assert!(cfg.retry_empty_rebalance);
|
||||||
assert_eq!(cfg.explicit_actions.len(), 1);
|
assert_eq!(cfg.explicit_actions.len(), 1);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cfg.explicit_action_stage,
|
cfg.explicit_action_stage,
|
||||||
|
|||||||
@@ -1090,6 +1090,9 @@ pub struct CnSmallCapRotationConfig {
|
|||||||
pub base_index_level: f64,
|
pub base_index_level: f64,
|
||||||
pub base_cap_floor: f64,
|
pub base_cap_floor: f64,
|
||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
pub short_ma_days: usize,
|
pub short_ma_days: usize,
|
||||||
pub long_ma_days: usize,
|
pub long_ma_days: usize,
|
||||||
pub stock_short_ma_days: usize,
|
pub stock_short_ma_days: usize,
|
||||||
@@ -1114,6 +1117,9 @@ impl CnSmallCapRotationConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
short_ma_days: 3,
|
short_ma_days: 3,
|
||||||
long_ma_days: 5,
|
long_ma_days: 5,
|
||||||
stock_short_ma_days: 3,
|
stock_short_ma_days: 3,
|
||||||
@@ -1138,6 +1144,9 @@ impl CnSmallCapRotationConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
short_ma_days: 5,
|
short_ma_days: 5,
|
||||||
long_ma_days: 10,
|
long_ma_days: 10,
|
||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
@@ -1185,6 +1194,9 @@ impl CnSmallCapRotationStrategy {
|
|||||||
config.cap_span,
|
config.cap_span,
|
||||||
config.xs,
|
config.xs,
|
||||||
config.stocknum,
|
config.stocknum,
|
||||||
|
config.padding_ratio,
|
||||||
|
config.min_padding,
|
||||||
|
config.max_padding,
|
||||||
),
|
),
|
||||||
config,
|
config,
|
||||||
last_gross_exposure: None,
|
last_gross_exposure: None,
|
||||||
@@ -1508,6 +1520,9 @@ pub struct OmniMicroCapConfig {
|
|||||||
pub base_index_level: f64,
|
pub base_index_level: f64,
|
||||||
pub base_cap_floor: f64,
|
pub base_cap_floor: f64,
|
||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
pub benchmark_signal_symbol: String,
|
pub benchmark_signal_symbol: String,
|
||||||
pub benchmark_short_ma_days: usize,
|
pub benchmark_short_ma_days: usize,
|
||||||
pub benchmark_long_ma_days: usize,
|
pub benchmark_long_ma_days: usize,
|
||||||
@@ -1531,6 +1546,9 @@ impl OmniMicroCapConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
benchmark_signal_symbol: "000001.SH".to_string(),
|
benchmark_signal_symbol: "000001.SH".to_string(),
|
||||||
benchmark_short_ma_days: 5,
|
benchmark_short_ma_days: 5,
|
||||||
benchmark_long_ma_days: 10,
|
benchmark_long_ma_days: 10,
|
||||||
@@ -1547,6 +1565,32 @@ impl OmniMicroCapConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn aiquant_v104() -> Self {
|
||||||
|
Self {
|
||||||
|
strategy_name: "aiquant-v1.0.4".to_string(),
|
||||||
|
refresh_rate: 120,
|
||||||
|
stocknum: 5,
|
||||||
|
xs: 4.0 / 500.0,
|
||||||
|
base_index_level: 2000.0,
|
||||||
|
base_cap_floor: 7.0,
|
||||||
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 1.2,
|
||||||
|
min_padding: 29.5,
|
||||||
|
max_padding: 50.0,
|
||||||
|
benchmark_signal_symbol: "000852.SH".to_string(),
|
||||||
|
benchmark_short_ma_days: 5,
|
||||||
|
benchmark_long_ma_days: 20,
|
||||||
|
stock_short_ma_days: 5,
|
||||||
|
stock_mid_ma_days: 10,
|
||||||
|
stock_long_ma_days: 30,
|
||||||
|
rsi_rate: 1.0001,
|
||||||
|
trade_rate: 0.5,
|
||||||
|
stop_loss_ratio: 0.92,
|
||||||
|
take_profit_ratio: 1.16,
|
||||||
|
skip_month_day_ranges: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
||||||
let month = date.month();
|
let month = date.month();
|
||||||
let day = date.day();
|
let day = date.day();
|
||||||
@@ -2097,7 +2141,8 @@ impl OmniMicroCapStrategy {
|
|||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
) -> Result<(f64, f64, f64, f64), BacktestError> {
|
) -> Result<(f64, f64, f64, f64, f64), BacktestError> {
|
||||||
|
// 当前交易日的指数价格(用于MA计算和仓位控制)
|
||||||
let current_level = ctx
|
let current_level = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
||||||
@@ -2106,6 +2151,16 @@ impl OmniMicroCapStrategy {
|
|||||||
symbol: self.config.benchmark_signal_symbol.clone(),
|
symbol: self.config.benchmark_signal_symbol.clone(),
|
||||||
field: "decision_close",
|
field: "decision_close",
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
// 前一交易日的指数价格(用于市值区间计算,模拟实盘场景)
|
||||||
|
let prev_level = if let Some(prev_date) = ctx.data.previous_trading_date(date, 1) {
|
||||||
|
ctx.data
|
||||||
|
.market_decision_close(prev_date, &self.config.benchmark_signal_symbol)
|
||||||
|
.unwrap_or(current_level)
|
||||||
|
} else {
|
||||||
|
current_level
|
||||||
|
};
|
||||||
|
|
||||||
let ma_short = ctx
|
let ma_short = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(
|
.market_decision_close_moving_average(
|
||||||
@@ -2137,14 +2192,25 @@ impl OmniMicroCapStrategy {
|
|||||||
} else {
|
} else {
|
||||||
1.0
|
1.0
|
||||||
};
|
};
|
||||||
Ok((current_level, ma_short, ma_long, trading_ratio))
|
Ok((current_level, prev_level, ma_short, ma_long, trading_ratio))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
|
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
|
||||||
let y = (index_level - self.config.base_index_level) * self.config.xs
|
let y = (index_level - self.config.base_index_level) * self.config.xs
|
||||||
+ self.config.base_cap_floor;
|
+ self.config.base_cap_floor;
|
||||||
let start = y.round();
|
let start = y.round();
|
||||||
(start, start + self.config.cap_span)
|
let end = start + self.config.cap_span;
|
||||||
|
|
||||||
|
// Apply padding to expand the range
|
||||||
|
let span = end - start;
|
||||||
|
let padding = (span * self.config.padding_ratio)
|
||||||
|
.max(self.config.min_padding)
|
||||||
|
.min(self.config.max_padding);
|
||||||
|
|
||||||
|
let lower_bound = (start - padding).max(0.0);
|
||||||
|
let upper_bound = end + padding;
|
||||||
|
|
||||||
|
(lower_bound, upper_bound)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stock_passes_ma_filter(
|
fn stock_passes_ma_filter(
|
||||||
@@ -2175,7 +2241,57 @@ impl OmniMicroCapStrategy {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid > ma_long
|
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
|
||||||
|
let ma_pass = ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
||||||
|
|
||||||
|
// Debug logging for ALL stocks on first decision date
|
||||||
|
static DEBUG_DATE: std::sync::Mutex<Option<NaiveDate>> = std::sync::Mutex::new(None);
|
||||||
|
let mut debug_date = DEBUG_DATE.lock().unwrap();
|
||||||
|
let should_debug = if let Some(d) = *debug_date {
|
||||||
|
d == date
|
||||||
|
} else {
|
||||||
|
*debug_date = Some(date);
|
||||||
|
true
|
||||||
|
};
|
||||||
|
|
||||||
|
if should_debug {
|
||||||
|
eprintln!("[MA_FILTER] {} cap={:.2} ma5={:.4} ma10={:.4} ma30={:.4} ma10*rsi={:.4} pass={} ({}>{:.4}? {} && {:.4}>{}? {})",
|
||||||
|
symbol,
|
||||||
|
ctx.data.market_decision_close(date, symbol).unwrap_or(0.0),
|
||||||
|
ma_short, ma_mid, ma_long,
|
||||||
|
ma_mid * self.config.rsi_rate,
|
||||||
|
ma_pass,
|
||||||
|
ma_short, ma_mid * self.config.rsi_rate, ma_short > ma_mid * self.config.rsi_rate,
|
||||||
|
ma_mid * self.config.rsi_rate, ma_long, ma_mid * self.config.rsi_rate > ma_long);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ma_pass {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
|
||||||
|
if self.config.strategy_name.contains("aiquant") || self.config.strategy_name.contains("AiQuant") || self.config.strategy_name.contains("omni") {
|
||||||
|
let Some(volume_ma5) = ctx.data.market_decision_volume_moving_average(
|
||||||
|
date,
|
||||||
|
symbol,
|
||||||
|
5,
|
||||||
|
) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(volume_ma60) = ctx.data.market_decision_volume_moving_average(
|
||||||
|
date,
|
||||||
|
symbol,
|
||||||
|
60,
|
||||||
|
) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
if volume_ma5 >= volume_ma60 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
||||||
@@ -2546,7 +2662,7 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let (index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
|
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
|
||||||
Ok(value) => value,
|
Ok(value) => value,
|
||||||
Err(BacktestError::Execution(message))
|
Err(BacktestError::Execution(message))
|
||||||
if message.contains("insufficient benchmark") =>
|
if message.contains("insufficient benchmark") =>
|
||||||
@@ -2564,7 +2680,10 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
}
|
}
|
||||||
Err(err) => return Err(err),
|
Err(err) => return Err(err),
|
||||||
};
|
};
|
||||||
let (band_low, band_high) = self.market_cap_band(index_level);
|
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||||
|
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
||||||
|
eprintln!("[DEBUG] date={} current_index={:.2} prev_index={:.2} band=[{:.0}, {:.0}]",
|
||||||
|
date, index_level, prev_index_level, band_low, band_high);
|
||||||
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
||||||
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||||
let mut projected = ctx.portfolio.clone();
|
let mut projected = ctx.portfolio.clone();
|
||||||
|
|||||||
@@ -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() {
|
||||||
|
|||||||
@@ -78,6 +78,9 @@ pub struct DynamicMarketCapBandSelector {
|
|||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
pub xs: f64,
|
pub xs: f64,
|
||||||
pub top_n: usize,
|
pub top_n: usize,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DynamicMarketCapBandSelector {
|
impl DynamicMarketCapBandSelector {
|
||||||
@@ -87,6 +90,9 @@ impl DynamicMarketCapBandSelector {
|
|||||||
cap_span: f64,
|
cap_span: f64,
|
||||||
xs: f64,
|
xs: f64,
|
||||||
top_n: usize,
|
top_n: usize,
|
||||||
|
padding_ratio: f64,
|
||||||
|
min_padding: f64,
|
||||||
|
max_padding: f64,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
base_index_level,
|
base_index_level,
|
||||||
@@ -94,11 +100,14 @@ impl DynamicMarketCapBandSelector {
|
|||||||
cap_span,
|
cap_span,
|
||||||
xs,
|
xs,
|
||||||
top_n,
|
top_n,
|
||||||
|
padding_ratio,
|
||||||
|
min_padding,
|
||||||
|
max_padding,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn demo(top_n: usize) -> Self {
|
pub fn demo(top_n: usize) -> Self {
|
||||||
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n)
|
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n, 0.5, 8.0, 20.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn regime(&self, benchmark_level: f64) -> BandRegime {
|
pub fn regime(&self, benchmark_level: f64) -> BandRegime {
|
||||||
@@ -114,7 +123,18 @@ impl DynamicMarketCapBandSelector {
|
|||||||
pub fn band_for_level(&self, benchmark_level: f64) -> (f64, f64) {
|
pub fn band_for_level(&self, benchmark_level: f64) -> (f64, f64) {
|
||||||
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
|
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
|
||||||
let low = start.round();
|
let low = start.round();
|
||||||
(low, low + self.cap_span)
|
let high = low + self.cap_span;
|
||||||
|
|
||||||
|
// Apply padding to expand the range
|
||||||
|
let span = high - low;
|
||||||
|
let padding = (span * self.padding_ratio)
|
||||||
|
.max(self.min_padding)
|
||||||
|
.min(self.max_padding);
|
||||||
|
|
||||||
|
let lower_bound = (low - padding).max(0.0);
|
||||||
|
let upper_bound = high + padding;
|
||||||
|
|
||||||
|
(lower_bound, upper_bound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
|||||||
#[test]
|
#[test]
|
||||||
fn broker_executes_explicit_order_value_buy() {
|
fn broker_executes_explicit_order_value_buy() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
let data = DataSet::from_components(
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
vec![Instrument {
|
vec![Instrument {
|
||||||
symbol: "000002.SZ".to_string(),
|
symbol: "000002.SZ".to_string(),
|
||||||
name: "Test".to_string(),
|
name: "Test".to_string(),
|
||||||
@@ -72,6 +72,20 @@ fn broker_executes_explicit_order_value_buy() {
|
|||||||
prev_close: 99.0,
|
prev_close: 99.0,
|
||||||
volume: 1_000_000,
|
volume: 1_000_000,
|
||||||
}],
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
vec![IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
bid1_volume: 1,
|
||||||
|
ask1_volume: 1,
|
||||||
|
volume_delta: 1,
|
||||||
|
amount_delta: 0.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
}],
|
||||||
)
|
)
|
||||||
.expect("dataset");
|
.expect("dataset");
|
||||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
@@ -111,7 +125,7 @@ fn broker_executes_explicit_order_value_buy() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn broker_executes_order_shares_and_order_lots() {
|
fn broker_executes_order_shares_and_order_lots() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
let data = DataSet::from_components(
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
vec![Instrument {
|
vec![Instrument {
|
||||||
symbol: "000002.SZ".to_string(),
|
symbol: "000002.SZ".to_string(),
|
||||||
name: "Test".to_string(),
|
name: "Test".to_string(),
|
||||||
@@ -173,6 +187,20 @@ fn broker_executes_order_shares_and_order_lots() {
|
|||||||
prev_close: 99.0,
|
prev_close: 99.0,
|
||||||
volume: 1_000_000,
|
volume: 1_000_000,
|
||||||
}],
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
vec![IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
bid1_volume: 1,
|
||||||
|
ask1_volume: 1,
|
||||||
|
volume_delta: 1,
|
||||||
|
amount_delta: 0.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
}],
|
||||||
)
|
)
|
||||||
.expect("dataset");
|
.expect("dataset");
|
||||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
@@ -1192,6 +1220,120 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
name: "Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: Some("2024-01-10 10:18:00".to_string()),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.1,
|
||||||
|
low: 9.9,
|
||||||
|
close: 10.0,
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 100_000,
|
||||||
|
tick_volume: 100_000,
|
||||||
|
bid1_volume: 80_000,
|
||||||
|
ask1_volume: 80_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 11.0,
|
||||||
|
lower_limit: 9.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
market_cap_bn: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "000002.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,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000300.SH".to_string(),
|
||||||
|
open: 100.0,
|
||||||
|
close: 100.0,
|
||||||
|
prev_close: 99.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
vec![IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
bid1_volume: 1,
|
||||||
|
ask1_volume: 1,
|
||||||
|
volume_delta: 1,
|
||||||
|
amount_delta: 0.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Last,
|
||||||
|
)
|
||||||
|
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap())
|
||||||
|
.with_slippage_model(SlippageModel::TickSize(2.0));
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::Value {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
value: 100_000.0,
|
||||||
|
reason: "tick_slippage".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_rejects_intraday_last_order_without_execution_quotes() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
let data = DataSet::from_components(
|
let data = DataSet::from_components(
|
||||||
vec![Instrument {
|
vec![Instrument {
|
||||||
@@ -1263,8 +1405,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
|||||||
ChinaEquityRuleHooks::default(),
|
ChinaEquityRuleHooks::default(),
|
||||||
PriceField::Last,
|
PriceField::Last,
|
||||||
)
|
)
|
||||||
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap())
|
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap());
|
||||||
.with_slippage_model(SlippageModel::TickSize(2.0));
|
|
||||||
|
|
||||||
let report = broker
|
let report = broker
|
||||||
.execute(
|
.execute(
|
||||||
@@ -1278,7 +1419,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
|||||||
order_intents: vec![OrderIntent::Value {
|
order_intents: vec![OrderIntent::Value {
|
||||||
symbol: "000002.SZ".to_string(),
|
symbol: "000002.SZ".to_string(),
|
||||||
value: 100_000.0,
|
value: 100_000.0,
|
||||||
reason: "tick_slippage".to_string(),
|
reason: "missing_tick_quotes".to_string(),
|
||||||
}],
|
}],
|
||||||
notes: Vec::new(),
|
notes: Vec::new(),
|
||||||
diagnostics: Vec::new(),
|
diagnostics: Vec::new(),
|
||||||
@@ -1286,8 +1427,15 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
|||||||
)
|
)
|
||||||
.expect("broker execution");
|
.expect("broker execution");
|
||||||
|
|
||||||
assert_eq!(report.fill_events.len(), 1);
|
assert!(report.fill_events.is_empty());
|
||||||
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
assert_eq!(report.order_events.len(), 1);
|
||||||
|
assert_eq!(report.order_events[0].status, OrderStatus::Canceled);
|
||||||
|
assert!(
|
||||||
|
report.order_events[0]
|
||||||
|
.reason
|
||||||
|
.contains("no execution quotes after start")
|
||||||
|
);
|
||||||
|
assert!(portfolio.position("000002.SZ").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
Reference in New Issue
Block a user