Compare commits
4 Commits
v2026.05.0
...
v2026.5.10
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b033fd294 | ||
|
|
d9de9715ef | ||
|
|
65742d4d5e | ||
|
|
a47c7c3e49 |
@@ -110,6 +110,7 @@ pub struct BrokerSimulator<C, R> {
|
||||
volume_limit: bool,
|
||||
inactive_limit: bool,
|
||||
liquidity_limit: bool,
|
||||
strict_value_budget: bool,
|
||||
intraday_execution_start_time: Option<NaiveTime>,
|
||||
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
|
||||
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
||||
@@ -130,6 +131,7 @@ impl<C, R> BrokerSimulator<C, R> {
|
||||
volume_limit: true,
|
||||
inactive_limit: true,
|
||||
liquidity_limit: true,
|
||||
strict_value_budget: false,
|
||||
intraday_execution_start_time: None,
|
||||
runtime_intraday_start_time: Cell::new(None),
|
||||
runtime_intraday_end_time: Cell::new(None),
|
||||
@@ -154,6 +156,7 @@ impl<C, R> BrokerSimulator<C, R> {
|
||||
volume_limit: true,
|
||||
inactive_limit: true,
|
||||
liquidity_limit: true,
|
||||
strict_value_budget: false,
|
||||
intraday_execution_start_time: None,
|
||||
runtime_intraday_start_time: Cell::new(None),
|
||||
runtime_intraday_end_time: Cell::new(None),
|
||||
@@ -177,6 +180,11 @@ impl<C, R> BrokerSimulator<C, R> {
|
||||
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 {
|
||||
self.volume_percent = volume_percent;
|
||||
self
|
||||
@@ -3388,6 +3396,16 @@ where
|
||||
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(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -3559,7 +3577,7 @@ where
|
||||
execution_cursors,
|
||||
None,
|
||||
Some(portfolio.cash()),
|
||||
value_budget.map(|budget| budget + 400.0),
|
||||
self.value_budget_gross_limit(value_budget),
|
||||
algo_request,
|
||||
limit_price,
|
||||
);
|
||||
@@ -3590,7 +3608,7 @@ where
|
||||
let filled_qty = self.affordable_buy_quantity(
|
||||
date,
|
||||
portfolio.cash(),
|
||||
value_budget.map(|budget| budget + 400.0),
|
||||
self.value_budget_gross_limit(value_budget),
|
||||
execution_price,
|
||||
constrained_qty,
|
||||
self.minimum_order_quantity(data, symbol),
|
||||
@@ -3601,7 +3619,7 @@ where
|
||||
partial_fill_reason,
|
||||
self.buy_reduction_reason(
|
||||
portfolio.cash(),
|
||||
value_budget.map(|budget| budget + 400.0),
|
||||
self.value_budget_gross_limit(value_budget),
|
||||
execution_price,
|
||||
constrained_qty,
|
||||
filled_qty,
|
||||
@@ -3660,7 +3678,7 @@ where
|
||||
side: OrderSide::Buy,
|
||||
requested_quantity: requested_qty,
|
||||
filled_quantity: 0,
|
||||
status: OrderStatus::Rejected,
|
||||
status: zero_fill_status_for_reason(detail),
|
||||
reason: format!("{reason}: {detail}"),
|
||||
});
|
||||
Self::emit_order_process_event(
|
||||
@@ -3670,7 +3688,10 @@ where
|
||||
order_id,
|
||||
symbol,
|
||||
OrderSide::Buy,
|
||||
format!("status=Rejected reason={detail}"),
|
||||
format!(
|
||||
"status={:?} reason={detail}",
|
||||
zero_fill_status_for_reason(detail)
|
||||
),
|
||||
);
|
||||
self.clear_open_order(order_id);
|
||||
return Ok(());
|
||||
@@ -4255,57 +4276,43 @@ where
|
||||
}
|
||||
|
||||
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
|
||||
.and_then(|request| request.start_time)
|
||||
.or(self.intraday_execution_start_time)
|
||||
.map(|start_time| date.and_time(start_time) + Duration::seconds(1))
|
||||
.unwrap_or_else(|| date.and_hms_opt(0, 0, 1).expect("valid midnight"));
|
||||
return Some(ExecutionFill {
|
||||
quantity,
|
||||
quantity: 0,
|
||||
next_cursor,
|
||||
legs: vec![ExecutionLeg {
|
||||
price: execution_price,
|
||||
quantity,
|
||||
}],
|
||||
unfilled_reason: self.buy_reduction_reason(
|
||||
cash_limit.unwrap_or(f64::INFINITY),
|
||||
gross_limit,
|
||||
execution_price,
|
||||
requested_qty,
|
||||
quantity,
|
||||
),
|
||||
legs: Vec::new(),
|
||||
unfilled_reason: Some(self.empty_intraday_quote_reason(
|
||||
quotes,
|
||||
start_cursor,
|
||||
end_cursor,
|
||||
)),
|
||||
});
|
||||
}
|
||||
|
||||
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(
|
||||
&self,
|
||||
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 {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -682,6 +682,23 @@ impl BenchmarkPriceSeries {
|
||||
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(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -2123,6 +2140,15 @@ impl DataSet {
|
||||
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> {
|
||||
self.benchmark_series_cache
|
||||
.moving_average_for(date, lookback, PriceField::Open)
|
||||
|
||||
@@ -199,6 +199,9 @@ pub struct PlatformExprStrategyConfig {
|
||||
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
||||
pub rebalance_schedule: Option<PlatformRebalanceSchedule>,
|
||||
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_schedule: Option<PlatformRebalanceSchedule>,
|
||||
pub subscription_guard_required: bool,
|
||||
@@ -249,6 +252,9 @@ fn band_low(index_close) {
|
||||
skip_month_day_ranges: Vec::new(),
|
||||
rebalance_schedule: None,
|
||||
rotation_enabled: true,
|
||||
daily_top_up_enabled: false,
|
||||
retry_empty_rebalance: false,
|
||||
strict_value_budget: false,
|
||||
explicit_action_stage: PlatformExplicitActionStage::OnDay,
|
||||
explicit_action_schedule: None,
|
||||
subscription_guard_required: false,
|
||||
@@ -508,16 +514,21 @@ impl PlatformExprStrategy {
|
||||
scope: &mut Scope<'_>,
|
||||
script: &str,
|
||||
) -> Result<Dynamic, BacktestError> {
|
||||
// 注意:HashMap key 借用即可命中,避免重复克隆 String。
|
||||
if let Some(ast) = self.compiled_cache.borrow().get(script) {
|
||||
*self.cache_hits.borrow_mut() += 1;
|
||||
return self
|
||||
.engine
|
||||
.eval_ast_with_scope::<Dynamic>(scope, ast)
|
||||
.map_err(|error| {
|
||||
BacktestError::Execution(format!("platform expr eval failed: {}", error))
|
||||
});
|
||||
// 命中分支:先借用 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))
|
||||
@@ -867,53 +878,6 @@ impl PlatformExprStrategy {
|
||||
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 quotes = ctx.data.execution_quotes_on(date, symbol);
|
||||
let mut filled_qty = 0_u32;
|
||||
@@ -1028,12 +992,18 @@ impl PlatformExprStrategy {
|
||||
None,
|
||||
execution_state,
|
||||
)
|
||||
.unwrap_or(ProjectedExecutionFill {
|
||||
price: self.projected_execution_price(market, OrderSide::Sell),
|
||||
quantity,
|
||||
next_cursor: date.and_time(self.intraday_execution_start_time())
|
||||
+ Duration::seconds(1),
|
||||
});
|
||||
.or_else(|| {
|
||||
if ctx.data.execution_quotes_on(date, symbol).is_empty() {
|
||||
None
|
||||
} else {
|
||||
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 net_cash = gross_amount - self.sell_cost(date, gross_amount);
|
||||
projected
|
||||
@@ -1082,9 +1052,14 @@ impl PlatformExprStrategy {
|
||||
);
|
||||
let execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
||||
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 {
|
||||
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
|
||||
{
|
||||
break;
|
||||
@@ -1107,15 +1082,24 @@ impl PlatformExprStrategy {
|
||||
order_step_size,
|
||||
false,
|
||||
Some(projected.cash()),
|
||||
Some(order_value + 400.0),
|
||||
Some(gross_limit),
|
||||
execution_state,
|
||||
)
|
||||
.unwrap_or(ProjectedExecutionFill {
|
||||
price: execution_price,
|
||||
quantity,
|
||||
next_cursor: date.and_time(self.intraday_execution_start_time())
|
||||
+ Duration::seconds(1),
|
||||
.or_else(|| {
|
||||
if ctx.data.execution_quotes_on(date, symbol).is_empty() {
|
||||
None
|
||||
} else {
|
||||
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 cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||
if cash_out > projected.cash() + 1e-6 {
|
||||
@@ -1177,46 +1161,56 @@ impl PlatformExprStrategy {
|
||||
let benchmark_close = benchmark.close;
|
||||
let benchmark_ma_short = ctx
|
||||
.data
|
||||
.market_decision_close_moving_average(
|
||||
date,
|
||||
&self.config.signal_symbol,
|
||||
self.config.benchmark_short_ma_days,
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
BacktestError::Execution(format!(
|
||||
"insufficient benchmark short MA history for {} on {}",
|
||||
self.config.signal_symbol, date
|
||||
))
|
||||
})?;
|
||||
.benchmark_decision_moving_average(date, self.config.benchmark_short_ma_days)
|
||||
.or_else(|| {
|
||||
ctx.data
|
||||
.benchmark_moving_average(date, self.config.benchmark_short_ma_days)
|
||||
})
|
||||
.unwrap_or(benchmark_close);
|
||||
let benchmark_ma_long = ctx
|
||||
.data
|
||||
.market_decision_close_moving_average(
|
||||
date,
|
||||
&self.config.signal_symbol,
|
||||
self.config.benchmark_long_ma_days,
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
BacktestError::Execution(format!(
|
||||
"insufficient benchmark long MA history for {} on {}",
|
||||
self.config.signal_symbol, date
|
||||
))
|
||||
})?;
|
||||
.benchmark_decision_moving_average(date, self.config.benchmark_long_ma_days)
|
||||
.or_else(|| {
|
||||
ctx.data
|
||||
.benchmark_moving_average(date, self.config.benchmark_long_ma_days)
|
||||
})
|
||||
.unwrap_or(benchmark_ma_short);
|
||||
let benchmark_ma5 = ctx
|
||||
.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);
|
||||
let benchmark_ma10 = ctx
|
||||
.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);
|
||||
let benchmark_ma20 = ctx
|
||||
.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);
|
||||
let benchmark_ma30 = ctx
|
||||
.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);
|
||||
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 cash = account.cash;
|
||||
let market_value = account.market_value;
|
||||
@@ -1241,10 +1235,10 @@ impl PlatformExprStrategy {
|
||||
benchmark_ma10,
|
||||
benchmark_ma20,
|
||||
benchmark_ma30,
|
||||
signal_ma5: benchmark_ma5,
|
||||
signal_ma10: benchmark_ma10,
|
||||
signal_ma20: benchmark_ma20,
|
||||
signal_ma30: benchmark_ma30,
|
||||
signal_ma5,
|
||||
signal_ma10,
|
||||
signal_ma20,
|
||||
signal_ma30,
|
||||
cash,
|
||||
available_cash: account.available_cash,
|
||||
frozen_cash: account.frozen_cash,
|
||||
@@ -4196,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(
|
||||
&self,
|
||||
candidate: &EligibleUniverseSnapshot,
|
||||
@@ -4359,7 +4424,7 @@ impl PlatformExprStrategy {
|
||||
band_high: f64,
|
||||
limit: usize,
|
||||
) -> 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 candidates = Vec::new();
|
||||
for candidate in universe {
|
||||
@@ -4631,6 +4696,8 @@ impl Strategy for PlatformExprStrategy {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let empty_rebalance_retry =
|
||||
self.config.retry_empty_rebalance && ctx.portfolio.positions().is_empty();
|
||||
let periodic_rebalance = if self.config.rotation_enabled {
|
||||
if let Some(schedule) = &self.config.rebalance_schedule {
|
||||
schedule.matches(
|
||||
@@ -4638,9 +4705,9 @@ impl Strategy for PlatformExprStrategy {
|
||||
execution_date,
|
||||
ScheduleStage::OnDay,
|
||||
default_stage_time(ScheduleStage::OnDay),
|
||||
)
|
||||
) || empty_rebalance_retry
|
||||
} else {
|
||||
ctx.decision_index % self.config.refresh_rate == 0
|
||||
ctx.decision_index % self.config.refresh_rate == 0 || empty_rebalance_retry
|
||||
}
|
||||
} else {
|
||||
false
|
||||
@@ -4759,7 +4826,7 @@ impl Strategy for PlatformExprStrategy {
|
||||
}
|
||||
|
||||
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 {
|
||||
break;
|
||||
}
|
||||
@@ -4798,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() {
|
||||
order_intents.extend(explicit_action_intents);
|
||||
@@ -5803,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]
|
||||
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
|
||||
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
||||
@@ -6074,6 +6333,139 @@ mod tests {
|
||||
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]
|
||||
fn platform_strategy_emits_target_shares_explicit_action() {
|
||||
let date = d(2025, 2, 3);
|
||||
@@ -7509,4 +7901,133 @@ mod tests {
|
||||
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,8 +318,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn runtime_schema_includes_known_identifiers() {
|
||||
let names: std::collections::HashSet<&str> =
|
||||
RESERVED_SCOPE_NAMES.iter().copied().collect();
|
||||
let names: std::collections::HashSet<&str> = RESERVED_SCOPE_NAMES.iter().copied().collect();
|
||||
for required in [
|
||||
"signal_close",
|
||||
"benchmark_close",
|
||||
@@ -328,7 +327,10 @@ mod tests {
|
||||
"current_price",
|
||||
"stock_ma_short",
|
||||
] {
|
||||
assert!(names.contains(required), "missing reserved name: {required}");
|
||||
assert!(
|
||||
names.contains(required),
|
||||
"missing reserved name: {required}"
|
||||
);
|
||||
}
|
||||
|
||||
let helpers: std::collections::HashSet<&str> =
|
||||
|
||||
@@ -20,6 +20,8 @@ pub struct StrategyRuntimeSpec {
|
||||
#[serde(default)]
|
||||
pub benchmark: Option<StrategyBenchmarkSpec>,
|
||||
#[serde(default)]
|
||||
pub universe: Option<StrategyUniverseSpec>,
|
||||
#[serde(default)]
|
||||
pub signal_symbol: Option<String>,
|
||||
#[serde(default)]
|
||||
pub execution: Option<StrategyExecutionSpec>,
|
||||
@@ -40,6 +42,13 @@ pub struct StrategyBenchmarkSpec {
|
||||
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)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StrategyExecutionSpec {
|
||||
@@ -49,6 +58,8 @@ pub struct StrategyExecutionSpec {
|
||||
pub slippage_model: Option<String>,
|
||||
#[serde(default)]
|
||||
pub slippage_value: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub strict_value_budget: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -83,6 +94,8 @@ pub struct StrategyEngineConfig {
|
||||
#[serde(default)]
|
||||
pub slippage_value: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub strict_value_budget: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub dividend_reinvestment: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
|
||||
@@ -224,6 +237,10 @@ pub struct StrategyExpressionTradingConfig {
|
||||
#[serde(default)]
|
||||
pub rotation_enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub daily_top_up: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub retry_empty_rebalance: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub subscription_guard_required: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub actions: Vec<StrategyExpressionActionConfig>,
|
||||
@@ -416,6 +433,14 @@ pub fn platform_expr_config_from_spec(
|
||||
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();
|
||||
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
||||
@@ -551,6 +576,24 @@ pub fn platform_expr_config_from_spec(
|
||||
if let Some(enabled) = trading.rotation_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 {
|
||||
cfg.subscription_guard_required = required;
|
||||
}
|
||||
@@ -998,6 +1041,7 @@ mod tests {
|
||||
"strategyId": "runtime_spec_test",
|
||||
"signalSymbol": "000852.SH",
|
||||
"benchmark": { "instrumentId": "000852.SH" },
|
||||
"universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] },
|
||||
"runtimeExpressions": {
|
||||
"prelude": "let stocknum = 8;",
|
||||
"selection": {
|
||||
@@ -1008,6 +1052,8 @@ mod tests {
|
||||
},
|
||||
"trading": {
|
||||
"rotationEnabled": false,
|
||||
"dailyTopUp": true,
|
||||
"retryEmptyRebalance": true,
|
||||
"stage": "open_auction",
|
||||
"actions": [
|
||||
{
|
||||
@@ -1026,7 +1072,10 @@ mod tests {
|
||||
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
||||
assert_eq!(cfg.signal_symbol, "000852.SH");
|
||||
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
||||
assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]);
|
||||
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_action_stage,
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
#[test]
|
||||
fn broker_executes_explicit_order_value_buy() {
|
||||
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 {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
@@ -72,6 +72,20 @@ fn broker_executes_explicit_order_value_buy() {
|
||||
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);
|
||||
@@ -111,7 +125,7 @@ fn broker_executes_explicit_order_value_buy() {
|
||||
#[test]
|
||||
fn broker_executes_order_shares_and_order_lots() {
|
||||
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 {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
@@ -173,6 +187,20 @@ fn broker_executes_order_shares_and_order_lots() {
|
||||
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);
|
||||
@@ -1192,6 +1220,120 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
|
||||
|
||||
#[test]
|
||||
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 data = DataSet::from_components(
|
||||
vec![Instrument {
|
||||
@@ -1263,8 +1405,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
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));
|
||||
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap());
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
@@ -1278,7 +1419,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
value: 100_000.0,
|
||||
reason: "tick_slippage".to_string(),
|
||||
reason: "missing_tick_quotes".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
@@ -1286,8 +1427,15 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
)
|
||||
.expect("broker execution");
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
||||
assert!(report.fill_events.is_empty());
|
||||
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]
|
||||
|
||||
Reference in New Issue
Block a user