Add bar and tick strategy lifecycle
This commit is contained in:
@@ -2,18 +2,24 @@ use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use chrono::{NaiveDate, NaiveDateTime};
|
||||
use fidc_core::{
|
||||
BacktestConfig, BacktestEngine, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility,
|
||||
ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet,
|
||||
Instrument, OrderIntent, PriceField, ProcessEventKind, ScheduleRule, ScheduleStage,
|
||||
ScheduleTimeRule, Strategy, StrategyContext, StrategyDecision,
|
||||
Instrument, IntradayExecutionQuote, OrderIntent, PriceField, ProcessEventKind, ScheduleRule,
|
||||
ScheduleStage, ScheduleTimeRule, Strategy, StrategyContext, StrategyDecision,
|
||||
};
|
||||
|
||||
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
|
||||
}
|
||||
|
||||
fn dt(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> NaiveDateTime {
|
||||
d(year, month, day)
|
||||
.and_hms_opt(hour, minute, second)
|
||||
.expect("valid datetime")
|
||||
}
|
||||
|
||||
struct HookProbeStrategy {
|
||||
log: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
@@ -133,6 +139,11 @@ struct UniverseDirectiveStrategy {
|
||||
snapshots: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
|
||||
struct TickProbeStrategy {
|
||||
seen_ticks: Rc<RefCell<Vec<String>>>,
|
||||
ordered: bool,
|
||||
}
|
||||
|
||||
impl Strategy for ScheduledProbeStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"scheduled-probe"
|
||||
@@ -287,6 +298,58 @@ impl Strategy for UniverseDirectiveStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
impl Strategy for TickProbeStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"tick-probe"
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
_ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
Ok(StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::Subscribe {
|
||||
symbols: BTreeSet::from(["000001.SZ".to_string()]),
|
||||
reason: "subscribe_tick_probe".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn on_tick(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
quote: &IntradayExecutionQuote,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
self.seen_ticks.borrow_mut().push(format!(
|
||||
"{}:{}:{}",
|
||||
quote.symbol,
|
||||
quote.timestamp.time(),
|
||||
ctx.is_subscribed("e.symbol)
|
||||
));
|
||||
if self.ordered {
|
||||
return Ok(StrategyDecision::default());
|
||||
}
|
||||
self.ordered = true;
|
||||
Ok(StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::Shares {
|
||||
symbol: quote.symbol.clone(),
|
||||
quantity: 100,
|
||||
reason: "tick_buy".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_runs_strategy_hooks_in_daily_order() {
|
||||
let date1 = d(2025, 1, 2);
|
||||
@@ -454,9 +517,9 @@ fn engine_runs_strategy_hooks_in_daily_order() {
|
||||
"settlement:2025-01-03",
|
||||
]
|
||||
);
|
||||
assert_eq!(result.process_events.len(), 30);
|
||||
assert_eq!(result.process_events.len(), 36);
|
||||
assert_eq!(
|
||||
result.process_events[..15]
|
||||
result.process_events[..18]
|
||||
.iter()
|
||||
.map(|event| &event.kind)
|
||||
.collect::<Vec<_>>(),
|
||||
@@ -469,7 +532,10 @@ fn engine_runs_strategy_hooks_in_daily_order() {
|
||||
&ProcessEventKind::PostOpenAuction,
|
||||
&ProcessEventKind::PreOnDay,
|
||||
&ProcessEventKind::OnDay,
|
||||
&ProcessEventKind::PreBar,
|
||||
&ProcessEventKind::Bar,
|
||||
&ProcessEventKind::PostOnDay,
|
||||
&ProcessEventKind::PostBar,
|
||||
&ProcessEventKind::PreAfterTrading,
|
||||
&ProcessEventKind::AfterTrading,
|
||||
&ProcessEventKind::PostAfterTrading,
|
||||
@@ -578,6 +644,156 @@ fn engine_executes_open_auction_decisions_before_on_day() {
|
||||
assert_eq!(result.fills[0].quantity, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_runs_subscribed_tick_hooks_and_executes_tick_orders() {
|
||||
let date = d(2025, 1, 2);
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
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,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2025-01-02 10:18:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 10.4,
|
||||
low: 9.9,
|
||||
close: 10.3,
|
||||
last_price: 10.2,
|
||||
bid1: 10.1,
|
||||
ask1: 10.2,
|
||||
prev_close: 10.0,
|
||||
volume: 100_000,
|
||||
tick_volume: 100_000,
|
||||
bid1_volume: 100_000,
|
||||
ask1_volume: 100_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: "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(),
|
||||
}],
|
||||
vec![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: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}],
|
||||
Vec::new(),
|
||||
vec![
|
||||
IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: dt(2025, 1, 2, 10, 18, 0),
|
||||
last_price: 10.2,
|
||||
bid1: 10.1,
|
||||
ask1: 10.2,
|
||||
bid1_volume: 1_000,
|
||||
ask1_volume: 1_000,
|
||||
volume_delta: 1_000,
|
||||
amount_delta: 10_200.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
},
|
||||
IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: dt(2025, 1, 2, 10, 19, 0),
|
||||
last_price: 10.3,
|
||||
bid1: 10.2,
|
||||
ask1: 10.3,
|
||||
bid1_volume: 1_000,
|
||||
ask1_volume: 1_000,
|
||||
volume_delta: 1_000,
|
||||
amount_delta: 10_300.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("dataset");
|
||||
|
||||
let seen_ticks = Rc::new(RefCell::new(Vec::new()));
|
||||
let strategy = TickProbeStrategy {
|
||||
seen_ticks: seen_ticks.clone(),
|
||||
ordered: false,
|
||||
};
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Last,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
data,
|
||||
strategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 10_000.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(date),
|
||||
end_date: Some(date),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Last,
|
||||
},
|
||||
);
|
||||
|
||||
let result = engine.run().expect("backtest run");
|
||||
|
||||
assert_eq!(
|
||||
seen_ticks.borrow().as_slice(),
|
||||
["000001.SZ:10:18:00:true", "000001.SZ:10:19:00:true"]
|
||||
);
|
||||
assert_eq!(result.fills.len(), 1);
|
||||
assert_eq!(result.fills[0].reason, "tick_buy");
|
||||
assert_eq!(result.fills[0].quantity, 100);
|
||||
assert!(
|
||||
result
|
||||
.process_events
|
||||
.iter()
|
||||
.any(|event| event.kind == ProcessEventKind::PreTick)
|
||||
);
|
||||
assert!(
|
||||
result
|
||||
.process_events
|
||||
.iter()
|
||||
.any(|event| event.kind == ProcessEventKind::Tick)
|
||||
);
|
||||
assert!(
|
||||
result
|
||||
.process_events
|
||||
.iter()
|
||||
.any(|event| event.kind == ProcessEventKind::PostTick)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_rejects_pending_limit_orders_at_market_close() {
|
||||
let date1 = d(2025, 1, 2);
|
||||
|
||||
Reference in New Issue
Block a user