Add rqalpha-style scheduler primitives

This commit is contained in:
boris
2026-04-23 01:49:24 -07:00
parent 452eb3324d
commit e5fe1f0432
5 changed files with 533 additions and 3 deletions

View File

@@ -6,7 +6,8 @@ use chrono::NaiveDate;
use fidc_core::{
BacktestConfig, BacktestEngine, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility,
ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet,
Instrument, PriceField, Strategy, StrategyContext, StrategyDecision,
Instrument, PriceField, ScheduleRule, ScheduleStage, Strategy, StrategyContext,
StrategyDecision,
};
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
@@ -115,6 +116,42 @@ impl Strategy for AuctionOrderStrategy {
}
}
struct ScheduledProbeStrategy {
log: Rc<RefCell<Vec<String>>>,
}
impl Strategy for ScheduledProbeStrategy {
fn name(&self) -> &str {
"scheduled-probe"
}
fn schedule_rules(&self) -> Vec<ScheduleRule> {
vec![
ScheduleRule::daily("daily_auction", ScheduleStage::OpenAuction),
ScheduleRule::weekly_by_weekday("friday_on_day", 5, ScheduleStage::OnDay),
ScheduleRule::monthly("first_trading_day_on_day", 1, ScheduleStage::OnDay),
]
}
fn on_scheduled(
&mut self,
ctx: &StrategyContext<'_>,
rule: &ScheduleRule,
) -> Result<StrategyDecision, fidc_core::BacktestError> {
self.log
.borrow_mut()
.push(format!("scheduled:{}:{}", rule.name, ctx.execution_date));
Ok(StrategyDecision::default())
}
fn on_day(
&mut self,
_ctx: &StrategyContext<'_>,
) -> Result<StrategyDecision, fidc_core::BacktestError> {
Ok(StrategyDecision::default())
}
}
#[test]
fn engine_runs_strategy_hooks_in_daily_order() {
let date1 = d(2025, 1, 2);
@@ -381,3 +418,221 @@ fn engine_executes_open_auction_decisions_before_on_day() {
assert_eq!(result.fills[0].reason, "auction_buy");
assert_eq!(result.fills[0].quantity, 100);
}
#[test]
fn engine_runs_scheduled_rules_for_daily_weekly_and_monthly_triggers() {
let date1 = d(2025, 1, 30);
let date2 = d(2025, 1, 31);
let date3 = d(2025, 2, 3);
let data = DataSet::from_components(
vec![Instrument {
symbol: "000001.SZ".to_string(),
name: "Anchor".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: None,
status: "active".to_string(),
}],
vec![
DailyMarketSnapshot {
date: date1,
symbol: "000001.SZ".to_string(),
timestamp: Some("2025-01-30 09:25:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.1,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 10.0,
ask1: 10.0,
prev_close: 9.9,
volume: 100_000,
tick_volume: 100_000,
bid1_volume: 100_000,
ask1_volume: 100_000,
trading_phase: Some("open_auction".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
},
DailyMarketSnapshot {
date: date2,
symbol: "000001.SZ".to_string(),
timestamp: Some("2025-01-31 09:25:00".to_string()),
day_open: 10.1,
open: 10.1,
high: 10.2,
low: 10.0,
close: 10.1,
last_price: 10.1,
bid1: 10.1,
ask1: 10.1,
prev_close: 10.0,
volume: 110_000,
tick_volume: 110_000,
bid1_volume: 110_000,
ask1_volume: 110_000,
trading_phase: Some("open_auction".to_string()),
paused: false,
upper_limit: 11.1,
lower_limit: 9.1,
price_tick: 0.01,
},
DailyMarketSnapshot {
date: date3,
symbol: "000001.SZ".to_string(),
timestamp: Some("2025-02-03 09:25:00".to_string()),
day_open: 10.2,
open: 10.2,
high: 10.3,
low: 10.1,
close: 10.2,
last_price: 10.2,
bid1: 10.2,
ask1: 10.2,
prev_close: 10.1,
volume: 120_000,
tick_volume: 120_000,
bid1_volume: 120_000,
ask1_volume: 120_000,
trading_phase: Some("open_auction".to_string()),
paused: false,
upper_limit: 11.2,
lower_limit: 9.2,
price_tick: 0.01,
},
],
vec![
DailyFactorSnapshot {
date: date1,
symbol: "000001.SZ".to_string(),
market_cap_bn: 20.0,
free_float_cap_bn: 18.0,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
DailyFactorSnapshot {
date: date2,
symbol: "000001.SZ".to_string(),
market_cap_bn: 21.0,
free_float_cap_bn: 19.0,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
DailyFactorSnapshot {
date: date3,
symbol: "000001.SZ".to_string(),
market_cap_bn: 22.0,
free_float_cap_bn: 20.0,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
},
],
vec![
CandidateEligibility {
date: date1,
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: date2,
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: date3,
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: date1,
benchmark: "000300.SH".to_string(),
open: 100.0,
close: 100.0,
prev_close: 99.0,
volume: 1_000_000,
},
BenchmarkSnapshot {
date: date2,
benchmark: "000300.SH".to_string(),
open: 101.0,
close: 101.0,
prev_close: 100.0,
volume: 1_100_000,
},
BenchmarkSnapshot {
date: date3,
benchmark: "000300.SH".to_string(),
open: 102.0,
close: 102.0,
prev_close: 101.0,
volume: 1_200_000,
},
],
)
.expect("dataset");
let log = Rc::new(RefCell::new(Vec::new()));
let strategy = ScheduledProbeStrategy { log: log.clone() };
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::DayOpen,
);
let mut engine = BacktestEngine::new(
data,
strategy,
broker,
BacktestConfig {
initial_cash: 100_000.0,
benchmark_code: "000300.SH".to_string(),
start_date: Some(date1),
end_date: Some(date3),
decision_lag_trading_days: 0,
execution_price_field: PriceField::DayOpen,
},
);
engine.run().expect("backtest run");
assert_eq!(
log.borrow().as_slice(),
[
"scheduled:daily_auction:2025-01-30",
"scheduled:first_trading_day_on_day:2025-01-30",
"scheduled:daily_auction:2025-01-31",
"scheduled:friday_on_day:2025-01-31",
"scheduled:daily_auction:2025-02-03",
"scheduled:first_trading_day_on_day:2025-02-03",
]
);
}