Compare commits
58 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c83526a6a4 | |||
| 9bd19aa042 | |||
| 2f62d82420 | |||
| 7f809fd875 | |||
| 8495bf6ad8 | |||
| 9d41971d3f | |||
| c409d500b3 | |||
| d0ab59669f | |||
| d264e39285 | |||
| 5b34f3b55b | |||
| 192ac3f843 | |||
| 581d4e32d0 | |||
| bb87d69224 | |||
| 0714d1f77b | |||
| 78af8c3219 | |||
| fd27429713 | |||
| a270e368c8 | |||
| a368fd5d7f | |||
| 0f982887a3 | |||
| beebc5fa58 | |||
| f8bc0679ee | |||
| cdca7984ed | |||
| 816fc48077 | |||
| 144483be4c | |||
| eb4e77f8c5 | |||
| 6ddbdac9cd | |||
| ecb9a1cfaf | |||
| 61fc93abf1 | |||
| 7ce28e6d0f | |||
| 1a4936d250 | |||
| 9692557746 | |||
| 8df6bfd19c | |||
| 5e66e9799c | |||
| 5ecb0e7986 | |||
| c3a5161db1 | |||
| 57aebe97ec | |||
| 651174dc57 | |||
| 4b6301cb37 | |||
| 1db80e1e13 | |||
| 938f4fec13 | |||
| daa505152a | |||
| 02d4ea9ca7 | |||
| 3633905459 | |||
| 2265a5dc67 | |||
| 616d9cdce2 | |||
| 213deb6e99 | |||
| 7ff443898c | |||
| d7c1674c6c | |||
| 4f39ac7dfe | |||
| 8d24badcf2 | |||
| 6c7f7130cf | |||
| d8b6130428 | |||
| dae573e318 | |||
| 674e4b0b14 | |||
| 828b55c747 | |||
| 596d64280b | |||
| 1683d875a0 | |||
| ed4658ccd0 |
+448
-11
@@ -908,6 +908,29 @@ where
|
||||
commission_state,
|
||||
report,
|
||||
),
|
||||
OrderIntent::TimedTargetValue {
|
||||
symbol,
|
||||
target_value,
|
||||
style,
|
||||
start_time,
|
||||
end_time,
|
||||
reason,
|
||||
} => self.process_timed_target_value(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
symbol,
|
||||
*target_value,
|
||||
*style,
|
||||
*start_time,
|
||||
*end_time,
|
||||
reason,
|
||||
intraday_turnover,
|
||||
execution_cursors,
|
||||
global_execution_cursor,
|
||||
commission_state,
|
||||
report,
|
||||
),
|
||||
OrderIntent::LimitTargetValue {
|
||||
symbol,
|
||||
target_value,
|
||||
@@ -2030,6 +2053,34 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn aiquant_order_limit_check_price(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
side: OrderSide,
|
||||
algo_request: Option<&AlgoExecutionRequest>,
|
||||
) -> f64 {
|
||||
let matching_type = self.matching_type_for_algo_request(algo_request);
|
||||
let start_cursor = algo_request
|
||||
.and_then(|request| request.start_time)
|
||||
.or(self.runtime_intraday_start_time.get())
|
||||
.or(self.intraday_execution_start_time)
|
||||
.map(|start_time| date.and_time(start_time));
|
||||
self.latest_known_quote_at_or_before(
|
||||
data.execution_quotes_on(date, symbol),
|
||||
start_cursor,
|
||||
snapshot,
|
||||
side,
|
||||
matching_type,
|
||||
false,
|
||||
)
|
||||
.and_then(|quote| self.select_quote_reference_price(snapshot, quote, side, matching_type))
|
||||
.unwrap_or_else(|| self.aiquant_limit_check_price(snapshot, side))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn buy_rule_check(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -2059,16 +2110,68 @@ where
|
||||
RuleCheck::allow()
|
||||
}
|
||||
|
||||
fn sell_rule_check(
|
||||
fn buy_rule_check_for_order(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
candidate: &crate::data::CandidateEligibility,
|
||||
instrument: Option<&Instrument>,
|
||||
algo_request: Option<&AlgoExecutionRequest>,
|
||||
) -> RuleCheck {
|
||||
let check_price = if self.aiquant_rqalpha_execution_rules {
|
||||
self.aiquant_order_limit_check_price(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
OrderSide::Buy,
|
||||
algo_request,
|
||||
)
|
||||
} else {
|
||||
ChinaAShareRiskControl::buy_check_price(snapshot, self.execution_price_field)
|
||||
};
|
||||
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
|
||||
date,
|
||||
candidate,
|
||||
snapshot,
|
||||
instrument,
|
||||
check_price,
|
||||
) {
|
||||
return RuleCheck::reject(reason);
|
||||
}
|
||||
if !self.aiquant_rqalpha_execution_rules {
|
||||
return self
|
||||
.rules
|
||||
.can_buy(date, snapshot, candidate, self.execution_price_field);
|
||||
}
|
||||
RuleCheck::allow()
|
||||
}
|
||||
|
||||
fn sell_rule_check_for_order(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
candidate: &crate::data::CandidateEligibility,
|
||||
instrument: Option<&Instrument>,
|
||||
position: &crate::portfolio::Position,
|
||||
algo_request: Option<&AlgoExecutionRequest>,
|
||||
) -> RuleCheck {
|
||||
if !self.aiquant_rqalpha_execution_rules && !candidate.allow_sell {
|
||||
return RuleCheck::reject("sell_disabled");
|
||||
}
|
||||
let check_price = if self.aiquant_rqalpha_execution_rules {
|
||||
self.aiquant_limit_check_price(snapshot, OrderSide::Sell)
|
||||
self.aiquant_order_limit_check_price(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
OrderSide::Sell,
|
||||
algo_request,
|
||||
)
|
||||
} else {
|
||||
ChinaAShareRiskControl::sell_check_price(snapshot, self.execution_price_field)
|
||||
};
|
||||
@@ -2116,8 +2219,16 @@ where
|
||||
let Ok(candidate) = data.require_candidate(date, symbol) else {
|
||||
return current_qty;
|
||||
};
|
||||
let rule =
|
||||
self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
|
||||
let rule = self.sell_rule_check_for_order(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
candidate,
|
||||
data.instrument(symbol),
|
||||
position,
|
||||
None,
|
||||
);
|
||||
if !rule.allowed {
|
||||
return current_qty;
|
||||
}
|
||||
@@ -2155,7 +2266,15 @@ where
|
||||
let Ok(candidate) = data.require_candidate(date, symbol) else {
|
||||
return current_qty;
|
||||
};
|
||||
let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
|
||||
let rule = self.buy_rule_check_for_order(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
candidate,
|
||||
data.instrument(symbol),
|
||||
None,
|
||||
);
|
||||
if !rule.allowed {
|
||||
return current_qty;
|
||||
}
|
||||
@@ -2199,8 +2318,16 @@ where
|
||||
let position = portfolio.position(symbol)?;
|
||||
let snapshot = data.require_market(date, symbol).ok()?;
|
||||
let candidate = data.require_candidate(date, symbol).ok()?;
|
||||
let rule =
|
||||
self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
|
||||
let rule = self.sell_rule_check_for_order(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
candidate,
|
||||
data.instrument(symbol),
|
||||
position,
|
||||
None,
|
||||
);
|
||||
if !rule.allowed {
|
||||
return rule.reason;
|
||||
}
|
||||
@@ -2240,7 +2367,15 @@ where
|
||||
) -> Option<String> {
|
||||
let snapshot = data.require_market(date, symbol).ok()?;
|
||||
let candidate = data.require_candidate(date, symbol).ok()?;
|
||||
let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
|
||||
let rule = self.buy_rule_check_for_order(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
candidate,
|
||||
data.instrument(symbol),
|
||||
None,
|
||||
);
|
||||
if !rule.allowed {
|
||||
return rule.reason;
|
||||
}
|
||||
@@ -2310,8 +2445,16 @@ where
|
||||
);
|
||||
}
|
||||
|
||||
let rule =
|
||||
self.sell_rule_check(date, snapshot, candidate, data.instrument(symbol), position);
|
||||
let rule = self.sell_rule_check_for_order(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
candidate,
|
||||
data.instrument(symbol),
|
||||
position,
|
||||
algo_request,
|
||||
);
|
||||
if !rule.allowed {
|
||||
let rule_reason = rule.reason.as_deref().unwrap_or_default().to_string();
|
||||
let status = match rule.reason.as_deref() {
|
||||
@@ -2891,6 +3034,118 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn process_timed_target_value(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
portfolio: &mut PortfolioState,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
target_value: f64,
|
||||
style: AlgoOrderStyle,
|
||||
start_time: Option<NaiveTime>,
|
||||
end_time: Option<NaiveTime>,
|
||||
reason: &str,
|
||||
intraday_turnover: &mut BTreeMap<String, u32>,
|
||||
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
||||
global_execution_cursor: &mut Option<NaiveDateTime>,
|
||||
commission_state: &mut BTreeMap<u64, f64>,
|
||||
report: &mut BrokerExecutionReport,
|
||||
) -> Result<(), BacktestError> {
|
||||
let snapshot = data
|
||||
.market(date, symbol)
|
||||
.ok_or_else(|| BacktestError::MissingPrice {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
field: price_field_name(self.execution_price_field),
|
||||
})?;
|
||||
let current_qty = portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.quantity)
|
||||
.unwrap_or(0);
|
||||
let algo_request = AlgoExecutionRequest {
|
||||
style: match style {
|
||||
AlgoOrderStyle::Vwap => AlgoExecutionStyle::Vwap,
|
||||
AlgoOrderStyle::Twap => AlgoExecutionStyle::Twap,
|
||||
},
|
||||
start_time,
|
||||
end_time,
|
||||
};
|
||||
|
||||
if target_value <= f64::EPSILON {
|
||||
if current_qty == 0 {
|
||||
report.order_events.push(OrderEvent {
|
||||
date,
|
||||
order_id: None,
|
||||
symbol: symbol.to_string(),
|
||||
side: OrderSide::Sell,
|
||||
requested_quantity: 0,
|
||||
filled_quantity: 0,
|
||||
status: OrderStatus::Filled,
|
||||
reason: format!("{reason}: already at target value"),
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
self.process_sell(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
symbol,
|
||||
current_qty,
|
||||
self.reserve_order_id(),
|
||||
reason,
|
||||
intraday_turnover,
|
||||
execution_cursors,
|
||||
global_execution_cursor,
|
||||
commission_state,
|
||||
None,
|
||||
false,
|
||||
true,
|
||||
Some(&algo_request),
|
||||
report,
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
|
||||
let current_value = valuation_price * current_qty as f64;
|
||||
let cash_delta = target_value.max(0.0) - current_value;
|
||||
if cash_delta.abs() > f64::EPSILON {
|
||||
self.process_algo_value(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
symbol,
|
||||
cash_delta,
|
||||
style,
|
||||
start_time,
|
||||
end_time,
|
||||
reason,
|
||||
intraday_turnover,
|
||||
execution_cursors,
|
||||
global_execution_cursor,
|
||||
commission_state,
|
||||
report,
|
||||
)?;
|
||||
} else {
|
||||
report.order_events.push(OrderEvent {
|
||||
date,
|
||||
order_id: None,
|
||||
symbol: symbol.to_string(),
|
||||
side: if current_qty > 0 {
|
||||
OrderSide::Sell
|
||||
} else {
|
||||
OrderSide::Buy
|
||||
},
|
||||
requested_quantity: 0,
|
||||
filled_quantity: 0,
|
||||
status: OrderStatus::Filled,
|
||||
reason: format!("{reason}: already at target value"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_target_shares(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -3765,7 +4020,15 @@ where
|
||||
);
|
||||
}
|
||||
|
||||
let rule = self.buy_rule_check(date, snapshot, candidate, data.instrument(symbol));
|
||||
let rule = self.buy_rule_check_for_order(
|
||||
date,
|
||||
data,
|
||||
symbol,
|
||||
snapshot,
|
||||
candidate,
|
||||
data.instrument(symbol),
|
||||
algo_request,
|
||||
);
|
||||
if !rule.allowed {
|
||||
let rule_reason = rule.reason.as_deref().unwrap_or_default().to_string();
|
||||
let status = match rule.reason.as_deref() {
|
||||
@@ -5137,6 +5400,7 @@ mod tests {
|
||||
use crate::instrument::Instrument;
|
||||
use crate::portfolio::PortfolioState;
|
||||
use crate::rules::ChinaEquityRuleHooks;
|
||||
use crate::strategy::AlgoOrderStyle;
|
||||
|
||||
fn limit_test_snapshot() -> DailyMarketSnapshot {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
|
||||
@@ -5194,6 +5458,7 @@ mod tests {
|
||||
allow_sell,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5282,6 +5547,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timed_target_value_zero_sells_full_position_at_requested_time_quote() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
|
||||
let prev_date = chrono::NaiveDate::from_ymd_opt(2025, 1, 1).expect("valid date");
|
||||
let symbol = "000001.SZ";
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_intraday_execution_start_time(date.and_hms_opt(10, 18, 0).unwrap().time())
|
||||
.with_matching_type(MatchingType::NextTickLast)
|
||||
.with_slippage_model(SlippageModel::PriceRatio(0.001))
|
||||
.with_volume_limit(false)
|
||||
.with_liquidity_limit(false);
|
||||
let mut snapshot = limit_test_snapshot();
|
||||
snapshot.symbol = symbol.to_string();
|
||||
snapshot.last_price = 4.21;
|
||||
snapshot.close = 4.21;
|
||||
snapshot.bid1 = 4.20;
|
||||
snapshot.ask1 = 4.22;
|
||||
snapshot.prev_close = 4.15;
|
||||
snapshot.upper_limit = 4.98;
|
||||
snapshot.lower_limit = 3.32;
|
||||
let mut quote_0931 = limit_test_quote(4.11, 4.10, 4.12);
|
||||
quote_0931.symbol = symbol.to_string();
|
||||
quote_0931.timestamp = date.and_hms_opt(9, 31, 0).expect("valid timestamp");
|
||||
let mut quote_1018 = limit_test_quote(4.21, 4.20, 4.22);
|
||||
quote_1018.symbol = symbol.to_string();
|
||||
quote_1018.timestamp = date.and_hms_opt(10, 18, 0).expect("valid timestamp");
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![limit_test_instrument()],
|
||||
vec![snapshot],
|
||||
Vec::new(),
|
||||
vec![limit_test_candidate(true, true)],
|
||||
vec![limit_test_benchmark()],
|
||||
Vec::new(),
|
||||
vec![quote_0931, quote_1018],
|
||||
)
|
||||
.expect("valid dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
portfolio.position_mut(symbol).buy(prev_date, 72_600, 4.0);
|
||||
portfolio.apply_cash_delta(-290_400.0);
|
||||
let mut report = BrokerExecutionReport::default();
|
||||
|
||||
broker
|
||||
.process_timed_target_value(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
symbol,
|
||||
0.0,
|
||||
AlgoOrderStyle::Twap,
|
||||
Some(date.and_hms_opt(9, 31, 0).unwrap().time()),
|
||||
Some(date.and_hms_opt(9, 31, 0).unwrap().time()),
|
||||
"risk_forced_exit",
|
||||
&mut BTreeMap::new(),
|
||||
&mut BTreeMap::new(),
|
||||
&mut None,
|
||||
&mut BTreeMap::new(),
|
||||
&mut report,
|
||||
)
|
||||
.expect("timed target value");
|
||||
|
||||
assert!(
|
||||
!report.fill_events.is_empty(),
|
||||
"order_events={:?}",
|
||||
report.order_events
|
||||
);
|
||||
let fill = report.fill_events.last().expect("fill event");
|
||||
assert_eq!(fill.quantity, 72_600);
|
||||
assert!((fill.price - 4.10589).abs() < 1e-6, "{fill:?}");
|
||||
assert_eq!(
|
||||
portfolio
|
||||
.position(symbol)
|
||||
.map(|position| position.quantity)
|
||||
.unwrap_or(0),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiquant_target_value_delta_uses_scheduled_mark_price() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2023, 5, 8).expect("valid date");
|
||||
@@ -5361,6 +5707,7 @@ mod tests {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -5773,4 +6120,94 @@ mod tests {
|
||||
assert_eq!(fill.quantity, 0);
|
||||
assert_eq!(fill.unfilled_reason, Some("open at or below lower limit"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiquant_sell_rule_uses_intraday_quote_when_daily_snapshot_is_stale_lower_limit() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2024, 4, 17).expect("valid date");
|
||||
let prev_date = chrono::NaiveDate::from_ymd_opt(2024, 4, 16).expect("valid date");
|
||||
let symbol = "000001.SZ";
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_aiquant_rqalpha_execution_rules(true)
|
||||
.with_intraday_execution_start_time(date.and_hms_opt(10, 18, 0).unwrap().time())
|
||||
.with_volume_limit(false)
|
||||
.with_liquidity_limit(false)
|
||||
.with_inactive_limit(false)
|
||||
.with_slippage_model(SlippageModel::None);
|
||||
|
||||
let mut snapshot = limit_test_snapshot();
|
||||
snapshot.date = date;
|
||||
snapshot.timestamp = Some("2024-04-17 10:18:00".to_string());
|
||||
snapshot.day_open = 9.0;
|
||||
snapshot.open = 9.0;
|
||||
snapshot.high = 10.0;
|
||||
snapshot.low = 9.0;
|
||||
snapshot.close = 9.9;
|
||||
snapshot.last_price = 9.0;
|
||||
snapshot.bid1 = 9.0;
|
||||
snapshot.ask1 = 9.0;
|
||||
snapshot.prev_close = 10.0;
|
||||
snapshot.upper_limit = 11.0;
|
||||
snapshot.lower_limit = 9.0;
|
||||
let mut candidate = limit_test_candidate(true, false);
|
||||
candidate.date = date;
|
||||
let mut quote = limit_test_quote(10.0, 9.99, 10.0);
|
||||
quote.date = date;
|
||||
quote.timestamp = date.and_hms_opt(10, 18, 0).unwrap();
|
||||
quote.last_price = 10.0;
|
||||
quote.bid1 = 9.99;
|
||||
quote.ask1 = 10.0;
|
||||
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![limit_test_instrument()],
|
||||
vec![snapshot],
|
||||
Vec::new(),
|
||||
vec![candidate],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1000.0,
|
||||
prev_close: 1000.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![quote],
|
||||
)
|
||||
.expect("valid dataset");
|
||||
let mut portfolio = PortfolioState::new(100.0);
|
||||
portfolio.position_mut(symbol).buy(prev_date, 7_200, 8.48);
|
||||
let mut report = BrokerExecutionReport::default();
|
||||
|
||||
broker
|
||||
.process_target_value(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
symbol,
|
||||
0.0,
|
||||
"stop_loss_exit",
|
||||
&mut BTreeMap::new(),
|
||||
&mut BTreeMap::new(),
|
||||
&mut None,
|
||||
&mut BTreeMap::new(),
|
||||
&mut report,
|
||||
)
|
||||
.expect("target sell processed");
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert_eq!(report.fill_events[0].quantity, 7_200);
|
||||
assert!(portfolio.position(symbol).is_none());
|
||||
assert!(
|
||||
report
|
||||
.order_events
|
||||
.iter()
|
||||
.all(|event| !event.reason.contains("open at or below lower limit")),
|
||||
"{:?}",
|
||||
report.order_events
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+438
-163
@@ -1,6 +1,7 @@
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, OnceLock, RwLock};
|
||||
|
||||
use chrono::{NaiveDate, NaiveDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -207,6 +208,8 @@ pub struct CandidateEligibility {
|
||||
pub allow_sell: bool,
|
||||
pub is_kcb: bool,
|
||||
pub is_one_yuan: bool,
|
||||
#[serde(default)]
|
||||
pub risk_level_code: Option<String>,
|
||||
}
|
||||
|
||||
impl CandidateEligibility {
|
||||
@@ -364,6 +367,17 @@ pub struct DailySnapshotBundle {
|
||||
pub corporate_actions: Vec<CorporateAction>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DataSetSnapshotComponents {
|
||||
pub instruments: Vec<Instrument>,
|
||||
pub market: Vec<DailyMarketSnapshot>,
|
||||
pub factors: Vec<DailyFactorSnapshot>,
|
||||
pub candidates: Vec<CandidateEligibility>,
|
||||
pub benchmarks: Vec<BenchmarkSnapshot>,
|
||||
pub corporate_actions: Vec<CorporateAction>,
|
||||
pub execution_quotes: Vec<IntradayExecutionQuote>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PriceBar {
|
||||
#[serde(with = "date_format")]
|
||||
@@ -466,7 +480,17 @@ pub fn decision_adjusted_cap_bn(
|
||||
raw_cap_bn * market.prev_close / market.close
|
||||
}
|
||||
|
||||
fn factor_market_cap_is_decision_adjusted(factor: &DailyFactorSnapshot) -> bool {
|
||||
factor
|
||||
.extra_factors
|
||||
.get("__market_cap_decision_adjusted")
|
||||
.is_some_and(|value| value.is_finite() && *value > 0.0)
|
||||
}
|
||||
|
||||
pub fn decision_market_cap_bn(factor: &DailyFactorSnapshot, market: &DailyMarketSnapshot) -> f64 {
|
||||
if factor_market_cap_is_decision_adjusted(factor) {
|
||||
return factor.market_cap_bn;
|
||||
}
|
||||
decision_adjusted_cap_bn(factor.date, factor.market_cap_bn, market)
|
||||
}
|
||||
|
||||
@@ -474,18 +498,35 @@ pub fn decision_free_float_cap_bn(
|
||||
factor: &DailyFactorSnapshot,
|
||||
market: &DailyMarketSnapshot,
|
||||
) -> f64 {
|
||||
if factor_market_cap_is_decision_adjusted(factor) {
|
||||
return factor.free_float_cap_bn;
|
||||
}
|
||||
decision_adjusted_cap_bn(factor.date, factor.free_float_cap_bn, market)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct SymbolPriceSeries {
|
||||
snapshots: Vec<DailyMarketSnapshot>,
|
||||
symbol: String,
|
||||
dates: Vec<NaiveDate>,
|
||||
timestamps: Vec<Option<String>>,
|
||||
day_opens: Vec<f64>,
|
||||
opens: Vec<f64>,
|
||||
highs: Vec<f64>,
|
||||
lows: Vec<f64>,
|
||||
closes: Vec<f64>,
|
||||
prev_closes: Vec<f64>,
|
||||
last_prices: Vec<f64>,
|
||||
volumes: Vec<f64>,
|
||||
bid1s: Vec<f64>,
|
||||
ask1s: Vec<f64>,
|
||||
volumes: Vec<u64>,
|
||||
tick_volumes: Vec<u64>,
|
||||
bid1_volumes: Vec<u64>,
|
||||
ask1_volumes: Vec<u64>,
|
||||
trading_phases: Vec<Option<String>>,
|
||||
paused: Vec<bool>,
|
||||
upper_limits: Vec<f64>,
|
||||
lower_limits: Vec<f64>,
|
||||
price_ticks: Vec<f64>,
|
||||
open_prefix: Vec<f64>,
|
||||
close_prefix: Vec<f64>,
|
||||
prev_close_prefix: Vec<f64>,
|
||||
@@ -494,33 +535,71 @@ struct SymbolPriceSeries {
|
||||
}
|
||||
|
||||
impl SymbolPriceSeries {
|
||||
fn new(rows: &[DailyMarketSnapshot]) -> Self {
|
||||
let mut sorted = rows.to_vec();
|
||||
fn new<'a, I>(symbol: String, rows: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = &'a DailyMarketSnapshot>,
|
||||
{
|
||||
let mut sorted = rows.into_iter().collect::<Vec<_>>();
|
||||
sorted.sort_by_key(|row| row.date);
|
||||
|
||||
let dates = sorted.iter().map(|row| row.date).collect::<Vec<_>>();
|
||||
let timestamps = sorted
|
||||
.iter()
|
||||
.map(|row| row.timestamp.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let day_opens = sorted.iter().map(|row| row.day_open).collect::<Vec<_>>();
|
||||
let opens = sorted.iter().map(|row| row.open).collect::<Vec<_>>();
|
||||
let highs = sorted.iter().map(|row| row.high).collect::<Vec<_>>();
|
||||
let lows = sorted.iter().map(|row| row.low).collect::<Vec<_>>();
|
||||
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
|
||||
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
|
||||
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
|
||||
let volumes = sorted
|
||||
let bid1s = sorted.iter().map(|row| row.bid1).collect::<Vec<_>>();
|
||||
let ask1s = sorted.iter().map(|row| row.ask1).collect::<Vec<_>>();
|
||||
let volumes = sorted.iter().map(|row| row.volume).collect::<Vec<_>>();
|
||||
let tick_volumes = sorted.iter().map(|row| row.tick_volume).collect::<Vec<_>>();
|
||||
let bid1_volumes = sorted.iter().map(|row| row.bid1_volume).collect::<Vec<_>>();
|
||||
let ask1_volumes = sorted.iter().map(|row| row.ask1_volume).collect::<Vec<_>>();
|
||||
let trading_phases = sorted
|
||||
.iter()
|
||||
.map(|row| row.volume as f64)
|
||||
.map(|row| row.trading_phase.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let paused = sorted.iter().map(|row| row.paused).collect::<Vec<_>>();
|
||||
let upper_limits = sorted.iter().map(|row| row.upper_limit).collect::<Vec<_>>();
|
||||
let lower_limits = sorted.iter().map(|row| row.lower_limit).collect::<Vec<_>>();
|
||||
let price_ticks = sorted.iter().map(|row| row.price_tick).collect::<Vec<_>>();
|
||||
let open_prefix = prefix_sums(&opens);
|
||||
let close_prefix = prefix_sums(&closes);
|
||||
let prev_close_prefix = prefix_sums(&prev_closes);
|
||||
let last_prefix = prefix_sums(&last_prices);
|
||||
let volume_prefix = prefix_sums(&volumes);
|
||||
let volume_values = volumes
|
||||
.iter()
|
||||
.map(|value| *value as f64)
|
||||
.collect::<Vec<_>>();
|
||||
let volume_prefix = prefix_sums(&volume_values);
|
||||
|
||||
Self {
|
||||
snapshots: sorted,
|
||||
symbol,
|
||||
dates,
|
||||
timestamps,
|
||||
day_opens,
|
||||
opens,
|
||||
highs,
|
||||
lows,
|
||||
closes,
|
||||
prev_closes,
|
||||
last_prices,
|
||||
bid1s,
|
||||
ask1s,
|
||||
volumes,
|
||||
tick_volumes,
|
||||
bid1_volumes,
|
||||
ask1_volumes,
|
||||
trading_phases,
|
||||
paused,
|
||||
upper_limits,
|
||||
lower_limits,
|
||||
price_ticks,
|
||||
open_prefix,
|
||||
close_prefix,
|
||||
prev_close_prefix,
|
||||
@@ -548,7 +627,7 @@ impl SymbolPriceSeries {
|
||||
return Vec::new();
|
||||
};
|
||||
let start = end.saturating_sub(lookback);
|
||||
self.values_for(field)[start..end].to_vec()
|
||||
self.price_values_for(field)[start..end].to_vec()
|
||||
}
|
||||
|
||||
fn trailing_snapshots(
|
||||
@@ -569,7 +648,31 @@ impl SymbolPriceSeries {
|
||||
return Vec::new();
|
||||
};
|
||||
let start = end.saturating_sub(lookback);
|
||||
self.snapshots[start..end].to_vec()
|
||||
(start..end).map(|index| self.snapshot_at(index)).collect()
|
||||
}
|
||||
|
||||
fn trailing_numeric_values(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
lookback: usize,
|
||||
field: &str,
|
||||
include_now: bool,
|
||||
) -> Vec<f64> {
|
||||
if lookback == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let end = if include_now {
|
||||
self.end_index(date)
|
||||
} else {
|
||||
self.previous_completed_end_index(date)
|
||||
};
|
||||
let Some(end) = end else {
|
||||
return Vec::new();
|
||||
};
|
||||
let start = end.saturating_sub(lookback);
|
||||
(start..end)
|
||||
.filter_map(|index| self.numeric_value_at(index, field))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn decision_price_on_or_before(&self, date: NaiveDate) -> Option<f64> {
|
||||
@@ -656,7 +759,12 @@ impl SymbolPriceSeries {
|
||||
return None;
|
||||
}
|
||||
let start = end - lookback;
|
||||
Some(self.volumes[start..end].to_vec())
|
||||
Some(
|
||||
self.volumes[start..end]
|
||||
.iter()
|
||||
.map(|value| *value as f64)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn end_index(&self, date: NaiveDate) -> Option<usize> {
|
||||
@@ -667,9 +775,9 @@ impl SymbolPriceSeries {
|
||||
}
|
||||
}
|
||||
|
||||
fn values_for(&self, field: PriceField) -> &[f64] {
|
||||
fn price_values_for(&self, field: PriceField) -> &[f64] {
|
||||
match field {
|
||||
PriceField::DayOpen => &self.opens,
|
||||
PriceField::DayOpen => &self.day_opens,
|
||||
PriceField::Open => &self.opens,
|
||||
PriceField::Close => &self.closes,
|
||||
PriceField::Last => &self.last_prices,
|
||||
@@ -681,15 +789,7 @@ impl SymbolPriceSeries {
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
self.values_for(field).get(end - 1).copied()
|
||||
}
|
||||
|
||||
fn snapshot_before(&self, date: NaiveDate) -> Option<&DailyMarketSnapshot> {
|
||||
let end = self.previous_completed_end_index(date)?;
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
self.snapshots.get(end - 1)
|
||||
self.price_values_for(field).get(end - 1).copied()
|
||||
}
|
||||
|
||||
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
||||
@@ -700,6 +800,54 @@ impl SymbolPriceSeries {
|
||||
PriceField::Last => &self.last_prefix,
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot_at(&self, index: usize) -> DailyMarketSnapshot {
|
||||
DailyMarketSnapshot {
|
||||
date: self.dates[index],
|
||||
symbol: self.symbol.clone(),
|
||||
timestamp: self.timestamps[index].clone(),
|
||||
day_open: self.day_opens[index],
|
||||
open: self.opens[index],
|
||||
high: self.highs[index],
|
||||
low: self.lows[index],
|
||||
close: self.closes[index],
|
||||
last_price: self.last_prices[index],
|
||||
bid1: self.bid1s[index],
|
||||
ask1: self.ask1s[index],
|
||||
prev_close: self.prev_closes[index],
|
||||
volume: self.volumes[index],
|
||||
tick_volume: self.tick_volumes[index],
|
||||
bid1_volume: self.bid1_volumes[index],
|
||||
ask1_volume: self.ask1_volumes[index],
|
||||
trading_phase: self.trading_phases[index].clone(),
|
||||
paused: self.paused[index],
|
||||
upper_limit: self.upper_limits[index],
|
||||
lower_limit: self.lower_limits[index],
|
||||
price_tick: self.price_ticks[index],
|
||||
}
|
||||
}
|
||||
|
||||
fn numeric_value_at(&self, index: usize, field: &str) -> Option<f64> {
|
||||
match normalize_field(field).as_str() {
|
||||
"day_open" | "dayopen" => Some(self.day_opens[index]),
|
||||
"open" => Some(self.opens[index]),
|
||||
"high" => Some(self.highs[index]),
|
||||
"low" => Some(self.lows[index]),
|
||||
"close" | "price" => Some(self.closes[index]),
|
||||
"last" | "last_price" => Some(self.last_prices[index]),
|
||||
"prev_close" | "pre_close" => Some(self.prev_closes[index]),
|
||||
"volume" => Some(self.volumes[index] as f64),
|
||||
"tick_volume" => Some(self.tick_volumes[index] as f64),
|
||||
"bid1" => Some(self.bid1s[index]),
|
||||
"ask1" => Some(self.ask1s[index]),
|
||||
"bid1_volume" => Some(self.bid1_volumes[index] as f64),
|
||||
"ask1_volume" => Some(self.ask1_volumes[index] as f64),
|
||||
"upper_limit" => Some(self.upper_limits[index]),
|
||||
"lower_limit" => Some(self.lower_limits[index]),
|
||||
"price_tick" => Some(self.price_ticks[index]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -835,21 +983,18 @@ impl BenchmarkPriceSeries {
|
||||
pub struct DataSet {
|
||||
instruments: HashMap<String, Instrument>,
|
||||
calendar: TradingCalendar,
|
||||
market_by_date: BTreeMap<NaiveDate, Vec<DailyMarketSnapshot>>,
|
||||
market_index: HashMap<(NaiveDate, String), DailyMarketSnapshot>,
|
||||
factor_by_date: BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
|
||||
factor_index: HashMap<(NaiveDate, String), DailyFactorSnapshot>,
|
||||
market_by_date: BTreeMap<NaiveDate, Vec<Arc<DailyMarketSnapshot>>>,
|
||||
factor_by_date: BTreeMap<NaiveDate, Vec<Arc<DailyFactorSnapshot>>>,
|
||||
factor_text_by_date: BTreeMap<NaiveDate, Vec<FactorTextValue>>,
|
||||
factor_text_index: HashMap<(NaiveDate, String, String), FactorTextValue>,
|
||||
candidate_by_date: BTreeMap<NaiveDate, Vec<CandidateEligibility>>,
|
||||
candidate_index: HashMap<(NaiveDate, String), CandidateEligibility>,
|
||||
candidate_by_date: BTreeMap<NaiveDate, Vec<Arc<CandidateEligibility>>>,
|
||||
corporate_actions_by_date: BTreeMap<NaiveDate, Vec<CorporateAction>>,
|
||||
execution_quotes_by_date: HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>,
|
||||
order_book_depth_index: HashMap<(NaiveDate, String), Vec<IntradayOrderBookDepthLevel>>,
|
||||
benchmark_by_date: BTreeMap<NaiveDate, BenchmarkSnapshot>,
|
||||
market_series_by_symbol: HashMap<String, SymbolPriceSeries>,
|
||||
market_series_by_symbol: Arc<RwLock<HashMap<String, Arc<SymbolPriceSeries>>>>,
|
||||
benchmark_series_cache: BenchmarkPriceSeries,
|
||||
eligible_universe_by_date: BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>>,
|
||||
eligible_universe_by_date: Arc<OnceLock<BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>>>>,
|
||||
benchmark_code: String,
|
||||
futures_params_by_symbol: HashMap<String, Vec<FuturesTradingParameter>>,
|
||||
}
|
||||
@@ -1087,24 +1232,23 @@ impl DataSet {
|
||||
) -> Result<Self, DataSetError> {
|
||||
let benchmark_code = collect_benchmark_code(&benchmarks)?;
|
||||
let calendar = TradingCalendar::new(benchmarks.iter().map(|item| item.date).collect());
|
||||
let factors = normalize_factor_snapshots(factors);
|
||||
let factors = normalize_factor_snapshots(factors)
|
||||
.into_iter()
|
||||
.map(Arc::new)
|
||||
.collect::<Vec<_>>();
|
||||
let candidates = candidates.into_iter().map(Arc::new).collect::<Vec<_>>();
|
||||
|
||||
let instruments = instruments
|
||||
.into_iter()
|
||||
.map(|instrument| (instrument.symbol.clone(), instrument))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let market_by_date = group_by_date(market.clone(), |item| item.date);
|
||||
let market_index = market
|
||||
.into_iter()
|
||||
.map(|item| ((item.date, item.symbol.clone()), item))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let market = market.into_iter().map(Arc::new).collect::<Vec<_>>();
|
||||
let mut market_by_date = group_arc_by_date(&market, |item| item.date);
|
||||
sort_arc_groups_by_symbol(&mut market_by_date, |item| item.symbol.as_str());
|
||||
|
||||
let factor_by_date = group_by_date(factors.clone(), |item| item.date);
|
||||
let factor_index = factors
|
||||
.into_iter()
|
||||
.map(|item| ((item.date, item.symbol.clone()), item))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut factor_by_date = group_arc_by_date(&factors, |item| item.date);
|
||||
sort_arc_groups_by_symbol(&mut factor_by_date, |item| item.symbol.as_str());
|
||||
let factor_texts = factor_texts
|
||||
.into_iter()
|
||||
.filter_map(|mut item| {
|
||||
@@ -1122,11 +1266,8 @@ impl DataSet {
|
||||
.map(|item| ((item.date, item.symbol.clone(), item.field.clone()), item))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let candidate_by_date = group_by_date(candidates.clone(), |item| item.date);
|
||||
let candidate_index = candidates
|
||||
.into_iter()
|
||||
.map(|item| ((item.date, item.symbol.clone()), item))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut candidate_by_date = group_arc_by_date(&candidates, |item| item.date);
|
||||
sort_arc_groups_by_symbol(&mut candidate_by_date, |item| item.symbol.as_str());
|
||||
let corporate_actions_by_date = group_by_date(corporate_actions, |item| item.date);
|
||||
let execution_quotes_by_date = build_execution_quote_index(execution_quotes);
|
||||
let order_book_depth_index = build_order_book_depth_index(order_book_depth);
|
||||
@@ -1135,35 +1276,25 @@ impl DataSet {
|
||||
.into_iter()
|
||||
.map(|item| (item.date, item))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let market_series_by_symbol = build_market_series(&market_by_date);
|
||||
let benchmark_series_cache =
|
||||
BenchmarkPriceSeries::new(&benchmark_by_date.values().cloned().collect::<Vec<_>>());
|
||||
let eligible_universe_by_date = build_eligible_universe(
|
||||
&factor_by_date,
|
||||
&candidate_index,
|
||||
&market_index,
|
||||
&instruments,
|
||||
);
|
||||
let futures_params_by_symbol = build_futures_params_index(futures_params);
|
||||
|
||||
Ok(Self {
|
||||
instruments,
|
||||
calendar,
|
||||
market_by_date,
|
||||
market_index,
|
||||
factor_by_date,
|
||||
factor_index,
|
||||
factor_text_by_date,
|
||||
factor_text_index,
|
||||
candidate_by_date,
|
||||
candidate_index,
|
||||
corporate_actions_by_date,
|
||||
execution_quotes_by_date,
|
||||
order_book_depth_index,
|
||||
benchmark_by_date,
|
||||
market_series_by_symbol,
|
||||
market_series_by_symbol: Arc::new(RwLock::new(HashMap::new())),
|
||||
benchmark_series_cache,
|
||||
eligible_universe_by_date,
|
||||
eligible_universe_by_date: Arc::new(OnceLock::new()),
|
||||
benchmark_code,
|
||||
futures_params_by_symbol,
|
||||
})
|
||||
@@ -1207,15 +1338,54 @@ impl DataSet {
|
||||
}
|
||||
|
||||
pub fn market(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||
self.market_index.get(&(date, symbol.to_string()))
|
||||
self.market_by_date
|
||||
.get(&date)
|
||||
.and_then(|rows| find_arc_by_symbol(rows, symbol, |row| row.symbol.as_str()))
|
||||
}
|
||||
|
||||
fn market_series(&self, symbol: &str) -> Option<Arc<SymbolPriceSeries>> {
|
||||
if let Some(series) = self
|
||||
.market_series_by_symbol
|
||||
.read()
|
||||
.expect("market series cache lock poisoned")
|
||||
.get(symbol)
|
||||
.cloned()
|
||||
{
|
||||
return Some(series);
|
||||
}
|
||||
|
||||
let rows = self
|
||||
.market_by_date
|
||||
.values()
|
||||
.filter_map(|day_rows| find_arc_by_symbol(day_rows, symbol, |row| row.symbol.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
if rows.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let series = Arc::new(SymbolPriceSeries::new(symbol.to_string(), rows));
|
||||
let mut cache = self
|
||||
.market_series_by_symbol
|
||||
.write()
|
||||
.expect("market series cache lock poisoned");
|
||||
Some(
|
||||
cache
|
||||
.entry(symbol.to_string())
|
||||
.or_insert_with(|| Arc::clone(&series))
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn factor(&self, date: NaiveDate, symbol: &str) -> Option<&DailyFactorSnapshot> {
|
||||
self.factor_index.get(&(date, symbol.to_string()))
|
||||
self.factor_by_date
|
||||
.get(&date)
|
||||
.and_then(|rows| find_arc_by_symbol(rows, symbol, |row| row.symbol.as_str()))
|
||||
}
|
||||
|
||||
pub fn candidate(&self, date: NaiveDate, symbol: &str) -> Option<&CandidateEligibility> {
|
||||
self.candidate_index.get(&(date, symbol.to_string()))
|
||||
self.candidate_by_date
|
||||
.get(&date)
|
||||
.and_then(|rows| find_arc_by_symbol(rows, symbol, |row| row.symbol.as_str()))
|
||||
}
|
||||
|
||||
pub fn benchmark(&self, date: NaiveDate) -> Option<&BenchmarkSnapshot> {
|
||||
@@ -1255,6 +1425,14 @@ impl DataSet {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn execution_quote_count(&self) -> usize {
|
||||
self.execution_quotes_by_date
|
||||
.values()
|
||||
.flat_map(|rows_by_symbol| rows_by_symbol.values())
|
||||
.map(Vec::len)
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn add_execution_quotes(&mut self, quotes: Vec<IntradayExecutionQuote>) -> usize {
|
||||
let mut added = 0usize;
|
||||
let mut touched = HashSet::<(NaiveDate, String)>::new();
|
||||
@@ -1314,6 +1492,49 @@ impl DataSet {
|
||||
quotes
|
||||
}
|
||||
|
||||
pub fn snapshot_components(&self) -> DataSetSnapshotComponents {
|
||||
let mut instruments = self.instruments.values().cloned().collect::<Vec<_>>();
|
||||
instruments.sort_by(|left, right| left.symbol.cmp(&right.symbol));
|
||||
|
||||
let market = self
|
||||
.market_by_date
|
||||
.values()
|
||||
.flat_map(|rows| rows.iter().map(|row| row.as_ref().clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let factors = self
|
||||
.factor_by_date
|
||||
.values()
|
||||
.flat_map(|rows| rows.iter().map(|row| row.as_ref().clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let candidates = self
|
||||
.candidate_by_date
|
||||
.values()
|
||||
.flat_map(|rows| rows.iter().map(|row| row.as_ref().clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let benchmarks = self.benchmark_by_date.values().cloned().collect::<Vec<_>>();
|
||||
let corporate_actions = self
|
||||
.corporate_actions_by_date
|
||||
.values()
|
||||
.flat_map(|rows| rows.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
let execution_quotes = self
|
||||
.execution_quotes_by_date
|
||||
.values()
|
||||
.flat_map(|rows_by_symbol| rows_by_symbol.values())
|
||||
.flat_map(|rows| rows.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
DataSetSnapshotComponents {
|
||||
instruments,
|
||||
market,
|
||||
factors,
|
||||
candidates,
|
||||
benchmarks,
|
||||
corporate_actions,
|
||||
execution_quotes,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn benchmark_series(&self) -> Vec<BenchmarkSnapshot> {
|
||||
self.benchmark_by_date.values().cloned().collect()
|
||||
}
|
||||
@@ -1396,8 +1617,7 @@ impl DataSet {
|
||||
bar_count: usize,
|
||||
include_now: bool,
|
||||
) -> Vec<DailyMarketSnapshot> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.map(|series| series.trailing_snapshots(date, bar_count, include_now))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -1920,6 +2140,7 @@ impl DataSet {
|
||||
.range(start..=end)
|
||||
.flat_map(|(_, rows)| rows.iter())
|
||||
.filter(|row| row.symbol == symbol)
|
||||
.map(Arc::as_ref)
|
||||
.map(daily_market_price_bar)
|
||||
.collect(),
|
||||
Some("1m") | Some("tick") => {
|
||||
@@ -1953,21 +2174,24 @@ impl DataSet {
|
||||
symbol: &str,
|
||||
field: PriceField,
|
||||
) -> Option<f64> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.and_then(|series| series.price_on_or_before(date, field))
|
||||
}
|
||||
|
||||
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.snapshot_before(date))
|
||||
let series = self.market_series(symbol)?;
|
||||
let end = series.previous_completed_end_index(date)?;
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
let previous_date = *series.dates.get(end - 1)?;
|
||||
self.market(previous_date, symbol)
|
||||
}
|
||||
|
||||
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
||||
self.factor_by_date
|
||||
.get(&date)
|
||||
.map(|rows| rows.iter().collect())
|
||||
.map(|rows| rows.iter().map(Arc::as_ref).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -1981,14 +2205,14 @@ impl DataSet {
|
||||
pub fn market_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyMarketSnapshot> {
|
||||
self.market_by_date
|
||||
.get(&date)
|
||||
.map(|rows| rows.iter().collect())
|
||||
.map(|rows| rows.iter().map(Arc::as_ref).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn candidate_snapshots_on(&self, date: NaiveDate) -> Vec<&CandidateEligibility> {
|
||||
self.candidate_by_date
|
||||
.get(&date)
|
||||
.map(|rows| rows.iter().collect())
|
||||
.map(|rows| rows.iter().map(Arc::as_ref).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -2000,12 +2224,20 @@ impl DataSet {
|
||||
Ok(DailySnapshotBundle {
|
||||
date,
|
||||
benchmark,
|
||||
market: self.market_by_date.get(&date).cloned().unwrap_or_default(),
|
||||
factors: self.factor_by_date.get(&date).cloned().unwrap_or_default(),
|
||||
market: self
|
||||
.market_by_date
|
||||
.get(&date)
|
||||
.map(|rows| rows.iter().map(|row| row.as_ref().clone()).collect())
|
||||
.unwrap_or_default(),
|
||||
factors: self
|
||||
.factor_by_date
|
||||
.get(&date)
|
||||
.map(|rows| rows.iter().map(|row| row.as_ref().clone()).collect())
|
||||
.unwrap_or_default(),
|
||||
candidates: self
|
||||
.candidate_by_date
|
||||
.get(&date)
|
||||
.cloned()
|
||||
.map(|rows| rows.iter().map(|row| row.as_ref().clone()).collect())
|
||||
.unwrap_or_default(),
|
||||
corporate_actions: self
|
||||
.corporate_actions_by_date
|
||||
@@ -2020,8 +2252,7 @@ impl DataSet {
|
||||
}
|
||||
|
||||
pub fn market_closes_up_to(&self, date: NaiveDate, symbol: &str, lookback: usize) -> Vec<f64> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::Close))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -2034,10 +2265,9 @@ impl DataSet {
|
||||
field: &str,
|
||||
include_now: bool,
|
||||
) -> Vec<f64> {
|
||||
self.history_daily_snapshots(date, symbol, bar_count, include_now)
|
||||
.into_iter()
|
||||
.filter_map(|row| daily_market_numeric_value(&row, field))
|
||||
.collect()
|
||||
self.market_series(symbol)
|
||||
.map(|series| series.trailing_numeric_values(date, bar_count, field, include_now))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn history_intraday_values(
|
||||
@@ -2076,18 +2306,12 @@ impl DataSet {
|
||||
let start = days.len().saturating_sub(count);
|
||||
days[start..]
|
||||
.iter()
|
||||
.map(|day| {
|
||||
evaluator(
|
||||
self.candidate_index.get(&(*day, symbol.to_string())),
|
||||
self.market_index.get(&(*day, symbol.to_string())),
|
||||
)
|
||||
})
|
||||
.map(|day| evaluator(self.candidate(*day, symbol), self.market(*day, symbol)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn market_decision_close(&self, date: NaiveDate, symbol: &str) -> Option<f64> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.and_then(|series| series.decision_price_on_or_before(date))
|
||||
}
|
||||
|
||||
@@ -2097,8 +2321,7 @@ impl DataSet {
|
||||
symbol: &str,
|
||||
lookback: usize,
|
||||
) -> Option<f64> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.and_then(|series| series.decision_close_moving_average(date, lookback))
|
||||
}
|
||||
|
||||
@@ -2108,8 +2331,7 @@ impl DataSet {
|
||||
symbol: &str,
|
||||
lookback: usize,
|
||||
) -> Option<f64> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.and_then(|series| series.decision_volume_moving_average(date, lookback))
|
||||
}
|
||||
|
||||
@@ -2196,12 +2418,10 @@ impl DataSet {
|
||||
let field = normalize_field(field);
|
||||
match field.as_str() {
|
||||
"close" | "prev_close" | "stock_close" | "price" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.and_then(|series| series.decision_close_moving_average(date, lookback)),
|
||||
"volume" | "stock_volume" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.and_then(|series| series.decision_volume_moving_average(date, lookback)),
|
||||
"day_open" | "dayopen" => {
|
||||
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
|
||||
@@ -2227,8 +2447,7 @@ impl DataSet {
|
||||
self.market_moving_average(date, symbol, lookback, PriceField::Close)
|
||||
}
|
||||
"volume" | "stock_volume" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.and_then(|series| series.current_volume_moving_average(date, lookback))
|
||||
.or_else(|| self.factor_moving_average(date, symbol, "daily_volume", lookback)),
|
||||
"day_open" | "dayopen" => {
|
||||
@@ -2255,28 +2474,23 @@ impl DataSet {
|
||||
let field = normalize_field(field);
|
||||
match field.as_str() {
|
||||
"close" | "prev_close" | "stock_close" | "price" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.and_then(|series| series.decision_prev_close_values(date, lookback))
|
||||
.unwrap_or_default(),
|
||||
"volume" | "stock_volume" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.and_then(|series| series.decision_volume_values(date, lookback))
|
||||
.unwrap_or_default(),
|
||||
"day_open" | "dayopen" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::DayOpen))
|
||||
.unwrap_or_default(),
|
||||
"open" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::Open))
|
||||
.unwrap_or_default(),
|
||||
"last" | "last_price" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.market_series(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::Last))
|
||||
.unwrap_or_default(),
|
||||
other => self.factor_numeric_values(date, symbol, other, lookback),
|
||||
@@ -2308,8 +2522,7 @@ impl DataSet {
|
||||
lookback: usize,
|
||||
field: PriceField,
|
||||
) -> Option<f64> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
self.market_series(symbol)
|
||||
.and_then(|series| series.moving_average(date, lookback, field))
|
||||
}
|
||||
|
||||
@@ -2378,6 +2591,14 @@ impl DataSet {
|
||||
|
||||
pub fn eligible_universe_on(&self, date: NaiveDate) -> &[EligibleUniverseSnapshot] {
|
||||
self.eligible_universe_by_date
|
||||
.get_or_init(|| {
|
||||
build_eligible_universe(
|
||||
&self.factor_by_date,
|
||||
&self.candidate_by_date,
|
||||
&self.market_by_date,
|
||||
&self.instruments,
|
||||
)
|
||||
})
|
||||
.get(&date)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[])
|
||||
@@ -2761,28 +2982,6 @@ fn factor_numeric_value(snapshot: &DailyFactorSnapshot, field: &str) -> Option<f
|
||||
}
|
||||
}
|
||||
|
||||
fn daily_market_numeric_value(snapshot: &DailyMarketSnapshot, field: &str) -> Option<f64> {
|
||||
match normalize_field(field).as_str() {
|
||||
"day_open" | "dayopen" => Some(snapshot.day_open),
|
||||
"open" => Some(snapshot.open),
|
||||
"high" => Some(snapshot.high),
|
||||
"low" => Some(snapshot.low),
|
||||
"close" | "price" => Some(snapshot.close),
|
||||
"last" | "last_price" => Some(snapshot.last_price),
|
||||
"prev_close" | "pre_close" => Some(snapshot.prev_close),
|
||||
"volume" => Some(snapshot.volume as f64),
|
||||
"tick_volume" => Some(snapshot.tick_volume as f64),
|
||||
"bid1" => Some(snapshot.bid1),
|
||||
"ask1" => Some(snapshot.ask1),
|
||||
"bid1_volume" => Some(snapshot.bid1_volume as f64),
|
||||
"ask1_volume" => Some(snapshot.ask1_volume as f64),
|
||||
"upper_limit" => Some(snapshot.upper_limit),
|
||||
"lower_limit" => Some(snapshot.lower_limit),
|
||||
"price_tick" => Some(snapshot.price_tick),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn intraday_quote_numeric_value(snapshot: &IntradayExecutionQuote, field: &str) -> Option<f64> {
|
||||
match normalize_field(field).as_str() {
|
||||
"last" | "last_price" | "close" | "price" => Some(snapshot.last_price),
|
||||
@@ -2918,6 +3117,13 @@ fn read_candidates(path: &Path) -> Result<Vec<CandidateEligibility>, DataSetErro
|
||||
allow_sell: row.parse_bool(6)?,
|
||||
is_kcb: row.parse_optional_bool(7).unwrap_or(false),
|
||||
is_one_yuan: row.parse_optional_bool(8).unwrap_or(false),
|
||||
risk_level_code: row
|
||||
.fields
|
||||
.get(9)
|
||||
.map(String::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned),
|
||||
});
|
||||
}
|
||||
Ok(snapshots)
|
||||
@@ -3275,6 +3481,38 @@ where
|
||||
grouped
|
||||
}
|
||||
|
||||
fn group_arc_by_date<T, F>(rows: &[Arc<T>], mut date_of: F) -> BTreeMap<NaiveDate, Vec<Arc<T>>>
|
||||
where
|
||||
F: FnMut(&T) -> NaiveDate,
|
||||
{
|
||||
let mut grouped = BTreeMap::<NaiveDate, Vec<Arc<T>>>::new();
|
||||
for row in rows {
|
||||
grouped
|
||||
.entry(date_of(row.as_ref()))
|
||||
.or_default()
|
||||
.push(Arc::clone(row));
|
||||
}
|
||||
grouped
|
||||
}
|
||||
|
||||
fn sort_arc_groups_by_symbol<T, F>(groups: &mut BTreeMap<NaiveDate, Vec<Arc<T>>>, symbol_of: F)
|
||||
where
|
||||
F: Fn(&T) -> &str + Copy,
|
||||
{
|
||||
for rows in groups.values_mut() {
|
||||
rows.sort_by(|left, right| symbol_of(left.as_ref()).cmp(symbol_of(right.as_ref())));
|
||||
}
|
||||
}
|
||||
|
||||
fn find_arc_by_symbol<'a, T, F>(rows: &'a [Arc<T>], symbol: &str, symbol_of: F) -> Option<&'a T>
|
||||
where
|
||||
F: Fn(&T) -> &str,
|
||||
{
|
||||
rows.binary_search_by(|row| symbol_of(row.as_ref()).cmp(symbol))
|
||||
.ok()
|
||||
.map(|index| rows[index].as_ref())
|
||||
}
|
||||
|
||||
fn collect_benchmark_code(benchmarks: &[BenchmarkSnapshot]) -> Result<String, DataSetError> {
|
||||
let mut codes = benchmarks
|
||||
.iter()
|
||||
@@ -3343,25 +3581,6 @@ mod optional_date_format {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_market_series(
|
||||
market_by_date: &BTreeMap<NaiveDate, Vec<DailyMarketSnapshot>>,
|
||||
) -> HashMap<String, SymbolPriceSeries> {
|
||||
let mut grouped = HashMap::<String, Vec<DailyMarketSnapshot>>::new();
|
||||
for rows in market_by_date.values() {
|
||||
for row in rows {
|
||||
grouped
|
||||
.entry(row.symbol.clone())
|
||||
.or_default()
|
||||
.push(row.clone());
|
||||
}
|
||||
}
|
||||
|
||||
grouped
|
||||
.into_iter()
|
||||
.map(|(symbol, rows)| (symbol, SymbolPriceSeries::new(&rows)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn build_futures_params_index(
|
||||
rows: Vec<FuturesTradingParameter>,
|
||||
) -> HashMap<String, Vec<FuturesTradingParameter>> {
|
||||
@@ -3420,9 +3639,9 @@ fn build_order_book_depth_index(
|
||||
}
|
||||
|
||||
fn build_eligible_universe(
|
||||
factor_by_date: &BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
|
||||
candidate_index: &HashMap<(NaiveDate, String), CandidateEligibility>,
|
||||
market_index: &HashMap<(NaiveDate, String), DailyMarketSnapshot>,
|
||||
factor_by_date: &BTreeMap<NaiveDate, Vec<Arc<DailyFactorSnapshot>>>,
|
||||
candidate_by_date: &BTreeMap<NaiveDate, Vec<Arc<CandidateEligibility>>>,
|
||||
market_by_date: &BTreeMap<NaiveDate, Vec<Arc<DailyMarketSnapshot>>>,
|
||||
instruments: &HashMap<String, Instrument>,
|
||||
) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> {
|
||||
let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new();
|
||||
@@ -3433,11 +3652,14 @@ fn build_eligible_universe(
|
||||
if factor.market_cap_bn <= 0.0 || !factor.market_cap_bn.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let key = (*date, factor.symbol.clone());
|
||||
let Some(candidate) = candidate_index.get(&key) else {
|
||||
let Some(candidate) = candidate_by_date.get(date).and_then(|rows| {
|
||||
find_arc_by_symbol(rows, &factor.symbol, |row| row.symbol.as_str())
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let Some(market) = market_index.get(&key) else {
|
||||
let Some(market) = market_by_date.get(date).and_then(|rows| {
|
||||
find_arc_by_symbol(rows, &factor.symbol, |row| row.symbol.as_str())
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if ChinaAShareRiskControl::selection_rejection_reason(
|
||||
@@ -3581,11 +3803,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn decision_volume_average_uses_previous_completed_days_only() {
|
||||
let series = SymbolPriceSeries::new(&[
|
||||
let series = SymbolPriceSeries::new(
|
||||
"000001.SZ".to_string(),
|
||||
&[
|
||||
market_row("2025-01-02", 10.0, 100),
|
||||
market_row("2025-01-03", 11.0, 200),
|
||||
market_row("2025-01-06", 12.0, 10_000),
|
||||
]);
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
series.decision_close_moving_average(
|
||||
@@ -3615,11 +3840,14 @@ mod tests {
|
||||
let mut current = market_row("2025-01-06", 12.0, 10_000);
|
||||
current.close = 9_999.0;
|
||||
current.last_price = 9_999.0;
|
||||
let series = SymbolPriceSeries::new(&[
|
||||
let series = SymbolPriceSeries::new(
|
||||
"000001.SZ".to_string(),
|
||||
&[
|
||||
market_row("2025-01-02", 10.0, 100),
|
||||
market_row("2025-01-03", 11.0, 200),
|
||||
current,
|
||||
]);
|
||||
],
|
||||
);
|
||||
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
@@ -3636,12 +3864,15 @@ mod tests {
|
||||
fn decision_volume_average_includes_paused_zero_volume_days() {
|
||||
let mut paused = market_row("2025-01-03", 11.0, 0);
|
||||
paused.paused = true;
|
||||
let series = SymbolPriceSeries::new(&[
|
||||
let series = SymbolPriceSeries::new(
|
||||
"000001.SZ".to_string(),
|
||||
&[
|
||||
market_row("2025-01-02", 10.0, 100),
|
||||
paused,
|
||||
market_row("2025-01-06", 12.0, 300),
|
||||
market_row("2025-01-07", 13.0, 10_000),
|
||||
]);
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
series.decision_volume_moving_average(
|
||||
@@ -3715,6 +3946,7 @@ mod tests {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
};
|
||||
let data = DataSet::from_components(
|
||||
vec![instrument("000001.SZ"), instrument("000002.SZ")],
|
||||
@@ -3747,6 +3979,49 @@ mod tests {
|
||||
assert!((rows[1].market_cap_bn - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_market_cap_keeps_pre_adjusted_factor() {
|
||||
let date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
|
||||
let market = DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2025-01-06 10:18:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 20.0,
|
||||
low: 10.0,
|
||||
close: 20.0,
|
||||
last_price: 10.0,
|
||||
bid1: 10.0,
|
||||
ask1: 10.0,
|
||||
prev_close: 10.0,
|
||||
volume: 100_000,
|
||||
tick_volume: 1_000,
|
||||
bid1_volume: 1_000,
|
||||
ask1_volume: 1_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 11.0,
|
||||
lower_limit: 9.0,
|
||||
price_tick: 0.01,
|
||||
};
|
||||
let mut extra_factors = BTreeMap::new();
|
||||
extra_factors.insert("__market_cap_decision_adjusted".to_string(), 1.0);
|
||||
let factor = DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 12.0,
|
||||
free_float_cap_bn: 4.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: Some(1.0),
|
||||
effective_turnover_ratio: Some(1.0),
|
||||
extra_factors,
|
||||
};
|
||||
|
||||
assert!((decision_market_cap_bn(&factor, &market) - 12.0).abs() < 1e-9);
|
||||
assert!((decision_free_float_cap_bn(&factor, &market) - 4.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn benchmark_decision_close_windows_exclude_current_close() {
|
||||
let series = BenchmarkPriceSeries::new(&[
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use chrono::{Datelike, NaiveDate, NaiveTime};
|
||||
use chrono::{Datelike, Duration, NaiveDate, NaiveTime};
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -561,7 +561,12 @@ where
|
||||
return false;
|
||||
}
|
||||
if start_time.is_some() && end_time.is_none() {
|
||||
return true;
|
||||
return !has_execution_quote_near_start_time(
|
||||
&self.data,
|
||||
execution_date,
|
||||
symbol,
|
||||
start_time.expect("checked start_time"),
|
||||
);
|
||||
}
|
||||
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
|
||||
});
|
||||
@@ -622,6 +627,35 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_execution_quotes_for_symbols_at_times(
|
||||
&mut self,
|
||||
execution_date: NaiveDate,
|
||||
symbols: &BTreeSet<String>,
|
||||
quote_times: &[NaiveTime],
|
||||
) -> Result<(), BacktestError> {
|
||||
if self.execution_quote_loader.is_none() || quote_times.is_empty() || symbols.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let base_symbols = symbols
|
||||
.iter()
|
||||
.filter(|symbol| !symbol.trim().is_empty())
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
if base_symbols.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for quote_time in quote_times {
|
||||
let mut symbols = base_symbols.clone();
|
||||
self.load_missing_execution_quotes(
|
||||
execution_date,
|
||||
Some(*quote_time),
|
||||
None,
|
||||
&mut symbols,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_strategy_directives(
|
||||
&mut self,
|
||||
execution_date: NaiveDate,
|
||||
@@ -1951,6 +1985,33 @@ where
|
||||
)?;
|
||||
let on_day_open_orders = self.open_order_views();
|
||||
let decision_quote_times = self.strategy.decision_quote_times();
|
||||
if !decision_quote_times.is_empty() {
|
||||
let decision_quote_symbols =
|
||||
self.strategy.decision_quote_symbols(&StrategyContext {
|
||||
execution_date,
|
||||
decision_date,
|
||||
decision_index,
|
||||
data: &self.data,
|
||||
portfolio: &portfolio,
|
||||
futures_account: self.futures_account.as_ref(),
|
||||
open_orders: &on_day_open_orders,
|
||||
dynamic_universe: self.dynamic_universe.as_ref(),
|
||||
subscriptions: &self.subscriptions,
|
||||
process_events: &process_events,
|
||||
active_process_event: None,
|
||||
active_datetime: stage_datetime(
|
||||
execution_date,
|
||||
default_stage_time(ScheduleStage::OnDay),
|
||||
),
|
||||
order_events: result.order_events.as_slice(),
|
||||
fills: result.fills.as_slice(),
|
||||
})?;
|
||||
self.ensure_execution_quotes_for_symbols_at_times(
|
||||
execution_date,
|
||||
&decision_quote_symbols,
|
||||
&decision_quote_times,
|
||||
)?;
|
||||
}
|
||||
self.ensure_execution_quotes_for_portfolio_times(
|
||||
execution_date,
|
||||
&portfolio,
|
||||
@@ -3292,12 +3353,31 @@ fn has_execution_quote_in_window(
|
||||
})
|
||||
}
|
||||
|
||||
fn has_execution_quote_near_start_time(
|
||||
data: &DataSet,
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
start_time: NaiveTime,
|
||||
) -> bool {
|
||||
let cursor = date.and_time(start_time);
|
||||
let Some(latest) = data
|
||||
.execution_quotes_on(date, symbol)
|
||||
.iter()
|
||||
.filter(|quote| quote.timestamp <= cursor)
|
||||
.max_by_key(|quote| quote.timestamp)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
cursor.signed_duration_since(latest.timestamp) <= Duration::seconds(90)
|
||||
}
|
||||
|
||||
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
|
||||
decision.order_intents.iter().any(|intent| {
|
||||
matches!(
|
||||
intent,
|
||||
OrderIntent::AlgoValue { .. }
|
||||
| OrderIntent::AlgoPercent { .. }
|
||||
| OrderIntent::TimedTargetValue { .. }
|
||||
| OrderIntent::TargetPortfolioSmart {
|
||||
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
|
||||
..
|
||||
@@ -3330,6 +3410,7 @@ fn execution_quote_symbols_for_decision(
|
||||
| OrderIntent::TargetShares { symbol, .. }
|
||||
| OrderIntent::LimitTargetShares { symbol, .. }
|
||||
| OrderIntent::TargetValue { symbol, .. }
|
||||
| OrderIntent::TimedTargetValue { symbol, .. }
|
||||
| OrderIntent::LimitTargetValue { symbol, .. }
|
||||
| OrderIntent::Value { symbol, .. }
|
||||
| OrderIntent::LimitValue { symbol, .. }
|
||||
@@ -3382,6 +3463,12 @@ fn algo_execution_quote_windows_for_decision(
|
||||
start_time,
|
||||
end_time,
|
||||
..
|
||||
}
|
||||
| OrderIntent::TimedTargetValue {
|
||||
symbol,
|
||||
start_time,
|
||||
end_time,
|
||||
..
|
||||
} => {
|
||||
if start_time.is_some() || end_time.is_some() {
|
||||
groups
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -140,6 +140,8 @@ pub struct StrategyEngineConfig {
|
||||
#[serde(default)]
|
||||
pub dividend_reinvestment: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub weak_market_shrink_overweight_threshold: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
|
||||
#[serde(default)]
|
||||
pub skip_windows: Vec<SkipWindowConfig>,
|
||||
@@ -300,6 +302,8 @@ pub struct StrategyExpressionTradingConfig {
|
||||
#[serde(default)]
|
||||
pub retry_empty_rebalance: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub weak_market_shrink_overweight_threshold: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub delayed_limit_open_exit: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub delayed_limit_open_exit_time: Option<String>,
|
||||
@@ -566,6 +570,20 @@ fn sorted_unique_positive(mut values: Vec<usize>) -> Vec<usize> {
|
||||
values
|
||||
}
|
||||
|
||||
fn stock_close_ma_expr(days: usize) -> String {
|
||||
match days {
|
||||
5 | 10 | 20 | 30 => format!("stock_ma{days}"),
|
||||
_ => format!("rolling_mean(\"close\", {days})"),
|
||||
}
|
||||
}
|
||||
|
||||
fn stock_volume_ma_expr(days: usize) -> String {
|
||||
match days {
|
||||
5 | 10 | 20 | 60 | 100 => format!("stock_volume_ma{days}"),
|
||||
_ => format!("rolling_mean(\"volume\", {days})"),
|
||||
}
|
||||
}
|
||||
|
||||
fn infer_expression_windows(
|
||||
cfg: &mut PlatformExprStrategyConfig,
|
||||
benchmark_short_explicit: bool,
|
||||
@@ -647,6 +665,12 @@ pub fn platform_expr_config_from_spec(
|
||||
if let Some(refresh_rate) = engine.refresh_rate.filter(|value| *value > 0) {
|
||||
cfg.refresh_rate = refresh_rate;
|
||||
}
|
||||
if let Some(threshold) = engine
|
||||
.weak_market_shrink_overweight_threshold
|
||||
.filter(|value| value.is_finite() && *value > 0.0)
|
||||
{
|
||||
cfg.weak_market_shrink_overweight_threshold = Some(threshold);
|
||||
}
|
||||
if let Some(schedule) = engine
|
||||
.rebalance_schedule
|
||||
.as_ref()
|
||||
@@ -927,6 +951,12 @@ pub fn platform_expr_config_from_spec(
|
||||
if let Some(enabled) = trading.retry_empty_rebalance {
|
||||
cfg.retry_empty_rebalance = enabled;
|
||||
}
|
||||
if let Some(threshold) = trading
|
||||
.weak_market_shrink_overweight_threshold
|
||||
.filter(|value| value.is_finite() && *value > 0.0)
|
||||
{
|
||||
cfg.weak_market_shrink_overweight_threshold = Some(threshold);
|
||||
}
|
||||
if let Some(enabled) = trading.release_slot_on_exit_signal {
|
||||
cfg.release_slot_on_exit_signal = enabled;
|
||||
}
|
||||
@@ -1001,10 +1031,36 @@ pub fn platform_expr_config_from_spec(
|
||||
}
|
||||
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
||||
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
||||
cfg.stock_filter_expr = format!(
|
||||
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid * {} > stock_ma_long",
|
||||
ratio, ratio
|
||||
);
|
||||
let short_days = stock_ma_filter
|
||||
.short_days
|
||||
.unwrap_or(cfg.stock_short_ma_days);
|
||||
let mid_days = stock_ma_filter.mid_days.unwrap_or(cfg.stock_mid_ma_days);
|
||||
let long_days = stock_ma_filter.long_days.unwrap_or(cfg.stock_long_ma_days);
|
||||
let mut conditions = vec![
|
||||
format!(
|
||||
"{} > {} * {}",
|
||||
stock_close_ma_expr(short_days),
|
||||
stock_close_ma_expr(mid_days),
|
||||
ratio
|
||||
),
|
||||
format!(
|
||||
"{} > {} * {}",
|
||||
stock_close_ma_expr(mid_days),
|
||||
stock_close_ma_expr(long_days),
|
||||
ratio
|
||||
),
|
||||
];
|
||||
if let (Some(volume_short_days), Some(volume_long_days)) = (
|
||||
stock_ma_filter.volume_short_days.filter(|value| *value > 0),
|
||||
stock_ma_filter.volume_long_days.filter(|value| *value > 0),
|
||||
) {
|
||||
conditions.push(format!(
|
||||
"{} < {}",
|
||||
stock_volume_ma_expr(volume_short_days),
|
||||
stock_volume_ma_expr(volume_long_days)
|
||||
));
|
||||
}
|
||||
cfg.stock_filter_expr = conditions.join(" && ");
|
||||
}
|
||||
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
||||
let ratio = index_throttle.rsi_rate.unwrap_or(1.0001);
|
||||
@@ -1529,6 +1585,7 @@ mod tests {
|
||||
"rotationEnabled": false,
|
||||
"dailyTopUp": true,
|
||||
"retryEmptyRebalance": true,
|
||||
"weakMarketShrinkOverweightThreshold": 1.1,
|
||||
"stage": "open_auction",
|
||||
"actions": [
|
||||
{
|
||||
@@ -1552,6 +1609,7 @@ mod tests {
|
||||
assert!(!cfg.rotation_enabled);
|
||||
assert!(cfg.daily_top_up_enabled);
|
||||
assert!(cfg.retry_empty_rebalance);
|
||||
assert_eq!(cfg.weak_market_shrink_overweight_threshold, Some(1.1));
|
||||
assert!(!cfg.calendar_rebalance_interval);
|
||||
assert!(cfg.aiquant_transaction_cost);
|
||||
assert_eq!(cfg.explicit_actions.len(), 1);
|
||||
@@ -1561,6 +1619,19 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_config_parses_weak_market_shrink_overweight_threshold() {
|
||||
let spec = serde_json::json!({
|
||||
"engineConfig": {
|
||||
"weakMarketShrinkOverweightThreshold": 1.2
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert_eq!(cfg.weak_market_shrink_overweight_threshold, Some(1.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_execution_cost_overrides_into_platform_config() {
|
||||
let spec = serde_json::json!({
|
||||
@@ -1629,6 +1700,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_stock_ma_filter_generates_price_and_volume_expr() {
|
||||
let spec = serde_json::json!({
|
||||
"engineConfig": {
|
||||
"rankLimit": 40,
|
||||
"stockMaFilter": {
|
||||
"shortDays": 5,
|
||||
"midDays": 10,
|
||||
"longDays": 30,
|
||||
"volumeShortDays": 5,
|
||||
"volumeLongDays": 100,
|
||||
"rsiRate": 1.00001
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.stock_filter_expr,
|
||||
"stock_ma5 > stock_ma10 * 1.00001 && stock_ma10 > stock_ma30 * 1.00001 && stock_volume_ma5 < stock_volume_ma100"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
|
||||
let spec = serde_json::json!({
|
||||
|
||||
@@ -20,6 +20,7 @@ pub struct Position {
|
||||
pub average_cost: f64,
|
||||
pub last_price: f64,
|
||||
pub realized_pnl: f64,
|
||||
realized_entry_pnl: f64,
|
||||
pub trading_pnl: f64,
|
||||
pub position_pnl: f64,
|
||||
pub dividend_receivable: f64,
|
||||
@@ -44,6 +45,7 @@ impl Position {
|
||||
average_cost: 0.0,
|
||||
last_price: 0.0,
|
||||
realized_pnl: 0.0,
|
||||
realized_entry_pnl: 0.0,
|
||||
trading_pnl: 0.0,
|
||||
position_pnl: 0.0,
|
||||
dividend_receivable: 0.0,
|
||||
@@ -114,6 +116,7 @@ impl Position {
|
||||
|
||||
let mut remaining = quantity;
|
||||
let mut realized = 0.0;
|
||||
let mut realized_entry = 0.0;
|
||||
|
||||
while remaining > 0 {
|
||||
let Some(first_lot) = self.lots.first_mut() else {
|
||||
@@ -122,6 +125,7 @@ impl Position {
|
||||
|
||||
let lot_sell = remaining.min(first_lot.quantity);
|
||||
realized += (execution_price - first_lot.price) * lot_sell as f64;
|
||||
realized_entry += (execution_price - first_lot.entry_price) * lot_sell as f64;
|
||||
first_lot.quantity -= lot_sell;
|
||||
remaining -= lot_sell;
|
||||
|
||||
@@ -133,6 +137,7 @@ impl Position {
|
||||
self.quantity -= quantity;
|
||||
self.last_price = normalized_mark_price(mark_price, execution_price);
|
||||
self.realized_pnl += realized;
|
||||
self.realized_entry_pnl += realized_entry;
|
||||
self.day_trade_quantity_delta -= quantity as i32;
|
||||
self.day_sell_quantity += quantity;
|
||||
self.day_sell_value += execution_price * quantity as f64;
|
||||
@@ -157,10 +162,21 @@ impl Position {
|
||||
(self.last_price - self.average_cost) * self.quantity as f64
|
||||
}
|
||||
|
||||
pub fn unrealized_entry_pnl(&self) -> f64 {
|
||||
let Some(avg_price) = self.average_entry_price() else {
|
||||
return 0.0;
|
||||
};
|
||||
(self.last_price - avg_price) * self.quantity as f64
|
||||
}
|
||||
|
||||
pub fn pnl(&self) -> f64 {
|
||||
self.realized_pnl + self.unrealized_pnl()
|
||||
}
|
||||
|
||||
pub fn entry_pnl(&self) -> f64 {
|
||||
self.realized_entry_pnl + self.unrealized_entry_pnl()
|
||||
}
|
||||
|
||||
pub fn day_start_quantity(&self) -> u32 {
|
||||
self.day_start_quantity
|
||||
}
|
||||
@@ -765,21 +781,27 @@ impl PortfolioState {
|
||||
self.positions
|
||||
.values()
|
||||
.filter(|position| position.quantity > 0)
|
||||
.map(|position| HoldingSummary {
|
||||
.map(|position| {
|
||||
let market_value = position.market_value();
|
||||
let entry_average_cost = position
|
||||
.average_entry_price()
|
||||
.filter(|value| value.is_finite() && *value > 0.0)
|
||||
.unwrap_or(position.average_cost);
|
||||
HoldingSummary {
|
||||
date,
|
||||
symbol: position.symbol.clone(),
|
||||
quantity: position.quantity,
|
||||
average_cost: position.average_cost,
|
||||
average_cost: entry_average_cost,
|
||||
last_price: position.last_price,
|
||||
market_value: position.market_value(),
|
||||
market_value,
|
||||
value_percent: if total_equity > 0.0 {
|
||||
position.market_value() / total_equity
|
||||
market_value / total_equity
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
unrealized_pnl: position.unrealized_pnl(),
|
||||
realized_pnl: position.realized_pnl,
|
||||
pnl: position.pnl(),
|
||||
unrealized_pnl: position.unrealized_entry_pnl(),
|
||||
realized_pnl: position.realized_entry_pnl,
|
||||
pnl: position.entry_pnl(),
|
||||
trading_pnl: position.trading_pnl,
|
||||
position_pnl: position.position_pnl,
|
||||
dividend_receivable: position.dividend_receivable,
|
||||
@@ -792,6 +814,7 @@ impl PortfolioState {
|
||||
sold_value: position.sold_value(),
|
||||
transaction_cost: position.transaction_cost(),
|
||||
day_trade_quantity_delta: position.day_trade_quantity_delta(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -815,6 +838,7 @@ impl PortfolioState {
|
||||
let old_quantity = old_position.quantity;
|
||||
let last_price = old_position.last_price;
|
||||
let realized_pnl = old_position.realized_pnl;
|
||||
let realized_entry_pnl = old_position.realized_entry_pnl;
|
||||
let mut converted_lots = old_position
|
||||
.lots
|
||||
.into_iter()
|
||||
@@ -851,6 +875,7 @@ impl PortfolioState {
|
||||
successor.lots.extend(converted_lots);
|
||||
successor.quantity = successor.lots.iter().map(|lot| lot.quantity).sum();
|
||||
successor.realized_pnl += realized_pnl;
|
||||
successor.realized_entry_pnl += realized_entry_pnl;
|
||||
if converted_last_price > 0.0 {
|
||||
successor.last_price = converted_last_price;
|
||||
}
|
||||
@@ -930,6 +955,31 @@ mod tests {
|
||||
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holdings_summary_reports_entry_price_pnl_excluding_buy_commission() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
let mut portfolio = PortfolioState::new(10_000.0);
|
||||
{
|
||||
let position = portfolio.position_mut("600561.SH");
|
||||
position.buy(date, 100, 10.0);
|
||||
position.record_buy_trade_cost(100, 5.0);
|
||||
position.last_price = 10.5;
|
||||
}
|
||||
|
||||
let summary = portfolio.holdings_summary(date);
|
||||
assert_eq!(summary.len(), 1);
|
||||
assert!((summary[0].average_cost - 10.0).abs() < 1e-12);
|
||||
assert!((summary[0].unrealized_pnl - 50.0).abs() < 1e-12);
|
||||
assert!((summary[0].realized_pnl - 0.0).abs() < 1e-12);
|
||||
assert!(
|
||||
portfolio
|
||||
.position("600561.SH")
|
||||
.expect("position")
|
||||
.average_cost
|
||||
> summary[0].average_cost
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cash_dividend_can_preserve_avg_cost_for_aiquant_compatibility() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
@@ -1036,6 +1086,7 @@ mod tests {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1122,6 +1173,7 @@ mod tests {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
|
||||
@@ -111,9 +111,10 @@ impl ChinaAShareRiskControl {
|
||||
if market.paused || candidate.is_paused {
|
||||
return Some("paused");
|
||||
}
|
||||
if !candidate.allow_sell {
|
||||
return Some("sell_disabled");
|
||||
}
|
||||
// `allow_sell` is derived from the daily candidate snapshot and may
|
||||
// reflect an open/close fallback rather than the actual execution tick.
|
||||
// A sell order must be blocked by the execution price lower-limit check
|
||||
// below, while suspension and delisting are handled above.
|
||||
if market.is_at_lower_limit_price(check_price) {
|
||||
return Some("open at or below lower limit");
|
||||
}
|
||||
@@ -134,3 +135,99 @@ impl ChinaAShareRiskControl {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
|
||||
}
|
||||
|
||||
fn candidate(date: NaiveDate) -> CandidateEligibility {
|
||||
CandidateEligibility {
|
||||
date,
|
||||
symbol: "002633.SZ".to_string(),
|
||||
is_st: false,
|
||||
is_new_listing: false,
|
||||
is_paused: false,
|
||||
allow_buy: true,
|
||||
allow_sell: false,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn market(date: NaiveDate, last_price: f64, lower_limit: f64) -> DailyMarketSnapshot {
|
||||
DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: "002633.SZ".to_string(),
|
||||
timestamp: Some(format!("{date} 10:18:00")),
|
||||
day_open: last_price,
|
||||
open: last_price,
|
||||
high: last_price,
|
||||
low: last_price,
|
||||
close: last_price,
|
||||
last_price,
|
||||
bid1: last_price,
|
||||
ask1: last_price,
|
||||
prev_close: 6.25,
|
||||
volume: 1_000_000,
|
||||
tick_volume: 10_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 6.89,
|
||||
lower_limit,
|
||||
price_tick: 0.01,
|
||||
}
|
||||
}
|
||||
|
||||
fn position(prev_date: NaiveDate) -> Position {
|
||||
let mut position = Position::new("002633.SZ");
|
||||
position.buy(prev_date, 7_200, 8.48);
|
||||
position
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sell_rejection_uses_execution_price_not_stale_allow_sell() {
|
||||
let prev_date = d(2024, 4, 16);
|
||||
let date = d(2024, 4, 17);
|
||||
let candidate = candidate(date);
|
||||
let market = market(date, 6.27, 5.63);
|
||||
let position = position(prev_date);
|
||||
|
||||
let reason = ChinaAShareRiskControl::sell_rejection_reason(
|
||||
date,
|
||||
&candidate,
|
||||
&market,
|
||||
None,
|
||||
Some(&position),
|
||||
6.27,
|
||||
);
|
||||
|
||||
assert_eq!(reason, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sell_rejection_blocks_execution_price_at_lower_limit() {
|
||||
let prev_date = d(2024, 4, 16);
|
||||
let date = d(2024, 4, 17);
|
||||
let candidate = candidate(date);
|
||||
let market = market(date, 5.63, 5.63);
|
||||
let position = position(prev_date);
|
||||
|
||||
let reason = ChinaAShareRiskControl::sell_rejection_reason(
|
||||
date,
|
||||
&candidate,
|
||||
&market,
|
||||
None,
|
||||
Some(&position),
|
||||
5.63,
|
||||
);
|
||||
|
||||
assert_eq!(reason, Some("open at or below lower limit"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,12 @@ pub trait Strategy {
|
||||
fn decision_quote_times(&self) -> Vec<NaiveTime> {
|
||||
Vec::new()
|
||||
}
|
||||
fn decision_quote_symbols(
|
||||
&mut self,
|
||||
_ctx: &StrategyContext<'_>,
|
||||
) -> Result<BTreeSet<String>, BacktestError> {
|
||||
Ok(BTreeSet::new())
|
||||
}
|
||||
fn on_scheduled(
|
||||
&mut self,
|
||||
_ctx: &StrategyContext<'_>,
|
||||
@@ -983,6 +989,14 @@ pub enum OrderIntent {
|
||||
target_value: f64,
|
||||
reason: String,
|
||||
},
|
||||
TimedTargetValue {
|
||||
symbol: String,
|
||||
target_value: f64,
|
||||
style: AlgoOrderStyle,
|
||||
start_time: Option<NaiveTime>,
|
||||
end_time: Option<NaiveTime>,
|
||||
reason: String,
|
||||
},
|
||||
LimitTargetValue {
|
||||
symbol: String,
|
||||
target_value: f64,
|
||||
|
||||
@@ -277,7 +277,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
ManualField { name: "latest_symbol_open_order_status/latest_symbol_open_order_unfilled_qty".to_string(), field_type: "string/int".to_string(), detail: "当前证券最近一笔挂单的状态和未成交数量。".to_string() },
|
||||
ManualField { name: "in_dynamic_universe/is_subscribed".to_string(), field_type: "bool".to_string(), detail: "当前证券是否在动态 universe 内,以及是否仍在订阅集合中。".to_string() },
|
||||
ManualField { name: "stock_ma5/stock_ma10/stock_ma20/stock_ma30".to_string(), field_type: "float".to_string(), detail: "个股价格均线内建别名,按当前交易日前 N 个已完成交易日的收盘价计算;历史窗口不足时为 NaN,比较条件会自然不通过;15 日、45 日等任意窗口请改用 sma(\"close\", n)。".to_string() },
|
||||
ManualField { name: "stock_volume_ma5/stock_volume_ma10/stock_volume_ma20/stock_volume_ma60".to_string(), field_type: "float".to_string(), detail: "个股成交量均线内建别名,按当前交易日前 N 个已完成交易日的成交量计算,不包含回测当天未来成交量;历史窗口不足时为 NaN,比较条件会自然不通过;任意窗口请改用 rolling_mean(\"volume\", n)。".to_string() },
|
||||
ManualField { name: "stock_volume_ma5/stock_volume_ma10/stock_volume_ma20/stock_volume_ma60/stock_volume_ma100".to_string(), field_type: "float".to_string(), detail: "个股成交量均线内建别名,按当前交易日前 N 个已完成交易日的成交量计算,不包含回测当天未来成交量;历史窗口不足时为 NaN,比较条件会自然不通过;任意窗口请改用 rolling_mean(\"volume\", n)。".to_string() },
|
||||
ManualField { name: "factors[\"field\"] / factor(\"field\")".to_string(), field_type: "float/string".to_string(), detail: "当前证券当日可用因子。默认可用字段以手册的“可用指标、参数和字段”清单为准;自定义因子需要预先写入策略数据或 extra_factors。数值字段返回数字,字符串字段返回字符串。".to_string() },
|
||||
ManualField { name: "listed_days".to_string(), field_type: "int".to_string(), detail: "上市天数。".to_string() },
|
||||
],
|
||||
|
||||
@@ -23,6 +23,7 @@ fn candidate() -> CandidateEligibility {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -221,6 +221,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: ex_date,
|
||||
@@ -232,6 +233,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: payable_date,
|
||||
@@ -243,6 +245,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
|
||||
@@ -149,6 +149,7 @@ fn engine_preloads_declared_decision_quotes_for_current_positions() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: second,
|
||||
@@ -160,6 +161,7 @@ fn engine_preloads_declared_decision_quotes_for_current_positions() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -226,6 +228,189 @@ fn engine_preloads_declared_decision_quotes_for_current_positions() {
|
||||
engine.run().expect("backtest should run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_reuses_preloaded_decision_quotes_without_loader_call() {
|
||||
let first = d(2026, 1, 5);
|
||||
let second = d(2026, 1, 6);
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
Vec::new(),
|
||||
vec![
|
||||
DailyMarketSnapshot {
|
||||
date: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2026-01-05 15:00:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 10.2,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
last_price: 10.0,
|
||||
bid1: 10.0,
|
||||
ask1: 10.0,
|
||||
prev_close: 9.8,
|
||||
volume: 10_000,
|
||||
tick_volume: 1_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 10.78,
|
||||
lower_limit: 8.82,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
DailyMarketSnapshot {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2026-01-06 15:00:00".to_string()),
|
||||
day_open: 10.5,
|
||||
open: 10.5,
|
||||
high: 11.2,
|
||||
low: 10.4,
|
||||
close: 10.6,
|
||||
last_price: 10.6,
|
||||
bid1: 10.6,
|
||||
ask1: 10.6,
|
||||
prev_close: 10.0,
|
||||
volume: 10_000,
|
||||
tick_volume: 1_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: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: None,
|
||||
effective_turnover_ratio: None,
|
||||
extra_factors: Default::default(),
|
||||
},
|
||||
DailyFactorSnapshot {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: None,
|
||||
effective_turnover_ratio: None,
|
||||
extra_factors: Default::default(),
|
||||
},
|
||||
],
|
||||
vec![
|
||||
CandidateEligibility {
|
||||
date: first,
|
||||
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,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: second,
|
||||
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,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
BenchmarkSnapshot {
|
||||
date: first,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1000.0,
|
||||
prev_close: 990.0,
|
||||
volume: 1_000_000,
|
||||
},
|
||||
BenchmarkSnapshot {
|
||||
date: second,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1001.0,
|
||||
prev_close: 1000.0,
|
||||
volume: 1_000_000,
|
||||
},
|
||||
],
|
||||
Vec::new(),
|
||||
vec![
|
||||
IntradayExecutionQuote {
|
||||
date: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: first.and_time(t(10, 39, 59)),
|
||||
last_price: 10.0,
|
||||
bid1: 10.0,
|
||||
ask1: 10.0,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
volume_delta: 10_000,
|
||||
amount_delta: 100_000.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
},
|
||||
IntradayExecutionQuote {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: second.and_time(t(10, 39, 59)),
|
||||
last_price: 11.0,
|
||||
bid1: 11.0,
|
||||
ask1: 11.0,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
volume_delta: 10_000,
|
||||
amount_delta: 100_000.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("dataset");
|
||||
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_matching_type(MatchingType::NextTickLast)
|
||||
.with_intraday_execution_start_time(t(10, 40, 0));
|
||||
let config = BacktestConfig {
|
||||
initial_cash: 10_000.0,
|
||||
benchmark_code: "000852.SH".to_string(),
|
||||
start_date: Some(first),
|
||||
end_date: Some(second),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Last,
|
||||
};
|
||||
let loader_calls = Arc::new(Mutex::new(0usize));
|
||||
let captured_loader_calls = Arc::clone(&loader_calls);
|
||||
let mut engine = BacktestEngine::new(data, DecisionQuoteReader::default(), broker, config)
|
||||
.with_execution_quote_loader(move |_| {
|
||||
*captured_loader_calls.lock().expect("loader mutex") += 1;
|
||||
Ok(Vec::new())
|
||||
});
|
||||
|
||||
engine.run().expect("backtest should run");
|
||||
assert_eq!(
|
||||
*loader_calls.lock().expect("loader mutex"),
|
||||
0,
|
||||
"preloaded execution quotes should satisfy decision-time quote requests"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MultiTimeDecisionQuoteReader {
|
||||
day_count: usize,
|
||||
@@ -361,6 +546,7 @@ fn engine_loads_distinct_decision_quote_times_on_same_day() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: second,
|
||||
@@ -372,6 +558,7 @@ fn engine_loads_distinct_decision_quote_times_on_same_day() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
|
||||
@@ -180,6 +180,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date1,
|
||||
@@ -191,6 +192,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -202,6 +204,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -400,6 +403,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date1,
|
||||
@@ -411,6 +415,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -422,6 +427,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
|
||||
@@ -87,6 +87,7 @@ fn single_day_anchor_data(date: NaiveDate) -> DataSet {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -154,6 +155,7 @@ fn candidate_row(date: NaiveDate, symbol: &str) -> CandidateEligibility {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1116,6 +1118,7 @@ fn engine_runs_strategy_hooks_in_daily_order() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -1127,6 +1130,7 @@ fn engine_runs_strategy_hooks_in_daily_order() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -1273,6 +1277,7 @@ fn engine_executes_open_auction_decisions_before_on_day() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1371,6 +1376,7 @@ fn engine_executes_futures_order_intents_against_future_account() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1960,6 +1966,7 @@ fn engine_runs_subscribed_tick_hooks_and_executes_tick_orders() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2143,6 +2150,7 @@ fn strategy_context_exposes_engine_native_data_helpers() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let benchmarks = [
|
||||
@@ -2302,6 +2310,7 @@ fn strategy_context_exposes_final_order_runtime_view() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2555,6 +2564,7 @@ fn engine_applies_account_cash_flow_and_financing_intents() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -2566,6 +2576,7 @@ fn engine_applies_account_cash_flow_and_financing_intents() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -2737,6 +2748,7 @@ fn engine_rejects_pending_limit_orders_at_market_close() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -2748,6 +2760,7 @@ fn engine_rejects_pending_limit_orders_at_market_close() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -2938,6 +2951,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -2949,6 +2963,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date3,
|
||||
@@ -2960,6 +2975,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -3184,6 +3200,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date2,
|
||||
@@ -3195,6 +3212,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: date3,
|
||||
@@ -3206,6 +3224,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -3538,6 +3557,7 @@ fn engine_applies_dynamic_universe_and_subscription_directives() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: *date,
|
||||
@@ -3549,6 +3569,7 @@ fn engine_applies_dynamic_universe_and_subscription_directives() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
]
|
||||
})
|
||||
@@ -3671,6 +3692,7 @@ fn engine_exposes_current_process_context_to_strategies() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
|
||||
@@ -61,6 +61,7 @@ fn order_value_rounding_data(date: NaiveDate, symbol: &str, price: f64) -> DataS
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -165,6 +166,7 @@ fn broker_executes_explicit_order_value_buy() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -314,6 +316,7 @@ fn broker_delayed_limit_open_sell_uses_tick_price() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -445,6 +448,7 @@ fn broker_executes_order_shares_and_order_lots() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -570,6 +574,7 @@ fn broker_executes_target_shares_like_order_to() {
|
||||
allow_buy: true,
|
||||
allow_sell: true,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -726,6 +731,7 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date,
|
||||
@@ -737,6 +743,7 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![BenchmarkSnapshot {
|
||||
@@ -867,6 +874,7 @@ fn broker_executes_target_portfolio_smart_with_algo_order_style() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1007,6 +1015,7 @@ fn broker_executes_order_percent_and_target_percent() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1127,6 +1136,7 @@ fn broker_uses_day_open_price_for_open_auction_matching() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1230,6 +1240,7 @@ fn broker_open_auction_uses_auction_volume_without_quote_liquidity() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1330,6 +1341,7 @@ fn broker_cancels_buy_when_open_hits_upper_limit() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1442,6 +1454,7 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1541,6 +1554,7 @@ fn broker_applies_dynamic_slippage_on_snapshot_fills() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1645,6 +1659,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1762,6 +1777,7 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1868,6 +1884,7 @@ fn broker_executes_intraday_last_on_start_quote_without_trade_delta() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -1983,6 +2000,7 @@ fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2110,6 +2128,7 @@ fn broker_cancels_market_buy_when_tick_has_no_volume() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2213,6 +2232,7 @@ fn broker_splits_intraday_quote_fills_and_tracks_commission_by_order() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2373,6 +2393,7 @@ fn broker_aggregates_intraday_quote_fills_into_vwap_leg() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2517,6 +2538,7 @@ fn broker_executes_algo_vwap_value_with_time_window() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2674,6 +2696,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2833,6 +2856,7 @@ fn broker_uses_best_own_price_for_intraday_matching() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -2947,6 +2971,7 @@ fn broker_uses_best_counterparty_price_for_intraday_matching() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -3111,6 +3136,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
|
||||
allow_sell: false,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date,
|
||||
@@ -3122,6 +3148,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![BenchmarkSnapshot {
|
||||
@@ -3298,6 +3325,7 @@ fn rebalance_uses_prev_close_for_open_auction_valuation() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date,
|
||||
@@ -3309,6 +3337,7 @@ fn rebalance_uses_prev_close_for_open_auction_valuation() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![BenchmarkSnapshot {
|
||||
@@ -3479,6 +3508,7 @@ fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date,
|
||||
@@ -3490,6 +3520,7 @@ fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![BenchmarkSnapshot {
|
||||
@@ -3615,6 +3646,7 @@ fn broker_uses_board_specific_min_quantity_and_step_size_for_buy_sizing() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -3713,6 +3745,7 @@ fn broker_allows_bjse_quantities_above_minimum_without_round_lot_step() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -3813,6 +3846,7 @@ fn broker_allows_full_odd_lot_sell_when_liquidating_position() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
@@ -3927,6 +3961,7 @@ fn same_day_sell_then_rebuy_reinserts_position_at_end() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let data = DataSet::from_components(
|
||||
@@ -4094,6 +4129,7 @@ fn two_day_limit_order_data(day1_open: f64, day2_open: f64) -> DataSet {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: day2,
|
||||
@@ -4105,6 +4141,7 @@ fn two_day_limit_order_data(day1_open: f64, day2_open: f64) -> DataSet {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -4502,6 +4539,7 @@ fn broker_reserves_sellable_quantity_for_open_limit_sells() {
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
risk_level_code: None,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
|
||||
Reference in New Issue
Block a user