Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| bc39df0ee5 | |||
| 70695d8c92 | |||
| 0533e2db3a | |||
| 716149c06c | |||
| 0628dd528a | |||
| e146ad6e7d | |||
| cf2c4fd179 | |||
| 6ba61ef80b | |||
| e45f990487 | |||
| 8e6c912a07 | |||
| 9a411f2403 | |||
| d2c65c91b7 | |||
| 5078aec840 | |||
| df949ab8ee | |||
| 2e036783bf | |||
| ff145300b4 | |||
| c2de9d8e83 | |||
| baeda3773d | |||
| 725f1845d9 | |||
| e0949a0eaa | |||
| 5d2bcd8366 | |||
| 5181d0e403 | |||
| 1c31fa80d2 | |||
| d3d08276ae | |||
| 80b34280c2 |
+839
-74
File diff suppressed because it is too large
Load Diff
+437
-120
@@ -1,6 +1,7 @@
|
|||||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
use std::sync::{Arc, OnceLock};
|
||||||
|
|
||||||
use chrono::{NaiveDate, NaiveDateTime};
|
use chrono::{NaiveDate, NaiveDateTime};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -159,14 +160,14 @@ impl DailyMarketSnapshot {
|
|||||||
if !self.upper_limit.is_finite() || self.upper_limit <= 0.0 {
|
if !self.upper_limit.is_finite() || self.upper_limit <= 0.0 {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
price >= self.upper_limit - self.effective_price_tick() + 1e-6
|
price >= self.upper_limit - 1e-9
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_at_lower_limit_price(&self, price: f64) -> bool {
|
pub fn is_at_lower_limit_price(&self, price: f64) -> bool {
|
||||||
if !self.lower_limit.is_finite() || self.lower_limit <= 0.0 {
|
if !self.lower_limit.is_finite() || self.lower_limit <= 0.0 {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
price <= self.lower_limit + self.effective_price_tick() - 1e-6
|
price <= self.lower_limit + 1e-9
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,6 +208,8 @@ pub struct CandidateEligibility {
|
|||||||
pub allow_sell: bool,
|
pub allow_sell: bool,
|
||||||
pub is_kcb: bool,
|
pub is_kcb: bool,
|
||||||
pub is_one_yuan: bool,
|
pub is_one_yuan: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub risk_level_code: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CandidateEligibility {
|
impl CandidateEligibility {
|
||||||
@@ -364,6 +367,17 @@ pub struct DailySnapshotBundle {
|
|||||||
pub corporate_actions: Vec<CorporateAction>,
|
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)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct PriceBar {
|
pub struct PriceBar {
|
||||||
#[serde(with = "date_format")]
|
#[serde(with = "date_format")]
|
||||||
@@ -466,7 +480,17 @@ pub fn decision_adjusted_cap_bn(
|
|||||||
raw_cap_bn * market.prev_close / market.close
|
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 {
|
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)
|
decision_adjusted_cap_bn(factor.date, factor.market_cap_bn, market)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,18 +498,35 @@ pub fn decision_free_float_cap_bn(
|
|||||||
factor: &DailyFactorSnapshot,
|
factor: &DailyFactorSnapshot,
|
||||||
market: &DailyMarketSnapshot,
|
market: &DailyMarketSnapshot,
|
||||||
) -> f64 {
|
) -> 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)
|
decision_adjusted_cap_bn(factor.date, factor.free_float_cap_bn, market)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct SymbolPriceSeries {
|
struct SymbolPriceSeries {
|
||||||
snapshots: Vec<DailyMarketSnapshot>,
|
symbol: String,
|
||||||
dates: Vec<NaiveDate>,
|
dates: Vec<NaiveDate>,
|
||||||
|
timestamps: Vec<Option<String>>,
|
||||||
|
day_opens: Vec<f64>,
|
||||||
opens: Vec<f64>,
|
opens: Vec<f64>,
|
||||||
|
highs: Vec<f64>,
|
||||||
|
lows: Vec<f64>,
|
||||||
closes: Vec<f64>,
|
closes: Vec<f64>,
|
||||||
prev_closes: Vec<f64>,
|
prev_closes: Vec<f64>,
|
||||||
last_prices: 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>,
|
open_prefix: Vec<f64>,
|
||||||
close_prefix: Vec<f64>,
|
close_prefix: Vec<f64>,
|
||||||
prev_close_prefix: Vec<f64>,
|
prev_close_prefix: Vec<f64>,
|
||||||
@@ -494,33 +535,71 @@ struct SymbolPriceSeries {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SymbolPriceSeries {
|
impl SymbolPriceSeries {
|
||||||
fn new(rows: &[DailyMarketSnapshot]) -> Self {
|
fn new<'a, I>(symbol: String, rows: I) -> Self
|
||||||
let mut sorted = rows.to_vec();
|
where
|
||||||
|
I: IntoIterator<Item = &'a DailyMarketSnapshot>,
|
||||||
|
{
|
||||||
|
let mut sorted = rows.into_iter().collect::<Vec<_>>();
|
||||||
sorted.sort_by_key(|row| row.date);
|
sorted.sort_by_key(|row| row.date);
|
||||||
|
|
||||||
let dates = sorted.iter().map(|row| row.date).collect::<Vec<_>>();
|
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 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 closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
|
||||||
let prev_closes = sorted.iter().map(|row| row.prev_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 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()
|
.iter()
|
||||||
.map(|row| row.volume as f64)
|
.map(|row| row.trading_phase.clone())
|
||||||
.collect::<Vec<_>>();
|
.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 open_prefix = prefix_sums(&opens);
|
||||||
let close_prefix = prefix_sums(&closes);
|
let close_prefix = prefix_sums(&closes);
|
||||||
let prev_close_prefix = prefix_sums(&prev_closes);
|
let prev_close_prefix = prefix_sums(&prev_closes);
|
||||||
let last_prefix = prefix_sums(&last_prices);
|
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 {
|
Self {
|
||||||
snapshots: sorted,
|
symbol,
|
||||||
dates,
|
dates,
|
||||||
|
timestamps,
|
||||||
|
day_opens,
|
||||||
opens,
|
opens,
|
||||||
|
highs,
|
||||||
|
lows,
|
||||||
closes,
|
closes,
|
||||||
prev_closes,
|
prev_closes,
|
||||||
last_prices,
|
last_prices,
|
||||||
|
bid1s,
|
||||||
|
ask1s,
|
||||||
volumes,
|
volumes,
|
||||||
|
tick_volumes,
|
||||||
|
bid1_volumes,
|
||||||
|
ask1_volumes,
|
||||||
|
trading_phases,
|
||||||
|
paused,
|
||||||
|
upper_limits,
|
||||||
|
lower_limits,
|
||||||
|
price_ticks,
|
||||||
open_prefix,
|
open_prefix,
|
||||||
close_prefix,
|
close_prefix,
|
||||||
prev_close_prefix,
|
prev_close_prefix,
|
||||||
@@ -548,7 +627,7 @@ impl SymbolPriceSeries {
|
|||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
let start = end.saturating_sub(lookback);
|
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(
|
fn trailing_snapshots(
|
||||||
@@ -569,7 +648,31 @@ impl SymbolPriceSeries {
|
|||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
let start = end.saturating_sub(lookback);
|
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> {
|
fn decision_price_on_or_before(&self, date: NaiveDate) -> Option<f64> {
|
||||||
@@ -656,7 +759,12 @@ impl SymbolPriceSeries {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let start = end - lookback;
|
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> {
|
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 {
|
match field {
|
||||||
PriceField::DayOpen => &self.opens,
|
PriceField::DayOpen => &self.day_opens,
|
||||||
PriceField::Open => &self.opens,
|
PriceField::Open => &self.opens,
|
||||||
PriceField::Close => &self.closes,
|
PriceField::Close => &self.closes,
|
||||||
PriceField::Last => &self.last_prices,
|
PriceField::Last => &self.last_prices,
|
||||||
@@ -681,15 +789,7 @@ impl SymbolPriceSeries {
|
|||||||
if end == 0 {
|
if end == 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
self.values_for(field).get(end - 1).copied()
|
self.price_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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
||||||
@@ -700,6 +800,54 @@ impl SymbolPriceSeries {
|
|||||||
PriceField::Last => &self.last_prefix,
|
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)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -835,21 +983,21 @@ impl BenchmarkPriceSeries {
|
|||||||
pub struct DataSet {
|
pub struct DataSet {
|
||||||
instruments: HashMap<String, Instrument>,
|
instruments: HashMap<String, Instrument>,
|
||||||
calendar: TradingCalendar,
|
calendar: TradingCalendar,
|
||||||
market_by_date: BTreeMap<NaiveDate, Vec<DailyMarketSnapshot>>,
|
market_by_date: BTreeMap<NaiveDate, Vec<Arc<DailyMarketSnapshot>>>,
|
||||||
market_index: HashMap<(NaiveDate, String), DailyMarketSnapshot>,
|
market_index: HashMap<NaiveDate, HashMap<String, Arc<DailyMarketSnapshot>>>,
|
||||||
factor_by_date: BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
|
factor_by_date: BTreeMap<NaiveDate, Vec<Arc<DailyFactorSnapshot>>>,
|
||||||
factor_index: HashMap<(NaiveDate, String), DailyFactorSnapshot>,
|
factor_index: HashMap<NaiveDate, HashMap<String, Arc<DailyFactorSnapshot>>>,
|
||||||
factor_text_by_date: BTreeMap<NaiveDate, Vec<FactorTextValue>>,
|
factor_text_by_date: BTreeMap<NaiveDate, Vec<FactorTextValue>>,
|
||||||
factor_text_index: HashMap<(NaiveDate, String, String), FactorTextValue>,
|
factor_text_index: HashMap<(NaiveDate, String, String), FactorTextValue>,
|
||||||
candidate_by_date: BTreeMap<NaiveDate, Vec<CandidateEligibility>>,
|
candidate_by_date: BTreeMap<NaiveDate, Vec<Arc<CandidateEligibility>>>,
|
||||||
candidate_index: HashMap<(NaiveDate, String), CandidateEligibility>,
|
candidate_index: HashMap<NaiveDate, HashMap<String, Arc<CandidateEligibility>>>,
|
||||||
corporate_actions_by_date: BTreeMap<NaiveDate, Vec<CorporateAction>>,
|
corporate_actions_by_date: BTreeMap<NaiveDate, Vec<CorporateAction>>,
|
||||||
execution_quotes_by_date: HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>,
|
execution_quotes_by_date: HashMap<NaiveDate, HashMap<String, Vec<IntradayExecutionQuote>>>,
|
||||||
order_book_depth_index: HashMap<(NaiveDate, String), Vec<IntradayOrderBookDepthLevel>>,
|
order_book_depth_index: HashMap<(NaiveDate, String), Vec<IntradayOrderBookDepthLevel>>,
|
||||||
benchmark_by_date: BTreeMap<NaiveDate, BenchmarkSnapshot>,
|
benchmark_by_date: BTreeMap<NaiveDate, BenchmarkSnapshot>,
|
||||||
market_series_by_symbol: HashMap<String, SymbolPriceSeries>,
|
market_series_by_symbol: HashMap<String, SymbolPriceSeries>,
|
||||||
benchmark_series_cache: BenchmarkPriceSeries,
|
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,
|
benchmark_code: String,
|
||||||
futures_params_by_symbol: HashMap<String, Vec<FuturesTradingParameter>>,
|
futures_params_by_symbol: HashMap<String, Vec<FuturesTradingParameter>>,
|
||||||
}
|
}
|
||||||
@@ -1087,24 +1235,37 @@ impl DataSet {
|
|||||||
) -> Result<Self, DataSetError> {
|
) -> Result<Self, DataSetError> {
|
||||||
let benchmark_code = collect_benchmark_code(&benchmarks)?;
|
let benchmark_code = collect_benchmark_code(&benchmarks)?;
|
||||||
let calendar = TradingCalendar::new(benchmarks.iter().map(|item| item.date).collect());
|
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
|
let instruments = instruments
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|instrument| (instrument.symbol.clone(), instrument))
|
.map(|instrument| (instrument.symbol.clone(), instrument))
|
||||||
.collect::<HashMap<_, _>>();
|
.collect::<HashMap<_, _>>();
|
||||||
|
|
||||||
let market_by_date = group_by_date(market.clone(), |item| item.date);
|
let market = market.into_iter().map(Arc::new).collect::<Vec<_>>();
|
||||||
let market_index = market
|
let market_by_date = group_arc_by_date(&market, |item| item.date);
|
||||||
.into_iter()
|
let mut market_index =
|
||||||
.map(|item| ((item.date, item.symbol.clone()), item))
|
HashMap::<NaiveDate, HashMap<String, Arc<DailyMarketSnapshot>>>::new();
|
||||||
.collect::<HashMap<_, _>>();
|
for item in market {
|
||||||
|
market_index
|
||||||
|
.entry(item.date)
|
||||||
|
.or_default()
|
||||||
|
.insert(item.symbol.clone(), item);
|
||||||
|
}
|
||||||
|
|
||||||
let factor_by_date = group_by_date(factors.clone(), |item| item.date);
|
let factor_by_date = group_arc_by_date(&factors, |item| item.date);
|
||||||
let factor_index = factors
|
let mut factor_index =
|
||||||
.into_iter()
|
HashMap::<NaiveDate, HashMap<String, Arc<DailyFactorSnapshot>>>::new();
|
||||||
.map(|item| ((item.date, item.symbol.clone()), item))
|
for item in factors {
|
||||||
.collect::<HashMap<_, _>>();
|
factor_index
|
||||||
|
.entry(item.date)
|
||||||
|
.or_default()
|
||||||
|
.insert(item.symbol.clone(), item);
|
||||||
|
}
|
||||||
let factor_texts = factor_texts
|
let factor_texts = factor_texts
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|mut item| {
|
.filter_map(|mut item| {
|
||||||
@@ -1122,11 +1283,15 @@ impl DataSet {
|
|||||||
.map(|item| ((item.date, item.symbol.clone(), item.field.clone()), item))
|
.map(|item| ((item.date, item.symbol.clone(), item.field.clone()), item))
|
||||||
.collect::<HashMap<_, _>>();
|
.collect::<HashMap<_, _>>();
|
||||||
|
|
||||||
let candidate_by_date = group_by_date(candidates.clone(), |item| item.date);
|
let candidate_by_date = group_arc_by_date(&candidates, |item| item.date);
|
||||||
let candidate_index = candidates
|
let mut candidate_index =
|
||||||
.into_iter()
|
HashMap::<NaiveDate, HashMap<String, Arc<CandidateEligibility>>>::new();
|
||||||
.map(|item| ((item.date, item.symbol.clone()), item))
|
for item in candidates {
|
||||||
.collect::<HashMap<_, _>>();
|
candidate_index
|
||||||
|
.entry(item.date)
|
||||||
|
.or_default()
|
||||||
|
.insert(item.symbol.clone(), item);
|
||||||
|
}
|
||||||
let corporate_actions_by_date = group_by_date(corporate_actions, |item| item.date);
|
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 execution_quotes_by_date = build_execution_quote_index(execution_quotes);
|
||||||
let order_book_depth_index = build_order_book_depth_index(order_book_depth);
|
let order_book_depth_index = build_order_book_depth_index(order_book_depth);
|
||||||
@@ -1138,12 +1303,6 @@ impl DataSet {
|
|||||||
let market_series_by_symbol = build_market_series(&market_by_date);
|
let market_series_by_symbol = build_market_series(&market_by_date);
|
||||||
let benchmark_series_cache =
|
let benchmark_series_cache =
|
||||||
BenchmarkPriceSeries::new(&benchmark_by_date.values().cloned().collect::<Vec<_>>());
|
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);
|
let futures_params_by_symbol = build_futures_params_index(futures_params);
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -1163,7 +1322,7 @@ impl DataSet {
|
|||||||
benchmark_by_date,
|
benchmark_by_date,
|
||||||
market_series_by_symbol,
|
market_series_by_symbol,
|
||||||
benchmark_series_cache,
|
benchmark_series_cache,
|
||||||
eligible_universe_by_date,
|
eligible_universe_by_date: Arc::new(OnceLock::new()),
|
||||||
benchmark_code,
|
benchmark_code,
|
||||||
futures_params_by_symbol,
|
futures_params_by_symbol,
|
||||||
})
|
})
|
||||||
@@ -1207,15 +1366,24 @@ impl DataSet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn market(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
pub fn market(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||||
self.market_index.get(&(date, symbol.to_string()))
|
self.market_index
|
||||||
|
.get(&date)
|
||||||
|
.and_then(|rows| rows.get(symbol))
|
||||||
|
.map(Arc::as_ref)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn factor(&self, date: NaiveDate, symbol: &str) -> Option<&DailyFactorSnapshot> {
|
pub fn factor(&self, date: NaiveDate, symbol: &str) -> Option<&DailyFactorSnapshot> {
|
||||||
self.factor_index.get(&(date, symbol.to_string()))
|
self.factor_index
|
||||||
|
.get(&date)
|
||||||
|
.and_then(|rows| rows.get(symbol))
|
||||||
|
.map(Arc::as_ref)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn candidate(&self, date: NaiveDate, symbol: &str) -> Option<&CandidateEligibility> {
|
pub fn candidate(&self, date: NaiveDate, symbol: &str) -> Option<&CandidateEligibility> {
|
||||||
self.candidate_index.get(&(date, symbol.to_string()))
|
self.candidate_index
|
||||||
|
.get(&date)
|
||||||
|
.and_then(|rows| rows.get(symbol))
|
||||||
|
.map(Arc::as_ref)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn benchmark(&self, date: NaiveDate) -> Option<&BenchmarkSnapshot> {
|
pub fn benchmark(&self, date: NaiveDate) -> Option<&BenchmarkSnapshot> {
|
||||||
@@ -1237,6 +1405,13 @@ impl DataSet {
|
|||||||
.unwrap_or(&[])
|
.unwrap_or(&[])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn has_execution_quotes_on_date(&self, date: NaiveDate) -> bool {
|
||||||
|
self.execution_quotes_by_date
|
||||||
|
.get(&date)
|
||||||
|
.map(|rows_by_symbol| !rows_by_symbol.is_empty())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
|
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
|
||||||
self.execution_quotes_by_date
|
self.execution_quotes_by_date
|
||||||
.iter()
|
.iter()
|
||||||
@@ -1248,6 +1423,14 @@ impl DataSet {
|
|||||||
.collect()
|
.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 {
|
pub fn add_execution_quotes(&mut self, quotes: Vec<IntradayExecutionQuote>) -> usize {
|
||||||
let mut added = 0usize;
|
let mut added = 0usize;
|
||||||
let mut touched = HashSet::<(NaiveDate, String)>::new();
|
let mut touched = HashSet::<(NaiveDate, String)>::new();
|
||||||
@@ -1307,6 +1490,49 @@ impl DataSet {
|
|||||||
quotes
|
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> {
|
pub fn benchmark_series(&self) -> Vec<BenchmarkSnapshot> {
|
||||||
self.benchmark_by_date.values().cloned().collect()
|
self.benchmark_by_date.values().cloned().collect()
|
||||||
}
|
}
|
||||||
@@ -1913,6 +2139,7 @@ impl DataSet {
|
|||||||
.range(start..=end)
|
.range(start..=end)
|
||||||
.flat_map(|(_, rows)| rows.iter())
|
.flat_map(|(_, rows)| rows.iter())
|
||||||
.filter(|row| row.symbol == symbol)
|
.filter(|row| row.symbol == symbol)
|
||||||
|
.map(Arc::as_ref)
|
||||||
.map(daily_market_price_bar)
|
.map(daily_market_price_bar)
|
||||||
.collect(),
|
.collect(),
|
||||||
Some("1m") | Some("tick") => {
|
Some("1m") | Some("tick") => {
|
||||||
@@ -1952,15 +2179,22 @@ impl DataSet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||||
self.market_series_by_symbol
|
let series = self.market_series_by_symbol.get(symbol)?;
|
||||||
.get(symbol)
|
let end = series.previous_completed_end_index(date)?;
|
||||||
.and_then(|series| series.snapshot_before(date))
|
if end == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let previous_date = *series.dates.get(end - 1)?;
|
||||||
|
self.market_index
|
||||||
|
.get(&previous_date)
|
||||||
|
.and_then(|rows| rows.get(symbol))
|
||||||
|
.map(Arc::as_ref)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
||||||
self.factor_by_date
|
self.factor_by_date
|
||||||
.get(&date)
|
.get(&date)
|
||||||
.map(|rows| rows.iter().collect())
|
.map(|rows| rows.iter().map(Arc::as_ref).collect())
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1974,14 +2208,14 @@ impl DataSet {
|
|||||||
pub fn market_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyMarketSnapshot> {
|
pub fn market_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyMarketSnapshot> {
|
||||||
self.market_by_date
|
self.market_by_date
|
||||||
.get(&date)
|
.get(&date)
|
||||||
.map(|rows| rows.iter().collect())
|
.map(|rows| rows.iter().map(Arc::as_ref).collect())
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn candidate_snapshots_on(&self, date: NaiveDate) -> Vec<&CandidateEligibility> {
|
pub fn candidate_snapshots_on(&self, date: NaiveDate) -> Vec<&CandidateEligibility> {
|
||||||
self.candidate_by_date
|
self.candidate_by_date
|
||||||
.get(&date)
|
.get(&date)
|
||||||
.map(|rows| rows.iter().collect())
|
.map(|rows| rows.iter().map(Arc::as_ref).collect())
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1993,12 +2227,20 @@ impl DataSet {
|
|||||||
Ok(DailySnapshotBundle {
|
Ok(DailySnapshotBundle {
|
||||||
date,
|
date,
|
||||||
benchmark,
|
benchmark,
|
||||||
market: self.market_by_date.get(&date).cloned().unwrap_or_default(),
|
market: self
|
||||||
factors: self.factor_by_date.get(&date).cloned().unwrap_or_default(),
|
.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
|
candidates: self
|
||||||
.candidate_by_date
|
.candidate_by_date
|
||||||
.get(&date)
|
.get(&date)
|
||||||
.cloned()
|
.map(|rows| rows.iter().map(|row| row.as_ref().clone()).collect())
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
corporate_actions: self
|
corporate_actions: self
|
||||||
.corporate_actions_by_date
|
.corporate_actions_by_date
|
||||||
@@ -2027,10 +2269,10 @@ impl DataSet {
|
|||||||
field: &str,
|
field: &str,
|
||||||
include_now: bool,
|
include_now: bool,
|
||||||
) -> Vec<f64> {
|
) -> Vec<f64> {
|
||||||
self.history_daily_snapshots(date, symbol, bar_count, include_now)
|
self.market_series_by_symbol
|
||||||
.into_iter()
|
.get(symbol)
|
||||||
.filter_map(|row| daily_market_numeric_value(&row, field))
|
.map(|series| series.trailing_numeric_values(date, bar_count, field, include_now))
|
||||||
.collect()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn history_intraday_values(
|
fn history_intraday_values(
|
||||||
@@ -2071,8 +2313,14 @@ impl DataSet {
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|day| {
|
.map(|day| {
|
||||||
evaluator(
|
evaluator(
|
||||||
self.candidate_index.get(&(*day, symbol.to_string())),
|
self.candidate_index
|
||||||
self.market_index.get(&(*day, symbol.to_string())),
|
.get(day)
|
||||||
|
.and_then(|rows| rows.get(symbol))
|
||||||
|
.map(Arc::as_ref),
|
||||||
|
self.market_index
|
||||||
|
.get(day)
|
||||||
|
.and_then(|rows| rows.get(symbol))
|
||||||
|
.map(Arc::as_ref),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
@@ -2371,6 +2619,14 @@ impl DataSet {
|
|||||||
|
|
||||||
pub fn eligible_universe_on(&self, date: NaiveDate) -> &[EligibleUniverseSnapshot] {
|
pub fn eligible_universe_on(&self, date: NaiveDate) -> &[EligibleUniverseSnapshot] {
|
||||||
self.eligible_universe_by_date
|
self.eligible_universe_by_date
|
||||||
|
.get_or_init(|| {
|
||||||
|
build_eligible_universe(
|
||||||
|
&self.factor_by_date,
|
||||||
|
&self.candidate_index,
|
||||||
|
&self.market_index,
|
||||||
|
&self.instruments,
|
||||||
|
)
|
||||||
|
})
|
||||||
.get(&date)
|
.get(&date)
|
||||||
.map(Vec::as_slice)
|
.map(Vec::as_slice)
|
||||||
.unwrap_or(&[])
|
.unwrap_or(&[])
|
||||||
@@ -2754,28 +3010,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> {
|
fn intraday_quote_numeric_value(snapshot: &IntradayExecutionQuote, field: &str) -> Option<f64> {
|
||||||
match normalize_field(field).as_str() {
|
match normalize_field(field).as_str() {
|
||||||
"last" | "last_price" | "close" | "price" => Some(snapshot.last_price),
|
"last" | "last_price" | "close" | "price" => Some(snapshot.last_price),
|
||||||
@@ -2911,6 +3145,13 @@ fn read_candidates(path: &Path) -> Result<Vec<CandidateEligibility>, DataSetErro
|
|||||||
allow_sell: row.parse_bool(6)?,
|
allow_sell: row.parse_bool(6)?,
|
||||||
is_kcb: row.parse_optional_bool(7).unwrap_or(false),
|
is_kcb: row.parse_optional_bool(7).unwrap_or(false),
|
||||||
is_one_yuan: row.parse_optional_bool(8).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)
|
Ok(snapshots)
|
||||||
@@ -3268,6 +3509,20 @@ where
|
|||||||
grouped
|
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 collect_benchmark_code(benchmarks: &[BenchmarkSnapshot]) -> Result<String, DataSetError> {
|
fn collect_benchmark_code(benchmarks: &[BenchmarkSnapshot]) -> Result<String, DataSetError> {
|
||||||
let mut codes = benchmarks
|
let mut codes = benchmarks
|
||||||
.iter()
|
.iter()
|
||||||
@@ -3337,21 +3592,24 @@ mod optional_date_format {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn build_market_series(
|
fn build_market_series(
|
||||||
market_by_date: &BTreeMap<NaiveDate, Vec<DailyMarketSnapshot>>,
|
market_by_date: &BTreeMap<NaiveDate, Vec<Arc<DailyMarketSnapshot>>>,
|
||||||
) -> HashMap<String, SymbolPriceSeries> {
|
) -> HashMap<String, SymbolPriceSeries> {
|
||||||
let mut grouped = HashMap::<String, Vec<DailyMarketSnapshot>>::new();
|
let mut grouped = HashMap::<String, Vec<&DailyMarketSnapshot>>::new();
|
||||||
for rows in market_by_date.values() {
|
for rows in market_by_date.values() {
|
||||||
for row in rows {
|
for row in rows {
|
||||||
grouped
|
grouped
|
||||||
.entry(row.symbol.clone())
|
.entry(row.symbol.clone())
|
||||||
.or_default()
|
.or_default()
|
||||||
.push(row.clone());
|
.push(row.as_ref());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
grouped
|
grouped
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(symbol, rows)| (symbol, SymbolPriceSeries::new(&rows)))
|
.map(|(symbol, rows)| {
|
||||||
|
let series = SymbolPriceSeries::new(symbol.clone(), rows);
|
||||||
|
(symbol, series)
|
||||||
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3413,9 +3671,9 @@ fn build_order_book_depth_index(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn build_eligible_universe(
|
fn build_eligible_universe(
|
||||||
factor_by_date: &BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
|
factor_by_date: &BTreeMap<NaiveDate, Vec<Arc<DailyFactorSnapshot>>>,
|
||||||
candidate_index: &HashMap<(NaiveDate, String), CandidateEligibility>,
|
candidate_index: &HashMap<NaiveDate, HashMap<String, Arc<CandidateEligibility>>>,
|
||||||
market_index: &HashMap<(NaiveDate, String), DailyMarketSnapshot>,
|
market_index: &HashMap<NaiveDate, HashMap<String, Arc<DailyMarketSnapshot>>>,
|
||||||
instruments: &HashMap<String, Instrument>,
|
instruments: &HashMap<String, Instrument>,
|
||||||
) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> {
|
) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> {
|
||||||
let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new();
|
let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new();
|
||||||
@@ -3426,13 +3684,19 @@ fn build_eligible_universe(
|
|||||||
if factor.market_cap_bn <= 0.0 || !factor.market_cap_bn.is_finite() {
|
if factor.market_cap_bn <= 0.0 || !factor.market_cap_bn.is_finite() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let key = (*date, factor.symbol.clone());
|
let Some(candidate) = candidate_index
|
||||||
let Some(candidate) = candidate_index.get(&key) else {
|
.get(date)
|
||||||
|
.and_then(|rows| rows.get(&factor.symbol))
|
||||||
|
else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let Some(market) = market_index.get(&key) else {
|
let Some(market) = market_index
|
||||||
|
.get(date)
|
||||||
|
.and_then(|rows| rows.get(&factor.symbol))
|
||||||
|
else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
let market = market.as_ref();
|
||||||
if ChinaAShareRiskControl::selection_rejection_reason(
|
if ChinaAShareRiskControl::selection_rejection_reason(
|
||||||
*date,
|
*date,
|
||||||
candidate,
|
candidate,
|
||||||
@@ -3574,11 +3838,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn decision_volume_average_uses_previous_completed_days_only() {
|
fn decision_volume_average_uses_previous_completed_days_only() {
|
||||||
let series = SymbolPriceSeries::new(&[
|
let series = SymbolPriceSeries::new(
|
||||||
market_row("2025-01-02", 10.0, 100),
|
"000001.SZ".to_string(),
|
||||||
market_row("2025-01-03", 11.0, 200),
|
&[
|
||||||
market_row("2025-01-06", 12.0, 10_000),
|
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!(
|
assert_eq!(
|
||||||
series.decision_close_moving_average(
|
series.decision_close_moving_average(
|
||||||
@@ -3608,11 +3875,14 @@ mod tests {
|
|||||||
let mut current = market_row("2025-01-06", 12.0, 10_000);
|
let mut current = market_row("2025-01-06", 12.0, 10_000);
|
||||||
current.close = 9_999.0;
|
current.close = 9_999.0;
|
||||||
current.last_price = 9_999.0;
|
current.last_price = 9_999.0;
|
||||||
let series = SymbolPriceSeries::new(&[
|
let series = SymbolPriceSeries::new(
|
||||||
market_row("2025-01-02", 10.0, 100),
|
"000001.SZ".to_string(),
|
||||||
market_row("2025-01-03", 11.0, 200),
|
&[
|
||||||
current,
|
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();
|
let decision_date = NaiveDate::parse_from_str("2025-01-06", "%Y-%m-%d").unwrap();
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -3629,12 +3899,15 @@ mod tests {
|
|||||||
fn decision_volume_average_includes_paused_zero_volume_days() {
|
fn decision_volume_average_includes_paused_zero_volume_days() {
|
||||||
let mut paused = market_row("2025-01-03", 11.0, 0);
|
let mut paused = market_row("2025-01-03", 11.0, 0);
|
||||||
paused.paused = true;
|
paused.paused = true;
|
||||||
let series = SymbolPriceSeries::new(&[
|
let series = SymbolPriceSeries::new(
|
||||||
market_row("2025-01-02", 10.0, 100),
|
"000001.SZ".to_string(),
|
||||||
paused,
|
&[
|
||||||
market_row("2025-01-06", 12.0, 300),
|
market_row("2025-01-02", 10.0, 100),
|
||||||
market_row("2025-01-07", 13.0, 10_000),
|
paused,
|
||||||
]);
|
market_row("2025-01-06", 12.0, 300),
|
||||||
|
market_row("2025-01-07", 13.0, 10_000),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
series.decision_volume_moving_average(
|
series.decision_volume_moving_average(
|
||||||
@@ -3708,6 +3981,7 @@ mod tests {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
};
|
};
|
||||||
let data = DataSet::from_components(
|
let data = DataSet::from_components(
|
||||||
vec![instrument("000001.SZ"), instrument("000002.SZ")],
|
vec![instrument("000001.SZ"), instrument("000002.SZ")],
|
||||||
@@ -3740,6 +4014,49 @@ mod tests {
|
|||||||
assert!((rows[1].market_cap_bn - 10.0).abs() < 1e-9);
|
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]
|
#[test]
|
||||||
fn benchmark_decision_close_windows_exclude_current_close() {
|
fn benchmark_decision_close_windows_exclude_current_close() {
|
||||||
let series = BenchmarkPriceSeries::new(&[
|
let series = BenchmarkPriceSeries::new(&[
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use chrono::{Datelike, NaiveDate};
|
use chrono::{Datelike, Duration, NaiveDate, NaiveTime};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
@@ -341,6 +341,8 @@ pub struct BacktestEngine<S, C, R> {
|
|||||||
futures_cost_model: FuturesTransactionCostModel,
|
futures_cost_model: FuturesTransactionCostModel,
|
||||||
futures_validation_config: FuturesValidationConfig,
|
futures_validation_config: FuturesValidationConfig,
|
||||||
execution_quote_loader: Option<ExecutionQuoteLoader>,
|
execution_quote_loader: Option<ExecutionQuoteLoader>,
|
||||||
|
execution_quote_request_cache:
|
||||||
|
BTreeSet<(NaiveDate, String, Option<NaiveTime>, Option<NaiveTime>)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, C, R> BacktestEngine<S, C, R> {
|
impl<S, C, R> BacktestEngine<S, C, R> {
|
||||||
@@ -369,6 +371,7 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
|||||||
futures_cost_model: FuturesTransactionCostModel::default(),
|
futures_cost_model: FuturesTransactionCostModel::default(),
|
||||||
futures_validation_config: FuturesValidationConfig::default(),
|
futures_validation_config: FuturesValidationConfig::default(),
|
||||||
execution_quote_loader: None,
|
execution_quote_loader: None,
|
||||||
|
execution_quote_request_cache: BTreeSet::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -523,20 +526,60 @@ where
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time = start_time.or_else(|| self.broker.intraday_execution_start_time());
|
let caller_start_time = start_time;
|
||||||
|
let caller_end_time = end_time;
|
||||||
|
let start_time = caller_start_time.or_else(|| self.broker.intraday_execution_start_time());
|
||||||
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
|
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
|
||||||
|
self.load_missing_execution_quotes(execution_date, start_time, end_time, &mut symbols)?;
|
||||||
|
|
||||||
|
if caller_start_time.is_none() && caller_end_time.is_none() {
|
||||||
|
for ((intent_start_time, intent_end_time), mut intent_symbols) in
|
||||||
|
algo_execution_quote_windows_for_decision(decision, portfolio)
|
||||||
|
{
|
||||||
|
self.load_missing_execution_quotes(
|
||||||
|
execution_date,
|
||||||
|
intent_start_time,
|
||||||
|
intent_end_time,
|
||||||
|
&mut intent_symbols,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_missing_execution_quotes(
|
||||||
|
&mut self,
|
||||||
|
execution_date: NaiveDate,
|
||||||
|
start_time: Option<NaiveTime>,
|
||||||
|
end_time: Option<NaiveTime>,
|
||||||
|
symbols: &mut BTreeSet<String>,
|
||||||
|
) -> Result<(), BacktestError> {
|
||||||
symbols.retain(|symbol| {
|
symbols.retain(|symbol| {
|
||||||
|
let request_key = (execution_date, symbol.clone(), start_time, end_time);
|
||||||
|
if self.execution_quote_request_cache.contains(&request_key) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if start_time.is_some() && end_time.is_none() {
|
||||||
|
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)
|
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
|
||||||
});
|
});
|
||||||
if symbols.is_empty() {
|
if symbols.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let requested_symbols = symbols.iter().cloned().collect::<Vec<_>>();
|
||||||
let request = ExecutionQuoteRequest {
|
let request = ExecutionQuoteRequest {
|
||||||
date: execution_date,
|
date: execution_date,
|
||||||
start_time,
|
start_time,
|
||||||
end_time,
|
end_time,
|
||||||
symbols,
|
symbols: std::mem::take(symbols),
|
||||||
};
|
};
|
||||||
let quotes = self
|
let quotes = self
|
||||||
.execution_quote_loader
|
.execution_quote_loader
|
||||||
@@ -544,6 +587,72 @@ where
|
|||||||
.expect("checked execution quote loader")
|
.expect("checked execution quote loader")
|
||||||
.as_mut()(request)?;
|
.as_mut()(request)?;
|
||||||
self.data.add_execution_quotes(quotes);
|
self.data.add_execution_quotes(quotes);
|
||||||
|
for symbol in requested_symbols {
|
||||||
|
self.execution_quote_request_cache.insert((
|
||||||
|
execution_date,
|
||||||
|
symbol,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_execution_quotes_for_portfolio_times(
|
||||||
|
&mut self,
|
||||||
|
execution_date: NaiveDate,
|
||||||
|
portfolio: &PortfolioState,
|
||||||
|
quote_times: &[NaiveTime],
|
||||||
|
) -> Result<(), BacktestError> {
|
||||||
|
if self.execution_quote_loader.is_none() || quote_times.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let base_symbols = portfolio
|
||||||
|
.positions()
|
||||||
|
.keys()
|
||||||
|
.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 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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1875,6 +1984,39 @@ where
|
|||||||
"on_day:pre",
|
"on_day:pre",
|
||||||
)?;
|
)?;
|
||||||
let on_day_open_orders = self.open_order_views();
|
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,
|
||||||
|
&decision_quote_times,
|
||||||
|
)?;
|
||||||
let mut decision = decision_slot
|
let mut decision = decision_slot
|
||||||
.map(|(decision_idx, decision_date)| {
|
.map(|(decision_idx, decision_date)| {
|
||||||
self.strategy.on_day(&StrategyContext {
|
self.strategy.on_day(&StrategyContext {
|
||||||
@@ -3211,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 {
|
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
|
||||||
decision.order_intents.iter().any(|intent| {
|
decision.order_intents.iter().any(|intent| {
|
||||||
matches!(
|
matches!(
|
||||||
intent,
|
intent,
|
||||||
OrderIntent::AlgoValue { .. }
|
OrderIntent::AlgoValue { .. }
|
||||||
| OrderIntent::AlgoPercent { .. }
|
| OrderIntent::AlgoPercent { .. }
|
||||||
|
| OrderIntent::TimedTargetValue { .. }
|
||||||
| OrderIntent::TargetPortfolioSmart {
|
| OrderIntent::TargetPortfolioSmart {
|
||||||
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
|
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
|
||||||
..
|
..
|
||||||
@@ -3249,6 +3410,7 @@ fn execution_quote_symbols_for_decision(
|
|||||||
| OrderIntent::TargetShares { symbol, .. }
|
| OrderIntent::TargetShares { symbol, .. }
|
||||||
| OrderIntent::LimitTargetShares { symbol, .. }
|
| OrderIntent::LimitTargetShares { symbol, .. }
|
||||||
| OrderIntent::TargetValue { symbol, .. }
|
| OrderIntent::TargetValue { symbol, .. }
|
||||||
|
| OrderIntent::TimedTargetValue { symbol, .. }
|
||||||
| OrderIntent::LimitTargetValue { symbol, .. }
|
| OrderIntent::LimitTargetValue { symbol, .. }
|
||||||
| OrderIntent::Value { symbol, .. }
|
| OrderIntent::Value { symbol, .. }
|
||||||
| OrderIntent::LimitValue { symbol, .. }
|
| OrderIntent::LimitValue { symbol, .. }
|
||||||
@@ -3283,6 +3445,60 @@ fn execution_quote_symbols_for_decision(
|
|||||||
symbols
|
symbols
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn algo_execution_quote_windows_for_decision(
|
||||||
|
decision: &StrategyDecision,
|
||||||
|
portfolio: &PortfolioState,
|
||||||
|
) -> BTreeMap<(Option<NaiveTime>, Option<NaiveTime>), BTreeSet<String>> {
|
||||||
|
let mut groups = BTreeMap::<(Option<NaiveTime>, Option<NaiveTime>), BTreeSet<String>>::new();
|
||||||
|
for intent in &decision.order_intents {
|
||||||
|
match intent {
|
||||||
|
OrderIntent::AlgoValue {
|
||||||
|
symbol,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| OrderIntent::AlgoPercent {
|
||||||
|
symbol,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| OrderIntent::TimedTargetValue {
|
||||||
|
symbol,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
if start_time.is_some() || end_time.is_some() {
|
||||||
|
groups
|
||||||
|
.entry((*start_time, *end_time))
|
||||||
|
.or_default()
|
||||||
|
.insert(symbol.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OrderIntent::TargetPortfolioSmart {
|
||||||
|
target_weights,
|
||||||
|
order_prices:
|
||||||
|
Some(TargetPortfolioOrderPricing::AlgoOrder {
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
..
|
||||||
|
}),
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
if start_time.is_some() || end_time.is_some() {
|
||||||
|
let symbols = groups.entry((*start_time, *end_time)).or_default();
|
||||||
|
symbols.extend(portfolio.positions().keys().cloned());
|
||||||
|
symbols.extend(target_weights.keys().cloned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groups
|
||||||
|
}
|
||||||
|
|
||||||
fn collect_scheduled_decisions<S: Strategy>(
|
fn collect_scheduled_decisions<S: Strategy>(
|
||||||
strategy: &mut S,
|
strategy: &mut S,
|
||||||
scheduler: &Scheduler<'_>,
|
scheduler: &Scheduler<'_>,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -5,9 +5,10 @@ use serde::{Deserialize, Serialize};
|
|||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
|
DynamicSlippageConfig, MatchingType, PlatformAccountActionKind, PlatformExplicitActionStage,
|
||||||
PlatformExplicitOrderKind, PlatformExprStrategyConfig, PlatformRebalanceSchedule,
|
PlatformExplicitCancelKind, PlatformExplicitOrderKind, PlatformExprStrategyConfig,
|
||||||
PlatformScheduleFrequency, PlatformTradeAction, PlatformUniverseActionKind, ScheduleTimeRule,
|
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
||||||
|
PlatformUniverseActionKind, ScheduleTimeRule, SlippageModel,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
@@ -22,6 +23,10 @@ pub struct StrategyRuntimeSpec {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub universe: Option<StrategyUniverseSpec>,
|
pub universe: Option<StrategyUniverseSpec>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub rebalance: Option<StrategyRebalanceSpec>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub trade_times: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
pub signal_symbol: Option<String>,
|
pub signal_symbol: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub execution: Option<StrategyExecutionSpec>,
|
pub execution: Option<StrategyExecutionSpec>,
|
||||||
@@ -49,6 +54,13 @@ pub struct StrategyUniverseSpec {
|
|||||||
pub exclude: Vec<String>,
|
pub exclude: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct StrategyRebalanceSpec {
|
||||||
|
#[serde(default)]
|
||||||
|
pub trade_times: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct StrategyExecutionSpec {
|
pub struct StrategyExecutionSpec {
|
||||||
@@ -128,6 +140,8 @@ pub struct StrategyEngineConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub dividend_reinvestment: Option<bool>,
|
pub dividend_reinvestment: Option<bool>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub weak_market_shrink_overweight_threshold: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
|
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub skip_windows: Vec<SkipWindowConfig>,
|
pub skip_windows: Vec<SkipWindowConfig>,
|
||||||
@@ -165,6 +179,10 @@ pub struct MovingAverageFilterConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub long_days: Option<usize>,
|
pub long_days: Option<usize>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub volume_short_days: Option<usize>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub volume_long_days: Option<usize>,
|
||||||
|
#[serde(default)]
|
||||||
pub rsi_rate: Option<f64>,
|
pub rsi_rate: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,6 +302,14 @@ pub struct StrategyExpressionTradingConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub retry_empty_rebalance: Option<bool>,
|
pub retry_empty_rebalance: Option<bool>,
|
||||||
#[serde(default)]
|
#[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>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub release_slot_on_exit_signal: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
pub subscription_guard_required: Option<bool>,
|
pub subscription_guard_required: Option<bool>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub actions: Vec<StrategyExpressionActionConfig>,
|
pub actions: Vec<StrategyExpressionActionConfig>,
|
||||||
@@ -384,6 +410,97 @@ fn apply_cost_overrides(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalize_model_name(value: &str) -> String {
|
||||||
|
value.trim().to_ascii_lowercase().replace('-', "_")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_matching_type(value: Option<&str>) -> Option<MatchingType> {
|
||||||
|
match normalize_model_name(value?).as_str() {
|
||||||
|
"open_auction" => Some(MatchingType::OpenAuction),
|
||||||
|
"current_bar_close" => Some(MatchingType::CurrentBarClose),
|
||||||
|
"next_bar_open" => Some(MatchingType::NextBarOpen),
|
||||||
|
"next_tick_last" => Some(MatchingType::NextTickLast),
|
||||||
|
"next_tick_best_own" => Some(MatchingType::NextTickBestOwn),
|
||||||
|
"next_tick_best_counterparty" => Some(MatchingType::NextTickBestCounterparty),
|
||||||
|
"counterparty_offer" => Some(MatchingType::CounterpartyOffer),
|
||||||
|
"vwap" => Some(MatchingType::Vwap),
|
||||||
|
"twap" => Some(MatchingType::Twap),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_slippage_model(
|
||||||
|
model: Option<&str>,
|
||||||
|
value: Option<f64>,
|
||||||
|
impact_coefficient: Option<f64>,
|
||||||
|
volatility_coefficient: Option<f64>,
|
||||||
|
max_value: Option<f64>,
|
||||||
|
) -> Option<SlippageModel> {
|
||||||
|
let value = valid_non_negative(value);
|
||||||
|
let impact_coefficient = valid_non_negative(impact_coefficient);
|
||||||
|
let volatility_coefficient = valid_non_negative(volatility_coefficient);
|
||||||
|
let max_value = valid_non_negative(max_value);
|
||||||
|
let model = model
|
||||||
|
.map(normalize_model_name)
|
||||||
|
.filter(|item| !item.is_empty())
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
if value.is_some_and(|item| item > 0.0) {
|
||||||
|
"price_ratio".to_string()
|
||||||
|
} else {
|
||||||
|
"none".to_string()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
match model.as_str() {
|
||||||
|
"none" => Some(SlippageModel::None),
|
||||||
|
"price_ratio" => Some(SlippageModel::PriceRatio(value.unwrap_or(0.0))),
|
||||||
|
"tick_size" => Some(SlippageModel::TickSize(value.unwrap_or(0.0))),
|
||||||
|
"limit_price" => Some(SlippageModel::LimitPrice),
|
||||||
|
"dynamic" | "dynamic_volume_volatility" => {
|
||||||
|
Some(SlippageModel::Dynamic(DynamicSlippageConfig::new(
|
||||||
|
impact_coefficient.unwrap_or(0.5),
|
||||||
|
volatility_coefficient.unwrap_or(0.3),
|
||||||
|
max_value.or(value).unwrap_or(0.01),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_execution_behavior_overrides(
|
||||||
|
cfg: &mut PlatformExprStrategyConfig,
|
||||||
|
matching_type: Option<&str>,
|
||||||
|
slippage_model: Option<&str>,
|
||||||
|
slippage_value: Option<f64>,
|
||||||
|
slippage_impact_coefficient: Option<f64>,
|
||||||
|
slippage_volatility_coefficient: Option<f64>,
|
||||||
|
slippage_max_value: Option<f64>,
|
||||||
|
strict_value_budget: Option<bool>,
|
||||||
|
) {
|
||||||
|
if let Some(matching_type) = parse_matching_type(matching_type) {
|
||||||
|
cfg.matching_type = matching_type;
|
||||||
|
}
|
||||||
|
if slippage_model.is_some()
|
||||||
|
|| slippage_value.is_some()
|
||||||
|
|| slippage_impact_coefficient.is_some()
|
||||||
|
|| slippage_volatility_coefficient.is_some()
|
||||||
|
|| slippage_max_value.is_some()
|
||||||
|
{
|
||||||
|
if let Some(parsed) = parse_slippage_model(
|
||||||
|
slippage_model,
|
||||||
|
slippage_value,
|
||||||
|
slippage_impact_coefficient,
|
||||||
|
slippage_volatility_coefficient,
|
||||||
|
slippage_max_value,
|
||||||
|
) {
|
||||||
|
cfg.slippage_model = parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(enabled) = strict_value_budget {
|
||||||
|
cfg.strict_value_budget = enabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
|
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
|
||||||
let bytes = text.as_bytes();
|
let bytes = text.as_bytes();
|
||||||
let mut end = start;
|
let mut end = start;
|
||||||
@@ -453,6 +570,20 @@ fn sorted_unique_positive(mut values: Vec<usize>) -> Vec<usize> {
|
|||||||
values
|
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(
|
fn infer_expression_windows(
|
||||||
cfg: &mut PlatformExprStrategyConfig,
|
cfg: &mut PlatformExprStrategyConfig,
|
||||||
benchmark_short_explicit: bool,
|
benchmark_short_explicit: bool,
|
||||||
@@ -534,6 +665,12 @@ pub fn platform_expr_config_from_spec(
|
|||||||
if let Some(refresh_rate) = engine.refresh_rate.filter(|value| *value > 0) {
|
if let Some(refresh_rate) = engine.refresh_rate.filter(|value| *value > 0) {
|
||||||
cfg.refresh_rate = refresh_rate;
|
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
|
if let Some(schedule) = engine
|
||||||
.rebalance_schedule
|
.rebalance_schedule
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -607,6 +744,16 @@ pub fn platform_expr_config_from_spec(
|
|||||||
engine.stamp_tax_rate_before_change,
|
engine.stamp_tax_rate_before_change,
|
||||||
engine.stamp_tax_rate_after_change,
|
engine.stamp_tax_rate_after_change,
|
||||||
);
|
);
|
||||||
|
apply_execution_behavior_overrides(
|
||||||
|
&mut cfg,
|
||||||
|
engine.matching_type.as_deref(),
|
||||||
|
engine.slippage_model.as_deref(),
|
||||||
|
engine.slippage_value,
|
||||||
|
engine.slippage_impact_coefficient,
|
||||||
|
engine.slippage_volatility_coefficient,
|
||||||
|
engine.slippage_max_value,
|
||||||
|
engine.strict_value_budget,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(spec_signal_symbol) = spec
|
if let Some(spec_signal_symbol) = spec
|
||||||
@@ -804,6 +951,26 @@ pub fn platform_expr_config_from_spec(
|
|||||||
if let Some(enabled) = trading.retry_empty_rebalance {
|
if let Some(enabled) = trading.retry_empty_rebalance {
|
||||||
cfg.retry_empty_rebalance = enabled;
|
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;
|
||||||
|
}
|
||||||
|
if let Some(enabled) = trading.delayed_limit_open_exit {
|
||||||
|
cfg.delayed_limit_open_exit_enabled = enabled;
|
||||||
|
if enabled {
|
||||||
|
cfg.delayed_limit_open_exit_time = trading
|
||||||
|
.delayed_limit_open_exit_time
|
||||||
|
.as_deref()
|
||||||
|
.and_then(|value| parse_schedule_clock_time(Some(value)));
|
||||||
|
} else {
|
||||||
|
cfg.delayed_limit_open_exit_time = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
if let Some(enabled) = spec
|
if let Some(enabled) = spec
|
||||||
.engine_config
|
.engine_config
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -864,10 +1031,36 @@ pub fn platform_expr_config_from_spec(
|
|||||||
}
|
}
|
||||||
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
||||||
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
||||||
cfg.stock_filter_expr = format!(
|
let short_days = stock_ma_filter
|
||||||
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid * {} > stock_ma_long",
|
.short_days
|
||||||
ratio, ratio
|
.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() {
|
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
||||||
let ratio = index_throttle.rsi_rate.unwrap_or(1.0001);
|
let ratio = index_throttle.rsi_rate.unwrap_or(1.0001);
|
||||||
@@ -930,6 +1123,28 @@ pub fn platform_expr_config_from_spec(
|
|||||||
cfg.retry_empty_rebalance = true;
|
cfg.retry_empty_rebalance = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let trade_times = spec_trade_times(spec);
|
||||||
|
if let Some(main_trade_time) = trade_times.last().copied() {
|
||||||
|
cfg.intraday_execution_time = Some(main_trade_time);
|
||||||
|
}
|
||||||
|
let delayed_limit_open_exit_explicit = spec
|
||||||
|
.runtime_expressions
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|runtime_expr| runtime_expr.trading.as_ref())
|
||||||
|
.and_then(|trading| trading.delayed_limit_open_exit)
|
||||||
|
.is_some();
|
||||||
|
if aiquant_compat && !delayed_limit_open_exit_explicit && trade_times.len() > 1 {
|
||||||
|
let delayed_time = trade_times[0];
|
||||||
|
if trade_times
|
||||||
|
.last()
|
||||||
|
.copied()
|
||||||
|
.map(|main_time| main_time != delayed_time)
|
||||||
|
.unwrap_or(true)
|
||||||
|
{
|
||||||
|
cfg.delayed_limit_open_exit_enabled = true;
|
||||||
|
cfg.delayed_limit_open_exit_time = Some(delayed_time);
|
||||||
|
}
|
||||||
|
}
|
||||||
if let Some(execution) = spec.execution.as_ref() {
|
if let Some(execution) = spec.execution.as_ref() {
|
||||||
apply_cost_overrides(
|
apply_cost_overrides(
|
||||||
&mut cfg,
|
&mut cfg,
|
||||||
@@ -938,6 +1153,23 @@ pub fn platform_expr_config_from_spec(
|
|||||||
execution.stamp_tax_rate_before_change,
|
execution.stamp_tax_rate_before_change,
|
||||||
execution.stamp_tax_rate_after_change,
|
execution.stamp_tax_rate_after_change,
|
||||||
);
|
);
|
||||||
|
apply_execution_behavior_overrides(
|
||||||
|
&mut cfg,
|
||||||
|
execution.matching_type.as_deref(),
|
||||||
|
execution.slippage_model.as_deref(),
|
||||||
|
execution.slippage_value,
|
||||||
|
execution.slippage_impact_coefficient,
|
||||||
|
execution.slippage_volatility_coefficient,
|
||||||
|
execution.slippage_max_value,
|
||||||
|
execution.strict_value_budget,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if cfg.aiquant_transaction_cost
|
||||||
|
&& cfg
|
||||||
|
.minimum_commission
|
||||||
|
.is_some_and(|value| value.is_finite() && value <= 0.0)
|
||||||
|
{
|
||||||
|
cfg.minimum_commission = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg
|
cfg
|
||||||
@@ -1015,6 +1247,24 @@ fn parse_schedule_clock_time(raw: Option<&str>) -> Option<NaiveTime> {
|
|||||||
.or_else(|| NaiveTime::parse_from_str(value, "%H:%M").ok())
|
.or_else(|| NaiveTime::parse_from_str(value, "%H:%M").ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_trade_times(raw: &[String]) -> Vec<NaiveTime> {
|
||||||
|
raw.iter()
|
||||||
|
.filter_map(|item| parse_schedule_clock_time(Some(item.as_str())))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spec_trade_times(spec: &StrategyRuntimeSpec) -> Vec<NaiveTime> {
|
||||||
|
let rebalance_times = spec
|
||||||
|
.rebalance
|
||||||
|
.as_ref()
|
||||||
|
.map(|rebalance| parse_trade_times(&rebalance.trade_times))
|
||||||
|
.unwrap_or_default();
|
||||||
|
if !rebalance_times.is_empty() {
|
||||||
|
return rebalance_times;
|
||||||
|
}
|
||||||
|
parse_trade_times(&spec.trade_times)
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_platform_trade_action(
|
fn parse_platform_trade_action(
|
||||||
action: &StrategyExpressionActionConfig,
|
action: &StrategyExpressionActionConfig,
|
||||||
) -> Option<PlatformTradeAction> {
|
) -> Option<PlatformTradeAction> {
|
||||||
@@ -1335,6 +1585,7 @@ mod tests {
|
|||||||
"rotationEnabled": false,
|
"rotationEnabled": false,
|
||||||
"dailyTopUp": true,
|
"dailyTopUp": true,
|
||||||
"retryEmptyRebalance": true,
|
"retryEmptyRebalance": true,
|
||||||
|
"weakMarketShrinkOverweightThreshold": 1.1,
|
||||||
"stage": "open_auction",
|
"stage": "open_auction",
|
||||||
"actions": [
|
"actions": [
|
||||||
{
|
{
|
||||||
@@ -1358,6 +1609,7 @@ mod tests {
|
|||||||
assert!(!cfg.rotation_enabled);
|
assert!(!cfg.rotation_enabled);
|
||||||
assert!(cfg.daily_top_up_enabled);
|
assert!(cfg.daily_top_up_enabled);
|
||||||
assert!(cfg.retry_empty_rebalance);
|
assert!(cfg.retry_empty_rebalance);
|
||||||
|
assert_eq!(cfg.weak_market_shrink_overweight_threshold, Some(1.1));
|
||||||
assert!(!cfg.calendar_rebalance_interval);
|
assert!(!cfg.calendar_rebalance_interval);
|
||||||
assert!(cfg.aiquant_transaction_cost);
|
assert!(cfg.aiquant_transaction_cost);
|
||||||
assert_eq!(cfg.explicit_actions.len(), 1);
|
assert_eq!(cfg.explicit_actions.len(), 1);
|
||||||
@@ -1367,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]
|
#[test]
|
||||||
fn parses_execution_cost_overrides_into_platform_config() {
|
fn parses_execution_cost_overrides_into_platform_config() {
|
||||||
let spec = serde_json::json!({
|
let spec = serde_json::json!({
|
||||||
@@ -1391,6 +1656,74 @@ mod tests {
|
|||||||
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
|
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_execution_slippage_overrides_into_platform_config() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": {
|
||||||
|
"compatibilityProfile": "aiquant_rqalpha",
|
||||||
|
"matchingType": "next_tick_last",
|
||||||
|
"slippageModel": "price_ratio",
|
||||||
|
"slippageValue": 0.001,
|
||||||
|
"strictValueBudget": true
|
||||||
|
},
|
||||||
|
"engineConfig": {
|
||||||
|
"matchingType": "current_bar_close",
|
||||||
|
"slippageModel": "none",
|
||||||
|
"slippageValue": 0.0,
|
||||||
|
"strictValueBudget": false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert_eq!(cfg.matching_type, MatchingType::NextTickLast);
|
||||||
|
assert_eq!(cfg.slippage_model, SlippageModel::PriceRatio(0.001));
|
||||||
|
assert!(cfg.strict_value_budget);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_dynamic_slippage_into_platform_config() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": {
|
||||||
|
"slippageModel": "dynamic",
|
||||||
|
"slippageImpactCoefficient": 0.6,
|
||||||
|
"slippageVolatilityCoefficient": 0.2,
|
||||||
|
"slippageMaxValue": 0.015
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
cfg.slippage_model,
|
||||||
|
SlippageModel::Dynamic(DynamicSlippageConfig::new(0.6, 0.2, 0.015))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
|
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
|
||||||
let spec = serde_json::json!({
|
let spec = serde_json::json!({
|
||||||
@@ -1497,4 +1830,73 @@ mod tests {
|
|||||||
assert!(!cfg.calendar_rebalance_interval);
|
assert!(!cfg.calendar_rebalance_interval);
|
||||||
assert!(cfg.aiquant_transaction_cost);
|
assert!(cfg.aiquant_transaction_cost);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_aiquant_rebalance_trade_times_for_delayed_limit_exit() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
|
||||||
|
"rebalance": { "tradeTimes": ["10:31", "10:40"] },
|
||||||
|
"runtimeExpressions": {
|
||||||
|
"schedule": { "frequency": "daily", "time": "10:40" }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
cfg.intraday_execution_time,
|
||||||
|
Some(NaiveTime::from_hms_opt(10, 40, 0).unwrap())
|
||||||
|
);
|
||||||
|
assert!(cfg.delayed_limit_open_exit_enabled);
|
||||||
|
assert_eq!(
|
||||||
|
cfg.delayed_limit_open_exit_time,
|
||||||
|
Some(NaiveTime::from_hms_opt(10, 31, 0).unwrap())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_explicit_delayed_limit_open_exit() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
|
||||||
|
"runtimeExpressions": {
|
||||||
|
"schedule": { "frequency": "daily", "time": "10:40" },
|
||||||
|
"trading": {
|
||||||
|
"delayedLimitOpenExit": true,
|
||||||
|
"delayedLimitOpenExitTime": "10:31"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
cfg.intraday_execution_time,
|
||||||
|
Some(NaiveTime::from_hms_opt(10, 40, 0).unwrap())
|
||||||
|
);
|
||||||
|
assert!(cfg.delayed_limit_open_exit_enabled);
|
||||||
|
assert_eq!(
|
||||||
|
cfg.delayed_limit_open_exit_time,
|
||||||
|
Some(NaiveTime::from_hms_opt(10, 31, 0).unwrap())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_delayed_limit_open_exit_false_overrides_aiquant_trade_times() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
|
||||||
|
"rebalance": { "tradeTimes": ["10:31", "10:40"] },
|
||||||
|
"runtimeExpressions": {
|
||||||
|
"schedule": { "frequency": "daily", "time": "10:40" },
|
||||||
|
"trading": {
|
||||||
|
"delayedLimitOpenExit": false,
|
||||||
|
"delayedLimitOpenExitTime": "10:31"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert!(!cfg.delayed_limit_open_exit_enabled);
|
||||||
|
assert_eq!(cfg.delayed_limit_open_exit_time, None);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ pub struct Position {
|
|||||||
pub average_cost: f64,
|
pub average_cost: f64,
|
||||||
pub last_price: f64,
|
pub last_price: f64,
|
||||||
pub realized_pnl: f64,
|
pub realized_pnl: f64,
|
||||||
|
realized_entry_pnl: f64,
|
||||||
pub trading_pnl: f64,
|
pub trading_pnl: f64,
|
||||||
pub position_pnl: f64,
|
pub position_pnl: f64,
|
||||||
pub dividend_receivable: f64,
|
pub dividend_receivable: f64,
|
||||||
@@ -44,6 +45,7 @@ impl Position {
|
|||||||
average_cost: 0.0,
|
average_cost: 0.0,
|
||||||
last_price: 0.0,
|
last_price: 0.0,
|
||||||
realized_pnl: 0.0,
|
realized_pnl: 0.0,
|
||||||
|
realized_entry_pnl: 0.0,
|
||||||
trading_pnl: 0.0,
|
trading_pnl: 0.0,
|
||||||
position_pnl: 0.0,
|
position_pnl: 0.0,
|
||||||
dividend_receivable: 0.0,
|
dividend_receivable: 0.0,
|
||||||
@@ -66,6 +68,16 @@ impl Position {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn buy(&mut self, date: NaiveDate, quantity: u32, price: f64) {
|
pub fn buy(&mut self, date: NaiveDate, quantity: u32, price: f64) {
|
||||||
|
self.buy_with_mark_price(date, quantity, price, price);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn buy_with_mark_price(
|
||||||
|
&mut self,
|
||||||
|
date: NaiveDate,
|
||||||
|
quantity: u32,
|
||||||
|
execution_price: f64,
|
||||||
|
mark_price: f64,
|
||||||
|
) {
|
||||||
if quantity == 0 {
|
if quantity == 0 {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -73,19 +85,28 @@ impl Position {
|
|||||||
self.lots.push(PositionLot {
|
self.lots.push(PositionLot {
|
||||||
acquired_date: date,
|
acquired_date: date,
|
||||||
quantity,
|
quantity,
|
||||||
entry_price: price,
|
entry_price: execution_price,
|
||||||
price,
|
price: execution_price,
|
||||||
});
|
});
|
||||||
self.quantity += quantity;
|
self.quantity += quantity;
|
||||||
self.last_price = price;
|
self.last_price = normalized_mark_price(mark_price, execution_price);
|
||||||
self.day_trade_quantity_delta += quantity as i32;
|
self.day_trade_quantity_delta += quantity as i32;
|
||||||
self.day_buy_quantity += quantity;
|
self.day_buy_quantity += quantity;
|
||||||
self.day_buy_value += price * quantity as f64;
|
self.day_buy_value += execution_price * quantity as f64;
|
||||||
self.recalculate_average_cost();
|
self.recalculate_average_cost();
|
||||||
self.refresh_day_pnl();
|
self.refresh_day_pnl();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sell(&mut self, quantity: u32, price: f64) -> Result<f64, String> {
|
pub fn sell(&mut self, quantity: u32, price: f64) -> Result<f64, String> {
|
||||||
|
self.sell_with_mark_price(quantity, price, price)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sell_with_mark_price(
|
||||||
|
&mut self,
|
||||||
|
quantity: u32,
|
||||||
|
execution_price: f64,
|
||||||
|
mark_price: f64,
|
||||||
|
) -> Result<f64, String> {
|
||||||
if quantity > self.quantity {
|
if quantity > self.quantity {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"sell quantity {} exceeds current quantity {} for {}",
|
"sell quantity {} exceeds current quantity {} for {}",
|
||||||
@@ -95,6 +116,7 @@ impl Position {
|
|||||||
|
|
||||||
let mut remaining = quantity;
|
let mut remaining = quantity;
|
||||||
let mut realized = 0.0;
|
let mut realized = 0.0;
|
||||||
|
let mut realized_entry = 0.0;
|
||||||
|
|
||||||
while remaining > 0 {
|
while remaining > 0 {
|
||||||
let Some(first_lot) = self.lots.first_mut() else {
|
let Some(first_lot) = self.lots.first_mut() else {
|
||||||
@@ -102,7 +124,8 @@ impl Position {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let lot_sell = remaining.min(first_lot.quantity);
|
let lot_sell = remaining.min(first_lot.quantity);
|
||||||
realized += (price - first_lot.price) * lot_sell as f64;
|
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;
|
first_lot.quantity -= lot_sell;
|
||||||
remaining -= lot_sell;
|
remaining -= lot_sell;
|
||||||
|
|
||||||
@@ -112,11 +135,12 @@ impl Position {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.quantity -= quantity;
|
self.quantity -= quantity;
|
||||||
self.last_price = price;
|
self.last_price = normalized_mark_price(mark_price, execution_price);
|
||||||
self.realized_pnl += realized;
|
self.realized_pnl += realized;
|
||||||
|
self.realized_entry_pnl += realized_entry;
|
||||||
self.day_trade_quantity_delta -= quantity as i32;
|
self.day_trade_quantity_delta -= quantity as i32;
|
||||||
self.day_sell_quantity += quantity;
|
self.day_sell_quantity += quantity;
|
||||||
self.day_sell_value += price * quantity as f64;
|
self.day_sell_value += execution_price * quantity as f64;
|
||||||
self.recalculate_average_cost();
|
self.recalculate_average_cost();
|
||||||
self.refresh_day_pnl();
|
self.refresh_day_pnl();
|
||||||
Ok(realized)
|
Ok(realized)
|
||||||
@@ -138,10 +162,21 @@ impl Position {
|
|||||||
(self.last_price - self.average_cost) * self.quantity as f64
|
(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 {
|
pub fn pnl(&self) -> f64 {
|
||||||
self.realized_pnl + self.unrealized_pnl()
|
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 {
|
pub fn day_start_quantity(&self) -> u32 {
|
||||||
self.day_start_quantity
|
self.day_start_quantity
|
||||||
}
|
}
|
||||||
@@ -356,6 +391,14 @@ impl Position {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalized_mark_price(mark_price: f64, fallback: f64) -> f64 {
|
||||||
|
if mark_price.is_finite() && mark_price > 0.0 {
|
||||||
|
mark_price
|
||||||
|
} else {
|
||||||
|
fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct PortfolioState {
|
pub struct PortfolioState {
|
||||||
initial_cash: f64,
|
initial_cash: f64,
|
||||||
@@ -738,33 +781,40 @@ impl PortfolioState {
|
|||||||
self.positions
|
self.positions
|
||||||
.values()
|
.values()
|
||||||
.filter(|position| position.quantity > 0)
|
.filter(|position| position.quantity > 0)
|
||||||
.map(|position| HoldingSummary {
|
.map(|position| {
|
||||||
date,
|
let market_value = position.market_value();
|
||||||
symbol: position.symbol.clone(),
|
let entry_average_cost = position
|
||||||
quantity: position.quantity,
|
.average_entry_price()
|
||||||
average_cost: position.average_cost,
|
.filter(|value| value.is_finite() && *value > 0.0)
|
||||||
last_price: position.last_price,
|
.unwrap_or(position.average_cost);
|
||||||
market_value: position.market_value(),
|
HoldingSummary {
|
||||||
value_percent: if total_equity > 0.0 {
|
date,
|
||||||
position.market_value() / total_equity
|
symbol: position.symbol.clone(),
|
||||||
} else {
|
quantity: position.quantity,
|
||||||
0.0
|
average_cost: entry_average_cost,
|
||||||
},
|
last_price: position.last_price,
|
||||||
unrealized_pnl: position.unrealized_pnl(),
|
market_value,
|
||||||
realized_pnl: position.realized_pnl,
|
value_percent: if total_equity > 0.0 {
|
||||||
pnl: position.pnl(),
|
market_value / total_equity
|
||||||
trading_pnl: position.trading_pnl,
|
} else {
|
||||||
position_pnl: position.position_pnl,
|
0.0
|
||||||
dividend_receivable: position.dividend_receivable,
|
},
|
||||||
old_quantity: position.day_start_quantity(),
|
unrealized_pnl: position.unrealized_entry_pnl(),
|
||||||
bought_quantity: position.bought_quantity(),
|
realized_pnl: position.realized_entry_pnl,
|
||||||
sold_quantity: position.sold_quantity(),
|
pnl: position.entry_pnl(),
|
||||||
buy_avg_price: position.buy_avg_price(),
|
trading_pnl: position.trading_pnl,
|
||||||
sell_avg_price: position.sell_avg_price(),
|
position_pnl: position.position_pnl,
|
||||||
bought_value: position.bought_value(),
|
dividend_receivable: position.dividend_receivable,
|
||||||
sold_value: position.sold_value(),
|
old_quantity: position.day_start_quantity(),
|
||||||
transaction_cost: position.transaction_cost(),
|
bought_quantity: position.bought_quantity(),
|
||||||
day_trade_quantity_delta: position.day_trade_quantity_delta(),
|
sold_quantity: position.sold_quantity(),
|
||||||
|
buy_avg_price: position.buy_avg_price(),
|
||||||
|
sell_avg_price: position.sell_avg_price(),
|
||||||
|
bought_value: position.bought_value(),
|
||||||
|
sold_value: position.sold_value(),
|
||||||
|
transaction_cost: position.transaction_cost(),
|
||||||
|
day_trade_quantity_delta: position.day_trade_quantity_delta(),
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -788,6 +838,7 @@ impl PortfolioState {
|
|||||||
let old_quantity = old_position.quantity;
|
let old_quantity = old_position.quantity;
|
||||||
let last_price = old_position.last_price;
|
let last_price = old_position.last_price;
|
||||||
let realized_pnl = old_position.realized_pnl;
|
let realized_pnl = old_position.realized_pnl;
|
||||||
|
let realized_entry_pnl = old_position.realized_entry_pnl;
|
||||||
let mut converted_lots = old_position
|
let mut converted_lots = old_position
|
||||||
.lots
|
.lots
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -824,6 +875,7 @@ impl PortfolioState {
|
|||||||
successor.lots.extend(converted_lots);
|
successor.lots.extend(converted_lots);
|
||||||
successor.quantity = successor.lots.iter().map(|lot| lot.quantity).sum();
|
successor.quantity = successor.lots.iter().map(|lot| lot.quantity).sum();
|
||||||
successor.realized_pnl += realized_pnl;
|
successor.realized_pnl += realized_pnl;
|
||||||
|
successor.realized_entry_pnl += realized_entry_pnl;
|
||||||
if converted_last_price > 0.0 {
|
if converted_last_price > 0.0 {
|
||||||
successor.last_price = converted_last_price;
|
successor.last_price = converted_last_price;
|
||||||
}
|
}
|
||||||
@@ -903,6 +955,31 @@ mod tests {
|
|||||||
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
|
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]
|
#[test]
|
||||||
fn cash_dividend_can_preserve_avg_cost_for_aiquant_compatibility() {
|
fn cash_dividend_can_preserve_avg_cost_for_aiquant_compatibility() {
|
||||||
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||||
@@ -1009,6 +1086,7 @@ mod tests {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1095,6 +1173,7 @@ mod tests {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
|
|||||||
@@ -41,6 +41,21 @@ impl ChinaAShareRiskControl {
|
|||||||
candidate: &CandidateEligibility,
|
candidate: &CandidateEligibility,
|
||||||
market: &DailyMarketSnapshot,
|
market: &DailyMarketSnapshot,
|
||||||
instrument: Option<&Instrument>,
|
instrument: Option<&Instrument>,
|
||||||
|
) -> Option<&'static str> {
|
||||||
|
if let Some(reason) = Self::baseline_rejection_reason(date, candidate, market, instrument) {
|
||||||
|
return Some(reason);
|
||||||
|
}
|
||||||
|
if !candidate.allow_buy || !candidate.allow_sell {
|
||||||
|
return Some("trade_disabled");
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn baseline_rejection_reason(
|
||||||
|
date: NaiveDate,
|
||||||
|
candidate: &CandidateEligibility,
|
||||||
|
market: &DailyMarketSnapshot,
|
||||||
|
instrument: Option<&Instrument>,
|
||||||
) -> Option<&'static str> {
|
) -> Option<&'static str> {
|
||||||
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
|
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
|
||||||
return Some(reason);
|
return Some(reason);
|
||||||
@@ -60,9 +75,6 @@ impl ChinaAShareRiskControl {
|
|||||||
if candidate.is_one_yuan || market.day_open <= 1.0 {
|
if candidate.is_one_yuan || market.day_open <= 1.0 {
|
||||||
return Some("one_yuan");
|
return Some("one_yuan");
|
||||||
}
|
}
|
||||||
if !candidate.allow_buy || !candidate.allow_sell {
|
|
||||||
return Some("trade_disabled");
|
|
||||||
}
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,8 +85,7 @@ impl ChinaAShareRiskControl {
|
|||||||
instrument: Option<&Instrument>,
|
instrument: Option<&Instrument>,
|
||||||
check_price: f64,
|
check_price: f64,
|
||||||
) -> Option<&'static str> {
|
) -> Option<&'static str> {
|
||||||
if let Some(reason) = Self::selection_rejection_reason(date, candidate, market, instrument)
|
if let Some(reason) = Self::baseline_rejection_reason(date, candidate, market, instrument) {
|
||||||
{
|
|
||||||
return Some(reason);
|
return Some(reason);
|
||||||
}
|
}
|
||||||
if !candidate.allow_buy {
|
if !candidate.allow_buy {
|
||||||
@@ -100,9 +111,10 @@ impl ChinaAShareRiskControl {
|
|||||||
if market.paused || candidate.is_paused {
|
if market.paused || candidate.is_paused {
|
||||||
return Some("paused");
|
return Some("paused");
|
||||||
}
|
}
|
||||||
if !candidate.allow_sell {
|
// `allow_sell` is derived from the daily candidate snapshot and may
|
||||||
return Some("sell_disabled");
|
// 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) {
|
if market.is_at_lower_limit_price(check_price) {
|
||||||
return Some("open at or below lower limit");
|
return Some("open at or below lower limit");
|
||||||
}
|
}
|
||||||
@@ -123,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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -40,6 +40,15 @@ pub trait Strategy {
|
|||||||
fn schedule_rules(&self) -> Vec<ScheduleRule> {
|
fn schedule_rules(&self) -> Vec<ScheduleRule> {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
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(
|
fn on_scheduled(
|
||||||
&mut self,
|
&mut self,
|
||||||
_ctx: &StrategyContext<'_>,
|
_ctx: &StrategyContext<'_>,
|
||||||
@@ -980,6 +989,14 @@ pub enum OrderIntent {
|
|||||||
target_value: f64,
|
target_value: f64,
|
||||||
reason: String,
|
reason: String,
|
||||||
},
|
},
|
||||||
|
TimedTargetValue {
|
||||||
|
symbol: String,
|
||||||
|
target_value: f64,
|
||||||
|
style: AlgoOrderStyle,
|
||||||
|
start_time: Option<NaiveTime>,
|
||||||
|
end_time: Option<NaiveTime>,
|
||||||
|
reason: String,
|
||||||
|
},
|
||||||
LimitTargetValue {
|
LimitTargetValue {
|
||||||
symbol: String,
|
symbol: String,
|
||||||
target_value: f64,
|
target_value: f64,
|
||||||
@@ -1536,6 +1553,8 @@ pub struct OmniMicroCapConfig {
|
|||||||
pub stock_short_ma_days: usize,
|
pub stock_short_ma_days: usize,
|
||||||
pub stock_mid_ma_days: usize,
|
pub stock_mid_ma_days: usize,
|
||||||
pub stock_long_ma_days: usize,
|
pub stock_long_ma_days: usize,
|
||||||
|
pub stock_volume_short_ma_days: usize,
|
||||||
|
pub stock_volume_long_ma_days: usize,
|
||||||
pub rsi_rate: f64,
|
pub rsi_rate: f64,
|
||||||
pub trade_rate: f64,
|
pub trade_rate: f64,
|
||||||
pub stop_loss_ratio: f64,
|
pub stop_loss_ratio: f64,
|
||||||
@@ -1562,6 +1581,8 @@ impl OmniMicroCapConfig {
|
|||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
stock_mid_ma_days: 10,
|
stock_mid_ma_days: 10,
|
||||||
stock_long_ma_days: 20,
|
stock_long_ma_days: 20,
|
||||||
|
stock_volume_short_ma_days: 5,
|
||||||
|
stock_volume_long_ma_days: 60,
|
||||||
rsi_rate: 1.0001,
|
rsi_rate: 1.0001,
|
||||||
trade_rate: 0.5,
|
trade_rate: 0.5,
|
||||||
stop_loss_ratio: 0.93,
|
stop_loss_ratio: 0.93,
|
||||||
@@ -1590,6 +1611,8 @@ impl OmniMicroCapConfig {
|
|||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
stock_mid_ma_days: 10,
|
stock_mid_ma_days: 10,
|
||||||
stock_long_ma_days: 30,
|
stock_long_ma_days: 30,
|
||||||
|
stock_volume_short_ma_days: 5,
|
||||||
|
stock_volume_long_ma_days: 60,
|
||||||
rsi_rate: 1.0001,
|
rsi_rate: 1.0001,
|
||||||
trade_rate: 0.5,
|
trade_rate: 0.5,
|
||||||
stop_loss_ratio: 0.92,
|
stop_loss_ratio: 0.92,
|
||||||
@@ -2268,62 +2291,33 @@ impl OmniMicroCapStrategy {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
|
|
||||||
let ma_pass =
|
let ma_pass =
|
||||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
||||||
|
|
||||||
// Debug logging for ALL stocks on first decision date
|
|
||||||
static DEBUG_DATE: std::sync::Mutex<Option<NaiveDate>> = std::sync::Mutex::new(None);
|
|
||||||
let mut debug_date = DEBUG_DATE.lock().unwrap();
|
|
||||||
let should_debug = if let Some(d) = *debug_date {
|
|
||||||
d == date
|
|
||||||
} else {
|
|
||||||
*debug_date = Some(date);
|
|
||||||
true
|
|
||||||
};
|
|
||||||
|
|
||||||
if should_debug {
|
|
||||||
eprintln!(
|
|
||||||
"[MA_FILTER] {} cap={:.2} ma5={:.4} ma10={:.4} ma30={:.4} ma10*rsi={:.4} pass={} ({}>{:.4}? {} && {:.4}>{}? {})",
|
|
||||||
symbol,
|
|
||||||
ctx.data.market_decision_close(date, symbol).unwrap_or(0.0),
|
|
||||||
ma_short,
|
|
||||||
ma_mid,
|
|
||||||
ma_long,
|
|
||||||
ma_mid * self.config.rsi_rate,
|
|
||||||
ma_pass,
|
|
||||||
ma_short,
|
|
||||||
ma_mid * self.config.rsi_rate,
|
|
||||||
ma_short > ma_mid * self.config.rsi_rate,
|
|
||||||
ma_mid * self.config.rsi_rate,
|
|
||||||
ma_long,
|
|
||||||
ma_mid * self.config.rsi_rate > ma_long
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if !ma_pass {
|
if !ma_pass {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
|
|
||||||
if self.config.strategy_name.contains("aiquant")
|
if self.config.strategy_name.contains("aiquant")
|
||||||
|| self.config.strategy_name.contains("AiQuant")
|
|| self.config.strategy_name.contains("AiQuant")
|
||||||
|| self.config.strategy_name.contains("omni")
|
|| self.config.strategy_name.contains("omni")
|
||||||
{
|
{
|
||||||
let Some(volume_ma5) = ctx
|
let Some(volume_ma5) = ctx.data.market_decision_volume_moving_average(
|
||||||
.data
|
date,
|
||||||
.market_decision_volume_moving_average(date, symbol, 5)
|
symbol,
|
||||||
else {
|
self.config.stock_volume_short_ma_days,
|
||||||
|
) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
let Some(volume_ma60) = ctx
|
let Some(volume_ma_long) = ctx.data.market_decision_volume_moving_average(
|
||||||
.data
|
date,
|
||||||
.market_decision_volume_moving_average(date, symbol, 60)
|
symbol,
|
||||||
else {
|
self.config.stock_volume_long_ma_days,
|
||||||
|
) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
if volume_ma5 >= volume_ma60 {
|
if volume_ma5 >= volume_ma_long {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2516,18 +2510,6 @@ fn omni_truth_stock_list_candidates() -> Vec<PathBuf> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let suffix = PathBuf::from("data/demo/engine_truth_stock_list.csv");
|
|
||||||
let manifest_root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
|
||||||
push_unique_truth_path(
|
|
||||||
&mut candidates,
|
|
||||||
manifest_root.join("../../../").join(&suffix),
|
|
||||||
);
|
|
||||||
if let Ok(current_dir) = env::current_dir() {
|
|
||||||
for ancestor in current_dir.ancestors() {
|
|
||||||
push_unique_truth_path(&mut candidates, ancestor.join(&suffix));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
candidates
|
candidates
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2696,10 +2678,6 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
};
|
};
|
||||||
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||||
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
||||||
eprintln!(
|
|
||||||
"[DEBUG] date={} current_index={:.2} prev_index={:.2} band=[{:.0}, {:.0}]",
|
|
||||||
date, index_level, prev_index_level, band_low, band_high
|
|
||||||
);
|
|
||||||
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
||||||
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||||
let mut projected = ctx.portfolio.clone();
|
let mut projected = ctx.portfolio.clone();
|
||||||
@@ -2723,7 +2701,8 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
+ self.stop_loss_tolerance(market);
|
+ self.stop_loss_tolerance(market);
|
||||||
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
|
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
|
||||||
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
|
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
|
||||||
if stop_hit || profit_hit {
|
let at_upper_limit = market.is_at_upper_limit_price(current_price);
|
||||||
|
if stop_hit || (profit_hit && !at_upper_limit) {
|
||||||
let sell_reason = if stop_hit {
|
let sell_reason = if stop_hit {
|
||||||
"stop_loss_exit"
|
"stop_loss_exit"
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -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: "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: "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_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: "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() },
|
ManualField { name: "listed_days".to_string(), field_type: "int".to_string(), detail: "上市天数。".to_string() },
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ fn candidate() -> CandidateEligibility {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +176,7 @@ fn china_rule_hooks_block_buy_at_limit_up_and_sell_at_limit_down() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
|
fn china_rule_hooks_use_strict_price_limits() {
|
||||||
let hooks = ChinaEquityRuleHooks;
|
let hooks = ChinaEquityRuleHooks;
|
||||||
let candidate = candidate();
|
let candidate = candidate();
|
||||||
|
|
||||||
@@ -184,6 +185,13 @@ fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
|
|||||||
..snapshot(10.9995, 11.0, 9.0)
|
..snapshot(10.9995, 11.0, 9.0)
|
||||||
};
|
};
|
||||||
let buy_check = hooks.can_buy(d(2024, 1, 3), &near_upper, &candidate, PriceField::Open);
|
let buy_check = hooks.can_buy(d(2024, 1, 3), &near_upper, &candidate, PriceField::Open);
|
||||||
|
assert!(buy_check.allowed);
|
||||||
|
|
||||||
|
let exact_upper = DailyMarketSnapshot {
|
||||||
|
price_tick: 0.001,
|
||||||
|
..snapshot(11.0, 11.0, 9.0)
|
||||||
|
};
|
||||||
|
let buy_check = hooks.can_buy(d(2024, 1, 3), &exact_upper, &candidate, PriceField::Open);
|
||||||
assert!(!buy_check.allowed);
|
assert!(!buy_check.allowed);
|
||||||
|
|
||||||
let near_lower = DailyMarketSnapshot {
|
let near_lower = DailyMarketSnapshot {
|
||||||
@@ -199,6 +207,19 @@ fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
|
|||||||
&position,
|
&position,
|
||||||
PriceField::Open,
|
PriceField::Open,
|
||||||
);
|
);
|
||||||
|
assert!(sell_check.allowed);
|
||||||
|
|
||||||
|
let exact_lower = DailyMarketSnapshot {
|
||||||
|
price_tick: 0.001,
|
||||||
|
..snapshot(9.0, 11.0, 9.0)
|
||||||
|
};
|
||||||
|
let sell_check = hooks.can_sell(
|
||||||
|
d(2024, 1, 3),
|
||||||
|
&exact_lower,
|
||||||
|
&candidate,
|
||||||
|
&position,
|
||||||
|
PriceField::Open,
|
||||||
|
);
|
||||||
assert!(!sell_check.allowed);
|
assert!(!sell_check.allowed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -221,6 +221,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: ex_date,
|
date: ex_date,
|
||||||
@@ -232,6 +233,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: payable_date,
|
date: payable_date,
|
||||||
@@ -243,6 +245,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
|
|||||||
@@ -0,0 +1,646 @@
|
|||||||
|
use chrono::{Duration, NaiveDate, NaiveTime};
|
||||||
|
use fidc_core::{
|
||||||
|
BacktestConfig, BacktestEngine, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility,
|
||||||
|
ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet,
|
||||||
|
IntradayExecutionQuote, MatchingType, OrderIntent, PriceField, Strategy, StrategyContext,
|
||||||
|
StrategyDecision,
|
||||||
|
};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
|
||||||
|
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn t(hour: u32, minute: u32, second: u32) -> NaiveTime {
|
||||||
|
NaiveTime::from_hms_opt(hour, minute, second).expect("valid time")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct DecisionQuoteReader {
|
||||||
|
day_count: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Strategy for DecisionQuoteReader {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"decision_quote_reader"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decision_quote_times(&self) -> Vec<NaiveTime> {
|
||||||
|
vec![t(10, 40, 0)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_day(
|
||||||
|
&mut self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||||
|
self.day_count += 1;
|
||||||
|
if self.day_count == 1 {
|
||||||
|
return Ok(StrategyDecision {
|
||||||
|
order_intents: vec![OrderIntent::Value {
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
value: 5_000.0,
|
||||||
|
reason: "seed_position".to_string(),
|
||||||
|
}],
|
||||||
|
..StrategyDecision::default()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
ctx.portfolio.position("000001.SZ").is_some(),
|
||||||
|
"second day should carry the first day position"
|
||||||
|
);
|
||||||
|
let quote_loaded_before_decision = ctx
|
||||||
|
.data
|
||||||
|
.execution_quotes_on(ctx.execution_date, "000001.SZ")
|
||||||
|
.iter()
|
||||||
|
.any(|quote| quote.timestamp.time() == t(10, 39, 59) && quote.last_price == 11.0);
|
||||||
|
assert!(
|
||||||
|
quote_loaded_before_decision,
|
||||||
|
"engine must load declared decision quote before strategy.on_day"
|
||||||
|
);
|
||||||
|
Ok(StrategyDecision::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn engine_preloads_declared_decision_quotes_for_current_positions() {
|
||||||
|
let first = d(2026, 1, 5);
|
||||||
|
let second = d(2026, 1, 6);
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.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 mut engine = BacktestEngine::new(data, DecisionQuoteReader::default(), broker, config)
|
||||||
|
.with_execution_quote_loader(move |request| {
|
||||||
|
assert_eq!(
|
||||||
|
request.end_time, None,
|
||||||
|
"decision quote preload must request latest quote at or before start_time"
|
||||||
|
);
|
||||||
|
Ok(request
|
||||||
|
.symbols
|
||||||
|
.into_iter()
|
||||||
|
.map(|symbol| IntradayExecutionQuote {
|
||||||
|
date: request.date,
|
||||||
|
symbol,
|
||||||
|
timestamp: request.date.and_time(t(10, 39, 59)),
|
||||||
|
last_price: if request.date == second { 11.0 } else { 10.0 },
|
||||||
|
bid1: if request.date == second { 11.0 } else { 10.0 },
|
||||||
|
ask1: if request.date == second { 11.0 } else { 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()),
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Strategy for MultiTimeDecisionQuoteReader {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"multi_time_decision_quote_reader"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decision_quote_times(&self) -> Vec<NaiveTime> {
|
||||||
|
vec![t(10, 31, 0), t(10, 40, 0)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_day(
|
||||||
|
&mut self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||||
|
self.day_count += 1;
|
||||||
|
if self.day_count == 1 {
|
||||||
|
return Ok(StrategyDecision {
|
||||||
|
order_intents: vec![OrderIntent::Value {
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
value: 5_000.0,
|
||||||
|
reason: "seed_position".to_string(),
|
||||||
|
}],
|
||||||
|
..StrategyDecision::default()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let quote_times = ctx
|
||||||
|
.data
|
||||||
|
.execution_quotes_on(ctx.execution_date, "000001.SZ")
|
||||||
|
.iter()
|
||||||
|
.map(|quote| quote.timestamp.time())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert!(
|
||||||
|
quote_times.contains(&t(10, 30, 59)),
|
||||||
|
"10:31 decision quote must be loaded"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
quote_times.contains(&t(10, 39, 59)),
|
||||||
|
"10:40 decision quote must not be skipped because 10:31 was loaded"
|
||||||
|
);
|
||||||
|
Ok(StrategyDecision::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn engine_loads_distinct_decision_quote_times_on_same_day() {
|
||||||
|
let first = d(2026, 1, 5);
|
||||||
|
let second = d(2026, 1, 6);
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.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 requests = Arc::new(Mutex::new(Vec::<(NaiveDate, NaiveTime)>::new()));
|
||||||
|
let captured_requests = Arc::clone(&requests);
|
||||||
|
let mut engine = BacktestEngine::new(
|
||||||
|
data,
|
||||||
|
MultiTimeDecisionQuoteReader::default(),
|
||||||
|
broker,
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
.with_execution_quote_loader(move |request| {
|
||||||
|
let start_time = request
|
||||||
|
.start_time
|
||||||
|
.expect("decision quote loader request must include start_time");
|
||||||
|
captured_requests
|
||||||
|
.lock()
|
||||||
|
.expect("request mutex")
|
||||||
|
.push((request.date, start_time));
|
||||||
|
Ok(request
|
||||||
|
.symbols
|
||||||
|
.into_iter()
|
||||||
|
.map(|symbol| IntradayExecutionQuote {
|
||||||
|
date: request.date,
|
||||||
|
symbol,
|
||||||
|
timestamp: request.date.and_time(start_time) - Duration::seconds(1),
|
||||||
|
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()),
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
});
|
||||||
|
|
||||||
|
engine.run().expect("backtest should run");
|
||||||
|
|
||||||
|
let requests = requests.lock().expect("request mutex").clone();
|
||||||
|
assert!(
|
||||||
|
requests.contains(&(second, t(10, 31, 0))),
|
||||||
|
"second-day 10:31 quote request is required"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
requests.contains(&(second, t(10, 40, 0))),
|
||||||
|
"second-day 10:40 quote request must not be skipped by earlier quote"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -180,6 +180,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date1,
|
date: date1,
|
||||||
@@ -191,6 +192,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -202,6 +204,7 @@ fn engine_settles_delisted_position_before_missing_market_snapshot_breaks_run()
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -400,6 +403,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date1,
|
date: date1,
|
||||||
@@ -411,6 +415,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -422,6 +427,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ fn single_day_anchor_data(date: NaiveDate) -> DataSet {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -154,6 +155,7 @@ fn candidate_row(date: NaiveDate, symbol: &str) -> CandidateEligibility {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1116,6 +1118,7 @@ fn engine_runs_strategy_hooks_in_daily_order() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -1127,6 +1130,7 @@ fn engine_runs_strategy_hooks_in_daily_order() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -1273,6 +1277,7 @@ fn engine_executes_open_auction_decisions_before_on_day() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1371,6 +1376,7 @@ fn engine_executes_futures_order_intents_against_future_account() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1960,6 +1966,7 @@ fn engine_runs_subscribed_tick_hooks_and_executes_tick_orders() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2143,6 +2150,7 @@ fn strategy_context_exposes_engine_native_data_helpers() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
let benchmarks = [
|
let benchmarks = [
|
||||||
@@ -2302,6 +2310,7 @@ fn strategy_context_exposes_final_order_runtime_view() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2555,6 +2564,7 @@ fn engine_applies_account_cash_flow_and_financing_intents() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -2566,6 +2576,7 @@ fn engine_applies_account_cash_flow_and_financing_intents() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -2737,6 +2748,7 @@ fn engine_rejects_pending_limit_orders_at_market_close() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -2748,6 +2760,7 @@ fn engine_rejects_pending_limit_orders_at_market_close() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -2938,6 +2951,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -2949,6 +2963,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date3,
|
date: date3,
|
||||||
@@ -2960,6 +2975,7 @@ fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -3184,6 +3200,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date2,
|
date: date2,
|
||||||
@@ -3195,6 +3212,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: date3,
|
date: date3,
|
||||||
@@ -3206,6 +3224,7 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -3538,6 +3557,7 @@ fn engine_applies_dynamic_universe_and_subscription_directives() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: *date,
|
date: *date,
|
||||||
@@ -3549,6 +3569,7 @@ fn engine_applies_dynamic_universe_and_subscription_directives() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
@@ -3671,6 +3692,7 @@ fn engine_exposes_current_process_context_to_strategies() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ fn order_value_rounding_data(date: NaiveDate, symbol: &str, price: f64) -> DataS
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -165,6 +166,7 @@ fn broker_executes_explicit_order_value_buy() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -314,6 +316,7 @@ fn broker_delayed_limit_open_sell_uses_tick_price() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -445,6 +448,7 @@ fn broker_executes_order_shares_and_order_lots() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -570,6 +574,7 @@ fn broker_executes_target_shares_like_order_to() {
|
|||||||
allow_buy: true,
|
allow_buy: true,
|
||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -726,6 +731,7 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date,
|
date,
|
||||||
@@ -737,6 +743,7 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
@@ -867,6 +874,7 @@ fn broker_executes_target_portfolio_smart_with_algo_order_style() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1007,6 +1015,7 @@ fn broker_executes_order_percent_and_target_percent() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1127,6 +1136,7 @@ fn broker_uses_day_open_price_for_open_auction_matching() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1230,6 +1240,7 @@ fn broker_open_auction_uses_auction_volume_without_quote_liquidity() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1330,6 +1341,7 @@ fn broker_cancels_buy_when_open_hits_upper_limit() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1442,6 +1454,7 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1541,6 +1554,7 @@ fn broker_applies_dynamic_slippage_on_snapshot_fills() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1645,6 +1659,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1701,6 +1716,9 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
|||||||
|
|
||||||
assert_eq!(report.fill_events.len(), 1);
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
||||||
|
let position = portfolio.position("000002.SZ").expect("position");
|
||||||
|
assert!((position.last_price - 10.0).abs() < 1e-9);
|
||||||
|
assert!((position.market_value() - position.quantity as f64 * 10.0).abs() < 1e-6);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1759,6 +1777,7 @@ fn broker_rejects_intraday_last_order_without_execution_quotes() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1865,6 +1884,7 @@ fn broker_executes_intraday_last_on_start_quote_without_trade_delta() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -1980,6 +2000,7 @@ fn broker_cancels_market_order_remainder_when_intraday_quote_liquidity_exhausted
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2107,6 +2128,7 @@ fn broker_cancels_market_buy_when_tick_has_no_volume() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2210,6 +2232,7 @@ fn broker_splits_intraday_quote_fills_and_tracks_commission_by_order() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2370,6 +2393,7 @@ fn broker_aggregates_intraday_quote_fills_into_vwap_leg() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2514,6 +2538,7 @@ fn broker_executes_algo_vwap_value_with_time_window() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2671,6 +2696,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2830,6 +2856,7 @@ fn broker_uses_best_own_price_for_intraday_matching() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -2944,6 +2971,7 @@ fn broker_uses_best_counterparty_price_for_intraday_matching() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -3108,6 +3136,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
|
|||||||
allow_sell: false,
|
allow_sell: false,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date,
|
date,
|
||||||
@@ -3119,6 +3148,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
@@ -3295,6 +3325,7 @@ fn rebalance_uses_prev_close_for_open_auction_valuation() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date,
|
date,
|
||||||
@@ -3306,6 +3337,7 @@ fn rebalance_uses_prev_close_for_open_auction_valuation() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
@@ -3476,6 +3508,7 @@ fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date,
|
date,
|
||||||
@@ -3487,6 +3520,7 @@ fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
@@ -3612,6 +3646,7 @@ fn broker_uses_board_specific_min_quantity_and_step_size_for_buy_sizing() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -3710,6 +3745,7 @@ fn broker_allows_bjse_quantities_above_minimum_without_round_lot_step() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -3810,6 +3846,7 @@ fn broker_allows_full_odd_lot_sell_when_liquidating_position() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
@@ -3924,6 +3961,7 @@ fn same_day_sell_then_rebuy_reinserts_position_at_end() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
let data = DataSet::from_components(
|
let data = DataSet::from_components(
|
||||||
@@ -4091,6 +4129,7 @@ fn two_day_limit_order_data(day1_open: f64, day2_open: f64) -> DataSet {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
CandidateEligibility {
|
CandidateEligibility {
|
||||||
date: day2,
|
date: day2,
|
||||||
@@ -4102,6 +4141,7 @@ fn two_day_limit_order_data(day1_open: f64, day2_open: f64) -> DataSet {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -4234,6 +4274,50 @@ fn broker_uses_limit_price_slippage_for_limit_orders() {
|
|||||||
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
|
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_rejects_limit_buy_when_final_execution_price_reaches_upper_limit() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
let data = two_day_limit_order_data(10.0, 10.2);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Open,
|
||||||
|
)
|
||||||
|
.with_slippage_model(SlippageModel::LimitPrice);
|
||||||
|
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::LimitShares {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
quantity: 200,
|
||||||
|
limit_price: 11.0,
|
||||||
|
reason: "limit_entry_at_upper_limit".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert!(report.fill_events.is_empty());
|
||||||
|
assert_eq!(report.order_events.len(), 1);
|
||||||
|
assert_eq!(report.order_events[0].status, OrderStatus::Canceled);
|
||||||
|
assert!(
|
||||||
|
report.order_events[0]
|
||||||
|
.reason
|
||||||
|
.contains("open at or above upper limit")
|
||||||
|
);
|
||||||
|
assert!(portfolio.position("000002.SZ").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_executes_limit_value_and_limit_percent_intents() {
|
fn broker_executes_limit_value_and_limit_percent_intents() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
@@ -4455,6 +4539,7 @@ fn broker_reserves_sellable_quantity_for_open_limit_sells() {
|
|||||||
allow_sell: true,
|
allow_sell: true,
|
||||||
is_kcb: false,
|
is_kcb: false,
|
||||||
is_one_yuan: false,
|
is_one_yuan: false,
|
||||||
|
risk_level_code: None,
|
||||||
}],
|
}],
|
||||||
vec![BenchmarkSnapshot {
|
vec![BenchmarkSnapshot {
|
||||||
date,
|
date,
|
||||||
|
|||||||
Reference in New Issue
Block a user