Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc39df0ee5 | |||
| 70695d8c92 | |||
| 0533e2db3a | |||
| 716149c06c | |||
| 0628dd528a |
@@ -218,6 +218,7 @@ pub struct PlatformExprStrategyConfig {
|
|||||||
pub matching_type: MatchingType,
|
pub matching_type: MatchingType,
|
||||||
pub quote_quantity_limit: bool,
|
pub quote_quantity_limit: bool,
|
||||||
pub current_day_precomputed_factors: bool,
|
pub current_day_precomputed_factors: bool,
|
||||||
|
pub prefer_precomputed_rolling_factors: bool,
|
||||||
pub intraday_execution_time: Option<NaiveTime>,
|
pub intraday_execution_time: Option<NaiveTime>,
|
||||||
pub delayed_limit_open_exit_enabled: bool,
|
pub delayed_limit_open_exit_enabled: bool,
|
||||||
pub delayed_limit_open_exit_time: Option<NaiveTime>,
|
pub delayed_limit_open_exit_time: Option<NaiveTime>,
|
||||||
@@ -286,6 +287,7 @@ fn band_low(index_close) {
|
|||||||
matching_type: MatchingType::NextTickLast,
|
matching_type: MatchingType::NextTickLast,
|
||||||
quote_quantity_limit: true,
|
quote_quantity_limit: true,
|
||||||
current_day_precomputed_factors: false,
|
current_day_precomputed_factors: false,
|
||||||
|
prefer_precomputed_rolling_factors: false,
|
||||||
intraday_execution_time: None,
|
intraday_execution_time: None,
|
||||||
delayed_limit_open_exit_enabled: false,
|
delayed_limit_open_exit_enabled: false,
|
||||||
delayed_limit_open_exit_time: None,
|
delayed_limit_open_exit_time: None,
|
||||||
@@ -312,7 +314,7 @@ fn band_low(index_close) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default, Clone)]
|
||||||
struct ProjectedExecutionState {
|
struct ProjectedExecutionState {
|
||||||
execution_cursors: BTreeMap<String, NaiveDateTime>,
|
execution_cursors: BTreeMap<String, NaiveDateTime>,
|
||||||
intraday_turnover: BTreeMap<String, u32>,
|
intraday_turnover: BTreeMap<String, u32>,
|
||||||
@@ -1678,6 +1680,27 @@ impl PlatformExprStrategy {
|
|||||||
.unwrap_or(true)
|
.unwrap_or(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn projected_target_zero_would_fill(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
projected: &PortfolioState,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
execution_state: &ProjectedExecutionState,
|
||||||
|
) -> bool {
|
||||||
|
let mut trial_projected = projected.clone();
|
||||||
|
let mut trial_execution_state = execution_state.clone();
|
||||||
|
self.project_target_zero(
|
||||||
|
ctx,
|
||||||
|
&mut trial_projected,
|
||||||
|
date,
|
||||||
|
symbol,
|
||||||
|
&mut trial_execution_state,
|
||||||
|
)
|
||||||
|
.is_some()
|
||||||
|
&& Self::projected_position_is_flat(&trial_projected, symbol)
|
||||||
|
}
|
||||||
|
|
||||||
fn projected_position_value_at_execution_price(
|
fn projected_position_value_at_execution_price(
|
||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
@@ -2069,6 +2092,26 @@ impl PlatformExprStrategy {
|
|||||||
self.stock_state_with_factor_date_and_time(ctx, date, factor_date, symbol, None)
|
self.stock_state_with_factor_date_and_time(ctx, date, factor_date, symbol, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn stock_decision_rolling_mean(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
extra_factors: &BTreeMap<String, f64>,
|
||||||
|
field: &str,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Option<f64> {
|
||||||
|
let precomputed = precomputed_stock_rolling_mean(extra_factors, field, lookback);
|
||||||
|
let computed = ctx
|
||||||
|
.data
|
||||||
|
.market_decision_numeric_moving_average(date, symbol, field, lookback);
|
||||||
|
if self.config.prefer_precomputed_rolling_factors {
|
||||||
|
precomputed.or(computed)
|
||||||
|
} else {
|
||||||
|
computed.or(precomputed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn stock_state_at_time(
|
fn stock_state_at_time(
|
||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
@@ -2095,78 +2138,59 @@ impl PlatformExprStrategy {
|
|||||||
let factor = ctx.data.require_factor(factor_date, symbol)?;
|
let factor = ctx.data.require_factor(factor_date, symbol)?;
|
||||||
let candidate = ctx.data.require_candidate(date, symbol)?;
|
let candidate = ctx.data.require_candidate(date, symbol)?;
|
||||||
let instrument = ctx.data.instrument(symbol);
|
let instrument = ctx.data.instrument(symbol);
|
||||||
let stock_ma_short = ctx
|
let stock_ma_short = self
|
||||||
.data
|
.stock_decision_rolling_mean(
|
||||||
.market_decision_close_moving_average(date, symbol, self.config.stock_short_ma_days)
|
ctx,
|
||||||
.or_else(|| {
|
date,
|
||||||
precomputed_stock_rolling_mean(
|
symbol,
|
||||||
&factor.extra_factors,
|
&factor.extra_factors,
|
||||||
"close",
|
"close",
|
||||||
self.config.stock_short_ma_days,
|
self.config.stock_short_ma_days,
|
||||||
)
|
)
|
||||||
})
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_ma_mid = ctx
|
let stock_ma_mid = self
|
||||||
.data
|
.stock_decision_rolling_mean(
|
||||||
.market_decision_close_moving_average(date, symbol, self.config.stock_mid_ma_days)
|
ctx,
|
||||||
.or_else(|| {
|
date,
|
||||||
precomputed_stock_rolling_mean(
|
symbol,
|
||||||
&factor.extra_factors,
|
&factor.extra_factors,
|
||||||
"close",
|
"close",
|
||||||
self.config.stock_mid_ma_days,
|
self.config.stock_mid_ma_days,
|
||||||
)
|
)
|
||||||
})
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_ma_long = ctx
|
let stock_ma_long = self
|
||||||
.data
|
.stock_decision_rolling_mean(
|
||||||
.market_decision_close_moving_average(date, symbol, self.config.stock_long_ma_days)
|
ctx,
|
||||||
.or_else(|| {
|
date,
|
||||||
precomputed_stock_rolling_mean(
|
symbol,
|
||||||
&factor.extra_factors,
|
&factor.extra_factors,
|
||||||
"close",
|
"close",
|
||||||
self.config.stock_long_ma_days,
|
self.config.stock_long_ma_days,
|
||||||
)
|
)
|
||||||
})
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_ma5 = ctx
|
let stock_ma5 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "close", 5)
|
||||||
.market_decision_close_moving_average(date, symbol, 5)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "close", 5))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_ma10 = ctx
|
let stock_ma10 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "close", 10)
|
||||||
.market_decision_close_moving_average(date, symbol, 10)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "close", 10))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_ma20 = ctx
|
let stock_ma20 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "close", 20)
|
||||||
.market_decision_close_moving_average(date, symbol, 20)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "close", 20))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_ma30 = ctx
|
let stock_ma30 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "close", 30)
|
||||||
.market_decision_close_moving_average(date, symbol, 30)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "close", 30))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_volume_ma5 = ctx
|
let stock_volume_ma5 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "volume", 5)
|
||||||
.market_decision_volume_moving_average(date, symbol, 5)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "volume", 5))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_volume_ma10 = ctx
|
let stock_volume_ma10 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "volume", 10)
|
||||||
.market_decision_volume_moving_average(date, symbol, 10)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "volume", 10))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_volume_ma20 = ctx
|
let stock_volume_ma20 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "volume", 20)
|
||||||
.market_decision_volume_moving_average(date, symbol, 20)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "volume", 20))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let stock_volume_ma60 = ctx
|
let stock_volume_ma60 = self
|
||||||
.data
|
.stock_decision_rolling_mean(ctx, date, symbol, &factor.extra_factors, "volume", 60)
|
||||||
.market_decision_volume_moving_average(date, symbol, 60)
|
|
||||||
.or_else(|| precomputed_stock_rolling_mean(&factor.extra_factors, "volume", 60))
|
|
||||||
.unwrap_or(f64::NAN);
|
.unwrap_or(f64::NAN);
|
||||||
let touched_upper_limit = !market.paused
|
let touched_upper_limit = !market.paused
|
||||||
&& (market.is_at_upper_limit_price(market.close)
|
&& (market.is_at_upper_limit_price(market.close)
|
||||||
@@ -4002,16 +4026,14 @@ impl PlatformExprStrategy {
|
|||||||
"rolling_mean(\"{other}\", {lookback}) requires stock context"
|
"rolling_mean(\"{other}\", {lookback}) requires stock context"
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
ctx.data
|
self.stock_decision_rolling_mean(
|
||||||
.market_decision_numeric_moving_average(
|
ctx,
|
||||||
day.date,
|
day.date,
|
||||||
&stock.symbol,
|
&stock.symbol,
|
||||||
|
&stock.extra_factors,
|
||||||
other,
|
other,
|
||||||
lookback,
|
lookback,
|
||||||
)
|
)
|
||||||
.or_else(|| {
|
|
||||||
precomputed_stock_rolling_mean(&stock.extra_factors, other, lookback)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
value.ok_or_else(|| {
|
value.ok_or_else(|| {
|
||||||
@@ -6490,13 +6512,19 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
let (stop_hit, profit_hit) =
|
let (stop_hit, profit_hit) =
|
||||||
self.stop_take_action_for_position(ctx, execution_date, &day, position)?;
|
self.stop_take_action_for_position(ctx, execution_date, &day, position)?;
|
||||||
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
|
|
||||||
if stop_hit {
|
if stop_hit {
|
||||||
if can_sell {
|
if self.projected_target_zero_would_fill(
|
||||||
|
ctx,
|
||||||
|
&projected,
|
||||||
|
execution_date,
|
||||||
|
&position.symbol,
|
||||||
|
&projected_execution_state,
|
||||||
|
) {
|
||||||
pending_full_close_symbols.insert(position.symbol.clone());
|
pending_full_close_symbols.insert(position.symbol.clone());
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let can_sell = self.can_sell_position(ctx, execution_date, &position.symbol);
|
||||||
if !can_sell {
|
if !can_sell {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -6518,10 +6546,18 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if profit_hit {
|
if profit_hit {
|
||||||
|
if self.projected_target_zero_would_fill(
|
||||||
|
ctx,
|
||||||
|
&projected,
|
||||||
|
execution_date,
|
||||||
|
&position.symbol,
|
||||||
|
&projected_execution_state,
|
||||||
|
) {
|
||||||
pending_full_close_symbols.insert(position.symbol.clone());
|
pending_full_close_symbols.insert(position.symbol.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if self.config.aiquant_transaction_cost
|
if self.config.aiquant_transaction_cost
|
||||||
&& self.config.rotation_enabled
|
&& self.config.rotation_enabled
|
||||||
@@ -12502,6 +12538,169 @@ mod tests {
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_weak_market_keeps_positive_adjust_when_intraday_stop_loss_sell_blocked() {
|
||||||
|
let prev_date = d(2025, 2, 2);
|
||||||
|
let date = d(2025, 2, 3);
|
||||||
|
let symbols = ["000001.SZ", "000002.SZ"];
|
||||||
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| Instrument {
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
name: (*symbol).to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2020, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
timestamp: Some("2025-02-03 10:40:00".to_string()),
|
||||||
|
day_open: 9.6,
|
||||||
|
open: 9.6,
|
||||||
|
high: 9.7,
|
||||||
|
low: 9.0,
|
||||||
|
close: 9.5,
|
||||||
|
last_price: 9.5,
|
||||||
|
bid1: 9.5,
|
||||||
|
ask1: 9.51,
|
||||||
|
prev_close: 10.0,
|
||||||
|
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(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, symbol)| DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
market_cap_bn: 10.0 + index as f64,
|
||||||
|
free_float_cap_bn: 10.0 + index as f64,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| 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,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1000.0,
|
||||||
|
prev_close: 1000.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
symbols
|
||||||
|
.iter()
|
||||||
|
.map(|symbol| IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: (*symbol).to_string(),
|
||||||
|
timestamp: date.and_hms_opt(10, 40, 0).expect("timestamp"),
|
||||||
|
last_price: 9.0,
|
||||||
|
bid1: 9.0,
|
||||||
|
ask1: 9.01,
|
||||||
|
bid1_volume: 2_000,
|
||||||
|
ask1_volume: 2_000,
|
||||||
|
volume_delta: 10_000,
|
||||||
|
amount_delta: 90_000.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
|
||||||
|
let mut portfolio = PortfolioState::new(40_000.0);
|
||||||
|
portfolio
|
||||||
|
.position_mut("000001.SZ")
|
||||||
|
.buy(prev_date, 800, 11.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 2,
|
||||||
|
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 = 99;
|
||||||
|
cfg.max_positions = 2;
|
||||||
|
cfg.benchmark_short_ma_days = 1;
|
||||||
|
cfg.benchmark_long_ma_days = 1;
|
||||||
|
cfg.market_cap_lower_expr = "0".to_string();
|
||||||
|
cfg.market_cap_upper_expr = "1000".to_string();
|
||||||
|
cfg.selection_limit_expr = "2".to_string();
|
||||||
|
cfg.stock_filter_expr = "close > 0".to_string();
|
||||||
|
cfg.exposure_expr = "0.5".to_string();
|
||||||
|
cfg.stop_loss_expr = "0.92".to_string();
|
||||||
|
cfg.take_profit_expr.clear();
|
||||||
|
cfg.daily_top_up_enabled = true;
|
||||||
|
cfg.aiquant_transaction_cost = true;
|
||||||
|
cfg.slippage_model = SlippageModel::PriceRatio(0.002);
|
||||||
|
cfg.intraday_execution_time = Some(NaiveTime::from_hms_opt(10, 40, 0).expect("time"));
|
||||||
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
strategy.rebalance_day_counter = 2;
|
||||||
|
|
||||||
|
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||||
|
|
||||||
|
assert!(decision.order_intents.iter().any(|intent| matches!(
|
||||||
|
intent,
|
||||||
|
OrderIntent::Shares {
|
||||||
|
symbol,
|
||||||
|
quantity,
|
||||||
|
reason,
|
||||||
|
} if symbol == "000001.SZ"
|
||||||
|
&& reason == "daily_position_target_adjust"
|
||||||
|
&& *quantity > 0
|
||||||
|
)));
|
||||||
|
assert!(decision.order_intents.iter().any(|intent| matches!(
|
||||||
|
intent,
|
||||||
|
OrderIntent::TargetValue {
|
||||||
|
symbol,
|
||||||
|
target_value,
|
||||||
|
reason,
|
||||||
|
} if symbol == "000001.SZ" && *target_value == 0.0 && reason == "stop_loss_exit"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn platform_refresh_rate_uses_stateful_aiquant_day_counter() {
|
fn platform_refresh_rate_uses_stateful_aiquant_day_counter() {
|
||||||
let dates = [d(2025, 2, 5), d(2025, 2, 6), d(2025, 2, 7)];
|
let dates = [d(2025, 2, 5), d(2025, 2, 6), d(2025, 2, 7)];
|
||||||
@@ -13632,10 +13831,10 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.expect("dataset");
|
.expect("dataset");
|
||||||
|
|
||||||
let mut portfolio = PortfolioState::new(100.0);
|
let mut portfolio = PortfolioState::new(1_000.0);
|
||||||
portfolio
|
portfolio
|
||||||
.position_mut("000003.SZ")
|
.position_mut("000003.SZ")
|
||||||
.buy(prev_date, 100, 10.0);
|
.buy(prev_date, 1_000, 10.0);
|
||||||
let subscriptions = BTreeSet::new();
|
let subscriptions = BTreeSet::new();
|
||||||
let ctx = StrategyContext {
|
let ctx = StrategyContext {
|
||||||
execution_date: date,
|
execution_date: date,
|
||||||
@@ -13666,6 +13865,7 @@ mod tests {
|
|||||||
cfg.take_profit_expr.clear();
|
cfg.take_profit_expr.clear();
|
||||||
cfg.stop_loss_expr.clear();
|
cfg.stop_loss_expr.clear();
|
||||||
cfg.daily_top_up_enabled = true;
|
cfg.daily_top_up_enabled = true;
|
||||||
|
cfg.intraday_execution_time = Some(NaiveTime::from_hms_opt(9, 33, 0).unwrap());
|
||||||
let mut strategy = PlatformExprStrategy::new(cfg);
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
strategy.rebalance_day_counter = 20;
|
strategy.rebalance_day_counter = 20;
|
||||||
|
|
||||||
@@ -13838,6 +14038,7 @@ mod tests {
|
|||||||
cfg.take_profit_expr.clear();
|
cfg.take_profit_expr.clear();
|
||||||
cfg.stop_loss_expr.clear();
|
cfg.stop_loss_expr.clear();
|
||||||
cfg.aiquant_transaction_cost = true;
|
cfg.aiquant_transaction_cost = true;
|
||||||
|
cfg.intraday_execution_time = Some(NaiveTime::from_hms_opt(14, 59, 0).unwrap());
|
||||||
let mut strategy = PlatformExprStrategy::new(cfg);
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
strategy.rebalance_day_counter = 20;
|
strategy.rebalance_day_counter = 20;
|
||||||
|
|
||||||
@@ -13846,13 +14047,13 @@ mod tests {
|
|||||||
assert!(
|
assert!(
|
||||||
decision.order_intents.iter().any(|intent| matches!(
|
decision.order_intents.iter().any(|intent| matches!(
|
||||||
intent,
|
intent,
|
||||||
OrderIntent::Value {
|
OrderIntent::Shares {
|
||||||
symbol,
|
symbol,
|
||||||
value,
|
quantity,
|
||||||
reason,
|
reason,
|
||||||
} if symbol == "000002.SZ"
|
} if symbol == "000002.SZ"
|
||||||
&& reason == "periodic_rebalance_buy"
|
&& reason == "periodic_rebalance_buy"
|
||||||
&& (*value - 10_000.0).abs() < 1e-6
|
&& *quantity == 900
|
||||||
)),
|
)),
|
||||||
"{:?}",
|
"{:?}",
|
||||||
decision.order_intents
|
decision.order_intents
|
||||||
@@ -14499,6 +14700,123 @@ mod tests {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_stock_state_can_prefer_precomputed_rolling_factors() {
|
||||||
|
let dates = [
|
||||||
|
d(2025, 1, 2),
|
||||||
|
d(2025, 1, 3),
|
||||||
|
d(2025, 1, 6),
|
||||||
|
d(2025, 1, 7),
|
||||||
|
d(2025, 1, 8),
|
||||||
|
d(2025, 1, 9),
|
||||||
|
];
|
||||||
|
let date = dates[5];
|
||||||
|
let symbol = "300001.SZ";
|
||||||
|
let mut extra_factors = BTreeMap::new();
|
||||||
|
extra_factors.insert("ma5_prev_close".to_string(), 99.0);
|
||||||
|
extra_factors.insert("avg_volume5".to_string(), 88.0);
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
name: symbol.to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2020, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
dates
|
||||||
|
.into_iter()
|
||||||
|
.map(|trade_date| DailyMarketSnapshot {
|
||||||
|
date: trade_date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: None,
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.2,
|
||||||
|
low: 9.8,
|
||||||
|
close: 10.0,
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 1_000,
|
||||||
|
tick_volume: 1_000,
|
||||||
|
bid1_volume: 1_000,
|
||||||
|
ask1_volume: 1_000,
|
||||||
|
trading_phase: None,
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 11.0,
|
||||||
|
lower_limit: 9.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
market_cap_bn: 20.0,
|
||||||
|
free_float_cap_bn: 20.0,
|
||||||
|
pe_ttm: 0.0,
|
||||||
|
turnover_ratio: None,
|
||||||
|
effective_turnover_ratio: None,
|
||||||
|
extra_factors,
|
||||||
|
}],
|
||||||
|
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: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1002.0,
|
||||||
|
prev_close: 998.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(100_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: date,
|
||||||
|
decision_date: date,
|
||||||
|
decision_index: 5,
|
||||||
|
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.prefer_precomputed_rolling_factors = true;
|
||||||
|
let strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
let stock = strategy
|
||||||
|
.stock_state_with_factor_date(&ctx, date, date, symbol)
|
||||||
|
.expect("stock state");
|
||||||
|
assert_eq!(stock.stock_ma5, 99.0);
|
||||||
|
assert_eq!(stock.stock_volume_ma5, 88.0);
|
||||||
|
|
||||||
|
let strategy = PlatformExprStrategy::new(PlatformExprStrategyConfig::microcap_rotation());
|
||||||
|
let stock = strategy
|
||||||
|
.stock_state_with_factor_date(&ctx, date, date, symbol)
|
||||||
|
.expect("stock state");
|
||||||
|
assert_eq!(stock.stock_ma5, 10.0);
|
||||||
|
assert_eq!(stock.stock_volume_ma5, 1_000.0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn platform_strategy_emits_target_shares_explicit_action() {
|
fn platform_strategy_emits_target_shares_explicit_action() {
|
||||||
let date = d(2025, 2, 3);
|
let date = d(2025, 2, 3);
|
||||||
|
|||||||
@@ -5,9 +5,10 @@ use serde::{Deserialize, Serialize};
|
|||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
|
DynamicSlippageConfig, MatchingType, PlatformAccountActionKind, PlatformExplicitActionStage,
|
||||||
PlatformExplicitOrderKind, PlatformExprStrategyConfig, PlatformRebalanceSchedule,
|
PlatformExplicitCancelKind, PlatformExplicitOrderKind, PlatformExprStrategyConfig,
|
||||||
PlatformScheduleFrequency, PlatformTradeAction, PlatformUniverseActionKind, ScheduleTimeRule,
|
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
||||||
|
PlatformUniverseActionKind, ScheduleTimeRule, SlippageModel,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
@@ -176,6 +177,10 @@ pub struct MovingAverageFilterConfig {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub long_days: Option<usize>,
|
pub long_days: Option<usize>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub volume_short_days: Option<usize>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub volume_long_days: Option<usize>,
|
||||||
|
#[serde(default)]
|
||||||
pub rsi_rate: Option<f64>,
|
pub rsi_rate: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -401,6 +406,97 @@ fn apply_cost_overrides(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalize_model_name(value: &str) -> String {
|
||||||
|
value.trim().to_ascii_lowercase().replace('-', "_")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_matching_type(value: Option<&str>) -> Option<MatchingType> {
|
||||||
|
match normalize_model_name(value?).as_str() {
|
||||||
|
"open_auction" => Some(MatchingType::OpenAuction),
|
||||||
|
"current_bar_close" => Some(MatchingType::CurrentBarClose),
|
||||||
|
"next_bar_open" => Some(MatchingType::NextBarOpen),
|
||||||
|
"next_tick_last" => Some(MatchingType::NextTickLast),
|
||||||
|
"next_tick_best_own" => Some(MatchingType::NextTickBestOwn),
|
||||||
|
"next_tick_best_counterparty" => Some(MatchingType::NextTickBestCounterparty),
|
||||||
|
"counterparty_offer" => Some(MatchingType::CounterpartyOffer),
|
||||||
|
"vwap" => Some(MatchingType::Vwap),
|
||||||
|
"twap" => Some(MatchingType::Twap),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_slippage_model(
|
||||||
|
model: Option<&str>,
|
||||||
|
value: Option<f64>,
|
||||||
|
impact_coefficient: Option<f64>,
|
||||||
|
volatility_coefficient: Option<f64>,
|
||||||
|
max_value: Option<f64>,
|
||||||
|
) -> Option<SlippageModel> {
|
||||||
|
let value = valid_non_negative(value);
|
||||||
|
let impact_coefficient = valid_non_negative(impact_coefficient);
|
||||||
|
let volatility_coefficient = valid_non_negative(volatility_coefficient);
|
||||||
|
let max_value = valid_non_negative(max_value);
|
||||||
|
let model = model
|
||||||
|
.map(normalize_model_name)
|
||||||
|
.filter(|item| !item.is_empty())
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
if value.is_some_and(|item| item > 0.0) {
|
||||||
|
"price_ratio".to_string()
|
||||||
|
} else {
|
||||||
|
"none".to_string()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
match model.as_str() {
|
||||||
|
"none" => Some(SlippageModel::None),
|
||||||
|
"price_ratio" => Some(SlippageModel::PriceRatio(value.unwrap_or(0.0))),
|
||||||
|
"tick_size" => Some(SlippageModel::TickSize(value.unwrap_or(0.0))),
|
||||||
|
"limit_price" => Some(SlippageModel::LimitPrice),
|
||||||
|
"dynamic" | "dynamic_volume_volatility" => {
|
||||||
|
Some(SlippageModel::Dynamic(DynamicSlippageConfig::new(
|
||||||
|
impact_coefficient.unwrap_or(0.5),
|
||||||
|
volatility_coefficient.unwrap_or(0.3),
|
||||||
|
max_value.or(value).unwrap_or(0.01),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_execution_behavior_overrides(
|
||||||
|
cfg: &mut PlatformExprStrategyConfig,
|
||||||
|
matching_type: Option<&str>,
|
||||||
|
slippage_model: Option<&str>,
|
||||||
|
slippage_value: Option<f64>,
|
||||||
|
slippage_impact_coefficient: Option<f64>,
|
||||||
|
slippage_volatility_coefficient: Option<f64>,
|
||||||
|
slippage_max_value: Option<f64>,
|
||||||
|
strict_value_budget: Option<bool>,
|
||||||
|
) {
|
||||||
|
if let Some(matching_type) = parse_matching_type(matching_type) {
|
||||||
|
cfg.matching_type = matching_type;
|
||||||
|
}
|
||||||
|
if slippage_model.is_some()
|
||||||
|
|| slippage_value.is_some()
|
||||||
|
|| slippage_impact_coefficient.is_some()
|
||||||
|
|| slippage_volatility_coefficient.is_some()
|
||||||
|
|| slippage_max_value.is_some()
|
||||||
|
{
|
||||||
|
if let Some(parsed) = parse_slippage_model(
|
||||||
|
slippage_model,
|
||||||
|
slippage_value,
|
||||||
|
slippage_impact_coefficient,
|
||||||
|
slippage_volatility_coefficient,
|
||||||
|
slippage_max_value,
|
||||||
|
) {
|
||||||
|
cfg.slippage_model = parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(enabled) = strict_value_budget {
|
||||||
|
cfg.strict_value_budget = enabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
|
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
|
||||||
let bytes = text.as_bytes();
|
let bytes = text.as_bytes();
|
||||||
let mut end = start;
|
let mut end = start;
|
||||||
@@ -624,6 +720,16 @@ pub fn platform_expr_config_from_spec(
|
|||||||
engine.stamp_tax_rate_before_change,
|
engine.stamp_tax_rate_before_change,
|
||||||
engine.stamp_tax_rate_after_change,
|
engine.stamp_tax_rate_after_change,
|
||||||
);
|
);
|
||||||
|
apply_execution_behavior_overrides(
|
||||||
|
&mut cfg,
|
||||||
|
engine.matching_type.as_deref(),
|
||||||
|
engine.slippage_model.as_deref(),
|
||||||
|
engine.slippage_value,
|
||||||
|
engine.slippage_impact_coefficient,
|
||||||
|
engine.slippage_volatility_coefficient,
|
||||||
|
engine.slippage_max_value,
|
||||||
|
engine.strict_value_budget,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(spec_signal_symbol) = spec
|
if let Some(spec_signal_symbol) = spec
|
||||||
@@ -991,6 +1097,16 @@ pub fn platform_expr_config_from_spec(
|
|||||||
execution.stamp_tax_rate_before_change,
|
execution.stamp_tax_rate_before_change,
|
||||||
execution.stamp_tax_rate_after_change,
|
execution.stamp_tax_rate_after_change,
|
||||||
);
|
);
|
||||||
|
apply_execution_behavior_overrides(
|
||||||
|
&mut cfg,
|
||||||
|
execution.matching_type.as_deref(),
|
||||||
|
execution.slippage_model.as_deref(),
|
||||||
|
execution.slippage_value,
|
||||||
|
execution.slippage_impact_coefficient,
|
||||||
|
execution.slippage_volatility_coefficient,
|
||||||
|
execution.slippage_max_value,
|
||||||
|
execution.strict_value_budget,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if cfg.aiquant_transaction_cost
|
if cfg.aiquant_transaction_cost
|
||||||
&& cfg
|
&& cfg
|
||||||
@@ -1469,6 +1585,50 @@ mod tests {
|
|||||||
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
|
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_execution_slippage_overrides_into_platform_config() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": {
|
||||||
|
"compatibilityProfile": "aiquant_rqalpha",
|
||||||
|
"matchingType": "next_tick_last",
|
||||||
|
"slippageModel": "price_ratio",
|
||||||
|
"slippageValue": 0.001,
|
||||||
|
"strictValueBudget": true
|
||||||
|
},
|
||||||
|
"engineConfig": {
|
||||||
|
"matchingType": "current_bar_close",
|
||||||
|
"slippageModel": "none",
|
||||||
|
"slippageValue": 0.0,
|
||||||
|
"strictValueBudget": false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert_eq!(cfg.matching_type, MatchingType::NextTickLast);
|
||||||
|
assert_eq!(cfg.slippage_model, SlippageModel::PriceRatio(0.001));
|
||||||
|
assert!(cfg.strict_value_budget);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_dynamic_slippage_into_platform_config() {
|
||||||
|
let spec = serde_json::json!({
|
||||||
|
"execution": {
|
||||||
|
"slippageModel": "dynamic",
|
||||||
|
"slippageImpactCoefficient": 0.6,
|
||||||
|
"slippageVolatilityCoefficient": 0.2,
|
||||||
|
"slippageMaxValue": 0.015
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
cfg.slippage_model,
|
||||||
|
SlippageModel::Dynamic(DynamicSlippageConfig::new(0.6, 0.2, 0.015))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
|
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
|
||||||
let spec = serde_json::json!({
|
let spec = serde_json::json!({
|
||||||
|
|||||||
@@ -1539,6 +1539,8 @@ pub struct OmniMicroCapConfig {
|
|||||||
pub stock_short_ma_days: usize,
|
pub stock_short_ma_days: usize,
|
||||||
pub stock_mid_ma_days: usize,
|
pub stock_mid_ma_days: usize,
|
||||||
pub stock_long_ma_days: usize,
|
pub stock_long_ma_days: usize,
|
||||||
|
pub stock_volume_short_ma_days: usize,
|
||||||
|
pub stock_volume_long_ma_days: usize,
|
||||||
pub rsi_rate: f64,
|
pub rsi_rate: f64,
|
||||||
pub trade_rate: f64,
|
pub trade_rate: f64,
|
||||||
pub stop_loss_ratio: f64,
|
pub stop_loss_ratio: f64,
|
||||||
@@ -1565,6 +1567,8 @@ impl OmniMicroCapConfig {
|
|||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
stock_mid_ma_days: 10,
|
stock_mid_ma_days: 10,
|
||||||
stock_long_ma_days: 20,
|
stock_long_ma_days: 20,
|
||||||
|
stock_volume_short_ma_days: 5,
|
||||||
|
stock_volume_long_ma_days: 60,
|
||||||
rsi_rate: 1.0001,
|
rsi_rate: 1.0001,
|
||||||
trade_rate: 0.5,
|
trade_rate: 0.5,
|
||||||
stop_loss_ratio: 0.93,
|
stop_loss_ratio: 0.93,
|
||||||
@@ -1593,6 +1597,8 @@ impl OmniMicroCapConfig {
|
|||||||
stock_short_ma_days: 5,
|
stock_short_ma_days: 5,
|
||||||
stock_mid_ma_days: 10,
|
stock_mid_ma_days: 10,
|
||||||
stock_long_ma_days: 30,
|
stock_long_ma_days: 30,
|
||||||
|
stock_volume_short_ma_days: 5,
|
||||||
|
stock_volume_long_ma_days: 60,
|
||||||
rsi_rate: 1.0001,
|
rsi_rate: 1.0001,
|
||||||
trade_rate: 0.5,
|
trade_rate: 0.5,
|
||||||
stop_loss_ratio: 0.92,
|
stop_loss_ratio: 0.92,
|
||||||
@@ -2271,62 +2277,33 @@ impl OmniMicroCapStrategy {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
|
|
||||||
let ma_pass =
|
let ma_pass =
|
||||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
||||||
|
|
||||||
// Debug logging for ALL stocks on first decision date
|
|
||||||
static DEBUG_DATE: std::sync::Mutex<Option<NaiveDate>> = std::sync::Mutex::new(None);
|
|
||||||
let mut debug_date = DEBUG_DATE.lock().unwrap();
|
|
||||||
let should_debug = if let Some(d) = *debug_date {
|
|
||||||
d == date
|
|
||||||
} else {
|
|
||||||
*debug_date = Some(date);
|
|
||||||
true
|
|
||||||
};
|
|
||||||
|
|
||||||
if should_debug {
|
|
||||||
eprintln!(
|
|
||||||
"[MA_FILTER] {} cap={:.2} ma5={:.4} ma10={:.4} ma30={:.4} ma10*rsi={:.4} pass={} ({}>{:.4}? {} && {:.4}>{}? {})",
|
|
||||||
symbol,
|
|
||||||
ctx.data.market_decision_close(date, symbol).unwrap_or(0.0),
|
|
||||||
ma_short,
|
|
||||||
ma_mid,
|
|
||||||
ma_long,
|
|
||||||
ma_mid * self.config.rsi_rate,
|
|
||||||
ma_pass,
|
|
||||||
ma_short,
|
|
||||||
ma_mid * self.config.rsi_rate,
|
|
||||||
ma_short > ma_mid * self.config.rsi_rate,
|
|
||||||
ma_mid * self.config.rsi_rate,
|
|
||||||
ma_long,
|
|
||||||
ma_mid * self.config.rsi_rate > ma_long
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if !ma_pass {
|
if !ma_pass {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
|
|
||||||
if self.config.strategy_name.contains("aiquant")
|
if self.config.strategy_name.contains("aiquant")
|
||||||
|| self.config.strategy_name.contains("AiQuant")
|
|| self.config.strategy_name.contains("AiQuant")
|
||||||
|| self.config.strategy_name.contains("omni")
|
|| self.config.strategy_name.contains("omni")
|
||||||
{
|
{
|
||||||
let Some(volume_ma5) = ctx
|
let Some(volume_ma5) = ctx.data.market_decision_volume_moving_average(
|
||||||
.data
|
date,
|
||||||
.market_decision_volume_moving_average(date, symbol, 5)
|
symbol,
|
||||||
else {
|
self.config.stock_volume_short_ma_days,
|
||||||
|
) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
let Some(volume_ma60) = ctx
|
let Some(volume_ma_long) = ctx.data.market_decision_volume_moving_average(
|
||||||
.data
|
date,
|
||||||
.market_decision_volume_moving_average(date, symbol, 60)
|
symbol,
|
||||||
else {
|
self.config.stock_volume_long_ma_days,
|
||||||
|
) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
if volume_ma5 >= volume_ma60 {
|
if volume_ma5 >= volume_ma_long {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2519,18 +2496,6 @@ fn omni_truth_stock_list_candidates() -> Vec<PathBuf> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let suffix = PathBuf::from("data/demo/engine_truth_stock_list.csv");
|
|
||||||
let manifest_root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
|
||||||
push_unique_truth_path(
|
|
||||||
&mut candidates,
|
|
||||||
manifest_root.join("../../../").join(&suffix),
|
|
||||||
);
|
|
||||||
if let Ok(current_dir) = env::current_dir() {
|
|
||||||
for ancestor in current_dir.ancestors() {
|
|
||||||
push_unique_truth_path(&mut candidates, ancestor.join(&suffix));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
candidates
|
candidates
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2699,10 +2664,6 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
};
|
};
|
||||||
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||||
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
||||||
eprintln!(
|
|
||||||
"[DEBUG] date={} current_index={:.2} prev_index={:.2} band=[{:.0}, {:.0}]",
|
|
||||||
date, index_level, prev_index_level, band_low, band_high
|
|
||||||
);
|
|
||||||
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
||||||
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||||
let mut projected = ctx.portfolio.clone();
|
let mut projected = ctx.portfolio.clone();
|
||||||
@@ -2726,7 +2687,8 @@ impl Strategy for OmniMicroCapStrategy {
|
|||||||
+ self.stop_loss_tolerance(market);
|
+ self.stop_loss_tolerance(market);
|
||||||
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
|
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
|
||||||
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
|
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
|
||||||
if stop_hit || profit_hit {
|
let at_upper_limit = market.is_at_upper_limit_price(current_price);
|
||||||
|
if stop_hit || (profit_hit && !at_upper_limit) {
|
||||||
let sell_reason = if stop_hit {
|
let sell_reason = if stop_hit {
|
||||||
"stop_loss_exit"
|
"stop_loss_exit"
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
Reference in New Issue
Block a user