Compare commits
4 Commits
v2026.05.0
...
v2026.5.12
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2165831708 | ||
|
|
1a402f2048 | ||
|
|
bbe60537ff | ||
|
|
3b033fd294 |
@@ -100,6 +100,57 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
let mut engine = BacktestEngine::new(data, strategy, broker, config);
|
||||||
engine.run()?
|
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();
|
let mut strategy_cfg = OmniMicroCapConfig::omni_microcap();
|
||||||
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
if let Ok(signal_symbol) = std::env::var("FIDC_BT_SIGNAL_SYMBOL") {
|
||||||
|
|||||||
@@ -4190,6 +4190,77 @@ impl PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn selectable_universe_on(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
date: NaiveDate,
|
||||||
|
) -> Vec<EligibleUniverseSnapshot> {
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for factor in ctx.data.factor_snapshots_on(date) {
|
||||||
|
if factor.market_cap_bn <= 0.0 || !factor.market_cap_bn.is_finite() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ctx.has_dynamic_universe() && !ctx.dynamic_universe_contains(&factor.symbol) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(candidate) = ctx.data.candidate(date, &factor.symbol) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(market) = ctx.data.market(date, &factor.symbol) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if market.paused {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !self.stock_passes_universe_exclude(
|
||||||
|
candidate,
|
||||||
|
market,
|
||||||
|
self.special_name(ctx, &factor.symbol),
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rows.push(EligibleUniverseSnapshot {
|
||||||
|
symbol: factor.symbol.clone(),
|
||||||
|
market_cap_bn: factor.market_cap_bn,
|
||||||
|
free_float_cap_bn: factor.free_float_cap_bn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
rows.sort_by(|left, right| {
|
||||||
|
left.market_cap_bn
|
||||||
|
.partial_cmp(&right.market_cap_bn)
|
||||||
|
.unwrap_or(std::cmp::Ordering::Equal)
|
||||||
|
.then_with(|| left.symbol.cmp(&right.symbol))
|
||||||
|
});
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stock_passes_universe_exclude(
|
||||||
|
&self,
|
||||||
|
candidate: &crate::data::CandidateEligibility,
|
||||||
|
market: &DailyMarketSnapshot,
|
||||||
|
has_special_name: bool,
|
||||||
|
) -> bool {
|
||||||
|
let excludes = &self.config.universe_exclude;
|
||||||
|
if excludes.iter().any(|item| item == "paused") && (market.paused || candidate.is_paused) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "st") && (candidate.is_st || has_special_name) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "kcb") && candidate.is_kcb {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "new_listing") && candidate.is_new_listing {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if excludes.iter().any(|item| item == "one_yuan")
|
||||||
|
&& (candidate.is_one_yuan || market.day_open <= 1.0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
candidate.allow_buy && candidate.allow_sell
|
||||||
|
}
|
||||||
|
|
||||||
fn stock_numeric_field_value(
|
fn stock_numeric_field_value(
|
||||||
&self,
|
&self,
|
||||||
candidate: &EligibleUniverseSnapshot,
|
candidate: &EligibleUniverseSnapshot,
|
||||||
@@ -4353,7 +4424,7 @@ impl PlatformExprStrategy {
|
|||||||
band_high: f64,
|
band_high: f64,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
) -> Result<(Vec<String>, Vec<String>), BacktestError> {
|
) -> Result<(Vec<String>, Vec<String>), BacktestError> {
|
||||||
let universe = ctx.eligible_universe_on(date);
|
let universe = self.selectable_universe_on(ctx, date);
|
||||||
let mut diagnostics = Vec::new();
|
let mut diagnostics = Vec::new();
|
||||||
let mut candidates = Vec::new();
|
let mut candidates = Vec::new();
|
||||||
for candidate in universe {
|
for candidate in universe {
|
||||||
@@ -5845,6 +5916,152 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_strategy_honors_configured_universe_excludes_for_new_listings() {
|
||||||
|
let date = d(2025, 2, 3);
|
||||||
|
let symbols = ["301001.SZ", "000001.SZ"];
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| Instrument {
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
name: (*symbol).to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2025, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
timestamp: Some("2025-02-03 09:33:00".to_string()),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.5,
|
||||||
|
low: 9.8,
|
||||||
|
close: 10.0,
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
prev_close: 9.9,
|
||||||
|
volume: 1_000_000,
|
||||||
|
tick_volume: 10_000,
|
||||||
|
bid1_volume: 2_000,
|
||||||
|
ask1_volume: 2_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 11.0,
|
||||||
|
lower_limit: 9.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![
|
||||||
|
DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "301001.SZ".to_string(),
|
||||||
|
market_cap_bn: 8.0,
|
||||||
|
free_float_cap_bn: 7.0,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
market_cap_bn: 12.0,
|
||||||
|
free_float_cap_bn: 10.0,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "301001.SZ".to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: true,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
},
|
||||||
|
CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1002.0,
|
||||||
|
prev_close: 998.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 0,
|
||||||
|
data: &data,
|
||||||
|
portfolio: &portfolio,
|
||||||
|
futures_account: None,
|
||||||
|
open_orders: &[],
|
||||||
|
dynamic_universe: None,
|
||||||
|
subscriptions: &subscriptions,
|
||||||
|
process_events: &[],
|
||||||
|
active_process_event: None,
|
||||||
|
active_datetime: None,
|
||||||
|
order_events: &[],
|
||||||
|
fills: &[],
|
||||||
|
};
|
||||||
|
let mut cfg = PlatformExprStrategyConfig::microcap_rotation();
|
||||||
|
cfg.signal_symbol = "000001.SZ".to_string();
|
||||||
|
cfg.refresh_rate = 1;
|
||||||
|
cfg.max_positions = 1;
|
||||||
|
cfg.benchmark_short_ma_days = 1;
|
||||||
|
cfg.benchmark_long_ma_days = 1;
|
||||||
|
cfg.stock_short_ma_days = 1;
|
||||||
|
cfg.stock_mid_ma_days = 1;
|
||||||
|
cfg.stock_long_ma_days = 1;
|
||||||
|
cfg.universe_exclude = vec![
|
||||||
|
"paused".to_string(),
|
||||||
|
"st".to_string(),
|
||||||
|
"kcb".to_string(),
|
||||||
|
"one_yuan".to_string(),
|
||||||
|
];
|
||||||
|
cfg.market_cap_lower_expr = "0".to_string();
|
||||||
|
cfg.market_cap_upper_expr = "100".to_string();
|
||||||
|
cfg.selection_limit_expr = "1".to_string();
|
||||||
|
cfg.stock_filter_expr = "true".to_string();
|
||||||
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||||
|
|
||||||
|
assert!(decision.order_intents.iter().any(|intent| matches!(
|
||||||
|
intent,
|
||||||
|
crate::strategy::OrderIntent::Value { symbol, .. } if symbol == "301001.SZ"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
|
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
|
||||||
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ pub struct StrategyRuntimeSpec {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub benchmark: Option<StrategyBenchmarkSpec>,
|
pub benchmark: Option<StrategyBenchmarkSpec>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub universe: Option<StrategyUniverseSpec>,
|
||||||
|
#[serde(default)]
|
||||||
pub signal_symbol: Option<String>,
|
pub signal_symbol: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub execution: Option<StrategyExecutionSpec>,
|
pub execution: Option<StrategyExecutionSpec>,
|
||||||
@@ -40,6 +42,13 @@ pub struct StrategyBenchmarkSpec {
|
|||||||
pub fallback_instrument_id: Option<String>,
|
pub fallback_instrument_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct StrategyUniverseSpec {
|
||||||
|
#[serde(default)]
|
||||||
|
pub exclude: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct StrategyExecutionSpec {
|
pub struct StrategyExecutionSpec {
|
||||||
@@ -105,6 +114,15 @@ pub struct DynamicRangeConfig {
|
|||||||
pub cap_span: Option<f64>,
|
pub cap_span: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub xs: Option<f64>,
|
pub xs: Option<f64>,
|
||||||
|
/// Padding ratio to expand the market cap range (e.g., 0.5 means 50% of span)
|
||||||
|
#[serde(default)]
|
||||||
|
pub padding_ratio: Option<f64>,
|
||||||
|
/// Minimum padding in billion yuan
|
||||||
|
#[serde(default)]
|
||||||
|
pub min_padding: Option<f64>,
|
||||||
|
/// Maximum padding in billion yuan
|
||||||
|
#[serde(default)]
|
||||||
|
pub max_padding: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
@@ -424,6 +442,14 @@ pub fn platform_expr_config_from_spec(
|
|||||||
cfg.signal_symbol = spec_signal_symbol.clone();
|
cfg.signal_symbol = spec_signal_symbol.clone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(universe) = spec.universe.as_ref() {
|
||||||
|
cfg.universe_exclude = universe
|
||||||
|
.exclude
|
||||||
|
.iter()
|
||||||
|
.map(|item| item.trim().to_ascii_lowercase())
|
||||||
|
.filter(|item| !item.is_empty())
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
let mut prelude_parts = Vec::new();
|
let mut prelude_parts = Vec::new();
|
||||||
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
if let Some(runtime_expr) = spec.runtime_expressions.as_ref()
|
||||||
@@ -619,8 +645,8 @@ pub fn platform_expr_config_from_spec(
|
|||||||
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
if let Some(stock_ma_filter) = engine.stock_ma_filter.as_ref() {
|
||||||
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
let ratio = stock_ma_filter.rsi_rate.unwrap_or(1.0001);
|
||||||
cfg.stock_filter_expr = format!(
|
cfg.stock_filter_expr = format!(
|
||||||
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid > stock_ma_long",
|
"stock_ma_short > stock_ma_mid * {} && stock_ma_mid * {} > stock_ma_long",
|
||||||
ratio
|
ratio, ratio
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
if let Some(index_throttle) = engine.index_throttle.as_ref() {
|
||||||
@@ -1024,6 +1050,7 @@ mod tests {
|
|||||||
"strategyId": "runtime_spec_test",
|
"strategyId": "runtime_spec_test",
|
||||||
"signalSymbol": "000852.SH",
|
"signalSymbol": "000852.SH",
|
||||||
"benchmark": { "instrumentId": "000852.SH" },
|
"benchmark": { "instrumentId": "000852.SH" },
|
||||||
|
"universe": { "exclude": ["paused", "st", "kcb", "one_yuan"] },
|
||||||
"runtimeExpressions": {
|
"runtimeExpressions": {
|
||||||
"prelude": "let stocknum = 8;",
|
"prelude": "let stocknum = 8;",
|
||||||
"selection": {
|
"selection": {
|
||||||
@@ -1054,6 +1081,7 @@ mod tests {
|
|||||||
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
assert_eq!(cfg.strategy_name, "runtime_spec_test");
|
||||||
assert_eq!(cfg.signal_symbol, "000852.SH");
|
assert_eq!(cfg.signal_symbol, "000852.SH");
|
||||||
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
assert_eq!(cfg.selection_limit_expr, "stocknum");
|
||||||
|
assert_eq!(cfg.universe_exclude, ["paused", "st", "kcb", "one_yuan"]);
|
||||||
assert!(!cfg.rotation_enabled);
|
assert!(!cfg.rotation_enabled);
|
||||||
assert!(cfg.daily_top_up_enabled);
|
assert!(cfg.daily_top_up_enabled);
|
||||||
assert!(cfg.retry_empty_rebalance);
|
assert!(cfg.retry_empty_rebalance);
|
||||||
|
|||||||
@@ -1090,6 +1090,9 @@ pub struct CnSmallCapRotationConfig {
|
|||||||
pub base_index_level: f64,
|
pub base_index_level: f64,
|
||||||
pub base_cap_floor: f64,
|
pub base_cap_floor: f64,
|
||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
pub short_ma_days: usize,
|
pub short_ma_days: usize,
|
||||||
pub long_ma_days: usize,
|
pub long_ma_days: usize,
|
||||||
pub stock_short_ma_days: usize,
|
pub stock_short_ma_days: usize,
|
||||||
@@ -1114,6 +1117,9 @@ impl CnSmallCapRotationConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
short_ma_days: 3,
|
short_ma_days: 3,
|
||||||
long_ma_days: 5,
|
long_ma_days: 5,
|
||||||
stock_short_ma_days: 3,
|
stock_short_ma_days: 3,
|
||||||
@@ -1138,6 +1144,9 @@ impl CnSmallCapRotationConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.0,
|
cap_span: 10.0,
|
||||||
|
padding_ratio: 0.5,
|
||||||
|
min_padding: 8.0,
|
||||||
|
max_padding: 20.0,
|
||||||
short_ma_days: 5,
|
short_ma_days: 5,
|
||||||
long_ma_days: 10,
|
long_ma_days: 10,
|
||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
@@ -1185,6 +1194,9 @@ impl CnSmallCapRotationStrategy {
|
|||||||
config.cap_span,
|
config.cap_span,
|
||||||
config.xs,
|
config.xs,
|
||||||
config.stocknum,
|
config.stocknum,
|
||||||
|
config.padding_ratio,
|
||||||
|
config.min_padding,
|
||||||
|
config.max_padding,
|
||||||
),
|
),
|
||||||
config,
|
config,
|
||||||
last_gross_exposure: None,
|
last_gross_exposure: None,
|
||||||
@@ -1508,6 +1520,9 @@ pub struct OmniMicroCapConfig {
|
|||||||
pub base_index_level: f64,
|
pub base_index_level: f64,
|
||||||
pub base_cap_floor: f64,
|
pub base_cap_floor: f64,
|
||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
pub benchmark_signal_symbol: String,
|
pub benchmark_signal_symbol: String,
|
||||||
pub benchmark_short_ma_days: usize,
|
pub benchmark_short_ma_days: usize,
|
||||||
pub benchmark_long_ma_days: usize,
|
pub benchmark_long_ma_days: usize,
|
||||||
@@ -1531,6 +1546,9 @@ impl OmniMicroCapConfig {
|
|||||||
base_index_level: 2000.0,
|
base_index_level: 2000.0,
|
||||||
base_cap_floor: 7.0,
|
base_cap_floor: 7.0,
|
||||||
cap_span: 10.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_signal_symbol: "000001.SH".to_string(),
|
||||||
benchmark_short_ma_days: 5,
|
benchmark_short_ma_days: 5,
|
||||||
benchmark_long_ma_days: 10,
|
benchmark_long_ma_days: 10,
|
||||||
@@ -1547,6 +1565,32 @@ 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 {
|
fn in_skip_window(&self, date: NaiveDate) -> bool {
|
||||||
let month = date.month();
|
let month = date.month();
|
||||||
let day = date.day();
|
let day = date.day();
|
||||||
@@ -2097,7 +2141,8 @@ impl OmniMicroCapStrategy {
|
|||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
) -> Result<(f64, f64, f64, f64), BacktestError> {
|
) -> Result<(f64, f64, f64, f64, f64), BacktestError> {
|
||||||
|
// 当前交易日的指数价格(用于MA计算和仓位控制)
|
||||||
let current_level = ctx
|
let current_level = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
.market_decision_close(date, &self.config.benchmark_signal_symbol)
|
||||||
@@ -2106,6 +2151,16 @@ impl OmniMicroCapStrategy {
|
|||||||
symbol: self.config.benchmark_signal_symbol.clone(),
|
symbol: self.config.benchmark_signal_symbol.clone(),
|
||||||
field: "decision_close",
|
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
|
let ma_short = ctx
|
||||||
.data
|
.data
|
||||||
.market_decision_close_moving_average(
|
.market_decision_close_moving_average(
|
||||||
@@ -2137,14 +2192,25 @@ impl OmniMicroCapStrategy {
|
|||||||
} else {
|
} else {
|
||||||
1.0
|
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) {
|
fn market_cap_band(&self, index_level: f64) -> (f64, f64) {
|
||||||
let y = (index_level - self.config.base_index_level) * self.config.xs
|
let y = (index_level - self.config.base_index_level) * self.config.xs
|
||||||
+ self.config.base_cap_floor;
|
+ self.config.base_cap_floor;
|
||||||
let start = y.round();
|
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(
|
fn stock_passes_ma_filter(
|
||||||
@@ -2175,7 +2241,57 @@ impl OmniMicroCapStrategy {
|
|||||||
return false;
|
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;
|
||||||
|
|
||||||
|
// 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 special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
fn special_name(&self, ctx: &StrategyContext<'_>, symbol: &str) -> bool {
|
||||||
@@ -2546,7 +2662,7 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let (index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
|
let (index_level, prev_index_level, ma_short, ma_long, trading_ratio) = match self.trading_ratio(ctx, date) {
|
||||||
Ok(value) => value,
|
Ok(value) => value,
|
||||||
Err(BacktestError::Execution(message))
|
Err(BacktestError::Execution(message))
|
||||||
if message.contains("insufficient benchmark") =>
|
if message.contains("insufficient benchmark") =>
|
||||||
@@ -2564,7 +2680,10 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
}
|
}
|
||||||
Err(err) => return Err(err),
|
Err(err) => return Err(err),
|
||||||
};
|
};
|
||||||
let (band_low, band_high) = self.market_cap_band(index_level);
|
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||||
|
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
||||||
|
eprintln!("[DEBUG] date={} current_index={:.2} prev_index={:.2} band=[{:.0}, {:.0}]",
|
||||||
|
date, index_level, prev_index_level, band_low, band_high);
|
||||||
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
||||||
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||||
let mut projected = ctx.portfolio.clone();
|
let mut projected = ctx.portfolio.clone();
|
||||||
|
|||||||
@@ -78,6 +78,9 @@ pub struct DynamicMarketCapBandSelector {
|
|||||||
pub cap_span: f64,
|
pub cap_span: f64,
|
||||||
pub xs: f64,
|
pub xs: f64,
|
||||||
pub top_n: usize,
|
pub top_n: usize,
|
||||||
|
pub padding_ratio: f64,
|
||||||
|
pub min_padding: f64,
|
||||||
|
pub max_padding: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DynamicMarketCapBandSelector {
|
impl DynamicMarketCapBandSelector {
|
||||||
@@ -87,6 +90,9 @@ impl DynamicMarketCapBandSelector {
|
|||||||
cap_span: f64,
|
cap_span: f64,
|
||||||
xs: f64,
|
xs: f64,
|
||||||
top_n: usize,
|
top_n: usize,
|
||||||
|
padding_ratio: f64,
|
||||||
|
min_padding: f64,
|
||||||
|
max_padding: f64,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
base_index_level,
|
base_index_level,
|
||||||
@@ -94,11 +100,14 @@ impl DynamicMarketCapBandSelector {
|
|||||||
cap_span,
|
cap_span,
|
||||||
xs,
|
xs,
|
||||||
top_n,
|
top_n,
|
||||||
|
padding_ratio,
|
||||||
|
min_padding,
|
||||||
|
max_padding,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn demo(top_n: usize) -> Self {
|
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 {
|
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) {
|
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 start = ((benchmark_level - self.base_index_level) * self.xs) + self.base_cap_floor;
|
||||||
let low = start.round();
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user