Add dynamic universe and subscription controls
This commit is contained in:
@@ -129,6 +129,10 @@ struct LimitCarryStrategy {
|
||||
issued: bool,
|
||||
}
|
||||
|
||||
struct UniverseDirectiveStrategy {
|
||||
snapshots: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl Strategy for ScheduledProbeStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"scheduled-probe"
|
||||
@@ -233,6 +237,56 @@ impl Strategy for ProcessContextProbeStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
impl Strategy for UniverseDirectiveStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"universe-directive-probe"
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
let eligible = ctx
|
||||
.eligible_universe_on(ctx.execution_date)
|
||||
.into_iter()
|
||||
.map(|row| row.symbol)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
self.snapshots.borrow_mut().push(format!(
|
||||
"{}:{}:{}:{}",
|
||||
ctx.execution_date,
|
||||
ctx.dynamic_universe_count(),
|
||||
ctx.subscription_count(),
|
||||
eligible
|
||||
));
|
||||
let order_intents = match ctx.execution_date {
|
||||
date if date == d(2025, 1, 2) => vec![
|
||||
OrderIntent::UpdateUniverse {
|
||||
symbols: BTreeSet::from(["000002.SZ".to_string()]),
|
||||
reason: "focus_single_symbol".to_string(),
|
||||
},
|
||||
OrderIntent::Subscribe {
|
||||
symbols: BTreeSet::from(["000001.SZ".to_string()]),
|
||||
reason: "subscribe_probe".to_string(),
|
||||
},
|
||||
],
|
||||
date if date == d(2025, 1, 3) => vec![OrderIntent::Unsubscribe {
|
||||
symbols: BTreeSet::from(["000001.SZ".to_string()]),
|
||||
reason: "unsubscribe_probe".to_string(),
|
||||
}],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Ok(StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents,
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_runs_strategy_hooks_in_daily_order() {
|
||||
let date1 = d(2025, 1, 2);
|
||||
@@ -1173,6 +1227,204 @@ fn engine_dispatches_process_events_to_external_bus_listeners() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_applies_dynamic_universe_and_subscription_directives() {
|
||||
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
||||
let snapshots = Rc::new(RefCell::new(Vec::new()));
|
||||
let strategy = UniverseDirectiveStrategy {
|
||||
snapshots: snapshots.clone(),
|
||||
};
|
||||
let instruments = vec![
|
||||
Instrument {
|
||||
symbol: "000001.SZ".to_string(),
|
||||
name: "One".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: Some(d(2020, 1, 1)),
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
},
|
||||
Instrument {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
name: "Two".to_string(),
|
||||
board: "SZ".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: Some(d(2020, 1, 1)),
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
},
|
||||
];
|
||||
let markets = dates
|
||||
.iter()
|
||||
.flat_map(|date| {
|
||||
[
|
||||
DailyMarketSnapshot {
|
||||
date: *date,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some(format!("{date} 10:18:00")),
|
||||
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: 9.95,
|
||||
volume: 100_000,
|
||||
tick_volume: 5_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,
|
||||
},
|
||||
DailyMarketSnapshot {
|
||||
date: *date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
timestamp: Some(format!("{date} 10:18:00")),
|
||||
day_open: 20.0,
|
||||
open: 20.0,
|
||||
high: 20.1,
|
||||
low: 19.9,
|
||||
close: 20.0,
|
||||
last_price: 20.0,
|
||||
bid1: 19.99,
|
||||
ask1: 20.01,
|
||||
prev_close: 19.95,
|
||||
volume: 100_000,
|
||||
tick_volume: 5_000,
|
||||
bid1_volume: 2_000,
|
||||
ask1_volume: 2_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 22.0,
|
||||
lower_limit: 18.0,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let factors = dates
|
||||
.iter()
|
||||
.flat_map(|date| {
|
||||
[
|
||||
DailyFactorSnapshot {
|
||||
date: *date,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 8.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: Some(1.0),
|
||||
effective_turnover_ratio: Some(1.0),
|
||||
extra_factors: BTreeMap::new(),
|
||||
},
|
||||
DailyFactorSnapshot {
|
||||
date: *date,
|
||||
symbol: "000002.SZ".to_string(),
|
||||
market_cap_bn: 12.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 12.0,
|
||||
turnover_ratio: Some(1.0),
|
||||
effective_turnover_ratio: Some(1.0),
|
||||
extra_factors: BTreeMap::new(),
|
||||
},
|
||||
]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let candidates = dates
|
||||
.iter()
|
||||
.flat_map(|date| {
|
||||
[
|
||||
CandidateEligibility {
|
||||
date: *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,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: *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,
|
||||
},
|
||||
]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let benchmarks = dates
|
||||
.iter()
|
||||
.map(|date| BenchmarkSnapshot {
|
||||
date: *date,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1000.0,
|
||||
prev_close: 999.0,
|
||||
volume: 100_000,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let data = DataSet::from_components(instruments, markets, factors, candidates, benchmarks)
|
||||
.expect("dataset");
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
data,
|
||||
strategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 1_000_000.0,
|
||||
benchmark_code: "000852.SH".to_string(),
|
||||
start_date: Some(dates[0]),
|
||||
end_date: Some(dates[2]),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Open,
|
||||
},
|
||||
);
|
||||
|
||||
let result = engine.run().expect("backtest result");
|
||||
|
||||
assert_eq!(
|
||||
snapshots.borrow().as_slice(),
|
||||
&[
|
||||
"2025-01-02:0:0:000001.SZ,000002.SZ",
|
||||
"2025-01-03:1:1:000002.SZ",
|
||||
"2025-01-06:1:0:000002.SZ",
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
result
|
||||
.process_events
|
||||
.iter()
|
||||
.any(|event| event.kind == ProcessEventKind::UniverseUpdated)
|
||||
);
|
||||
assert!(
|
||||
result
|
||||
.process_events
|
||||
.iter()
|
||||
.any(|event| event.kind == ProcessEventKind::UniverseSubscribed)
|
||||
);
|
||||
assert!(
|
||||
result
|
||||
.process_events
|
||||
.iter()
|
||||
.any(|event| event.kind == ProcessEventKind::UniverseUnsubscribed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_exposes_current_process_context_to_strategies() {
|
||||
let date = d(2025, 1, 2);
|
||||
|
||||
@@ -3,6 +3,7 @@ use fidc_core::{
|
||||
CnSmallCapRotationConfig, CnSmallCapRotationStrategy, DataSet, JqMicroCapConfig,
|
||||
JqMicroCapStrategy, PortfolioState, Strategy, StrategyContext,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
@@ -17,6 +18,7 @@ fn strategy_emits_target_weights_and_diagnostics() {
|
||||
cfg.short_ma_days = 3;
|
||||
cfg.long_ma_days = 5;
|
||||
let mut strategy = CnSmallCapRotationStrategy::new(cfg);
|
||||
let subscriptions = BTreeSet::new();
|
||||
|
||||
let decision = strategy
|
||||
.on_day(&StrategyContext {
|
||||
@@ -26,6 +28,8 @@ fn strategy_emits_target_weights_and_diagnostics() {
|
||||
data: &data,
|
||||
portfolio: &portfolio,
|
||||
open_orders: &[],
|
||||
dynamic_universe: None,
|
||||
subscriptions: &subscriptions,
|
||||
process_events: &[],
|
||||
active_process_event: None,
|
||||
})
|
||||
@@ -57,6 +61,7 @@ fn jq_strategy_emits_same_day_decision() {
|
||||
cfg.stock_mid_ma_days = 4;
|
||||
cfg.stock_long_ma_days = 5;
|
||||
let mut strategy = JqMicroCapStrategy::new(cfg);
|
||||
let subscriptions = BTreeSet::new();
|
||||
|
||||
let decision = strategy
|
||||
.on_day(&StrategyContext {
|
||||
@@ -66,6 +71,8 @@ fn jq_strategy_emits_same_day_decision() {
|
||||
data: &data,
|
||||
portfolio: &portfolio,
|
||||
open_orders: &[],
|
||||
dynamic_universe: None,
|
||||
subscriptions: &subscriptions,
|
||||
process_events: &[],
|
||||
active_process_event: None,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user