Compare commits
31 Commits
v2026.04.28
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b4462f880 | |||
| 87b7b2642d | |||
| 5eee5c7c63 | |||
| c6dc1d1474 | |||
| 8c86918970 | |||
| 200d5d1f41 | |||
| 3499d4aa74 | |||
| 7dbd66b467 | |||
| db8b0bf142 | |||
| 6e54471e57 | |||
| 3f383c1a88 | |||
| 4577657c90 | |||
| 94662b6e75 | |||
| 616cab0e7e | |||
| db72f6f515 | |||
| 2165831708 | |||
| 1a402f2048 | |||
| bbe60537ff | |||
| 3b033fd294 | |||
| d9de9715ef | |||
| 65742d4d5e | |||
| a47c7c3e49 | |||
| adc2f12ddf | |||
| e06a1e88e5 | |||
| ce49301b98 | |||
| e5439956eb | |||
| 8e4e0cd86f | |||
| c73649012f | |||
| 236ec62e44 | |||
| 52a8bced13 | |||
| 692cb666a0 |
@@ -1,2 +1,7 @@
|
||||
/target
|
||||
/output
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
Vendored
BIN
Binary file not shown.
@@ -100,6 +100,57 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||
engine.run()?
|
||||
}
|
||||
"aiquant-v104" => {
|
||||
let mut strategy_cfg = OmniMicroCapConfig::aiquant_v104();
|
||||
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||
if !signal_symbol.trim().is_empty() {
|
||||
strategy_cfg.benchmark_signal_symbol = signal_symbol;
|
||||
}
|
||||
}
|
||||
if let Some(date) = debug_date {
|
||||
let eligible = data.eligible_universe_on(date);
|
||||
eprintln!(
|
||||
"DEBUG eligible_universe_on {} count={}",
|
||||
date,
|
||||
eligible.len()
|
||||
);
|
||||
for row in eligible.iter().take(20) {
|
||||
eprintln!(" {} {:.6}", row.symbol, row.market_cap_bn);
|
||||
}
|
||||
let mut debug_strategy = OmniMicroCapStrategy::new(strategy_cfg.clone());
|
||||
let debug_subscriptions = BTreeSet::new();
|
||||
let decision = debug_strategy.on_day(&StrategyContext {
|
||||
execution_date: date,
|
||||
decision_date: date,
|
||||
decision_index: 1,
|
||||
data: &data,
|
||||
portfolio: &PortfolioState::new(20_000.0),
|
||||
futures_account: None,
|
||||
open_orders: &[],
|
||||
dynamic_universe: None,
|
||||
subscriptions: &debug_subscriptions,
|
||||
process_events: &[],
|
||||
active_process_event: None,
|
||||
active_datetime: None,
|
||||
order_events: &[],
|
||||
fills: &[],
|
||||
})?;
|
||||
eprintln!("DEBUG notes={:?}", decision.notes);
|
||||
eprintln!("DEBUG diagnostics={:?}", decision.diagnostics);
|
||||
return Ok(());
|
||||
}
|
||||
config.decision_lag_trading_days = decision_lag.unwrap_or(1);
|
||||
config.execution_price_field = execution_price.unwrap_or(PriceField::Close);
|
||||
config.initial_cash = initial_cash.unwrap_or(20_000.0);
|
||||
let strategy = OmniMicroCapStrategy::new(strategy_cfg);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
config.execution_price_field,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||
engine.run()?
|
||||
}
|
||||
_ => {
|
||||
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
|
||||
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//! 把 DSP 运行时 schema 序列化为 JSON 输出到 stdout。
|
||||
//!
|
||||
//! 用法(在 fidc-backtest-engine 仓库根):
|
||||
//! cargo run -p fidc-core --bin dump_platform_runtime_schema \
|
||||
//! > ../omniquant/src/generated/platformRuntimeSchema.json
|
||||
//!
|
||||
//! 这是 omniquant 前端编译期校验表达式标识符的事实源;任何对
|
||||
//! reserved_scope_names / is_runtime_helper / register_fn 清单的修改,记得
|
||||
//! 重新跑这个命令并把生成文件提交到 omniquant。
|
||||
|
||||
use fidc_core::runtime_schema_json;
|
||||
|
||||
fn main() {
|
||||
let schema = runtime_schema_json();
|
||||
let output = serde_json::to_string_pretty(&schema).expect("serialize schema");
|
||||
println!("{output}");
|
||||
}
|
||||
+701
-119
File diff suppressed because it is too large
Load Diff
@@ -44,7 +44,7 @@ pub struct ChinaAShareCostModel {
|
||||
impl Default for ChinaAShareCostModel {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
commission_rate: 0.0003,
|
||||
commission_rate: 0.0008,
|
||||
stamp_tax_rate_before_change: 0.001,
|
||||
stamp_tax_rate_after_change: 0.0005,
|
||||
minimum_commission: 5.0,
|
||||
@@ -53,6 +53,14 @@ impl Default for ChinaAShareCostModel {
|
||||
}
|
||||
|
||||
impl ChinaAShareCostModel {
|
||||
pub fn aiquant_rqalpha_default() -> Self {
|
||||
Self {
|
||||
stamp_tax_rate_before_change: 0.0005,
|
||||
stamp_tax_rate_after_change: 0.0005,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn commission_for(&self, gross_amount: f64) -> f64 {
|
||||
if gross_amount <= 0.0 {
|
||||
return 0.0;
|
||||
|
||||
+378
-15
@@ -1,4 +1,4 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -9,6 +9,7 @@ use thiserror::Error;
|
||||
use crate::calendar::TradingCalendar;
|
||||
use crate::futures::{FuturesCommissionType, FuturesTradingParameter};
|
||||
use crate::instrument::Instrument;
|
||||
use crate::risk_control::ChinaAShareRiskControl;
|
||||
|
||||
mod date_format {
|
||||
use chrono::NaiveDate;
|
||||
@@ -456,7 +457,9 @@ struct SymbolPriceSeries {
|
||||
close_prefix: Vec<f64>,
|
||||
prev_close_prefix: Vec<f64>,
|
||||
last_prefix: Vec<f64>,
|
||||
volume_prefix: Vec<f64>,
|
||||
unpaused_volumes: Vec<f64>,
|
||||
unpaused_volume_prefix: Vec<f64>,
|
||||
unpaused_count_prefix: Vec<usize>,
|
||||
}
|
||||
|
||||
impl SymbolPriceSeries {
|
||||
@@ -469,15 +472,20 @@ impl SymbolPriceSeries {
|
||||
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
|
||||
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
|
||||
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
|
||||
let volumes = sorted
|
||||
.iter()
|
||||
.map(|row| row.volume as f64)
|
||||
.collect::<Vec<_>>();
|
||||
let open_prefix = prefix_sums(&opens);
|
||||
let close_prefix = prefix_sums(&closes);
|
||||
let prev_close_prefix = prefix_sums(&prev_closes);
|
||||
let last_prefix = prefix_sums(&last_prices);
|
||||
let volume_prefix = prefix_sums(&volumes);
|
||||
let mut unpaused_volumes = Vec::new();
|
||||
let mut unpaused_count_prefix = Vec::with_capacity(sorted.len() + 1);
|
||||
unpaused_count_prefix.push(0);
|
||||
for row in &sorted {
|
||||
if !row.paused {
|
||||
unpaused_volumes.push(row.volume as f64);
|
||||
}
|
||||
unpaused_count_prefix.push(unpaused_volumes.len());
|
||||
}
|
||||
let unpaused_volume_prefix = prefix_sums(&unpaused_volumes);
|
||||
|
||||
Self {
|
||||
snapshots: sorted,
|
||||
@@ -490,7 +498,9 @@ impl SymbolPriceSeries {
|
||||
close_prefix,
|
||||
prev_close_prefix,
|
||||
last_prefix,
|
||||
volume_prefix,
|
||||
unpaused_volumes,
|
||||
unpaused_volume_prefix,
|
||||
unpaused_count_prefix,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -574,19 +584,65 @@ impl SymbolPriceSeries {
|
||||
Some(sum / lookback as f64)
|
||||
}
|
||||
|
||||
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||
fn decision_prev_close_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
|
||||
if lookback == 0 {
|
||||
return None;
|
||||
}
|
||||
let end = self.previous_completed_end_index(date)?;
|
||||
let end = self.decision_end_index(date)?;
|
||||
if end < lookback {
|
||||
return None;
|
||||
}
|
||||
let start = end - lookback;
|
||||
let sum = self.volume_prefix[end] - self.volume_prefix[start];
|
||||
Some(self.prev_closes[start..end].to_vec())
|
||||
}
|
||||
|
||||
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||
let values = self.decision_volume_values(date, lookback)?;
|
||||
if values.len() < lookback {
|
||||
return None;
|
||||
}
|
||||
let sum = values.iter().sum::<f64>();
|
||||
Some(sum / lookback as f64)
|
||||
}
|
||||
|
||||
fn current_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||
if lookback == 0 {
|
||||
return None;
|
||||
}
|
||||
let end = self.end_index(date)?;
|
||||
let end_count = *self.unpaused_count_prefix.get(end)?;
|
||||
if end_count < lookback {
|
||||
return None;
|
||||
}
|
||||
let start_count = end_count - lookback;
|
||||
let sum = self.unpaused_volume_prefix[end_count] - self.unpaused_volume_prefix[start_count];
|
||||
Some(sum / lookback as f64)
|
||||
}
|
||||
|
||||
fn decision_volume_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
|
||||
if lookback == 0 {
|
||||
return None;
|
||||
}
|
||||
let end = self.previous_completed_end_index(date)?;
|
||||
let values = self.trailing_unpaused_volumes(end, lookback)?;
|
||||
if values.len() < lookback {
|
||||
return None;
|
||||
}
|
||||
Some(values)
|
||||
}
|
||||
|
||||
fn trailing_unpaused_volumes(&self, end: usize, lookback: usize) -> Option<Vec<f64>> {
|
||||
if lookback == 0 || end == 0 {
|
||||
return None;
|
||||
}
|
||||
let end_count = *self.unpaused_count_prefix.get(end)?;
|
||||
if end_count < lookback {
|
||||
return None;
|
||||
}
|
||||
let start_count = end_count - lookback;
|
||||
Some(self.unpaused_volumes[start_count..end_count].to_vec())
|
||||
}
|
||||
|
||||
fn end_index(&self, date: NaiveDate) -> Option<usize> {
|
||||
match self.dates.binary_search(&date) {
|
||||
Ok(idx) => Some(idx + 1),
|
||||
@@ -612,6 +668,14 @@ impl SymbolPriceSeries {
|
||||
self.values_for(field).get(end - 1).copied()
|
||||
}
|
||||
|
||||
fn snapshot_before(&self, date: NaiveDate) -> Option<&DailyMarketSnapshot> {
|
||||
let end = self.previous_completed_end_index(date)?;
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
self.snapshots.get(end - 1)
|
||||
}
|
||||
|
||||
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
||||
match field {
|
||||
PriceField::DayOpen => &self.open_prefix,
|
||||
@@ -625,6 +689,7 @@ impl SymbolPriceSeries {
|
||||
#[derive(Debug, Clone)]
|
||||
struct BenchmarkPriceSeries {
|
||||
dates: Vec<NaiveDate>,
|
||||
opens: Vec<f64>,
|
||||
closes: Vec<f64>,
|
||||
open_prefix: Vec<f64>,
|
||||
close_prefix: Vec<f64>,
|
||||
@@ -641,6 +706,7 @@ impl BenchmarkPriceSeries {
|
||||
let close_prefix = prefix_sums(&closes);
|
||||
Self {
|
||||
dates,
|
||||
opens,
|
||||
closes,
|
||||
open_prefix,
|
||||
close_prefix,
|
||||
@@ -651,6 +717,23 @@ impl BenchmarkPriceSeries {
|
||||
self.moving_average_for(date, lookback, PriceField::Close)
|
||||
}
|
||||
|
||||
fn decision_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||
if lookback == 0 {
|
||||
return None;
|
||||
}
|
||||
let end = match self.dates.binary_search(&date) {
|
||||
Ok(idx) => idx,
|
||||
Err(0) => return None,
|
||||
Err(idx) => idx,
|
||||
};
|
||||
if end < lookback {
|
||||
return None;
|
||||
}
|
||||
let start = end - lookback;
|
||||
let sum = self.close_prefix[end] - self.close_prefix[start];
|
||||
Some(sum / lookback as f64)
|
||||
}
|
||||
|
||||
fn moving_average_for(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -678,13 +761,20 @@ impl BenchmarkPriceSeries {
|
||||
}
|
||||
|
||||
fn trailing_values(&self, date: NaiveDate, lookback: usize) -> Vec<f64> {
|
||||
self.trailing_values_for(date, lookback, PriceField::Close)
|
||||
}
|
||||
|
||||
fn trailing_values_for(&self, date: NaiveDate, lookback: usize, field: PriceField) -> Vec<f64> {
|
||||
let end = match self.dates.binary_search(&date) {
|
||||
Ok(idx) => idx + 1,
|
||||
Err(0) => return Vec::new(),
|
||||
Err(idx) => idx,
|
||||
};
|
||||
let start = end.saturating_sub(lookback);
|
||||
self.closes[start..end].to_vec()
|
||||
match field {
|
||||
PriceField::DayOpen | PriceField::Open => self.opens[start..end].to_vec(),
|
||||
PriceField::Close | PriceField::Last => self.closes[start..end].to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -944,6 +1034,7 @@ impl DataSet {
|
||||
) -> Result<Self, DataSetError> {
|
||||
let benchmark_code = collect_benchmark_code(&benchmarks)?;
|
||||
let calendar = TradingCalendar::new(benchmarks.iter().map(|item| item.date).collect());
|
||||
let factors = normalize_factor_snapshots(factors);
|
||||
|
||||
let instruments = instruments
|
||||
.into_iter()
|
||||
@@ -994,8 +1085,12 @@ impl DataSet {
|
||||
let market_series_by_symbol = build_market_series(&market_by_date);
|
||||
let benchmark_series_cache =
|
||||
BenchmarkPriceSeries::new(&benchmark_by_date.values().cloned().collect::<Vec<_>>());
|
||||
let eligible_universe_by_date =
|
||||
build_eligible_universe(&factor_by_date, &candidate_index, &market_index);
|
||||
let eligible_universe_by_date = build_eligible_universe(
|
||||
&factor_by_date,
|
||||
&candidate_index,
|
||||
&market_index,
|
||||
&instruments,
|
||||
);
|
||||
let futures_params_by_symbol = build_futures_params_index(futures_params);
|
||||
|
||||
Ok(Self {
|
||||
@@ -1088,6 +1183,33 @@ impl DataSet {
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
|
||||
self.execution_quotes_index.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn add_execution_quotes(&mut self, quotes: Vec<IntradayExecutionQuote>) -> usize {
|
||||
let mut added = 0usize;
|
||||
let mut touched = HashSet::<(NaiveDate, String)>::new();
|
||||
for quote in quotes {
|
||||
let key = (quote.date, quote.symbol.clone());
|
||||
let rows = self.execution_quotes_index.entry(key.clone()).or_default();
|
||||
if rows.iter().any(|existing| {
|
||||
existing.timestamp == quote.timestamp && existing.symbol == quote.symbol
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
rows.push(quote);
|
||||
touched.insert(key);
|
||||
added += 1;
|
||||
}
|
||||
for key in touched {
|
||||
if let Some(rows) = self.execution_quotes_index.get_mut(&key) {
|
||||
rows.sort_by_key(|quote| quote.timestamp);
|
||||
}
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
pub fn order_book_depth_on(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -1759,6 +1881,12 @@ impl DataSet {
|
||||
.and_then(|series| series.price_on_or_before(date, field))
|
||||
}
|
||||
|
||||
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.snapshot_before(date))
|
||||
}
|
||||
|
||||
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
||||
self.factor_by_date
|
||||
.get(&date)
|
||||
@@ -2009,6 +2137,93 @@ impl DataSet {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn market_current_numeric_moving_average(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
field: &str,
|
||||
lookback: usize,
|
||||
) -> Option<f64> {
|
||||
let field = normalize_field(field);
|
||||
match field.as_str() {
|
||||
"close" | "prev_close" | "stock_close" | "price" => {
|
||||
self.market_moving_average(date, symbol, lookback, PriceField::Close)
|
||||
}
|
||||
"volume" | "stock_volume" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.current_volume_moving_average(date, lookback))
|
||||
.or_else(|| self.factor_moving_average(date, symbol, "daily_volume", lookback)),
|
||||
"day_open" | "dayopen" => {
|
||||
self.market_moving_average(date, symbol, lookback, PriceField::DayOpen)
|
||||
}
|
||||
"open" => self.market_moving_average(date, symbol, lookback, PriceField::Open),
|
||||
"last" | "last_price" => {
|
||||
self.market_moving_average(date, symbol, lookback, PriceField::Last)
|
||||
}
|
||||
other => self.factor_moving_average(date, symbol, other, lookback),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn market_decision_numeric_values(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
field: &str,
|
||||
lookback: usize,
|
||||
) -> Vec<f64> {
|
||||
if lookback == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let field = normalize_field(field);
|
||||
match field.as_str() {
|
||||
"close" | "prev_close" | "stock_close" | "price" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.decision_prev_close_values(date, lookback))
|
||||
.unwrap_or_default(),
|
||||
"volume" | "stock_volume" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.decision_volume_values(date, lookback))
|
||||
.unwrap_or_default(),
|
||||
"day_open" | "dayopen" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::DayOpen))
|
||||
.unwrap_or_default(),
|
||||
"open" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::Open))
|
||||
.unwrap_or_default(),
|
||||
"last" | "last_price" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.map(|series| series.trailing_values(date, lookback, PriceField::Last))
|
||||
.unwrap_or_default(),
|
||||
other => self.factor_numeric_values(date, symbol, other, lookback),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn factor_numeric_values(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
field: &str,
|
||||
lookback: usize,
|
||||
) -> Vec<f64> {
|
||||
if lookback == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
self.calendar
|
||||
.trailing_days(date, lookback)
|
||||
.into_iter()
|
||||
.filter_map(|trading_day| self.factor(trading_day, symbol))
|
||||
.filter_map(|snapshot| factor_numeric_value(snapshot, field))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn market_moving_average(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -2025,11 +2240,35 @@ impl DataSet {
|
||||
self.benchmark_series_cache.moving_average(date, lookback)
|
||||
}
|
||||
|
||||
pub fn benchmark_decision_moving_average(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
lookback: usize,
|
||||
) -> Option<f64> {
|
||||
self.benchmark_series_cache
|
||||
.decision_moving_average(date, lookback)
|
||||
}
|
||||
|
||||
pub fn benchmark_open_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||
self.benchmark_series_cache
|
||||
.moving_average_for(date, lookback, PriceField::Open)
|
||||
}
|
||||
|
||||
pub fn benchmark_numeric_values(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
field: &str,
|
||||
lookback: usize,
|
||||
) -> Vec<f64> {
|
||||
let field = normalize_field(field);
|
||||
match field.as_str() {
|
||||
"open" | "day_open" | "dayopen" | "benchmark_open" => self
|
||||
.benchmark_series_cache
|
||||
.trailing_values_for(date, lookback, PriceField::Open),
|
||||
_ => self.benchmark_series_cache.trailing_values(date, lookback),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn market_open_moving_average(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -2400,6 +2639,26 @@ fn factor_numeric_value(snapshot: &DailyFactorSnapshot, field: &str) -> Option<f
|
||||
"pe_ttm" => Some(snapshot.pe_ttm),
|
||||
"turnover_ratio" => snapshot.turnover_ratio,
|
||||
"effective_turnover_ratio" => snapshot.effective_turnover_ratio,
|
||||
"ths_market_value_stock" | "ths_market_value_stock_bn" => snapshot
|
||||
.extra_factors
|
||||
.get(field.as_str())
|
||||
.copied()
|
||||
.or(Some(snapshot.market_cap_bn)),
|
||||
"ths_current_mv_stock" | "ths_current_mv_stock_bn" => snapshot
|
||||
.extra_factors
|
||||
.get(field.as_str())
|
||||
.copied()
|
||||
.or(Some(snapshot.free_float_cap_bn)),
|
||||
"ths_turnover_ratio_stock" => snapshot
|
||||
.extra_factors
|
||||
.get(field.as_str())
|
||||
.copied()
|
||||
.or(snapshot.turnover_ratio),
|
||||
"ths_vaild_turnover_stock" | "ths_valid_turnover_stock" => snapshot
|
||||
.extra_factors
|
||||
.get(field.as_str())
|
||||
.copied()
|
||||
.or(snapshot.effective_turnover_ratio),
|
||||
other => snapshot.extra_factors.get(other).copied(),
|
||||
}
|
||||
}
|
||||
@@ -2509,6 +2768,27 @@ fn normalize_field(field: &str) -> String {
|
||||
.to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn normalize_factor_snapshots(factors: Vec<DailyFactorSnapshot>) -> Vec<DailyFactorSnapshot> {
|
||||
factors
|
||||
.into_iter()
|
||||
.map(|mut snapshot| {
|
||||
snapshot.extra_factors = snapshot
|
||||
.extra_factors
|
||||
.into_iter()
|
||||
.filter_map(|(field, value)| {
|
||||
let normalized = normalize_field(&field);
|
||||
if normalized.is_empty() || !value.is_finite() {
|
||||
None
|
||||
} else {
|
||||
Some((normalized, value))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
snapshot
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn normalize_history_frequency(frequency: &str) -> Option<String> {
|
||||
let normalized = normalize_field(frequency);
|
||||
match normalized.as_str() {
|
||||
@@ -3041,6 +3321,7 @@ fn build_eligible_universe(
|
||||
factor_by_date: &BTreeMap<NaiveDate, Vec<DailyFactorSnapshot>>,
|
||||
candidate_index: &HashMap<(NaiveDate, String), CandidateEligibility>,
|
||||
market_index: &HashMap<(NaiveDate, String), DailyMarketSnapshot>,
|
||||
instruments: &HashMap<String, Instrument>,
|
||||
) -> BTreeMap<NaiveDate, Vec<EligibleUniverseSnapshot>> {
|
||||
let mut per_date = BTreeMap::<NaiveDate, Vec<EligibleUniverseSnapshot>>::new();
|
||||
|
||||
@@ -3057,7 +3338,14 @@ fn build_eligible_universe(
|
||||
let Some(market) = market_index.get(&key) else {
|
||||
continue;
|
||||
};
|
||||
if !candidate.eligible_for_selection() || market.paused {
|
||||
if ChinaAShareRiskControl::selection_rejection_reason(
|
||||
*date,
|
||||
candidate,
|
||||
market,
|
||||
instruments.get(&factor.symbol),
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
rows.push(EligibleUniverseSnapshot {
|
||||
@@ -3078,6 +3366,11 @@ fn build_eligible_universe(
|
||||
per_date
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn instrument_passes_baseline_selection(instrument: Option<&Instrument>, date: NaiveDate) -> bool {
|
||||
ChinaAShareRiskControl::instrument_rejection_reason(instrument, date).is_none()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -3117,6 +3410,49 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baseline_selection_uses_structured_instrument_dates_and_status_only() {
|
||||
let date = NaiveDate::parse_from_str("2025-01-02", "%Y-%m-%d").unwrap();
|
||||
let instrument = |name: &str, status: &str, delisted_at: Option<NaiveDate>| Instrument {
|
||||
symbol: "000001.SZ".to_string(),
|
||||
name: name.to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: Some(NaiveDate::parse_from_str("2020-01-01", "%Y-%m-%d").unwrap()),
|
||||
delisted_at,
|
||||
status: status.to_string(),
|
||||
};
|
||||
|
||||
assert!(instrument_passes_baseline_selection(
|
||||
Some(&instrument("Short History Stock", "active", None)),
|
||||
date
|
||||
));
|
||||
assert!(instrument_passes_baseline_selection(
|
||||
Some(&instrument("*ST测试", "active", None)),
|
||||
date
|
||||
));
|
||||
assert!(instrument_passes_baseline_selection(
|
||||
Some(&instrument("ST测试", "active", None)),
|
||||
date
|
||||
));
|
||||
assert!(instrument_passes_baseline_selection(
|
||||
Some(&instrument("退市测试", "active", None)),
|
||||
date
|
||||
));
|
||||
assert!(!instrument_passes_baseline_selection(
|
||||
Some(&instrument("正常名称", "delisted", None)),
|
||||
date
|
||||
));
|
||||
assert!(!instrument_passes_baseline_selection(
|
||||
Some(&instrument(
|
||||
"正常名称",
|
||||
"active",
|
||||
Some(NaiveDate::parse_from_str("2025-01-01", "%Y-%m-%d").unwrap()),
|
||||
)),
|
||||
date
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_volume_average_uses_previous_completed_days_only() {
|
||||
let series = SymbolPriceSeries::new(&[
|
||||
@@ -3148,6 +3484,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_volume_average_skips_paused_days_before_counting_window() {
|
||||
let mut paused = market_row("2025-01-03", 11.0, 0);
|
||||
paused.paused = true;
|
||||
let series = SymbolPriceSeries::new(&[
|
||||
market_row("2025-01-02", 10.0, 100),
|
||||
paused,
|
||||
market_row("2025-01-06", 12.0, 300),
|
||||
market_row("2025-01-07", 13.0, 10_000),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
series.decision_volume_moving_average(
|
||||
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
|
||||
2
|
||||
),
|
||||
Some(200.0)
|
||||
);
|
||||
assert_eq!(
|
||||
series.decision_volume_moving_average(
|
||||
NaiveDate::parse_from_str("2025-01-07", "%Y-%m-%d").unwrap(),
|
||||
3
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_mixed_numeric_and_text_extra_factors_from_quoted_csv_json() {
|
||||
let path = temp_csv_path("mixed_factor_maps");
|
||||
|
||||
+219
-16
@@ -6,7 +6,7 @@ use thiserror::Error;
|
||||
|
||||
use crate::broker::{BrokerExecutionReport, BrokerSimulator, MatchingType};
|
||||
use crate::cost::CostModel;
|
||||
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, PriceField};
|
||||
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, IntradayExecutionQuote, PriceField};
|
||||
use crate::event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
|
||||
use crate::events::{
|
||||
AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent, ProcessEvent,
|
||||
@@ -20,7 +20,10 @@ use crate::metrics::{BacktestMetrics, compute_backtest_metrics};
|
||||
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
|
||||
use crate::rules::EquityRuleHooks;
|
||||
use crate::scheduler::{ScheduleRule, ScheduleStage, Scheduler, default_stage_time};
|
||||
use crate::strategy::{Strategy, StrategyContext};
|
||||
use crate::strategy::{
|
||||
OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision,
|
||||
TargetPortfolioOrderPricing,
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum BacktestError {
|
||||
@@ -95,6 +98,18 @@ pub struct BacktestResult {
|
||||
pub metrics: BacktestMetrics,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExecutionQuoteRequest {
|
||||
pub date: NaiveDate,
|
||||
pub start_time: Option<chrono::NaiveTime>,
|
||||
pub end_time: Option<chrono::NaiveTime>,
|
||||
pub symbols: BTreeSet<String>,
|
||||
}
|
||||
|
||||
type ExecutionQuoteLoader = Box<
|
||||
dyn FnMut(ExecutionQuoteRequest) -> Result<Vec<IntradayExecutionQuote>, BacktestError> + Send,
|
||||
>;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AnalyzerTradeRow {
|
||||
#[serde(with = "date_format")]
|
||||
@@ -313,6 +328,8 @@ pub struct BacktestEngine<S, C, R> {
|
||||
broker: BrokerSimulator<C, R>,
|
||||
config: BacktestConfig,
|
||||
dividend_reinvestment: bool,
|
||||
cash_dividends_enabled: bool,
|
||||
cash_dividend_adjusts_cost_basis: bool,
|
||||
process_event_bus: ProcessEventBus,
|
||||
dynamic_universe: Option<BTreeSet<String>>,
|
||||
subscriptions: BTreeSet<String>,
|
||||
@@ -323,6 +340,7 @@ pub struct BacktestEngine<S, C, R> {
|
||||
futures_settlement_price_mode: String,
|
||||
futures_cost_model: FuturesTransactionCostModel,
|
||||
futures_validation_config: FuturesValidationConfig,
|
||||
execution_quote_loader: Option<ExecutionQuoteLoader>,
|
||||
}
|
||||
|
||||
impl<S, C, R> BacktestEngine<S, C, R> {
|
||||
@@ -338,6 +356,8 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
||||
broker,
|
||||
config,
|
||||
dividend_reinvestment: false,
|
||||
cash_dividends_enabled: true,
|
||||
cash_dividend_adjusts_cost_basis: true,
|
||||
process_event_bus: ProcessEventBus::new(),
|
||||
dynamic_universe: None,
|
||||
subscriptions: BTreeSet::new(),
|
||||
@@ -348,14 +368,39 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
||||
futures_settlement_price_mode: "close".to_string(),
|
||||
futures_cost_model: FuturesTransactionCostModel::default(),
|
||||
futures_validation_config: FuturesValidationConfig::default(),
|
||||
execution_quote_loader: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_data(self) -> DataSet {
|
||||
self.data
|
||||
}
|
||||
|
||||
pub fn with_execution_quote_loader<F>(mut self, loader: F) -> Self
|
||||
where
|
||||
F: FnMut(ExecutionQuoteRequest) -> Result<Vec<IntradayExecutionQuote>, BacktestError>
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
self.execution_quote_loader = Some(Box::new(loader));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_dividend_reinvestment(mut self, enabled: bool) -> Self {
|
||||
self.dividend_reinvestment = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_cash_dividends(mut self, enabled: bool) -> Self {
|
||||
self.cash_dividends_enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_cash_dividend_cost_basis_adjustment(mut self, enabled: bool) -> Self {
|
||||
self.cash_dividend_adjusts_cost_basis = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_futures_account(mut self, account: FuturesAccountState) -> Self {
|
||||
self.futures_account = Some(account);
|
||||
self
|
||||
@@ -460,6 +505,48 @@ where
|
||||
C: CostModel,
|
||||
R: EquityRuleHooks,
|
||||
{
|
||||
fn ensure_execution_quotes_for_decision(
|
||||
&mut self,
|
||||
execution_date: NaiveDate,
|
||||
portfolio: &PortfolioState,
|
||||
open_orders: &[OpenOrderView],
|
||||
decision: &StrategyDecision,
|
||||
start_time: Option<chrono::NaiveTime>,
|
||||
end_time: Option<chrono::NaiveTime>,
|
||||
) -> Result<(), BacktestError> {
|
||||
if self.execution_quote_loader.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.broker.execution_price_field() != PriceField::Last
|
||||
&& !decision_has_algo_execution(decision)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let start_time = start_time.or_else(|| self.broker.intraday_execution_start_time());
|
||||
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
|
||||
symbols.retain(|symbol| {
|
||||
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
|
||||
});
|
||||
if symbols.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let request = ExecutionQuoteRequest {
|
||||
date: execution_date,
|
||||
start_time,
|
||||
end_time,
|
||||
symbols,
|
||||
};
|
||||
let quotes = self
|
||||
.execution_quote_loader
|
||||
.as_mut()
|
||||
.expect("checked execution quote loader")
|
||||
.as_mut()(request)?;
|
||||
self.data.add_execution_quotes(quotes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_strategy_directives(
|
||||
&mut self,
|
||||
execution_date: NaiveDate,
|
||||
@@ -1721,6 +1808,15 @@ where
|
||||
&mut auction_decision,
|
||||
&mut directive_report,
|
||||
)?;
|
||||
let pre_auction_execution_orders = self.open_order_views();
|
||||
self.ensure_execution_quotes_for_decision(
|
||||
execution_date,
|
||||
&portfolio,
|
||||
&pre_auction_execution_orders,
|
||||
&auction_decision,
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
let mut report = self.broker.execute(
|
||||
execution_date,
|
||||
&mut portfolio,
|
||||
@@ -1925,6 +2021,15 @@ where
|
||||
&mut directive_report,
|
||||
)?;
|
||||
|
||||
let pre_intraday_execution_orders = self.open_order_views();
|
||||
self.ensure_execution_quotes_for_decision(
|
||||
execution_date,
|
||||
&portfolio,
|
||||
&pre_intraday_execution_orders,
|
||||
&decision,
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
let mut intraday_report =
|
||||
self.broker
|
||||
.execute(execution_date, &mut portfolio, &self.data, &decision)?;
|
||||
@@ -2082,6 +2187,15 @@ where
|
||||
&mut tick_decision,
|
||||
&mut directive_report,
|
||||
)?;
|
||||
let pre_tick_execution_orders = self.open_order_views();
|
||||
self.ensure_execution_quotes_for_decision(
|
||||
execution_date,
|
||||
&portfolio,
|
||||
&pre_tick_execution_orders,
|
||||
&tick_decision,
|
||||
Some(tick_time),
|
||||
Some(tick_time),
|
||||
)?;
|
||||
let mut tick_report = self.broker.execute_between(
|
||||
execution_date,
|
||||
&mut portfolio,
|
||||
@@ -2127,7 +2241,12 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
portfolio.update_prices(execution_date, &self.data, PriceField::Close)?;
|
||||
portfolio.update_prices_with_options(
|
||||
execution_date,
|
||||
&self.data,
|
||||
PriceField::Close,
|
||||
self.broker.same_day_buy_close_mark_at_fill(),
|
||||
)?;
|
||||
|
||||
let post_trade_open_orders = self.open_order_views();
|
||||
let visible_order_events = result
|
||||
@@ -2516,13 +2635,17 @@ where
|
||||
continue;
|
||||
}
|
||||
|
||||
if action.share_cash.abs() > f64::EPSILON {
|
||||
if self.cash_dividends_enabled && action.share_cash.abs() > f64::EPSILON {
|
||||
let cash_before = portfolio.cash();
|
||||
let (cash_delta, quantity_after, average_cost) = {
|
||||
let position = portfolio
|
||||
.position_mut_if_exists(&action.symbol)
|
||||
.expect("position exists for dividend action");
|
||||
let cash_delta = position.apply_cash_dividend(action.share_cash);
|
||||
let cash_delta = if self.cash_dividend_adjusts_cost_basis {
|
||||
position.apply_cash_dividend(action.share_cash)
|
||||
} else {
|
||||
position.apply_cash_dividend_preserve_cost_basis(action.share_cash)
|
||||
};
|
||||
(cash_delta, position.quantity, position.average_cost)
|
||||
};
|
||||
if cash_delta.abs() > f64::EPSILON {
|
||||
@@ -2985,24 +3108,17 @@ where
|
||||
}
|
||||
|
||||
let quantity = position.quantity;
|
||||
let fallback_reference_price = if position.last_price > 0.0 {
|
||||
let settlement_price = if position.last_price.is_finite() && position.last_price > 0.0 {
|
||||
position.last_price
|
||||
} else {
|
||||
} else if position.average_cost.is_finite() && position.average_cost > 0.0 {
|
||||
position.average_cost
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let effective_delisted_at = instrument
|
||||
.delisted_at
|
||||
.or_else(|| self.data.calendar().previous_day(date))
|
||||
.unwrap_or(date);
|
||||
let settlement_price = self
|
||||
.data
|
||||
.price_on_or_before(effective_delisted_at, &symbol, PriceField::Close)
|
||||
.or_else(|| {
|
||||
self.data
|
||||
.price_on_or_before(date, &symbol, PriceField::Close)
|
||||
})
|
||||
.filter(|price| price.is_finite() && *price > 0.0)
|
||||
.unwrap_or(fallback_reference_price);
|
||||
if !settlement_price.is_finite() || settlement_price <= 0.0 {
|
||||
return Err(BacktestError::Execution(format!(
|
||||
"missing delisting settlement price for {} on {}",
|
||||
@@ -3072,6 +3188,93 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn has_execution_quote_in_window(
|
||||
data: &DataSet,
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
start_time: Option<chrono::NaiveTime>,
|
||||
end_time: Option<chrono::NaiveTime>,
|
||||
) -> bool {
|
||||
let start_cursor = start_time.map(|time| date.and_time(time));
|
||||
let end_cursor = end_time.map(|time| date.and_time(time));
|
||||
data.execution_quotes_on(date, symbol).iter().any(|quote| {
|
||||
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
|
||||
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
|
||||
})
|
||||
}
|
||||
|
||||
fn decision_has_algo_execution(decision: &StrategyDecision) -> bool {
|
||||
decision.order_intents.iter().any(|intent| {
|
||||
matches!(
|
||||
intent,
|
||||
OrderIntent::AlgoValue { .. }
|
||||
| OrderIntent::AlgoPercent { .. }
|
||||
| OrderIntent::TargetPortfolioSmart {
|
||||
order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { .. }),
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn execution_quote_symbols_for_decision(
|
||||
decision: &StrategyDecision,
|
||||
portfolio: &PortfolioState,
|
||||
open_orders: &[OpenOrderView],
|
||||
) -> BTreeSet<String> {
|
||||
let mut symbols = BTreeSet::new();
|
||||
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
|
||||
if decision.rebalance {
|
||||
symbols.extend(portfolio.positions().keys().cloned());
|
||||
symbols.extend(decision.target_weights.keys().cloned());
|
||||
}
|
||||
if !decision.exit_symbols.is_empty() {
|
||||
symbols.extend(decision.exit_symbols.iter().cloned());
|
||||
}
|
||||
|
||||
for intent in &decision.order_intents {
|
||||
match intent {
|
||||
OrderIntent::Shares { symbol, .. }
|
||||
| OrderIntent::LimitShares { symbol, .. }
|
||||
| OrderIntent::Lots { symbol, .. }
|
||||
| OrderIntent::LimitLots { symbol, .. }
|
||||
| OrderIntent::TargetShares { symbol, .. }
|
||||
| OrderIntent::LimitTargetShares { symbol, .. }
|
||||
| OrderIntent::TargetValue { symbol, .. }
|
||||
| OrderIntent::LimitTargetValue { symbol, .. }
|
||||
| OrderIntent::Value { symbol, .. }
|
||||
| OrderIntent::LimitValue { symbol, .. }
|
||||
| OrderIntent::Percent { symbol, .. }
|
||||
| OrderIntent::LimitPercent { symbol, .. }
|
||||
| OrderIntent::TargetPercent { symbol, .. }
|
||||
| OrderIntent::LimitTargetPercent { symbol, .. }
|
||||
| OrderIntent::AlgoValue { symbol, .. }
|
||||
| OrderIntent::AlgoPercent { symbol, .. }
|
||||
| OrderIntent::CancelSymbol { symbol, .. } => {
|
||||
symbols.insert(symbol.clone());
|
||||
}
|
||||
OrderIntent::TargetPortfolioSmart { target_weights, .. } => {
|
||||
symbols.extend(portfolio.positions().keys().cloned());
|
||||
symbols.extend(target_weights.keys().cloned());
|
||||
}
|
||||
OrderIntent::CancelAll { .. } => {
|
||||
symbols.extend(open_orders.iter().map(|order| order.symbol.clone()));
|
||||
}
|
||||
OrderIntent::UpdateUniverse { .. }
|
||||
| OrderIntent::Subscribe { .. }
|
||||
| OrderIntent::Unsubscribe { .. }
|
||||
| OrderIntent::DepositWithdraw { .. }
|
||||
| OrderIntent::FinanceRepay { .. }
|
||||
| OrderIntent::SetManagementFeeRate { .. }
|
||||
| OrderIntent::CancelOrder { .. }
|
||||
| OrderIntent::Futures { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
symbols.retain(|symbol| !symbol.trim().is_empty());
|
||||
symbols
|
||||
}
|
||||
|
||||
fn collect_scheduled_decisions<S: Strategy>(
|
||||
strategy: &mut S,
|
||||
scheduler: &Scheduler<'_>,
|
||||
|
||||
@@ -9,14 +9,19 @@ pub mod futures;
|
||||
pub mod instrument;
|
||||
pub mod metrics;
|
||||
pub mod platform_expr_strategy;
|
||||
pub mod platform_runtime_schema;
|
||||
pub mod platform_strategy_spec;
|
||||
pub mod portfolio;
|
||||
pub mod risk_control;
|
||||
pub mod rules;
|
||||
pub mod scheduler;
|
||||
pub mod strategy;
|
||||
pub mod strategy_ai;
|
||||
pub mod universe;
|
||||
|
||||
pub use broker::{BrokerExecutionReport, BrokerSimulator, MatchingType, SlippageModel};
|
||||
pub use broker::{
|
||||
BrokerExecutionReport, BrokerSimulator, DynamicSlippageConfig, MatchingType, SlippageModel,
|
||||
};
|
||||
pub use calendar::TradingCalendar;
|
||||
pub use cost::{ChinaAShareCostModel, CostModel, TradingCost};
|
||||
pub use data::{
|
||||
@@ -29,7 +34,7 @@ pub use data::{
|
||||
pub use engine::{
|
||||
AnalyzerMonthlyReturnRow, AnalyzerPositionRow, AnalyzerReport, AnalyzerRiskSummary,
|
||||
AnalyzerTradeRow, BacktestConfig, BacktestDayProgress, BacktestEngine, BacktestError,
|
||||
BacktestResult, DailyEquityPoint, FuturesValidationConfig,
|
||||
BacktestResult, DailyEquityPoint, ExecutionQuoteRequest, FuturesValidationConfig,
|
||||
};
|
||||
pub use event_bus::{BacktestProcessMod, BacktestProcessModLoader, ProcessEventBus};
|
||||
pub use events::{
|
||||
@@ -46,10 +51,25 @@ pub use metrics::{BacktestMetrics, compute_backtest_metrics};
|
||||
pub use platform_expr_strategy::{
|
||||
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
|
||||
PlatformExplicitOrderKind, PlatformExprStrategy, PlatformExprStrategyConfig,
|
||||
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
||||
PlatformUniverseActionKind,
|
||||
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformSelectionQuotePlan,
|
||||
PlatformTradeAction, PlatformUniverseActionKind,
|
||||
};
|
||||
pub use platform_runtime_schema::{
|
||||
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
|
||||
rhai_builtin_functions, rhai_keywords, runtime_helper_functions, runtime_schema,
|
||||
runtime_schema_json,
|
||||
};
|
||||
pub use platform_strategy_spec::{
|
||||
DynamicRangeConfig, IndexThrottleConfig, MovingAverageFilterConfig, SkipWindowConfig,
|
||||
StrategyBenchmarkSpec, StrategyEngineConfig, StrategyExecutionSpec,
|
||||
StrategyExpressionActionConfig, StrategyExpressionAllocationConfig,
|
||||
StrategyExpressionOrderingConfig, StrategyExpressionRiskConfig,
|
||||
StrategyExpressionScheduleConfig, StrategyExpressionSelectionConfig,
|
||||
StrategyExpressionTradingConfig, StrategyRuntimeEnvironment, StrategyRuntimeExpressions,
|
||||
StrategyRuntimeSpec, platform_expr_config_from_spec, platform_expr_config_from_value,
|
||||
};
|
||||
pub use portfolio::{CashReceivable, HoldingSummary, PendingCashFlow, PortfolioState, Position};
|
||||
pub use risk_control::ChinaAShareRiskControl;
|
||||
pub use rules::{ChinaEquityRuleHooks, EquityRuleHooks, RuleCheck};
|
||||
pub use scheduler::{
|
||||
ScheduleFrequency, ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,346 @@
|
||||
//! DSP 运行时变量与函数 schema 导出。
|
||||
//!
|
||||
//! 这是前后端共享的"事实源":把引擎里 reserved_scope_names 和 is_runtime_helper
|
||||
//! 等清单按 JSON Schema 暴露出来,供 omniquant 前端在编译期做表达式标识符校验。
|
||||
//!
|
||||
//! 维护原则:
|
||||
//! - 任何对 platform_expr_strategy.rs 中变量名 / 函数名清单的修改都必须在这里
|
||||
//! 同步一份。两侧一致由 unit test `runtime_schema_matches_strategy_runtime`
|
||||
//! 守住。
|
||||
//! - 该 schema 的 version 字段需要与 omniquant/src/platformSchema.ts 里
|
||||
//! PLATFORM_RUNTIME_SCHEMA_VERSION 保持一致。前端读到不同版本时应给出诊断。
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
/// 当前 schema 版本号。每次 reserved/runtime 列表的破坏性变更需要 +1。
|
||||
pub const PLATFORM_RUNTIME_SCHEMA_VERSION: &str = "1";
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlatformRuntimeSchema {
|
||||
pub version: &'static str,
|
||||
pub reserved_scope_names: Vec<&'static str>,
|
||||
pub runtime_helper_functions: Vec<&'static str>,
|
||||
pub rhai_builtin_functions: Vec<&'static str>,
|
||||
pub rhai_keywords: Vec<&'static str>,
|
||||
}
|
||||
|
||||
/// reserved scope names 列表。镜像 PlatformExprStrategy::reserved_scope_names。
|
||||
pub fn reserved_scope_names() -> &'static [&'static str] {
|
||||
RESERVED_SCOPE_NAMES
|
||||
}
|
||||
|
||||
/// runtime helper functions 列表。镜像 PlatformExprStrategy::is_runtime_helper。
|
||||
pub fn runtime_helper_functions() -> &'static [&'static str] {
|
||||
RUNTIME_HELPER_FUNCTIONS
|
||||
}
|
||||
|
||||
/// rhai engine 注册的内置函数列表。镜像 PlatformExprStrategy::new 中 register_fn
|
||||
/// 的清单。
|
||||
pub fn rhai_builtin_functions() -> &'static [&'static str] {
|
||||
RHAI_BUILTIN_FUNCTIONS
|
||||
}
|
||||
|
||||
/// rhai 控制流关键字(避免被前端校验视为未知)。
|
||||
pub fn rhai_keywords() -> &'static [&'static str] {
|
||||
RHAI_KEYWORDS
|
||||
}
|
||||
|
||||
/// 构造完整 schema。
|
||||
pub fn runtime_schema() -> PlatformRuntimeSchema {
|
||||
PlatformRuntimeSchema {
|
||||
version: PLATFORM_RUNTIME_SCHEMA_VERSION,
|
||||
reserved_scope_names: RESERVED_SCOPE_NAMES.to_vec(),
|
||||
runtime_helper_functions: RUNTIME_HELPER_FUNCTIONS.to_vec(),
|
||||
rhai_builtin_functions: RHAI_BUILTIN_FUNCTIONS.to_vec(),
|
||||
rhai_keywords: RHAI_KEYWORDS.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把 schema 序列化为 JSON Value。给 fidc-data-center / strategy-runtime 接口使用。
|
||||
pub fn runtime_schema_json() -> Value {
|
||||
serde_json::to_value(runtime_schema()).expect("runtime schema serialization is infallible")
|
||||
}
|
||||
|
||||
const RESERVED_SCOPE_NAMES: &[&str] = &[
|
||||
// day-level
|
||||
"signal_close",
|
||||
"benchmark_close",
|
||||
"signal_ma5",
|
||||
"signal_ma10",
|
||||
"signal_ma20",
|
||||
"signal_ma30",
|
||||
"benchmark_ma5",
|
||||
"benchmark_ma10",
|
||||
"benchmark_ma20",
|
||||
"benchmark_ma30",
|
||||
"benchmark_ma_short",
|
||||
"benchmark_ma_long",
|
||||
"cash",
|
||||
"available_cash",
|
||||
"frozen_cash",
|
||||
"market_value",
|
||||
"total_equity",
|
||||
"total_value",
|
||||
"portfolio_value",
|
||||
"starting_cash",
|
||||
"unit_net_value",
|
||||
"static_unit_net_value",
|
||||
"daily_pnl",
|
||||
"daily_returns",
|
||||
"total_returns",
|
||||
"cash_liabilities",
|
||||
"management_fee_rate",
|
||||
"management_fees",
|
||||
"current_exposure",
|
||||
"position_count",
|
||||
"max_positions",
|
||||
"refresh_rate",
|
||||
"year",
|
||||
"month",
|
||||
"quarter",
|
||||
"day_of_month",
|
||||
"day_of_year",
|
||||
"week_of_year",
|
||||
"weekday",
|
||||
"is_month_start",
|
||||
"is_month_end",
|
||||
"has_open_orders",
|
||||
"open_order_count",
|
||||
"open_buy_order_count",
|
||||
"open_sell_order_count",
|
||||
"open_buy_qty",
|
||||
"open_sell_qty",
|
||||
"latest_open_order_id",
|
||||
"latest_open_order_status",
|
||||
"latest_open_order_unfilled_qty",
|
||||
"has_process_events",
|
||||
"process_event_count",
|
||||
"current_process_kind",
|
||||
"current_process_order_id",
|
||||
"current_process_symbol",
|
||||
"current_process_side",
|
||||
"current_process_detail",
|
||||
"latest_process_kind",
|
||||
"latest_process_order_id",
|
||||
"latest_process_symbol",
|
||||
"latest_process_side",
|
||||
"latest_process_detail",
|
||||
"process_event_counts",
|
||||
"day_factors",
|
||||
// stock-level
|
||||
"symbol",
|
||||
"market_cap",
|
||||
"free_float_cap",
|
||||
"pe_ttm",
|
||||
"volume",
|
||||
"tick_volume",
|
||||
"bid1_volume",
|
||||
"ask1_volume",
|
||||
"turnover_ratio",
|
||||
"effective_turnover_ratio",
|
||||
"open",
|
||||
"high",
|
||||
"low",
|
||||
"close",
|
||||
"last",
|
||||
"last_price",
|
||||
"prev_close",
|
||||
"amount",
|
||||
"upper_limit",
|
||||
"lower_limit",
|
||||
"price_tick",
|
||||
"round_lot",
|
||||
"paused",
|
||||
"is_st",
|
||||
"is_kcb",
|
||||
"is_one_yuan",
|
||||
"is_new_listing",
|
||||
"allow_buy",
|
||||
"allow_sell",
|
||||
"touched_upper_limit",
|
||||
"touched_lower_limit",
|
||||
"hit_upper_limit",
|
||||
"hit_lower_limit",
|
||||
"listed_days",
|
||||
"symbol_open_order_count",
|
||||
"symbol_open_buy_qty",
|
||||
"symbol_open_sell_qty",
|
||||
"latest_symbol_open_order_id",
|
||||
"latest_symbol_open_order_status",
|
||||
"latest_symbol_open_order_unfilled_qty",
|
||||
"stock_ma_short",
|
||||
"stock_ma_mid",
|
||||
"stock_ma_long",
|
||||
"stock_ma5",
|
||||
"stock_ma10",
|
||||
"stock_ma20",
|
||||
"stock_ma30",
|
||||
"ma5",
|
||||
"ma10",
|
||||
"ma20",
|
||||
"ma30",
|
||||
"factors",
|
||||
"order_book_id",
|
||||
// position-level
|
||||
"avg_cost",
|
||||
"avg_price",
|
||||
"current_price",
|
||||
"position_prev_close",
|
||||
"prev_position_close",
|
||||
"holding_return",
|
||||
"quantity",
|
||||
"sellable_qty",
|
||||
"sellable",
|
||||
"closable",
|
||||
"old_quantity",
|
||||
"buy_quantity",
|
||||
"sell_quantity",
|
||||
"bought_quantity",
|
||||
"sold_quantity",
|
||||
"buy_avg_price",
|
||||
"sell_avg_price",
|
||||
"bought_value",
|
||||
"sold_value",
|
||||
"transaction_cost",
|
||||
"position_market_value",
|
||||
"equity",
|
||||
"value_percent",
|
||||
"unrealized_pnl",
|
||||
"realized_pnl",
|
||||
"pnl",
|
||||
"day_trade_quantity_delta",
|
||||
"profit_pct",
|
||||
"trading_pnl",
|
||||
"position_pnl",
|
||||
"dividend_receivable",
|
||||
"at_upper_limit",
|
||||
"at_lower_limit",
|
||||
];
|
||||
|
||||
const RUNTIME_HELPER_FUNCTIONS: &[&str] = &[
|
||||
"factor",
|
||||
"day_factor",
|
||||
"rolling_mean",
|
||||
"rolling_mean_current",
|
||||
"ma",
|
||||
"sma",
|
||||
"vma",
|
||||
"rolling_sum",
|
||||
"rolling_min",
|
||||
"rolling_max",
|
||||
"rolling_stddev",
|
||||
"stddev",
|
||||
"rolling_zscore",
|
||||
"pct_change",
|
||||
"factor_value",
|
||||
"get_factor_value",
|
||||
"factor_text",
|
||||
"get_factor_text",
|
||||
"dividend_cash",
|
||||
"has_dividend",
|
||||
"split_ratio",
|
||||
"has_split",
|
||||
"securities_margin",
|
||||
"get_securities_margin_value",
|
||||
"shares",
|
||||
"get_shares_value",
|
||||
"turnover_rate",
|
||||
"get_turnover_rate_value",
|
||||
"price_change_rate",
|
||||
"get_price_change_rate_value",
|
||||
"stock_connect",
|
||||
"get_stock_connect_value",
|
||||
"current_performance",
|
||||
"fundamental",
|
||||
"get_fundamentals_value",
|
||||
"financial",
|
||||
"get_financials_value",
|
||||
"pit_financial",
|
||||
"get_pit_financials_value",
|
||||
"industry_code",
|
||||
"get_industry_code",
|
||||
"industry_name",
|
||||
"get_industry_name",
|
||||
"yield_curve",
|
||||
"get_yield_curve_value",
|
||||
"is_margin_stock",
|
||||
"dominant_future",
|
||||
"get_dominant_future",
|
||||
"dominant_future_price",
|
||||
"get_dominant_future_price_value",
|
||||
];
|
||||
|
||||
const RHAI_BUILTIN_FUNCTIONS: &[&str] = &[
|
||||
"round",
|
||||
"floor",
|
||||
"ceil",
|
||||
"abs",
|
||||
"min",
|
||||
"max",
|
||||
"sqrt",
|
||||
"pow",
|
||||
"log",
|
||||
"exp",
|
||||
"clamp",
|
||||
"between",
|
||||
"nz",
|
||||
"safe_div",
|
||||
"iff",
|
||||
"contains",
|
||||
"starts_with",
|
||||
"ends_with",
|
||||
"lower",
|
||||
"upper",
|
||||
"trim",
|
||||
"strlen",
|
||||
];
|
||||
|
||||
const RHAI_KEYWORDS: &[&str] = &[
|
||||
"if", "else", "while", "loop", "for", "in", "break", "continue", "return", "fn", "let",
|
||||
"const", "true", "false", "switch", "do",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn runtime_schema_serializes_to_json_object() {
|
||||
let value = runtime_schema_json();
|
||||
assert!(value.is_object());
|
||||
assert_eq!(value["version"], "1");
|
||||
assert!(value["reservedScopeNames"].is_array());
|
||||
assert!(value["runtimeHelperFunctions"].is_array());
|
||||
assert!(value["rhaiBuiltinFunctions"].is_array());
|
||||
assert!(value["rhaiKeywords"].is_array());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_schema_includes_known_identifiers() {
|
||||
let names: std::collections::HashSet<&str> = RESERVED_SCOPE_NAMES.iter().copied().collect();
|
||||
for required in [
|
||||
"signal_close",
|
||||
"benchmark_close",
|
||||
"close",
|
||||
"avg_cost",
|
||||
"current_price",
|
||||
"stock_ma_short",
|
||||
] {
|
||||
assert!(
|
||||
names.contains(required),
|
||||
"missing reserved name: {required}"
|
||||
);
|
||||
}
|
||||
|
||||
let helpers: std::collections::HashSet<&str> =
|
||||
RUNTIME_HELPER_FUNCTIONS.iter().copied().collect();
|
||||
for required in ["rolling_mean", "factor", "pct_change"] {
|
||||
assert!(
|
||||
helpers.contains(required),
|
||||
"missing helper function: {required}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
use chrono::NaiveDate;
|
||||
use indexmap::IndexMap;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::data::{DataSet, DataSetError, PriceField};
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::data::{DataSet, DataSetError, PriceField};
|
||||
pub struct PositionLot {
|
||||
pub acquired_date: NaiveDate,
|
||||
pub quantity: u32,
|
||||
pub entry_price: f64,
|
||||
pub price: f64,
|
||||
}
|
||||
|
||||
@@ -72,6 +73,7 @@ impl Position {
|
||||
self.lots.push(PositionLot {
|
||||
acquired_date: date,
|
||||
quantity,
|
||||
entry_price: price,
|
||||
price,
|
||||
});
|
||||
self.quantity += quantity;
|
||||
@@ -205,6 +207,22 @@ impl Position {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_buy_trade_cost(&mut self, quantity: u32, value: f64) {
|
||||
if quantity == 0 || !value.is_finite() {
|
||||
return;
|
||||
}
|
||||
let cost = value.max(0.0);
|
||||
if cost <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if let Some(lot) = self.lots.last_mut() {
|
||||
lot.price += cost / quantity as f64;
|
||||
self.recalculate_average_cost();
|
||||
}
|
||||
self.day_trade_cost += cost;
|
||||
self.refresh_day_pnl();
|
||||
}
|
||||
|
||||
pub fn set_dividend_receivable(&mut self, value: f64) {
|
||||
self.dividend_receivable = if value.is_finite() {
|
||||
value.max(0.0)
|
||||
@@ -214,13 +232,28 @@ impl Position {
|
||||
}
|
||||
|
||||
pub fn holding_return(&self, price: f64) -> Option<f64> {
|
||||
if self.quantity == 0 || self.average_cost <= 0.0 {
|
||||
let Some(avg_price) = self.average_entry_price() else {
|
||||
return None;
|
||||
};
|
||||
if avg_price <= 0.0 {
|
||||
None
|
||||
} else {
|
||||
Some((price / self.average_cost) - 1.0)
|
||||
Some((price / avg_price) - 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn average_entry_price(&self) -> Option<f64> {
|
||||
if self.quantity == 0 {
|
||||
return None;
|
||||
}
|
||||
let total = self
|
||||
.lots
|
||||
.iter()
|
||||
.map(|lot| lot.entry_price * lot.quantity as f64)
|
||||
.sum::<f64>();
|
||||
Some(total / self.quantity as f64)
|
||||
}
|
||||
|
||||
fn recalculate_average_cost(&mut self) {
|
||||
if self.quantity == 0 {
|
||||
self.average_cost = 0.0;
|
||||
@@ -237,14 +270,31 @@ impl Position {
|
||||
}
|
||||
|
||||
pub fn apply_cash_dividend(&mut self, dividend_per_share: f64) -> f64 {
|
||||
self.apply_cash_dividend_internal(dividend_per_share, true)
|
||||
}
|
||||
|
||||
pub fn apply_cash_dividend_preserve_cost_basis(&mut self, dividend_per_share: f64) -> f64 {
|
||||
self.apply_cash_dividend_internal(dividend_per_share, false)
|
||||
}
|
||||
|
||||
fn apply_cash_dividend_internal(
|
||||
&mut self,
|
||||
dividend_per_share: f64,
|
||||
adjust_cost_basis: bool,
|
||||
) -> f64 {
|
||||
if self.quantity == 0 || !dividend_per_share.is_finite() || dividend_per_share == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
for lot in &mut self.lots {
|
||||
lot.price -= dividend_per_share;
|
||||
lot.entry_price -= dividend_per_share;
|
||||
if adjust_cost_basis {
|
||||
lot.price -= dividend_per_share;
|
||||
}
|
||||
}
|
||||
if adjust_cost_basis {
|
||||
self.average_cost -= dividend_per_share;
|
||||
}
|
||||
self.average_cost -= dividend_per_share;
|
||||
self.last_price -= dividend_per_share;
|
||||
let cash_delta = self.quantity as f64 * dividend_per_share;
|
||||
self.day_dividend_cash += cash_delta;
|
||||
@@ -264,6 +314,7 @@ impl Position {
|
||||
.map(|lot| PositionLot {
|
||||
acquired_date: lot.acquired_date,
|
||||
quantity: round_half_up_u32(lot.quantity as f64 * ratio),
|
||||
entry_price: lot.entry_price / ratio,
|
||||
price: lot.price / ratio,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -316,6 +367,7 @@ pub struct PortfolioState {
|
||||
positions: IndexMap<String, Position>,
|
||||
cash_receivables: Vec<CashReceivable>,
|
||||
pending_cash_flows: Vec<PendingCashFlow>,
|
||||
day_sold_symbols: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -348,6 +400,7 @@ impl PortfolioState {
|
||||
positions: IndexMap::new(),
|
||||
cash_receivables: Vec::new(),
|
||||
pending_cash_flows: Vec::new(),
|
||||
day_sold_symbols: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -402,7 +455,18 @@ impl PortfolioState {
|
||||
}
|
||||
|
||||
pub fn prune_flat_positions(&mut self) {
|
||||
self.positions.retain(|_, position| !position.is_flat());
|
||||
let mut sold_symbols = Vec::new();
|
||||
self.positions.retain(|symbol, position| {
|
||||
if position.is_flat() {
|
||||
if position.sold_quantity() > 0 {
|
||||
sold_symbols.push(symbol.clone());
|
||||
}
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
self.day_sold_symbols.extend(sold_symbols);
|
||||
}
|
||||
|
||||
pub fn add_cash_receivable(&mut self, receivable: CashReceivable) {
|
||||
@@ -538,6 +602,7 @@ impl PortfolioState {
|
||||
}
|
||||
|
||||
pub fn begin_trading_day(&mut self) {
|
||||
self.day_sold_symbols.clear();
|
||||
for position in self.positions.values_mut() {
|
||||
position.begin_trading_day();
|
||||
}
|
||||
@@ -550,7 +615,31 @@ impl PortfolioState {
|
||||
data: &DataSet,
|
||||
field: PriceField,
|
||||
) -> Result<(), DataSetError> {
|
||||
self.update_prices_with_options(date, data, field, false)
|
||||
}
|
||||
|
||||
pub fn update_prices_with_options(
|
||||
&mut self,
|
||||
date: NaiveDate,
|
||||
data: &DataSet,
|
||||
field: PriceField,
|
||||
same_day_buy_close_mark_at_fill: bool,
|
||||
) -> Result<(), DataSetError> {
|
||||
let day_sold_symbols = self.day_sold_symbols.clone();
|
||||
for position in self.positions.values_mut() {
|
||||
let sold_today =
|
||||
position.sold_quantity() > 0 || day_sold_symbols.contains(&position.symbol);
|
||||
if same_day_buy_close_mark_at_fill
|
||||
&& field == PriceField::Close
|
||||
&& position.day_buy_quantity > 0
|
||||
&& !sold_today
|
||||
&& position.sellable_qty(date) == 0
|
||||
&& position.last_price.is_finite()
|
||||
&& position.last_price > 0.0
|
||||
{
|
||||
position.refresh_day_pnl();
|
||||
continue;
|
||||
}
|
||||
let price = data
|
||||
.price(date, &position.symbol, field)
|
||||
.or_else(|| data.price_on_or_before(date, &position.symbol, field))
|
||||
@@ -705,6 +794,7 @@ impl PortfolioState {
|
||||
.map(|lot| PositionLot {
|
||||
acquired_date: lot.acquired_date,
|
||||
quantity: round_half_up_u32(lot.quantity as f64 * ratio),
|
||||
entry_price: lot.entry_price / ratio,
|
||||
price: lot.price / ratio,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -801,6 +891,35 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strategy_entry_price_excludes_buy_commission_cost_basis() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
let mut position = Position::new("600561.SH");
|
||||
position.buy(date, 22_200, 5.66);
|
||||
position.record_buy_trade_cost(22_200, 100.0);
|
||||
|
||||
assert!(position.average_cost > 5.66);
|
||||
assert!((position.average_entry_price().unwrap() - 5.66).abs() < 1e-12);
|
||||
assert!((position.holding_return(6.06).unwrap() - (6.06 / 5.66 - 1.0)).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cash_dividend_can_preserve_avg_cost_for_aiquant_compatibility() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
let mut position = Position::new("603102.SH");
|
||||
position.buy(date, 1000, 46.45);
|
||||
position.record_buy_trade_cost(1000, 37.16);
|
||||
|
||||
let cost_before = position.average_cost;
|
||||
let entry_before = position.average_entry_price().unwrap();
|
||||
let cash = position.apply_cash_dividend_preserve_cost_basis(0.6);
|
||||
|
||||
assert!((cash - 600.0).abs() < 1e-12);
|
||||
assert!((position.average_cost - cost_before).abs() < 1e-12);
|
||||
assert!((position.average_entry_price().unwrap() - (entry_before - 0.6)).abs() < 1e-12);
|
||||
assert!((position.last_price - 45.85).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portfolio_tracks_dividend_receivable_and_day_pnl() {
|
||||
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
@@ -1066,6 +1185,132 @@ mod tests {
|
||||
assert!(position.position_pnl.abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portfolio_marks_same_day_buy_at_fill_until_next_trading_day() {
|
||||
let buy_date = NaiveDate::from_ymd_opt(2025, 2, 10).unwrap();
|
||||
let next_date = NaiveDate::from_ymd_opt(2025, 2, 11).unwrap();
|
||||
let symbol = "002652.SZ";
|
||||
let mut portfolio = PortfolioState::new(20_000.0);
|
||||
portfolio.position_mut(symbol).buy(buy_date, 1300, 3.01);
|
||||
|
||||
let dataset = DataSet::from_components(
|
||||
vec![Instrument {
|
||||
symbol: symbol.to_string(),
|
||||
name: "Same Day Buy Test".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: None,
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![
|
||||
DailyMarketSnapshot {
|
||||
date: buy_date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: None,
|
||||
day_open: 2.99,
|
||||
open: 2.99,
|
||||
high: 3.06,
|
||||
low: 2.98,
|
||||
close: 3.06,
|
||||
last_price: 3.06,
|
||||
bid1: 3.01,
|
||||
ask1: 3.02,
|
||||
prev_close: 2.98,
|
||||
volume: 152_975,
|
||||
tick_volume: 152_975,
|
||||
bid1_volume: 338,
|
||||
ask1_volume: 2476,
|
||||
trading_phase: None,
|
||||
paused: false,
|
||||
upper_limit: 3.28,
|
||||
lower_limit: 2.68,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
DailyMarketSnapshot {
|
||||
date: next_date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: None,
|
||||
day_open: 3.03,
|
||||
open: 3.03,
|
||||
high: 3.08,
|
||||
low: 3.00,
|
||||
close: 3.07,
|
||||
last_price: 3.07,
|
||||
bid1: 3.06,
|
||||
ask1: 3.07,
|
||||
prev_close: 3.06,
|
||||
volume: 160_000,
|
||||
tick_volume: 160_000,
|
||||
bid1_volume: 1000,
|
||||
ask1_volume: 1000,
|
||||
trading_phase: None,
|
||||
paused: false,
|
||||
upper_limit: 3.37,
|
||||
lower_limit: 2.75,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
BenchmarkSnapshot {
|
||||
date: buy_date,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1000.0,
|
||||
prev_close: 999.0,
|
||||
volume: 1000,
|
||||
},
|
||||
BenchmarkSnapshot {
|
||||
date: next_date,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1001.0,
|
||||
close: 1001.0,
|
||||
prev_close: 1000.0,
|
||||
volume: 1000,
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("dataset");
|
||||
|
||||
portfolio
|
||||
.update_prices_with_options(buy_date, &dataset, PriceField::Close, true)
|
||||
.expect("same day close");
|
||||
let position = portfolio.position(symbol).expect("position");
|
||||
assert!((position.last_price - 3.01).abs() < 1e-9);
|
||||
assert!((position.market_value() - 3913.0).abs() < 1e-6);
|
||||
|
||||
portfolio.begin_trading_day();
|
||||
portfolio
|
||||
.update_prices(next_date, &dataset, PriceField::Close)
|
||||
.expect("next day close");
|
||||
let position = portfolio.position(symbol).expect("position");
|
||||
assert!((position.last_price - 3.07).abs() < 1e-9);
|
||||
assert!((position.market_value() - 3991.0).abs() < 1e-6);
|
||||
|
||||
let prev_date = NaiveDate::from_ymd_opt(2025, 2, 7).unwrap();
|
||||
let mut roundtrip_portfolio = PortfolioState::new(20_000.0);
|
||||
roundtrip_portfolio
|
||||
.position_mut(symbol)
|
||||
.buy(prev_date, 2000, 2.90);
|
||||
roundtrip_portfolio.begin_trading_day();
|
||||
roundtrip_portfolio
|
||||
.position_mut(symbol)
|
||||
.sell(2000, 3.01)
|
||||
.expect("same day sell");
|
||||
roundtrip_portfolio.prune_flat_positions();
|
||||
roundtrip_portfolio
|
||||
.position_mut(symbol)
|
||||
.buy(buy_date, 1800, 3.01);
|
||||
roundtrip_portfolio
|
||||
.update_prices(buy_date, &dataset, PriceField::Close)
|
||||
.expect("same day roundtrip close");
|
||||
let position = roundtrip_portfolio.position(symbol).expect("position");
|
||||
assert!((position.last_price - 3.06).abs() < 1e-9);
|
||||
assert!((position.market_value() - 5508.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_tracks_day_lifecycle_fields() {
|
||||
let prev_date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
use chrono::NaiveDate;
|
||||
|
||||
use crate::data::{CandidateEligibility, DailyMarketSnapshot, PriceField};
|
||||
use crate::instrument::Instrument;
|
||||
use crate::portfolio::Position;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct ChinaAShareRiskControl;
|
||||
|
||||
impl ChinaAShareRiskControl {
|
||||
pub fn instrument_rejection_reason(
|
||||
instrument: Option<&Instrument>,
|
||||
date: NaiveDate,
|
||||
) -> Option<&'static str> {
|
||||
let instrument = instrument?;
|
||||
if instrument
|
||||
.listed_at
|
||||
.is_some_and(|listed_at| listed_at > date)
|
||||
{
|
||||
return Some("not_listed");
|
||||
}
|
||||
if instrument
|
||||
.delisted_at
|
||||
.is_some_and(|delisted_at| delisted_at <= date)
|
||||
{
|
||||
return Some("inactive_or_delisted");
|
||||
}
|
||||
let status = instrument.status.trim().to_ascii_lowercase();
|
||||
if matches!(
|
||||
status.as_str(),
|
||||
"inactive" | "delisted" | "terminated" | "expired"
|
||||
) || status.contains("delist")
|
||||
{
|
||||
return Some("inactive_or_delisted");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn selection_rejection_reason(
|
||||
date: NaiveDate,
|
||||
candidate: &CandidateEligibility,
|
||||
market: &DailyMarketSnapshot,
|
||||
instrument: Option<&Instrument>,
|
||||
) -> Option<&'static str> {
|
||||
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
|
||||
return Some(reason);
|
||||
}
|
||||
if market.paused || candidate.is_paused {
|
||||
return Some("paused");
|
||||
}
|
||||
if candidate.is_st {
|
||||
return Some("st");
|
||||
}
|
||||
if candidate.is_new_listing {
|
||||
return Some("new_listing");
|
||||
}
|
||||
if candidate.is_kcb {
|
||||
return Some("kcb");
|
||||
}
|
||||
if candidate.is_one_yuan || market.day_open <= 1.0 {
|
||||
return Some("one_yuan");
|
||||
}
|
||||
if !candidate.allow_buy || !candidate.allow_sell {
|
||||
return Some("trade_disabled");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn buy_rejection_reason(
|
||||
date: NaiveDate,
|
||||
candidate: &CandidateEligibility,
|
||||
market: &DailyMarketSnapshot,
|
||||
instrument: Option<&Instrument>,
|
||||
check_price: f64,
|
||||
) -> Option<&'static str> {
|
||||
if let Some(reason) = Self::selection_rejection_reason(date, candidate, market, instrument)
|
||||
{
|
||||
return Some(reason);
|
||||
}
|
||||
if !candidate.allow_buy {
|
||||
return Some("buy_disabled");
|
||||
}
|
||||
if market.is_at_upper_limit_price(check_price) {
|
||||
return Some("open at or above upper limit");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn sell_rejection_reason(
|
||||
date: NaiveDate,
|
||||
candidate: &CandidateEligibility,
|
||||
market: &DailyMarketSnapshot,
|
||||
instrument: Option<&Instrument>,
|
||||
position: Option<&Position>,
|
||||
check_price: f64,
|
||||
) -> Option<&'static str> {
|
||||
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
|
||||
return Some(reason);
|
||||
}
|
||||
if market.paused || candidate.is_paused {
|
||||
return Some("paused");
|
||||
}
|
||||
if !candidate.allow_sell {
|
||||
return Some("sell_disabled");
|
||||
}
|
||||
if market.is_at_lower_limit_price(check_price) {
|
||||
return Some("open at or below lower limit");
|
||||
}
|
||||
if position.is_some_and(|position| position.sellable_qty(date) == 0) {
|
||||
return Some("t+1 sellable quantity is zero");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn buy_check_price(market: &DailyMarketSnapshot, price_field: PriceField) -> f64 {
|
||||
market.buy_price(price_field)
|
||||
}
|
||||
|
||||
pub fn sell_check_price(market: &DailyMarketSnapshot, price_field: PriceField) -> f64 {
|
||||
match price_field {
|
||||
PriceField::Last => market.price(PriceField::Last),
|
||||
_ => market.sell_price(price_field),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ use chrono::NaiveDate;
|
||||
|
||||
use crate::data::{CandidateEligibility, DailyMarketSnapshot, PriceField};
|
||||
use crate::portfolio::Position;
|
||||
use crate::risk_control::ChinaAShareRiskControl;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RuleCheck {
|
||||
@@ -47,20 +48,6 @@ pub trait EquityRuleHooks {
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ChinaEquityRuleHooks;
|
||||
|
||||
impl ChinaEquityRuleHooks {
|
||||
fn at_upper_limit(snapshot: &DailyMarketSnapshot, price_field: PriceField) -> bool {
|
||||
snapshot.is_at_upper_limit_price(snapshot.buy_price(price_field))
|
||||
}
|
||||
|
||||
fn at_lower_limit(snapshot: &DailyMarketSnapshot, price_field: PriceField) -> bool {
|
||||
let check_price = match price_field {
|
||||
PriceField::Last => snapshot.price(PriceField::Last),
|
||||
_ => snapshot.sell_price(price_field),
|
||||
};
|
||||
snapshot.is_at_lower_limit_price(check_price)
|
||||
}
|
||||
}
|
||||
|
||||
impl EquityRuleHooks for ChinaEquityRuleHooks {
|
||||
fn can_buy(
|
||||
&self,
|
||||
@@ -69,14 +56,14 @@ impl EquityRuleHooks for ChinaEquityRuleHooks {
|
||||
candidate: &CandidateEligibility,
|
||||
price_field: PriceField,
|
||||
) -> RuleCheck {
|
||||
if snapshot.paused || candidate.is_paused {
|
||||
return RuleCheck::reject("paused");
|
||||
}
|
||||
if !candidate.allow_buy {
|
||||
return RuleCheck::reject("buy disabled by eligibility flags");
|
||||
}
|
||||
if Self::at_upper_limit(snapshot, price_field) {
|
||||
return RuleCheck::reject("open at or above upper limit");
|
||||
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
|
||||
_execution_date,
|
||||
candidate,
|
||||
snapshot,
|
||||
None,
|
||||
ChinaAShareRiskControl::buy_check_price(snapshot, price_field),
|
||||
) {
|
||||
return RuleCheck::reject(reason);
|
||||
}
|
||||
|
||||
RuleCheck::allow()
|
||||
@@ -90,17 +77,15 @@ impl EquityRuleHooks for ChinaEquityRuleHooks {
|
||||
position: &Position,
|
||||
price_field: PriceField,
|
||||
) -> RuleCheck {
|
||||
if snapshot.paused || candidate.is_paused {
|
||||
return RuleCheck::reject("paused");
|
||||
}
|
||||
if !candidate.allow_sell {
|
||||
return RuleCheck::reject("sell disabled by eligibility flags");
|
||||
}
|
||||
if Self::at_lower_limit(snapshot, price_field) {
|
||||
return RuleCheck::reject("open at or below lower limit");
|
||||
}
|
||||
if position.sellable_qty(execution_date) == 0 {
|
||||
return RuleCheck::reject("t+1 sellable quantity is zero");
|
||||
if let Some(reason) = ChinaAShareRiskControl::sell_rejection_reason(
|
||||
execution_date,
|
||||
candidate,
|
||||
snapshot,
|
||||
None,
|
||||
Some(position),
|
||||
ChinaAShareRiskControl::sell_check_price(snapshot, price_field),
|
||||
) {
|
||||
return RuleCheck::reject(reason);
|
||||
}
|
||||
|
||||
RuleCheck::allow()
|
||||
|
||||
@@ -17,6 +17,7 @@ use crate::events::{FillEvent, OrderEvent, OrderSide, OrderStatus, ProcessEvent}
|
||||
use crate::futures::{FuturesAccountState, FuturesOrderIntent};
|
||||
use crate::instrument::Instrument;
|
||||
use crate::portfolio::PortfolioState;
|
||||
use crate::risk_control::ChinaAShareRiskControl;
|
||||
use crate::scheduler::ScheduleRule;
|
||||
use crate::universe::{DynamicMarketCapBandSelector, SelectionContext, UniverseSelector};
|
||||
|
||||
@@ -1090,6 +1091,9 @@ pub struct CnSmallCapRotationConfig {
|
||||
pub base_index_level: f64,
|
||||
pub base_cap_floor: f64,
|
||||
pub cap_span: f64,
|
||||
pub padding_ratio: f64,
|
||||
pub min_padding: f64,
|
||||
pub max_padding: f64,
|
||||
pub short_ma_days: usize,
|
||||
pub long_ma_days: usize,
|
||||
pub stock_short_ma_days: usize,
|
||||
@@ -1101,7 +1105,7 @@ pub struct CnSmallCapRotationConfig {
|
||||
pub take_profit_pct: f64,
|
||||
pub signal_symbol: Option<String>,
|
||||
pub skip_months: Vec<u32>,
|
||||
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
||||
pub skip_month_day_ranges: Vec<(Option<u32>, u32, u32, u32)>,
|
||||
}
|
||||
|
||||
impl CnSmallCapRotationConfig {
|
||||
@@ -1114,6 +1118,9 @@ impl CnSmallCapRotationConfig {
|
||||
base_index_level: 2000.0,
|
||||
base_cap_floor: 7.0,
|
||||
cap_span: 10.0,
|
||||
padding_ratio: 0.5,
|
||||
min_padding: 8.0,
|
||||
max_padding: 20.0,
|
||||
short_ma_days: 3,
|
||||
long_ma_days: 5,
|
||||
stock_short_ma_days: 3,
|
||||
@@ -1138,6 +1145,9 @@ impl CnSmallCapRotationConfig {
|
||||
base_index_level: 2000.0,
|
||||
base_cap_floor: 7.0,
|
||||
cap_span: 10.0,
|
||||
padding_ratio: 0.5,
|
||||
min_padding: 8.0,
|
||||
max_padding: 20.0,
|
||||
short_ma_days: 5,
|
||||
long_ma_days: 10,
|
||||
stock_short_ma_days: 5,
|
||||
@@ -1150,23 +1160,29 @@ impl CnSmallCapRotationConfig {
|
||||
signal_symbol: Some("000852.SH".to_string()),
|
||||
skip_months: vec![],
|
||||
skip_month_day_ranges: vec![
|
||||
(1, 15, 30),
|
||||
(4, 15, 29),
|
||||
(8, 15, 31),
|
||||
(10, 20, 30),
|
||||
(12, 20, 30),
|
||||
(None, 1, 15, 30),
|
||||
(None, 4, 15, 29),
|
||||
(None, 8, 15, 31),
|
||||
(None, 10, 20, 30),
|
||||
(None, 12, 20, 30),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
||||
let year = date.year() as u32;
|
||||
let month = date.month();
|
||||
let day = date.day();
|
||||
self.skip_months.contains(&month)
|
||||
|| self
|
||||
.skip_month_day_ranges
|
||||
.iter()
|
||||
.any(|(m, start_day, end_day)| month == *m && day >= *start_day && day <= *end_day)
|
||||
.any(|(window_year, m, start_day, end_day)| {
|
||||
window_year.map(|value| value == year).unwrap_or(true)
|
||||
&& month == *m
|
||||
&& day >= *start_day
|
||||
&& day <= *end_day
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1185,6 +1201,9 @@ impl CnSmallCapRotationStrategy {
|
||||
config.cap_span,
|
||||
config.xs,
|
||||
config.stocknum,
|
||||
config.padding_ratio,
|
||||
config.min_padding,
|
||||
config.max_padding,
|
||||
),
|
||||
config,
|
||||
last_gross_exposure: None,
|
||||
@@ -1508,6 +1527,9 @@ pub struct OmniMicroCapConfig {
|
||||
pub base_index_level: f64,
|
||||
pub base_cap_floor: f64,
|
||||
pub cap_span: f64,
|
||||
pub padding_ratio: f64,
|
||||
pub min_padding: f64,
|
||||
pub max_padding: f64,
|
||||
pub benchmark_signal_symbol: String,
|
||||
pub benchmark_short_ma_days: usize,
|
||||
pub benchmark_long_ma_days: usize,
|
||||
@@ -1518,7 +1540,7 @@ pub struct OmniMicroCapConfig {
|
||||
pub trade_rate: f64,
|
||||
pub stop_loss_ratio: f64,
|
||||
pub take_profit_ratio: f64,
|
||||
pub skip_month_day_ranges: Vec<(u32, u32, u32)>,
|
||||
pub skip_month_day_ranges: Vec<(Option<u32>, u32, u32, u32)>,
|
||||
}
|
||||
|
||||
impl OmniMicroCapConfig {
|
||||
@@ -1531,6 +1553,9 @@ impl OmniMicroCapConfig {
|
||||
base_index_level: 2000.0,
|
||||
base_cap_floor: 7.0,
|
||||
cap_span: 10.0,
|
||||
padding_ratio: 0.5,
|
||||
min_padding: 8.0,
|
||||
max_padding: 20.0,
|
||||
benchmark_signal_symbol: "000001.SH".to_string(),
|
||||
benchmark_short_ma_days: 5,
|
||||
benchmark_long_ma_days: 10,
|
||||
@@ -1547,12 +1572,44 @@ impl OmniMicroCapConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn aiquant_v104() -> Self {
|
||||
Self {
|
||||
strategy_name: "aiquant-v1.0.4".to_string(),
|
||||
refresh_rate: 120,
|
||||
stocknum: 5,
|
||||
xs: 4.0 / 500.0,
|
||||
base_index_level: 2000.0,
|
||||
base_cap_floor: 7.0,
|
||||
cap_span: 10.0,
|
||||
padding_ratio: 1.2,
|
||||
min_padding: 29.5,
|
||||
max_padding: 50.0,
|
||||
benchmark_signal_symbol: "000852.SH".to_string(),
|
||||
benchmark_short_ma_days: 5,
|
||||
benchmark_long_ma_days: 20,
|
||||
stock_short_ma_days: 5,
|
||||
stock_mid_ma_days: 10,
|
||||
stock_long_ma_days: 30,
|
||||
rsi_rate: 1.0001,
|
||||
trade_rate: 0.5,
|
||||
stop_loss_ratio: 0.92,
|
||||
take_profit_ratio: 1.16,
|
||||
skip_month_day_ranges: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
||||
let year = date.year() as u32;
|
||||
let month = date.month();
|
||||
let day = date.day();
|
||||
self.skip_month_day_ranges
|
||||
.iter()
|
||||
.any(|(m, start_day, end_day)| month == *m && day >= *start_day && day <= *end_day)
|
||||
.any(|(window_year, m, start_day, end_day)| {
|
||||
window_year.map(|value| value == year).unwrap_or(true)
|
||||
&& month == *m
|
||||
&& day >= *start_day
|
||||
&& day <= *end_day
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1675,6 +1732,7 @@ impl OmniMicroCapStrategy {
|
||||
.max(1)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn projected_buy_quantity(&self, cash: f64, sizing_price: f64, execution_price: f64) -> u32 {
|
||||
if cash <= 0.0 || sizing_price <= 0.0 || execution_price <= 0.0 {
|
||||
return 0;
|
||||
@@ -1723,11 +1781,23 @@ impl OmniMicroCapStrategy {
|
||||
if !sizing_price.is_finite() || sizing_price <= 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let snapshot_requested_qty = self.round_lot_quantity(
|
||||
let mut snapshot_requested_qty = self.round_lot_quantity(
|
||||
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
|
||||
minimum_order_quantity,
|
||||
order_step_size,
|
||||
);
|
||||
while snapshot_requested_qty > 0 {
|
||||
let gross_amount = sizing_price * snapshot_requested_qty as f64;
|
||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||
break;
|
||||
}
|
||||
snapshot_requested_qty = self.decrement_order_quantity(
|
||||
snapshot_requested_qty,
|
||||
minimum_order_quantity,
|
||||
order_step_size,
|
||||
);
|
||||
}
|
||||
let projected_execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
||||
let projected_fill = self.projected_select_execution_fill(
|
||||
ctx,
|
||||
@@ -1739,14 +1809,15 @@ impl OmniMicroCapStrategy {
|
||||
minimum_order_quantity,
|
||||
order_step_size,
|
||||
false,
|
||||
Some(projected.cash()),
|
||||
Some(order_value + 400.0),
|
||||
Some(projected.cash().min(order_value)),
|
||||
Some(order_value),
|
||||
execution_state,
|
||||
);
|
||||
let mut quantity = snapshot_requested_qty;
|
||||
while quantity > 0 {
|
||||
let gross_amount = projected_execution_price * quantity as f64;
|
||||
if gross_amount <= order_value + 400.0 && gross_amount <= projected.cash() + 1e-6 {
|
||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||
break;
|
||||
}
|
||||
quantity =
|
||||
@@ -1761,7 +1832,8 @@ impl OmniMicroCapStrategy {
|
||||
.unwrap_or(projected_execution_price);
|
||||
while quantity > 0 {
|
||||
let gross_amount = execution_price * quantity as f64;
|
||||
if gross_amount <= projected.cash() + 1e-6 {
|
||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||
break;
|
||||
}
|
||||
quantity =
|
||||
@@ -1777,7 +1849,7 @@ impl OmniMicroCapStrategy {
|
||||
};
|
||||
let gross_amount = fill.price * fill.quantity as f64;
|
||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||
if gross_amount > projected.cash() + 1e-6 {
|
||||
if cash_out > projected.cash() + 1e-6 || cash_out > order_value + 1e-6 {
|
||||
return 0;
|
||||
}
|
||||
projected.apply_cash_delta(-cash_out);
|
||||
@@ -1856,6 +1928,7 @@ impl OmniMicroCapStrategy {
|
||||
Some(fill.quantity)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn projected_market_fillable_quantity(
|
||||
&self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
@@ -2095,7 +2168,8 @@ impl OmniMicroCapStrategy {
|
||||
&self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
date: NaiveDate,
|
||||
) -> Result<(f64, f64, f64, f64), BacktestError> {
|
||||
) -> Result<(f64, f64, f64, f64, f64), BacktestError> {
|
||||
// 当前交易日的指数价格(用于MA计算和仓位控制)
|
||||
let current_level = ctx
|
||||
.data
|
||||
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
||||
@@ -2104,6 +2178,16 @@ impl OmniMicroCapStrategy {
|
||||
symbol: self.config.benchmark_signal_symbol.clone(),
|
||||
field: "decision_close",
|
||||
})?;
|
||||
|
||||
// 前一交易日的指数价格(用于市值区间计算,模拟实盘场景)
|
||||
let prev_level = if let Some(prev_date) = ctx.data.previous_trading_date(date, 1) {
|
||||
ctx.data
|
||||
.market_decision_close(prev_date, &self.config.benchmark_signal_symbol)
|
||||
.unwrap_or(current_level)
|
||||
} else {
|
||||
current_level
|
||||
};
|
||||
|
||||
let ma_short = ctx
|
||||
.data
|
||||
.market_decision_close_moving_average(
|
||||
@@ -2135,14 +2219,25 @@ impl OmniMicroCapStrategy {
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Ok((current_level, ma_short, ma_long, trading_ratio))
|
||||
Ok((current_level, prev_level, ma_short, ma_long, trading_ratio))
|
||||
}
|
||||
|
||||
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
|
||||
let y = (index_level - self.config.base_index_level) * self.config.xs
|
||||
+ self.config.base_cap_floor;
|
||||
let start = y.round();
|
||||
(start, start + self.config.cap_span)
|
||||
let end = start + self.config.cap_span;
|
||||
|
||||
// Apply padding to expand the range
|
||||
let span = end - start;
|
||||
let padding = (span * self.config.padding_ratio)
|
||||
.max(self.config.min_padding)
|
||||
.min(self.config.max_padding);
|
||||
|
||||
let lower_bound = (start - padding).max(0.0);
|
||||
let upper_bound = end + padding;
|
||||
|
||||
(lower_bound, upper_bound)
|
||||
}
|
||||
|
||||
fn stock_passes_ma_filter(
|
||||
@@ -2173,19 +2268,67 @@ impl OmniMicroCapStrategy {
|
||||
return false;
|
||||
};
|
||||
|
||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid > ma_long
|
||||
}
|
||||
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
|
||||
let ma_pass =
|
||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
||||
|
||||
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
||||
let instrument_name = ctx
|
||||
.data
|
||||
.instruments()
|
||||
.get(symbol)
|
||||
.map(|instrument| instrument.name.as_str())
|
||||
.unwrap_or("");
|
||||
instrument_name.contains("ST")
|
||||
|| instrument_name.contains('*')
|
||||
|| instrument_name.contains('退')
|
||||
// Debug logging for ALL stocks on first decision date
|
||||
static DEBUG_DATE: std::sync::Mutex<Option<NaiveDate>> = std::sync::Mutex::new(None);
|
||||
let mut debug_date = DEBUG_DATE.lock().unwrap();
|
||||
let should_debug = if let Some(d) = *debug_date {
|
||||
d == date
|
||||
} else {
|
||||
*debug_date = Some(date);
|
||||
true
|
||||
};
|
||||
|
||||
if should_debug {
|
||||
eprintln!(
|
||||
"[MA_FILTER] {} cap={:.2} ma5={:.4} ma10={:.4} ma30={:.4} ma10*rsi={:.4} pass={} ({}>{:.4}? {} && {:.4}>{}? {})",
|
||||
symbol,
|
||||
ctx.data.market_decision_close(date, symbol).unwrap_or(0.0),
|
||||
ma_short,
|
||||
ma_mid,
|
||||
ma_long,
|
||||
ma_mid * self.config.rsi_rate,
|
||||
ma_pass,
|
||||
ma_short,
|
||||
ma_mid * self.config.rsi_rate,
|
||||
ma_short > ma_mid * self.config.rsi_rate,
|
||||
ma_mid * self.config.rsi_rate,
|
||||
ma_long,
|
||||
ma_mid * self.config.rsi_rate > ma_long
|
||||
);
|
||||
}
|
||||
|
||||
if !ma_pass {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
|
||||
if self.config.strategy_name.contains("aiquant")
|
||||
|| self.config.strategy_name.contains("AiQuant")
|
||||
|| self.config.strategy_name.contains("omni")
|
||||
{
|
||||
let Some(volume_ma5) = ctx
|
||||
.data
|
||||
.market_decision_volume_moving_average(date, symbol, 5)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(volume_ma60) = ctx
|
||||
.data
|
||||
.market_decision_volume_moving_average(date, symbol, 60)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if volume_ma5 >= volume_ma60 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn can_sell_position(&self, ctx: &StrategyContext<'_>, date: NaiveDate, symbol: &str) -> bool {
|
||||
@@ -2201,11 +2344,15 @@ impl OmniMicroCapStrategy {
|
||||
let Ok(candidate) = ctx.data.require_candidate(date, symbol) else {
|
||||
return false;
|
||||
};
|
||||
let lower_limit_check_price = market.price(PriceField::Last);
|
||||
!(market.paused
|
||||
|| candidate.is_paused
|
||||
|| !candidate.allow_sell
|
||||
|| market.is_at_lower_limit_price(lower_limit_check_price))
|
||||
ChinaAShareRiskControl::sell_rejection_reason(
|
||||
date,
|
||||
candidate,
|
||||
market,
|
||||
ctx.data.instrument(symbol),
|
||||
Some(position),
|
||||
ChinaAShareRiskControl::sell_check_price(market, PriceField::Last),
|
||||
)
|
||||
.is_none()
|
||||
}
|
||||
|
||||
fn buy_rejection_reason(
|
||||
@@ -2217,30 +2364,14 @@ impl OmniMicroCapStrategy {
|
||||
let market = ctx.data.require_market(date, symbol)?;
|
||||
let candidate = ctx.data.require_candidate(date, symbol)?;
|
||||
|
||||
if market.paused || candidate.is_paused {
|
||||
return Ok(Some("paused".to_string()));
|
||||
}
|
||||
if candidate.is_st || self.special_name(ctx, symbol) {
|
||||
return Ok(Some("st_or_special_name".to_string()));
|
||||
}
|
||||
if candidate.is_kcb {
|
||||
return Ok(Some("kcb".to_string()));
|
||||
}
|
||||
if !candidate.allow_buy {
|
||||
return Ok(Some("buy_disabled".to_string()));
|
||||
}
|
||||
if market.is_at_upper_limit_price(market.day_open)
|
||||
|| market.is_at_upper_limit_price(market.buy_price(PriceField::Last))
|
||||
{
|
||||
return Ok(Some("upper_limit".to_string()));
|
||||
}
|
||||
if market.is_at_lower_limit_price(market.day_open)
|
||||
|| market.is_at_lower_limit_price(market.sell_price(PriceField::Last))
|
||||
{
|
||||
return Ok(Some("lower_limit".to_string()));
|
||||
}
|
||||
if market.day_open <= 1.0 {
|
||||
return Ok(Some("one_yuan".to_string()));
|
||||
if let Some(reason) = ChinaAShareRiskControl::buy_rejection_reason(
|
||||
date,
|
||||
candidate,
|
||||
market,
|
||||
ctx.data.instrument(symbol),
|
||||
ChinaAShareRiskControl::buy_check_price(market, PriceField::Last),
|
||||
) {
|
||||
return Ok(Some(reason.to_string()));
|
||||
}
|
||||
if !self.truth_selection_contains(date, symbol)
|
||||
&& !self.stock_passes_ma_filter(ctx, date, symbol)
|
||||
@@ -2544,25 +2675,31 @@ impl Strategy for OmniMicroCapStrategy {
|
||||
});
|
||||
}
|
||||
|
||||
let (index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
|
||||
Ok(value) => value,
|
||||
Err(BacktestError::Execution(message))
|
||||
if message.contains("insufficient benchmark") =>
|
||||
{
|
||||
return Ok(StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: Vec::new(),
|
||||
notes: vec![format!("warmup: {}", message)],
|
||||
diagnostics: vec![
|
||||
"insufficient history; skip trading on warmup dates".to_string(),
|
||||
],
|
||||
});
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let (band_low, band_high) = self.market_cap_band(index_level);
|
||||
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) =
|
||||
match self.trading_ratio(ctx, date) {
|
||||
Ok(value) => value,
|
||||
Err(BacktestError::Execution(message))
|
||||
if message.contains("insufficient benchmark") =>
|
||||
{
|
||||
return Ok(StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: Vec::new(),
|
||||
notes: vec![format!("warmup: {}", message)],
|
||||
diagnostics: vec![
|
||||
"insufficient history; skip trading on warmup dates".to_string(),
|
||||
],
|
||||
});
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||
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 periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||
let mut projected = ctx.portfolio.clone();
|
||||
@@ -2584,8 +2721,7 @@ impl Strategy for OmniMicroCapStrategy {
|
||||
let stop_hit = current_price
|
||||
<= position.average_cost * self.config.stop_loss_ratio
|
||||
+ self.stop_loss_tolerance(market);
|
||||
let profit_hit = !market.is_at_upper_limit_price(current_price)
|
||||
&& 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);
|
||||
if stop_hit || profit_hit {
|
||||
let sell_reason = if stop_hit {
|
||||
|
||||
@@ -97,10 +97,11 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
"平台策略脚本采用声明式 DSL + 表达式执行模型。".to_string(),
|
||||
"支持 let 变量、fn 自定义函数、when/unless/else 条件块、可用指标/因子字段映射。".to_string(),
|
||||
"支持数值型和字符串型因子,字符串字段可用于行业、概念、标签、板块等分类过滤。".to_string(),
|
||||
"当前默认回测数据已支持 OHLCV、市值、流通市值、换手率、有效换手率、上市天数、停牌/ST/板块、涨跌停价格、tick 触达涨跌停、常用价格/成交量均线;复杂技术指标和财务报表字段必须来自预计算因子或后续扩展函数。".to_string(),
|
||||
"当前默认回测数据已支持 OHLCV、市值、流通市值、换手率、有效换手率、上市天数、停牌/ST/板块、涨跌停价格、tick 触达涨跌停、常用价格/成交量均线,以及 stock_indicator_factors_v1 中已入库的通用指标因子。".to_string(),
|
||||
"AI 生成策略时只能输出完整 engine-script 代码,不输出 Markdown、解释、推理过程、JSON 包装或手册复述。".to_string(),
|
||||
"表达式字段以运行时字段为准:市值使用 market_cap,流通市值使用 free_float_cap;不要在策略表达式中使用数据库原始字段 float_market_cap。".to_string(),
|
||||
"60日价格均线使用 rolling_mean(\"close\", 60),不要使用 ma60、stock_ma60、signal_ma60 或 benchmark_ma60。".to_string(),
|
||||
"任意窗口价格均线使用 rolling_mean(\"close\", n) 或 ma(\"close\", n),任意窗口均量使用 rolling_mean(\"volume\", n) 或 vma(n);不要使用未列出的 ma60、stock_ma60、signal_ma60 或 benchmark_ma60 变量。".to_string(),
|
||||
"next_bar_open 会用决策日信号生成订单,并在下一可交易开盘撮合;不得把执行日 open/high/low/close 当成下单前已知信息。".to_string(),
|
||||
"自定义 fn 必须通过参数传入运行时字段;不要用 fn score() 这类零参数函数直接引用 market_cap、close、ma5 等股票字段。".to_string(),
|
||||
"禁止自由 Python/JavaScript 命令式语句,最终必须输出平台 DSL。".to_string(),
|
||||
],
|
||||
@@ -165,6 +166,10 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
title: "诊断解释".to_string(),
|
||||
detail: "结果为空或收益异常时优先展示 diagnostics、选股数量、过滤原因、缺失字段、窗口不足、涨跌停/停牌拒单、快照缓存命中情况。不要只返回 JSON;要给用户自然语言结论和下一步优化建议。".to_string(),
|
||||
},
|
||||
ManualSection {
|
||||
title: "收益合理性复核".to_string(),
|
||||
detail: "展示或用于优化前,应按 finalEquity / initialCash - 1 复算总收益。若小资金回测出现极端收益、指标与资金不一致、或历史 run 来自旧引擎,应检查交易明细并用当前编译后的回测引擎重新回测,不要把异常 run 当成成功样本。".to_string(),
|
||||
},
|
||||
],
|
||||
optimization_playbook: vec![
|
||||
ManualSection {
|
||||
@@ -215,7 +220,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
},
|
||||
ManualSection {
|
||||
title: "execution.matching_type / execution.slippage".to_string(),
|
||||
detail: "设置撮合模式和滑点。支持 execution.matching_type(\"next_tick_last\" | \"next_tick_best_own\" | \"next_tick_best_counterparty\" | \"counterparty_offer\" | \"vwap\" | \"current_bar_close\" | \"next_bar_open\" | \"open_auction\")。其中 next_tick_last 使用 tick 的 last_price;next_tick_best_own / next_tick_best_counterparty 会按 L1 买一卖一近似 平台内核 的 tick 最优价语义;counterparty_offer 在存在 order_book_depth 多档盘口数据时会按真实档位逐档扫单并计算加权成交价,不存在 depth 时回退 L1 对手方报价;vwap 会在盘中执行价链路上聚合多笔成交为单条 VWAP 成交;open_auction 使用当日集合竞价开盘价 day_open 进行撮合,且不额外施加滑点,并按竞价成交量而不是盘口一档流动性限制成交;滑点支持 execution.slippage(\"none\") / execution.slippage(\"price_ratio\", 0.001) / execution.slippage(\"tick_size\", 1) / execution.slippage(\"limit_price\"),其中 limit_price 会在限价单成交时按挂单价模拟 平台内核 的最坏成交价。".to_string(),
|
||||
detail: "设置撮合模式和滑点。支持 execution.matching_type(\"next_tick_last\" | \"next_tick_best_own\" | \"next_tick_best_counterparty\" | \"counterparty_offer\" | \"vwap\" | \"current_bar_close\" | \"next_bar_open\" | \"open_auction\")。其中 next_tick_last 使用 tick 的 last_price;next_tick_best_own / next_tick_best_counterparty 会按 L1 买一卖一近似 平台内核 的 tick 最优价语义;counterparty_offer 在存在 order_book_depth 多档盘口数据时会按真实档位逐档扫单并计算加权成交价,不存在 depth 时回退 L1 对手方报价;vwap 会在盘中执行价链路上聚合多笔成交为单条 VWAP 成交;next_bar_open 使用决策日信号并在下一可交易日开盘撮合,禁止把执行日 open/high/low/close 解释为下单前已知数据;open_auction 使用当日集合竞价开盘价 day_open 进行撮合,且不额外施加滑点,并按竞价成交量而不是盘口一档流动性限制成交;滑点支持 execution.slippage(\"none\") / execution.slippage(\"price_ratio\", 0.001) / execution.slippage(\"tick_size\", 1) / execution.slippage(\"limit_price\"),其中 limit_price 会在限价单成交时按挂单价模拟 平台内核 的最坏成交价。".to_string(),
|
||||
},
|
||||
ManualSection {
|
||||
title: "期货提交校验".to_string(),
|
||||
@@ -262,7 +267,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
fields: vec![
|
||||
ManualField { name: "symbol".to_string(), field_type: "string".to_string(), detail: "证券代码。".to_string() },
|
||||
ManualField { name: "market_cap/free_float_cap".to_string(), field_type: "float".to_string(), detail: "总市值、流通市值。".to_string() },
|
||||
ManualField { name: "turnover_ratio/effective_turnover_ratio".to_string(), field_type: "float".to_string(), detail: "换手率、有效换手率。".to_string() },
|
||||
ManualField { name: "turnover/turnover_ratio/effective_turnover_ratio".to_string(), field_type: "float".to_string(), detail: "换手率、换手率标准字段、有效换手率;turnover 是 turnover_ratio 的兼容别名。".to_string() },
|
||||
ManualField { name: "open/high/low/close/last/last_price/prev_close/amount".to_string(), field_type: "float".to_string(), detail: "开盘、最高、最低、收盘、盘中价、昨收和成交额。".to_string() },
|
||||
ManualField { name: "upper_limit/lower_limit/price_tick/round_lot/minimum_order_quantity/order_step_size".to_string(), field_type: "float/int".to_string(), detail: "涨跌停、最小价位、整手、最小下单量和数量步长。KSH/BJSE 等板块可与 round_lot 不同。".to_string() },
|
||||
ManualField { name: "paused/is_st/is_kcb/is_one_yuan/is_new_listing".to_string(), field_type: "bool".to_string(), detail: "可交易性与板块标志。".to_string() },
|
||||
@@ -323,9 +328,11 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
ManualFunction { name: "order/order_status/order_avg_price/order_transaction_cost".to_string(), signature: "ctx.order(order_id)".to_string(), detail: "按订单 id 查询运行时订单对象,支持已结束订单和当前挂单。返回字段包括 status、filled_quantity、unfilled_quantity、avg_price、transaction_cost、symbol、side、reason;可用便捷函数读取状态、成交均价和费用,对齐 平台内核 Order 的核心属性。".to_string() },
|
||||
ManualFunction { name: "account/portfolio_view/accounts".to_string(), signature: "ctx.account()".to_string(), detail: "返回当前股票账户/组合运行时视图,字段包括 account_type、cash、available_cash、frozen_cash、market_value、total_value、unit_net_value、daily_pnl、daily_returns、total_returns、transaction_cost、trading_pnl、position_pnl 等;DSL 中同名字段可直接使用。也可用 ctx.stock_account()、ctx.account_by_type(\"STOCK\")、ctx.accounts() 按账户类型读取;当前股票回测路径不会把 FUTURE 虚假映射成 STOCK。".to_string() },
|
||||
ManualFunction { name: "deposit_withdraw/finance_repay/management_fee".to_string(), signature: "account.deposit_withdraw(amount, receiving_days=0)".to_string(), detail: "策略账户资金动作。deposit_withdraw 正数入金、负数出金;receiving_days 大于 0 时按交易日延迟到账,并保持净值口径不把外部资金流当成收益。finance_repay 正数融资、负数还款,会同步维护 cash_liabilities。set_management_fee_rate 设置结算管理费率;普通策略可覆盖 management_fee(ctx, rate) 自定义计算器,对齐 平台内核 管理费回调能力。".to_string() },
|
||||
ManualFunction { name: "rolling_mean".to_string(), signature: "rolling_mean(\"field\", lookback)".to_string(), detail: "任意字段滚动均值,支持 volume/amount/turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 等。个股 volume 与 close 均按当前交易日前已完成交易日计算;单只股票历史窗口不足时,在选股过滤和买入仓位表达式中按不通过/0 仓处理,不会中断整次回测。任意成交量窗口推荐用它,比如 rolling_mean(\"volume\", 15)。".to_string() },
|
||||
ManualFunction { name: "sma".to_string(), signature: "sma(\"field\", lookback)".to_string(), detail: "rolling_mean 的别名。任意价格均线窗口推荐用它,比如 sma(\"close\", 15)。".to_string() },
|
||||
ManualFunction { name: "复杂技术指标".to_string(), signature: "factor_value(\"macd\", 1) 或预计算字段".to_string(), detail: "BOLL、EMA、WMA、DEMA、TEMA、KAMA、SAR、ADX、CCI、MACD、RSI、KDJ、WILLR、ATR、ROC、TRIX、MFI、Aroon、OBV、ADL、Beta、相关系数、线性回归、标准差、方差、K 线形态等目前不是默认内建函数;可先预计算成数值因子,再用 factor_value/rolling_mean 读取。".to_string() },
|
||||
ManualFunction { name: "rolling_mean / sma / ma".to_string(), signature: "rolling_mean(\"field\", lookback) / ma(\"close\", 20)".to_string(), detail: "任意字段滚动均值,支持 close、volume、amount、turnover_ratio、effective_turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 和所有数值型 extra_factors。个股 close 使用当前交易日前已完成收盘序列,volume 使用当前交易日前已完成成交量序列;历史窗口不足时在选股过滤和买入仓位表达式中按不通过/0 仓处理。".to_string() },
|
||||
ManualFunction { name: "vma".to_string(), signature: "vma(60)".to_string(), detail: "rolling_mean(\"volume\", lookback) 的便捷别名,用于任意窗口成交量均线,例如 vma(5) < vma(60)。".to_string() },
|
||||
ManualFunction { name: "rolling_sum / rolling_min / rolling_max".to_string(), signature: "rolling_sum(\"volume\", 20)".to_string(), detail: "任意数值字段滚动求和、最小值、最大值。可用于量能收缩、区间高低点、资金活跃度等过滤或排序。".to_string() },
|
||||
ManualFunction { name: "rolling_stddev / stddev / rolling_zscore / pct_change".to_string(), signature: "stddev(\"close\", 20) / pct_change(\"close\", 10)".to_string(), detail: "滚动标准差、最新值 Z 分数和区间涨跌幅。pct_change(field, n) 会读取 n+1 个窗口点并计算 latest / first - 1。".to_string() },
|
||||
ManualFunction { name: "数据库指标因子".to_string(), signature: "factor_value(\"ths_valid_turnover_stock\", 1)".to_string(), detail: "stock_indicator_factors_v1 中的指标会进入 extra_factors,可用 factor(\"字段\")、factors[\"字段\"]、factor_value(\"字段\", lookback) 或 rolling_mean(\"字段\", n) 读取。市值类指标统一提供亿元口径别名 ths_market_value_stock、ths_market_value_stock_bn、ths_current_mv_stock、ths_current_mv_stock_bn,同时保留 raw 后缀原始值。".to_string() },
|
||||
ManualFunction { name: "round/floor/ceil/abs/min/max/clamp".to_string(), signature: "round(x)".to_string(), detail: "常用数值函数。".to_string() },
|
||||
ManualFunction { name: "safe_div".to_string(), signature: "safe_div(lhs, rhs, fallback)".to_string(), detail: "安全除法。".to_string() },
|
||||
ManualFunction { name: "contains/starts_with/ends_with/lower/upper/trim/strlen".to_string(), signature: "starts_with(symbol, \"60\")".to_string(), detail: "字符串辅助函数。".to_string() },
|
||||
@@ -343,7 +350,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
||||
},
|
||||
ManualFactorSource {
|
||||
table: "扩展指标因子".to_string(),
|
||||
detail: "当前可用扩展指标主要包括总市值、流通市值、换手率、有效换手率;其他财务、行业、概念、陆股通、技术指标等只有落地为可用因子后才可在策略中直接使用。".to_string(),
|
||||
detail: "来自 stock_indicator_factors_v1 和运行时 extra_factors。已入库指标会自动进入策略运行时,字段名使用 dataset 小写下划线;市值类默认换算为亿元口径,raw 后缀保留原始 indicator_value。".to_string(),
|
||||
fields: vec![],
|
||||
},
|
||||
ManualFactorSource {
|
||||
@@ -428,10 +435,15 @@ pub fn render_manual_markdown(manual: &StrategyAiManual) -> String {
|
||||
out.push_str("- 只使用支持语句块:`market`、`benchmark`、`signal`、`rebalance.every_days(...).at([...])`、`selection.limit`、`selection.market_cap_band`、`filter.stock_ma`、`filter.stock_expr`、`ordering.rank_by`、`ordering.rank_expr`、`allocation.buy_scale`、`risk.stop_loss`、`risk.take_profit`、`risk.index_exposure`、`execution.matching_type`、`execution.slippage`、`universe.exclude`。\n");
|
||||
out.push_str("- 禁止伪 DSL:`filter(...)`、`rank(...)`、`select.top(...)`、`weight.equal(...)`、`sell_rule(...)`、`backtest(...)`、`risk.max_position(...)`。\n");
|
||||
out.push_str("- 市值表达式字段只能用 `market_cap` 或 `free_float_cap`;不要使用数据库原始字段 `float_market_cap`。\n");
|
||||
out.push_str("- 60日价格均线使用 `rolling_mean(\"close\", 60)`;不要使用 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60`。\n");
|
||||
out.push_str("- 任意窗口价格均线使用 `rolling_mean(\"close\", n)` 或 `ma(\"close\", n)`;任意窗口均量使用 `rolling_mean(\"volume\", n)` 或 `vma(n)`;不要使用未列出的 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60` 变量。\n");
|
||||
out.push_str("- 自定义 `fn` 必须通过参数传入运行时字段;不要用 `fn score()` 这类零参数函数直接引用 `market_cap`、`close`、`ma5` 等股票字段。\n");
|
||||
out.push_str("- `selection.market_cap_band` 必须写命名参数:`field=\"market_cap\"` 或 `field=\"free_float_cap\"`,并包含 `lower=...` 与 `upper=...`。\n");
|
||||
out.push_str("- `risk.index_exposure(...)` 只能传一个表达式;`execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
|
||||
out.push_str(
|
||||
"- `risk.index_exposure(...)` 只能传一个表达式;不要生成 `risk.exposure(...)`。\n",
|
||||
);
|
||||
out.push_str("- 完整三元表达式 `cond ? a : b` 可在表达式参数中使用;若当前运行环境报 `Unknown operator: '?'`,先重编译并重启回测服务,不要改写策略语义掩盖运行时漂移。\n");
|
||||
out.push_str("- `next_bar_open` 的选股、排序和仓位信号来自决策日,订单在下一可交易开盘撮合;不要使用执行日价格作为下单前信号。\n");
|
||||
out.push_str("- `execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
|
||||
out.push_str("## 语句块\n");
|
||||
for item in &manual.statement_blocks {
|
||||
out.push_str(&format!("- `{}`: {}\n", item.title, item.detail));
|
||||
@@ -506,9 +518,9 @@ pub fn build_generation_prompt(
|
||||
prompt.push_str("- 生成的代码必须能转换为 strategy_spec 并提交 POST /v1/backtests。\n");
|
||||
prompt.push_str("- 不要使用手册未列出的字段、函数或外部平台 API 名称。\n\n");
|
||||
prompt.push_str("只允许使用这些可编译语句:market、benchmark、signal、rebalance.every_days(...).at([...])、selection.limit、selection.market_cap_band、filter.stock_ma、filter.stock_expr、ordering.rank_by、ordering.rank_expr、allocation.buy_scale、risk.stop_loss、risk.take_profit、risk.index_exposure、execution.matching_type、execution.slippage、universe.exclude。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
|
||||
prompt.push_str("参数形态必须严格:selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap;禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma60,60日价格均线写 rolling_mean(\"close\", 60);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit,不要写 is_st == 0;risk.index_exposure 只能传一个数值表达式,例如 ((signal_close < signal_ma20) ? 0.35 : 1.0);execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auction;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
|
||||
prompt.push_str("参数形态必须严格:selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap;禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma60,60日价格均线写 rolling_mean(\"close\", 60) 或 ma(\"close\", 60),任意窗口均量写 rolling_mean(\"volume\", n) 或 vma(n);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit,不要写 is_st == 0;risk.index_exposure 只能传一个数值表达式,不要使用 risk.exposure;完整三元表达式 cond ? a : b 可以使用,但不得输出残缺问号/冒号片段;execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auction;next_bar_open 只能使用决策日信号,不能把执行日价格当作下单前信息;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
|
||||
prompt.push_str("回测成功但 tradeCount=0 或 holdingCount=0 是无效策略;第一版必须保持稳定买入覆盖率,复杂因子只能在后续优化中逐步加严。\n");
|
||||
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure((signal_close < signal_ma20) ? 0.35 : 1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
|
||||
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure(1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
|
||||
prompt.push_str("用户目标:\n");
|
||||
prompt.push_str(&format!("- {}\n", request.user_goal));
|
||||
if !request.constraints.is_empty() {
|
||||
@@ -534,7 +546,8 @@ pub fn build_optimization_prompt(
|
||||
prompt.push_str("你是 OmniQuant 平台策略脚本优化器。必须输出完整、可运行的平台策略脚本,不要输出解释文本。\n");
|
||||
prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n");
|
||||
prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n");
|
||||
prompt.push_str("只修改与优化目标相关的少量参数或过滤条件,保留原策略的市场、基准、信号指数和核心风控;不要引入手册未列出的字段或外部平台 API 名称。\n");
|
||||
prompt.push_str("优化不限制在原策略已有参数或少量扰动。只要 OmniQuant/FIDC 已支持,可以自由增加、修改、删除策略代码、参数、候选池、过滤函数、排序、仓位、止盈止损、调仓周期、指标因子和辅助函数;不得引入手册未列出的字段或外部平台 API 名称。\n");
|
||||
prompt.push_str("可以使用所有已入库日频字段、指标因子和表达式函数,例如 rolling_mean/ma/vma/rolling_sum/rolling_stddev/pct_change/factor/factor_value/factors;如上一轮无交易或质量分过低,必须先扩大候选覆盖并修正不可交易过滤,再优化收益。\n");
|
||||
prompt.push_str("优化目标:\n");
|
||||
prompt.push_str(&format!("- {}\n\n", request.objective));
|
||||
prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n");
|
||||
|
||||
@@ -78,6 +78,9 @@ pub struct DynamicMarketCapBandSelector {
|
||||
pub cap_span: f64,
|
||||
pub xs: f64,
|
||||
pub top_n: usize,
|
||||
pub padding_ratio: f64,
|
||||
pub min_padding: f64,
|
||||
pub max_padding: f64,
|
||||
}
|
||||
|
||||
impl DynamicMarketCapBandSelector {
|
||||
@@ -87,6 +90,9 @@ impl DynamicMarketCapBandSelector {
|
||||
cap_span: f64,
|
||||
xs: f64,
|
||||
top_n: usize,
|
||||
padding_ratio: f64,
|
||||
min_padding: f64,
|
||||
max_padding: f64,
|
||||
) -> Self {
|
||||
Self {
|
||||
base_index_level,
|
||||
@@ -94,11 +100,14 @@ impl DynamicMarketCapBandSelector {
|
||||
cap_span,
|
||||
xs,
|
||||
top_n,
|
||||
padding_ratio,
|
||||
min_padding,
|
||||
max_padding,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn demo(top_n: usize) -> Self {
|
||||
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n)
|
||||
Self::new(2000.0, 7.0, 10.0, 4.0 / 500.0, top_n, 0.5, 8.0, 20.0)
|
||||
}
|
||||
|
||||
pub fn regime(&self, benchmark_level: f64) -> BandRegime {
|
||||
@@ -114,7 +123,18 @@ impl DynamicMarketCapBandSelector {
|
||||
pub fn band_for_level(&self, benchmark_level: f64) -> (f64, f64) {
|
||||
let start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
|
||||
let low = start.round();
|
||||
(low, low + self.cap_span)
|
||||
let high = low + self.cap_span;
|
||||
|
||||
// Apply padding to expand the range
|
||||
let span = high - low;
|
||||
let padding = (span * self.padding_ratio)
|
||||
.max(self.min_padding)
|
||||
.min(self.max_padding);
|
||||
|
||||
let lower_bound = (low - padding).max(0.0);
|
||||
let upper_bound = high + padding;
|
||||
|
||||
(lower_bound, upper_bound)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ fn china_cost_model_applies_minimum_commission_and_stamp_tax() {
|
||||
assert_eq!(buy.stamp_tax, 0.0);
|
||||
|
||||
let sell = model.calculate(d(2023, 8, 25), OrderSide::Sell, 100_000.0);
|
||||
assert!((sell.commission - 30.0).abs() < 1e-9);
|
||||
assert!((sell.commission - 80.0).abs() < 1e-9);
|
||||
assert!((sell.stamp_tax - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ fn china_cost_model_tracks_minimum_commission_per_order_id() {
|
||||
|
||||
assert!((first.commission - 5.0).abs() < 1e-9);
|
||||
assert!(second.commission.abs() < 1e-9);
|
||||
assert!((third.commission - 1.6).abs() < 1e-9);
|
||||
assert!((third.commission - 12.6).abs() < 1e-9);
|
||||
assert!((another_order.commission - 5.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
|
||||
@@ -300,7 +300,7 @@ fn engine_reinvests_dividend_receivable_in_round_lots() {
|
||||
PriceField::Open,
|
||||
),
|
||||
BacktestConfig {
|
||||
initial_cash: 11_005.0,
|
||||
initial_cash: 11_008.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(buy_date),
|
||||
end_date: Some(payable_date),
|
||||
|
||||
@@ -492,7 +492,7 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
||||
.iter()
|
||||
.find(|holding| holding.symbol == "000002.SZ")
|
||||
.expect("successor holding exists");
|
||||
assert_eq!(successor_holding.quantity, 500);
|
||||
assert_eq!(successor_holding.quantity, 450);
|
||||
assert!(
|
||||
result
|
||||
.holdings_summary
|
||||
@@ -503,6 +503,6 @@ fn engine_applies_successor_conversion_before_delisted_cash_settlement() {
|
||||
event
|
||||
.note
|
||||
.contains("successor_conversion 000001.SZ->000002.SZ")
|
||||
&& event.note.contains("cash=1000.00")
|
||||
&& event.note.contains("cash=900.00")
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -1,16 +1,118 @@
|
||||
use chrono::{NaiveDate, NaiveTime};
|
||||
use fidc_core::{
|
||||
AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel,
|
||||
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, Instrument,
|
||||
IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState, PriceField,
|
||||
ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
|
||||
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, DynamicSlippageConfig,
|
||||
Instrument, IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState,
|
||||
PriceField, ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing,
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
fn order_value_rounding_data(date: NaiveDate, symbol: &str, price: f64) -> DataSet {
|
||||
DataSet::from_components(
|
||||
vec![Instrument {
|
||||
symbol: symbol.to_string(),
|
||||
name: "Test".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: None,
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: Some(format!("{date} 09:33:00")),
|
||||
day_open: price,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
last_price: price,
|
||||
bid1: price,
|
||||
ask1: price,
|
||||
prev_close: price,
|
||||
volume: 100_000,
|
||||
tick_volume: 100_000,
|
||||
bid1_volume: 80_000,
|
||||
ask1_volume: 80_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: price * 1.1,
|
||||
lower_limit: price * 0.9,
|
||||
price_tick: 0.01,
|
||||
}],
|
||||
vec![DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
market_cap_bn: 50.0,
|
||||
free_float_cap_bn: 45.0,
|
||||
pe_ttm: 15.0,
|
||||
turnover_ratio: Some(2.0),
|
||||
effective_turnover_ratio: Some(1.8),
|
||||
extra_factors: BTreeMap::new(),
|
||||
}],
|
||||
vec![CandidateEligibility {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
is_st: false,
|
||||
is_new_listing: false,
|
||||
is_paused: false,
|
||||
allow_buy: true,
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
)
|
||||
.expect("dataset")
|
||||
}
|
||||
|
||||
fn execute_single_value_order(
|
||||
date: NaiveDate,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
value: f64,
|
||||
) -> (PortfolioState, fidc_core::BrokerExecutionReport) {
|
||||
let mut portfolio = PortfolioState::new(20_000.0);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
)
|
||||
.with_strict_value_budget(true);
|
||||
let report = broker
|
||||
.execute(
|
||||
date,
|
||||
&mut portfolio,
|
||||
data,
|
||||
&StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: symbol.to_string(),
|
||||
value,
|
||||
reason: "test_order_value_rounding".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("broker execution");
|
||||
(portfolio, report)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_executes_explicit_order_value_buy() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = DataSet::from_components(
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![Instrument {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
@@ -72,6 +174,20 @@ fn broker_executes_explicit_order_value_buy() {
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
|
||||
last_price: 10.0,
|
||||
bid1: 9.99,
|
||||
ask1: 10.01,
|
||||
bid1_volume: 1,
|
||||
ask1_volume: 1,
|
||||
volume_delta: 1,
|
||||
amount_delta: 0.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
}],
|
||||
)
|
||||
.expect("dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
@@ -108,10 +224,175 @@ fn broker_executes_explicit_order_value_buy() {
|
||||
assert!(portfolio.cash() < 1_000_000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_order_value_rounds_to_nearest_lot_when_min_lot_is_affordable() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 1, 24).unwrap();
|
||||
let symbol = "003017.SZ";
|
||||
let data = order_value_rounding_data(date, symbol, 19.97);
|
||||
|
||||
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 3_938.13);
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert_eq!(report.fill_events[0].quantity, 100);
|
||||
assert_eq!(portfolio.position(symbol).expect("position").quantity, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_order_value_budget_includes_buy_commission() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 6, 23).unwrap();
|
||||
let symbol = "605303.SH";
|
||||
let data = order_value_rounding_data(date, symbol, 11.93);
|
||||
|
||||
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_776.0);
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert_eq!(report.fill_events[0].quantity, 300);
|
||||
assert_eq!(portfolio.position(symbol).expect("position").quantity, 300);
|
||||
|
||||
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_848.0);
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert_eq!(report.fill_events[0].quantity, 400);
|
||||
assert_eq!(portfolio.position(symbol).expect("position").quantity, 400);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_delayed_limit_open_sell_uses_tick_price() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 6, 27).unwrap();
|
||||
let prev_date = NaiveDate::from_ymd_opt(2025, 6, 26).unwrap();
|
||||
let symbol = "300635.SZ";
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![Instrument {
|
||||
symbol: symbol.to_string(),
|
||||
name: "Test".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: None,
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: Some("2025-06-27 09:31:00".to_string()),
|
||||
day_open: 12.55,
|
||||
open: 12.55,
|
||||
high: 13.16,
|
||||
low: 12.26,
|
||||
close: 12.36,
|
||||
last_price: 12.39,
|
||||
bid1: 12.39,
|
||||
ask1: 12.40,
|
||||
prev_close: 13.24,
|
||||
volume: 329_575,
|
||||
tick_volume: 10_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 14.56,
|
||||
lower_limit: 11.92,
|
||||
price_tick: 0.01,
|
||||
}],
|
||||
vec![DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
market_cap_bn: 50.0,
|
||||
free_float_cap_bn: 45.0,
|
||||
pe_ttm: 15.0,
|
||||
turnover_ratio: Some(2.0),
|
||||
effective_turnover_ratio: Some(1.8),
|
||||
extra_factors: BTreeMap::new(),
|
||||
}],
|
||||
vec![CandidateEligibility {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
is_st: false,
|
||||
is_new_listing: false,
|
||||
is_paused: false,
|
||||
allow_buy: true,
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: date.and_hms_opt(9, 31, 0).unwrap(),
|
||||
last_price: 12.39,
|
||||
bid1: 12.39,
|
||||
ask1: 12.40,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
volume_delta: 10_000,
|
||||
amount_delta: 123_900.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
}],
|
||||
)
|
||||
.expect("dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000.0);
|
||||
portfolio.position_mut(symbol).buy(prev_date, 800, 10.92);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_matching_type(MatchingType::NextTickLast)
|
||||
.with_intraday_execution_start_time(NaiveTime::from_hms_opt(9, 31, 0).unwrap())
|
||||
.with_volume_limit(false)
|
||||
.with_liquidity_limit(false);
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
&StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::TargetValue {
|
||||
symbol: symbol.to_string(),
|
||||
target_value: 0.0,
|
||||
reason: "delayed_limit_open_sell".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("broker execution");
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert_eq!(report.fill_events[0].quantity, 800);
|
||||
assert_eq!(report.fill_events[0].price, 12.39);
|
||||
assert!(portfolio.position(symbol).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_order_value_skips_when_one_lot_exceeds_budget() {
|
||||
let date = NaiveDate::from_ymd_opt(2025, 1, 2).unwrap();
|
||||
let symbol = "300321.SZ";
|
||||
let data = order_value_rounding_data(date, symbol, 20.38);
|
||||
|
||||
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 2_000.0);
|
||||
|
||||
assert!(report.fill_events.is_empty());
|
||||
assert!(portfolio.position(symbol).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_executes_order_shares_and_order_lots() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = DataSet::from_components(
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![Instrument {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
@@ -173,6 +454,20 @@ fn broker_executes_order_shares_and_order_lots() {
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
|
||||
last_price: 10.0,
|
||||
bid1: 9.99,
|
||||
ask1: 10.01,
|
||||
bid1_volume: 1,
|
||||
ask1_volume: 1,
|
||||
volume_delta: 1,
|
||||
amount_delta: 0.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
}],
|
||||
)
|
||||
.expect("dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
@@ -750,7 +1045,7 @@ fn broker_executes_order_percent_and_target_percent() {
|
||||
)
|
||||
.expect("percent execution");
|
||||
assert_eq!(percent_report.fill_events.len(), 1);
|
||||
assert_eq!(percent_report.fill_events[0].quantity, 10_000);
|
||||
assert_eq!(percent_report.fill_events[0].quantity, 9_900);
|
||||
|
||||
let mut target_percent_portfolio = PortfolioState::new(1_000_000.0);
|
||||
let target_percent_report = broker
|
||||
@@ -1190,8 +1485,226 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
|
||||
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_applies_dynamic_slippage_on_snapshot_fills() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = DataSet::from_components(
|
||||
vec![Instrument {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: None,
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: Some("2024-01-10 10:18:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 10.1,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
last_price: 10.0,
|
||||
bid1: 9.99,
|
||||
ask1: 10.01,
|
||||
prev_close: 10.0,
|
||||
volume: 100_000,
|
||||
tick_volume: 100_000,
|
||||
bid1_volume: 80_000,
|
||||
ask1_volume: 80_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 11.0,
|
||||
lower_limit: 9.0,
|
||||
price_tick: 0.01,
|
||||
}],
|
||||
vec![DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
market_cap_bn: 50.0,
|
||||
free_float_cap_bn: 45.0,
|
||||
pe_ttm: 15.0,
|
||||
turnover_ratio: Some(2.0),
|
||||
effective_turnover_ratio: Some(1.8),
|
||||
extra_factors: BTreeMap::new(),
|
||||
}],
|
||||
vec![CandidateEligibility {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
is_st: false,
|
||||
is_new_listing: false,
|
||||
is_paused: false,
|
||||
allow_buy: true,
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
)
|
||||
.expect("dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
)
|
||||
.with_slippage_model(SlippageModel::Dynamic(DynamicSlippageConfig::new(
|
||||
0.5, 0.3, 0.1,
|
||||
)));
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
&StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
value: 100_000.0,
|
||||
reason: "dynamic_slippage".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("broker execution");
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
let expected_ratio = ((10.0 * report.fill_events[0].quantity as f64) / (100_000.0 * 10.0))
|
||||
* 0.5
|
||||
+ ((10.1 - 9.9) / 10.0) * 0.3;
|
||||
assert!((report.fill_events[0].price - 10.0 * (1.0 + expected_ratio)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![Instrument {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: None,
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: Some("2024-01-10 10:18:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 10.1,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
last_price: 10.0,
|
||||
bid1: 9.99,
|
||||
ask1: 10.01,
|
||||
prev_close: 10.0,
|
||||
volume: 100_000,
|
||||
tick_volume: 100_000,
|
||||
bid1_volume: 80_000,
|
||||
ask1_volume: 80_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 11.0,
|
||||
lower_limit: 9.0,
|
||||
price_tick: 0.01,
|
||||
}],
|
||||
vec![DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
market_cap_bn: 50.0,
|
||||
free_float_cap_bn: 45.0,
|
||||
pe_ttm: 15.0,
|
||||
turnover_ratio: Some(2.0),
|
||||
effective_turnover_ratio: Some(1.8),
|
||||
extra_factors: BTreeMap::new(),
|
||||
}],
|
||||
vec![CandidateEligibility {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
is_st: false,
|
||||
is_new_listing: false,
|
||||
is_paused: false,
|
||||
allow_buy: true,
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
|
||||
last_price: 10.0,
|
||||
bid1: 9.99,
|
||||
ask1: 10.01,
|
||||
bid1_volume: 1,
|
||||
ask1_volume: 1,
|
||||
volume_delta: 1,
|
||||
amount_delta: 0.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
}],
|
||||
)
|
||||
.expect("dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap())
|
||||
.with_slippage_model(SlippageModel::TickSize(2.0));
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
&StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
value: 100_000.0,
|
||||
reason: "tick_slippage".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("broker execution");
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_rejects_intraday_last_order_without_execution_quotes() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = DataSet::from_components(
|
||||
vec![Instrument {
|
||||
@@ -1263,8 +1776,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap())
|
||||
.with_slippage_model(SlippageModel::TickSize(2.0));
|
||||
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap());
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
@@ -1278,7 +1790,127 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
value: 100_000.0,
|
||||
reason: "tick_slippage".to_string(),
|
||||
reason: "missing_tick_quotes".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
)
|
||||
.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("no execution quotes after start")
|
||||
);
|
||||
assert!(portfolio.position("000002.SZ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_executes_intraday_last_on_start_quote_without_trade_delta() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![Instrument {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Test".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: None,
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: Some("2024-01-10 09:33:00".to_string()),
|
||||
day_open: 15.0,
|
||||
open: 15.0,
|
||||
high: 15.5,
|
||||
low: 14.8,
|
||||
close: 15.2,
|
||||
last_price: 15.2,
|
||||
bid1: 15.19,
|
||||
ask1: 15.21,
|
||||
prev_close: 15.0,
|
||||
volume: 100_000,
|
||||
tick_volume: 100_000,
|
||||
bid1_volume: 80_000,
|
||||
ask1_volume: 80_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 16.5,
|
||||
lower_limit: 13.5,
|
||||
price_tick: 0.01,
|
||||
}],
|
||||
vec![DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
market_cap_bn: 50.0,
|
||||
free_float_cap_bn: 45.0,
|
||||
pe_ttm: 15.0,
|
||||
turnover_ratio: Some(2.0),
|
||||
effective_turnover_ratio: Some(1.8),
|
||||
extra_factors: BTreeMap::new(),
|
||||
}],
|
||||
vec![CandidateEligibility {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
is_st: false,
|
||||
is_new_listing: false,
|
||||
is_paused: false,
|
||||
allow_buy: true,
|
||||
allow_sell: true,
|
||||
is_kcb: false,
|
||||
is_one_yuan: false,
|
||||
}],
|
||||
vec![BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: date.and_hms_opt(9, 33, 0).unwrap(),
|
||||
last_price: 15.2,
|
||||
bid1: 15.19,
|
||||
ask1: 15.21,
|
||||
bid1_volume: 8,
|
||||
ask1_volume: 8,
|
||||
volume_delta: 0,
|
||||
amount_delta: 0.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
}],
|
||||
)
|
||||
.expect("dataset");
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(9, 33, 0).unwrap());
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
&StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
value: 4_000.0,
|
||||
reason: "start_quote".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
@@ -1287,7 +1919,9 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
.expect("broker execution");
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
||||
assert_eq!(report.fill_events[0].quantity, 200);
|
||||
assert!((report.fill_events[0].price - 15.2).abs() < 1e-9);
|
||||
assert_eq!(report.order_events[0].status, OrderStatus::Filled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2108,7 +2742,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::AlgoPercent {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
percent: 0.0036,
|
||||
percent: 0.0037,
|
||||
style: AlgoOrderStyle::Twap,
|
||||
start_time: Some(NaiveTime::from_hms_opt(10, 0, 0).unwrap()),
|
||||
end_time: Some(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
|
||||
|
||||
Reference in New Issue
Block a user