修复next-open执行日风控价格
This commit is contained in:
@@ -5210,6 +5210,30 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn next_bar_open_execution_risk_uses_open_not_close_for_upper_limit_buy() {
|
||||||
|
let first = d(2025, 1, 2);
|
||||||
|
let second = d(2025, 1, 3);
|
||||||
|
let result = run_scheduled_next_open_with_dataset(dataset_with(
|
||||||
|
market(first, 10.0, 11.5),
|
||||||
|
market_with_state(second, 11.8, 12.0, false, 12.0, 1.0),
|
||||||
|
candidate(first),
|
||||||
|
candidate(second),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(result.fills.len(), 1);
|
||||||
|
assert_eq!(result.fills[0].date, second);
|
||||||
|
assert_eq!(result.fills[0].price, 11.8);
|
||||||
|
assert!(
|
||||||
|
result
|
||||||
|
.order_events
|
||||||
|
.iter()
|
||||||
|
.all(|event| !event.reason.contains("upper limit")),
|
||||||
|
"{:?}",
|
||||||
|
result.order_events
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn next_bar_open_execution_risk_rejects_execution_day_st_state() {
|
fn next_bar_open_execution_risk_rejects_execution_day_st_state() {
|
||||||
let first = d(2025, 1, 2);
|
let first = d(2025, 1, 2);
|
||||||
@@ -5344,6 +5368,47 @@ mod tests {
|
|||||||
assert_round_trip_sell_canceled_with_reason(&result, "open at or below lower limit");
|
assert_round_trip_sell_canceled_with_reason(&result, "open at or below lower limit");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn next_bar_open_sell_risk_uses_open_not_close_for_lower_limit_sell() {
|
||||||
|
let first = d(2025, 1, 2);
|
||||||
|
let second = d(2025, 1, 3);
|
||||||
|
let third = d(2025, 1, 6);
|
||||||
|
let fourth = d(2025, 1, 7);
|
||||||
|
let result = run_scheduled_round_trip_next_open_with_dataset_and_broker(
|
||||||
|
dataset_from_market_and_candidates(
|
||||||
|
vec![
|
||||||
|
market(first, 10.0, 10.5),
|
||||||
|
market(second, 11.0, 11.5),
|
||||||
|
market(third, 12.0, 12.5),
|
||||||
|
market_with_state(fourth, 9.2, 9.0, false, 20.0, 9.0),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
candidate(first),
|
||||||
|
candidate(second),
|
||||||
|
candidate(third),
|
||||||
|
candidate(fourth),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
scheduled_next_open_broker(FidcRiskControlConfig::default()),
|
||||||
|
);
|
||||||
|
|
||||||
|
let sell_fill = result
|
||||||
|
.fills
|
||||||
|
.iter()
|
||||||
|
.find(|fill| fill.side == OrderSide::Sell)
|
||||||
|
.expect("sell should execute when next-open is above lower limit");
|
||||||
|
assert_eq!(sell_fill.date, fourth);
|
||||||
|
assert_eq!(sell_fill.price, 9.2);
|
||||||
|
assert!(
|
||||||
|
result
|
||||||
|
.order_events
|
||||||
|
.iter()
|
||||||
|
.all(|event| !event.reason.contains("lower limit")),
|
||||||
|
"{:?}",
|
||||||
|
result.order_events
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn next_bar_open_sell_respects_allow_sell_policy_on_execution_day() {
|
fn next_bar_open_sell_respects_allow_sell_policy_on_execution_day() {
|
||||||
let first = d(2025, 1, 2);
|
let first = d(2025, 1, 2);
|
||||||
|
|||||||
@@ -1209,19 +1209,73 @@ impl PlatformExprStrategy {
|
|||||||
.max(1)
|
.max(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn projected_execution_price_field(&self) -> PriceField {
|
||||||
|
match self.config.matching_type {
|
||||||
|
MatchingType::OpenAuction => PriceField::DayOpen,
|
||||||
|
MatchingType::CurrentBarClose => PriceField::Close,
|
||||||
|
MatchingType::NextBarOpen => PriceField::Open,
|
||||||
|
MatchingType::MinuteLast
|
||||||
|
| MatchingType::MinuteBestOwn
|
||||||
|
| MatchingType::MinuteBestCounterparty
|
||||||
|
| MatchingType::Vwap
|
||||||
|
| MatchingType::Twap => PriceField::Last,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn projected_execution_price(&self, market: &DailyMarketSnapshot, side: OrderSide) -> f64 {
|
fn projected_execution_price(&self, market: &DailyMarketSnapshot, side: OrderSide) -> f64 {
|
||||||
if self.config.aiquant_transaction_cost {
|
let price_field = self.projected_execution_price_field();
|
||||||
|
if self.config.aiquant_transaction_cost && price_field != PriceField::Open {
|
||||||
let last = market.price(PriceField::Last);
|
let last = market.price(PriceField::Last);
|
||||||
if last.is_finite() && last > 0.0 {
|
if last.is_finite() && last > 0.0 {
|
||||||
return last;
|
return last;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match side {
|
match side {
|
||||||
OrderSide::Buy => market.buy_price(PriceField::Last),
|
OrderSide::Buy => market.buy_price(price_field),
|
||||||
OrderSide::Sell => market.sell_price(PriceField::Last),
|
OrderSide::Sell => market.sell_price(price_field),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn projected_risk_check_price(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
market: &DailyMarketSnapshot,
|
||||||
|
side: OrderSide,
|
||||||
|
execution_time: Option<NaiveTime>,
|
||||||
|
) -> f64 {
|
||||||
|
if self.config.matching_type == MatchingType::NextBarOpen {
|
||||||
|
return match side {
|
||||||
|
OrderSide::Buy => market.buy_price(PriceField::Open),
|
||||||
|
OrderSide::Sell => market.sell_price(PriceField::Open),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if self.config.aiquant_transaction_cost {
|
||||||
|
let scheduled_price = match side {
|
||||||
|
OrderSide::Buy => self.aiquant_scheduled_buy_price(ctx, date, symbol),
|
||||||
|
OrderSide::Sell => {
|
||||||
|
self.aiquant_scheduled_sell_price_at_time(ctx, date, symbol, execution_time)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return scheduled_price.unwrap_or_else(|| market.price(PriceField::Last));
|
||||||
|
}
|
||||||
|
if side == OrderSide::Buy {
|
||||||
|
let price_field = match self.config.matching_type {
|
||||||
|
MatchingType::NextBarOpen => PriceField::Open,
|
||||||
|
MatchingType::CurrentBarClose => PriceField::Close,
|
||||||
|
MatchingType::OpenAuction
|
||||||
|
| MatchingType::MinuteLast
|
||||||
|
| MatchingType::MinuteBestOwn
|
||||||
|
| MatchingType::MinuteBestCounterparty
|
||||||
|
| MatchingType::Vwap
|
||||||
|
| MatchingType::Twap => PriceField::DayOpen,
|
||||||
|
};
|
||||||
|
return market.buy_price(price_field);
|
||||||
|
}
|
||||||
|
self.projected_execution_price(market, side)
|
||||||
|
}
|
||||||
|
|
||||||
fn projected_execution_start_cursor(
|
fn projected_execution_start_cursor(
|
||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
@@ -6018,6 +6072,16 @@ impl PlatformExprStrategy {
|
|||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
factor_date: NaiveDate,
|
factor_date: NaiveDate,
|
||||||
|
) -> Vec<FidcRiskDecisionAudit> {
|
||||||
|
self.selection_risk_decisions_with_options(ctx, date, factor_date, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selection_risk_decisions_with_options(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
date: NaiveDate,
|
||||||
|
factor_date: NaiveDate,
|
||||||
|
defer_limit_state_selection_risk: bool,
|
||||||
) -> Vec<FidcRiskDecisionAudit> {
|
) -> Vec<FidcRiskDecisionAudit> {
|
||||||
let mut decisions = Vec::new();
|
let mut decisions = Vec::new();
|
||||||
for factor in ctx.data.factor_snapshots_on(factor_date) {
|
for factor in ctx.data.factor_snapshots_on(factor_date) {
|
||||||
@@ -6037,6 +6101,11 @@ impl PlatformExprStrategy {
|
|||||||
ctx.data.instrument(&factor.symbol),
|
ctx.data.instrument(&factor.symbol),
|
||||||
&self.config.risk_config,
|
&self.config.risk_config,
|
||||||
) {
|
) {
|
||||||
|
if defer_limit_state_selection_risk
|
||||||
|
&& matches!(decision.rule_code.as_str(), "upper_limit" | "lower_limit")
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
decisions.push(decision);
|
decisions.push(decision);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6326,12 +6395,14 @@ impl PlatformExprStrategy {
|
|||||||
if !self.config.aiquant_transaction_cost && !candidate.allow_sell {
|
if !self.config.aiquant_transaction_cost && !candidate.allow_sell {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let check_price = if self.config.aiquant_transaction_cost {
|
let check_price = self.projected_risk_check_price(
|
||||||
self.aiquant_scheduled_sell_price_at_time(ctx, date, symbol, execution_time)
|
ctx,
|
||||||
.unwrap_or_else(|| market.price(PriceField::Last))
|
date,
|
||||||
} else {
|
symbol,
|
||||||
market.price(PriceField::Last)
|
market,
|
||||||
};
|
OrderSide::Sell,
|
||||||
|
execution_time,
|
||||||
|
);
|
||||||
ChinaAShareRiskControl::sell_rejection_reason_with_config(
|
ChinaAShareRiskControl::sell_rejection_reason_with_config(
|
||||||
date,
|
date,
|
||||||
candidate,
|
candidate,
|
||||||
@@ -6363,12 +6434,8 @@ impl PlatformExprStrategy {
|
|||||||
{
|
{
|
||||||
return Ok(Some("bjse".to_string()));
|
return Ok(Some("bjse".to_string()));
|
||||||
}
|
}
|
||||||
let upper_limit_check_price = if self.config.aiquant_transaction_cost {
|
let upper_limit_check_price =
|
||||||
self.aiquant_scheduled_buy_price(ctx, date, symbol)
|
self.projected_risk_check_price(ctx, date, symbol, &market, OrderSide::Buy, None);
|
||||||
.unwrap_or_else(|| market.price(PriceField::Last))
|
|
||||||
} else {
|
|
||||||
market.buy_price(PriceField::DayOpen)
|
|
||||||
};
|
|
||||||
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason_with_config(
|
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason_with_config(
|
||||||
date,
|
date,
|
||||||
&candidate,
|
&candidate,
|
||||||
@@ -6397,8 +6464,17 @@ impl PlatformExprStrategy {
|
|||||||
band_high: f64,
|
band_high: f64,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
) -> Result<(Vec<String>, Vec<String>, Vec<FidcRiskDecisionAudit>), BacktestError> {
|
) -> Result<(Vec<String>, Vec<String>, Vec<FidcRiskDecisionAudit>), BacktestError> {
|
||||||
let universe = self.selectable_universe_on(ctx, date, universe_factor_date);
|
let defer_limit_state_selection_risk = ctx.is_lagged_execution();
|
||||||
let risk_decisions = self.selection_risk_decisions(ctx, date, universe_factor_date);
|
let universe = if defer_limit_state_selection_risk {
|
||||||
|
self.selectable_universe_on_with_options(ctx, date, universe_factor_date, true)
|
||||||
|
} else {
|
||||||
|
self.selectable_universe_on(ctx, date, universe_factor_date)
|
||||||
|
};
|
||||||
|
let risk_decisions = if defer_limit_state_selection_risk {
|
||||||
|
self.selection_risk_decisions_with_options(ctx, date, universe_factor_date, true)
|
||||||
|
} else {
|
||||||
|
self.selection_risk_decisions(ctx, date, universe_factor_date)
|
||||||
|
};
|
||||||
let mut diagnostics = Self::selection_risk_decision_diagnostics(
|
let mut diagnostics = Self::selection_risk_decision_diagnostics(
|
||||||
&risk_decisions,
|
&risk_decisions,
|
||||||
date,
|
date,
|
||||||
@@ -7085,7 +7161,8 @@ impl PlatformExprStrategy {
|
|||||||
ctx,
|
ctx,
|
||||||
date,
|
date,
|
||||||
universe_factor_date,
|
universe_factor_date,
|
||||||
self.selection_uses_intraday_quote_fields()
|
ctx.is_lagged_execution()
|
||||||
|
|| self.selection_uses_intraday_quote_fields()
|
||||||
|| quote_usage != StockFilterQuoteUsage::DailyOnly,
|
|| quote_usage != StockFilterQuoteUsage::DailyOnly,
|
||||||
);
|
);
|
||||||
let quote_candidate_limit = self.quote_plan_candidate_limit(selection_limit);
|
let quote_candidate_limit = self.quote_plan_candidate_limit(selection_limit);
|
||||||
@@ -8620,6 +8697,168 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_next_open_projected_execution_price_uses_open_not_close() {
|
||||||
|
let date = d(2025, 1, 2);
|
||||||
|
let market = DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
timestamp: Some(format!("{date} 15:00:00")),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 11.0,
|
||||||
|
low: 9.8,
|
||||||
|
close: 11.0,
|
||||||
|
last_price: 11.0,
|
||||||
|
bid1: 11.0,
|
||||||
|
ask1: 11.0,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
minute_volume: 10_000,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 11.0,
|
||||||
|
lower_limit: 9.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
};
|
||||||
|
let mut cfg = PlatformExprStrategyConfig::microcap_rotation();
|
||||||
|
cfg.matching_type = MatchingType::NextBarOpen;
|
||||||
|
let strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
strategy.projected_execution_price(&market, OrderSide::Buy),
|
||||||
|
10.0
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
strategy.projected_execution_price(&market, OrderSide::Sell),
|
||||||
|
10.0
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut aiquant_cfg = PlatformExprStrategyConfig::microcap_rotation();
|
||||||
|
aiquant_cfg.matching_type = MatchingType::NextBarOpen;
|
||||||
|
aiquant_cfg.aiquant_transaction_cost = true;
|
||||||
|
let aiquant_strategy = PlatformExprStrategy::new(aiquant_cfg);
|
||||||
|
assert_eq!(
|
||||||
|
aiquant_strategy.projected_execution_price(&market, OrderSide::Buy),
|
||||||
|
10.0
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
aiquant_strategy.projected_execution_price(&market, OrderSide::Sell),
|
||||||
|
10.0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_next_open_sell_risk_uses_open_not_close_for_lower_limit() {
|
||||||
|
let prev_date = d(2025, 1, 1);
|
||||||
|
let date = d(2025, 1, 2);
|
||||||
|
let symbol = "000001.SZ";
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
vec![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(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: Some(format!("{date} 15:00:00")),
|
||||||
|
day_open: 9.2,
|
||||||
|
open: 9.2,
|
||||||
|
high: 9.5,
|
||||||
|
low: 9.0,
|
||||||
|
close: 9.0,
|
||||||
|
last_price: 9.0,
|
||||||
|
bid1: 9.0,
|
||||||
|
ask1: 9.01,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
minute_volume: 10_000,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_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: symbol.to_string(),
|
||||||
|
market_cap_bn: 10.0,
|
||||||
|
free_float_cap_bn: 8.0,
|
||||||
|
pe_ttm: 12.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_star_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1000.0,
|
||||||
|
prev_close: 999.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
portfolio.position_mut(symbol).buy(prev_date, 1_000, 10.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.matching_type = MatchingType::NextBarOpen;
|
||||||
|
let strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
strategy.can_sell_position_at_time(&ctx, date, symbol, None),
|
||||||
|
"next-open sell should use open=9.2 instead of close=9.0 for lower-limit risk"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut aiquant_cfg = PlatformExprStrategyConfig::microcap_rotation();
|
||||||
|
aiquant_cfg.matching_type = MatchingType::NextBarOpen;
|
||||||
|
aiquant_cfg.aiquant_transaction_cost = true;
|
||||||
|
let aiquant_strategy = PlatformExprStrategy::new(aiquant_cfg);
|
||||||
|
assert!(
|
||||||
|
aiquant_strategy.can_sell_position_at_time(&ctx, date, symbol, None),
|
||||||
|
"next-open risk must still use open when compatibility profile enables scheduled quotes"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn platform_selection_kcb_switch_overrides_legacy_universe_exclude() {
|
fn platform_selection_kcb_switch_overrides_legacy_universe_exclude() {
|
||||||
let date = d(2025, 1, 2);
|
let date = d(2025, 1, 2);
|
||||||
@@ -11952,6 +12191,149 @@ mod tests {
|
|||||||
assert!(selected.is_empty());
|
assert!(selected.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_next_open_select_symbols_defers_decision_day_limit_state() {
|
||||||
|
let decision_date = d(2025, 1, 2);
|
||||||
|
let execution_date = d(2025, 1, 3);
|
||||||
|
let signal = "000001.SH";
|
||||||
|
let symbol = "600001.SH";
|
||||||
|
let market =
|
||||||
|
|date: NaiveDate, code: &str, open: f64, close: f64, upper: f64, lower: f64| {
|
||||||
|
DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: code.to_string(),
|
||||||
|
timestamp: Some(format!("{date} 15:00:00")),
|
||||||
|
day_open: open,
|
||||||
|
open,
|
||||||
|
high: close.max(open),
|
||||||
|
low: close.min(open),
|
||||||
|
close,
|
||||||
|
last_price: close,
|
||||||
|
bid1: close,
|
||||||
|
ask1: close,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
minute_volume: 10_000,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: upper,
|
||||||
|
lower_limit: lower,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
[signal, symbol]
|
||||||
|
.into_iter()
|
||||||
|
.map(|code| Instrument {
|
||||||
|
symbol: code.to_string(),
|
||||||
|
name: code.to_string(),
|
||||||
|
board: if code.ends_with(".SH") { "SH" } else { "SZ" }.to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2020, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![
|
||||||
|
market(decision_date, signal, 10.0, 10.1, 11.0, 9.0),
|
||||||
|
market(execution_date, signal, 10.0, 10.1, 11.0, 9.0),
|
||||||
|
market(decision_date, symbol, 10.9, 11.0, 11.0, 9.0),
|
||||||
|
market(execution_date, symbol, 10.5, 10.6, 11.0, 9.0),
|
||||||
|
],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date: decision_date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
market_cap_bn: 12.0,
|
||||||
|
free_float_cap_bn: 8.0,
|
||||||
|
pe_ttm: 10.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date: decision_date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_star_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
|
}],
|
||||||
|
[decision_date, execution_date]
|
||||||
|
.into_iter()
|
||||||
|
.map(|date| BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1000.0,
|
||||||
|
prev_close: 999.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date,
|
||||||
|
decision_date,
|
||||||
|
decision_index: 1,
|
||||||
|
data: &data,
|
||||||
|
portfolio: &portfolio,
|
||||||
|
futures_account: None,
|
||||||
|
open_orders: &[],
|
||||||
|
dynamic_universe: None,
|
||||||
|
subscriptions: &subscriptions,
|
||||||
|
process_events: &[],
|
||||||
|
active_process_event: None,
|
||||||
|
active_datetime: None,
|
||||||
|
order_events: &[],
|
||||||
|
fills: &[],
|
||||||
|
};
|
||||||
|
let mut cfg = PlatformExprStrategyConfig::microcap_rotation();
|
||||||
|
cfg.matching_type = MatchingType::NextBarOpen;
|
||||||
|
cfg.signal_symbol = signal.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();
|
||||||
|
cfg.benchmark_short_ma_days = 1;
|
||||||
|
cfg.benchmark_long_ma_days = 1;
|
||||||
|
let strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
let day = strategy.day_state(&ctx, decision_date).expect("day state");
|
||||||
|
|
||||||
|
let (selected, diagnostics, risk_decisions) = strategy
|
||||||
|
.select_symbols(
|
||||||
|
&ctx,
|
||||||
|
decision_date,
|
||||||
|
decision_date,
|
||||||
|
decision_date,
|
||||||
|
&day,
|
||||||
|
0.0,
|
||||||
|
100.0,
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
.expect("select symbols");
|
||||||
|
|
||||||
|
assert_eq!(selected, vec![symbol.to_string()]);
|
||||||
|
assert!(
|
||||||
|
diagnostics.iter().all(|line| !line.contains("upper_limit")),
|
||||||
|
"{diagnostics:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
risk_decisions
|
||||||
|
.iter()
|
||||||
|
.all(|decision| decision.rule_code != "upper_limit"),
|
||||||
|
"{risk_decisions:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn platform_market_cap_field_uses_storage_unit_without_extra_scaling() {
|
fn platform_market_cap_field_uses_storage_unit_without_extra_scaling() {
|
||||||
let date = d(2025, 4, 8);
|
let date = d(2025, 4, 8);
|
||||||
|
|||||||
@@ -135,7 +135,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(),
|
"next_bar_open 会用决策日信号生成订单,并在下一可交易开盘撮合;不得把执行日 open/high/low/close 当成下单前已知信息;涨停买入和跌停卖出风控必须用实际 next-open 成交价比较,不能用执行日 close/last 或 next-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(),
|
||||||
],
|
],
|
||||||
@@ -258,7 +258,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(\"current_bar_close\") 或 execution.matching_type(\"next_bar_open\");current_bar_close 使用决策日当日 close,next_bar_open 使用决策日信号并在下一可交易日 open 撮合,禁止把执行日 open/high/low/close 解释为下单前已知数据。分钟线回测使用当前分钟价格成交,只能写 execution.matching_type(\"minute_last\");不要把 vwap、twap、open_auction、minute_best_own、minute_best_counterparty 写成全局 matching_type,这些只属于显式订单或内部撮合能力。滑点支持 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(\"current_bar_close\") 或 execution.matching_type(\"next_bar_open\");current_bar_close 使用决策日当日 close,next_bar_open 使用决策日信号并在下一可交易日 open 撮合,禁止把执行日 open/high/low/close 解释为下单前已知数据;next_bar_open 的涨停买入和跌停卖出判断必须比较实际 open 成交价与涨跌停价,不能用执行日 close/last 或 next-close。分钟线回测使用当前分钟价格成交,只能写 execution.matching_type(\"minute_last\");不要把 vwap、twap、open_auction、minute_best_own、minute_best_counterparty 写成全局 matching_type,这些只属于显式订单或内部撮合能力。滑点支持 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(),
|
||||||
@@ -484,7 +484,7 @@ pub fn render_manual_markdown(manual: &StrategyAiManual) -> String {
|
|||||||
out.push_str("- `filter.stock_expr(...)` 只写 alpha 或业务过滤条件;不要把 `!is_st`、`!paused`、`!at_upper_limit`、`!at_lower_limit` 这类基础风控散落在过滤表达式里。\n");
|
out.push_str("- `filter.stock_expr(...)` 只写 alpha 或业务过滤条件;不要把 `!is_st`、`!paused`、`!at_upper_limit`、`!at_lower_limit` 这类基础风控散落在过滤表达式里。\n");
|
||||||
out.push_str("- 完整三元表达式 `cond ? a : b` 可在表达式参数中使用;若当前运行环境报 `Unknown operator: '?'`,先重编译并重启回测服务,不要改写策略语义掩盖运行时漂移。\n");
|
out.push_str("- 完整三元表达式 `cond ? a : b` 可在表达式参数中使用;若当前运行环境报 `Unknown operator: '?'`,先重编译并重启回测服务,不要改写策略语义掩盖运行时漂移。\n");
|
||||||
out.push_str("- `next_bar_open` 的选股、排序和仓位信号来自决策日,订单在下一可交易开盘撮合;不要使用执行日价格作为下单前信号。\n");
|
out.push_str("- `next_bar_open` 的选股、排序和仓位信号来自决策日,订单在下一可交易开盘撮合;不要使用执行日价格作为下单前信号。\n");
|
||||||
out.push_str("- `next_bar_open` 必须区分信号日、订单创建日和实际成交日:T 日只生成订单意图,涨跌停、停牌、ST、退市、一元股、黑名单、成交量和盘口流动性等执行约束必须由撮合/风控层按实际成交日判断,禁止用 T 日执行状态拦截 T+1 可交易订单。\n");
|
out.push_str("- `next_bar_open` 必须区分信号日、订单创建日和实际成交日:T 日只生成订单意图,涨跌停、停牌、ST、退市、一元股、黑名单、成交量和盘口流动性等执行约束必须由撮合/风控层按实际成交日判断;涨停买入和跌停卖出必须比较实际 next-open 成交价与涨跌停价,不能用执行日 close/last 或 next-close;禁止用 T 日执行状态拦截 T+1 可交易订单。\n");
|
||||||
out.push_str("- `execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\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 {
|
||||||
@@ -564,7 +564,7 @@ pub fn build_generation_prompt(
|
|||||||
prompt.push('\n');
|
prompt.push('\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、risk.policy、risk.blacklist、execution.matching_type、execution.slippage、universe.exclude。universe.exclude 只用于用户明确要求的业务排除项,不能表达 FIDC 基础风控。禁止输出 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、risk.policy、risk.blacklist、execution.matching_type、execution.slippage、universe.exclude。universe.exclude 只用于用户明确要求的业务排除项,不能表达 FIDC 基础风控。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
|
||||||
prompt.push_str(&format!("参数形态必须严格: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);rolling_mean、rolling_sum/min/max/stddev/zscore、pct_change、factor_value 等 helper 的第一个参数必须是字段名或字符串字段名,不能传嵌套表达式或另一个 helper 调用;不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,不要写 is_st == 0;filter.stock_expr 只写 alpha 或业务过滤条件,不要把 !is_st、!paused、!at_upper_limit、!at_lower_limit 这类基础风控散落在表达式里;risk.index_exposure 只能传一个数值表达式,不要使用 risk.exposure;risk.policy 只写 FIDC 基础风控、成交量和交易成本命名参数,必须覆盖完整默认配置面,例如 {DEFAULT_RISK_POLICY_DSL_PROMPT},不要用它表达策略择时或收益规则;完整三元表达式 cond ? a : b 可以使用,但不得输出残缺问号/冒号片段;日线回测 execution.matching_type 只能取 current_bar_close 或 next_bar_open,分钟线回测只能取 minute_last;不要把 vwap、twap、open_auction、minute_best_own、minute_best_counterparty 写成全局 matching_type;next_bar_open 只能使用决策日信号,不能把执行日价格当作下单前信息;next_bar_open 下 T 日只生成订单意图,涨跌停、停牌、ST、退市、一元股、黑名单、成交量和盘口流动性等执行约束必须由撮合/风控层按实际成交日判断,禁止用 T 日执行状态拦截 T+1 可交易订单;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n"));
|
prompt.push_str(&format!("参数形态必须严格: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);rolling_mean、rolling_sum/min/max/stddev/zscore、pct_change、factor_value 等 helper 的第一个参数必须是字段名或字符串字段名,不能传嵌套表达式或另一个 helper 调用;不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,不要写 is_st == 0;filter.stock_expr 只写 alpha 或业务过滤条件,不要把 !is_st、!paused、!at_upper_limit、!at_lower_limit 这类基础风控散落在表达式里;risk.index_exposure 只能传一个数值表达式,不要使用 risk.exposure;risk.policy 只写 FIDC 基础风控、成交量和交易成本命名参数,必须覆盖完整默认配置面,例如 {DEFAULT_RISK_POLICY_DSL_PROMPT},不要用它表达策略择时或收益规则;完整三元表达式 cond ? a : b 可以使用,但不得输出残缺问号/冒号片段;日线回测 execution.matching_type 只能取 current_bar_close 或 next_bar_open,分钟线回测只能取 minute_last;不要把 vwap、twap、open_auction、minute_best_own、minute_best_counterparty 写成全局 matching_type;next_bar_open 只能使用决策日信号,不能把执行日价格当作下单前信息;next_bar_open 下 T 日只生成订单意图,涨跌停、停牌、ST、退市、一元股、黑名单、成交量和盘口流动性等执行约束必须由撮合/风控层按实际成交日判断;涨停买入和跌停卖出必须用实际 next-open 成交价比较,不能用执行日 close/last 或 next-close;禁止用 T 日执行状态拦截 T+1 可交易订单;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 && close > 2)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.policy(");
|
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 && close > 2)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.policy(");
|
||||||
prompt.push_str(DEFAULT_RISK_POLICY_DSL_CODE);
|
prompt.push_str(DEFAULT_RISK_POLICY_DSL_CODE);
|
||||||
|
|||||||
Reference in New Issue
Block a user