Close RQAlpha P0-P2 parity gaps
This commit is contained in:
@@ -6,10 +6,10 @@ use chrono::{NaiveDate, NaiveDateTime};
|
||||
use fidc_core::{
|
||||
BacktestConfig, BacktestEngine, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility,
|
||||
ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet,
|
||||
FuturesAccountState, FuturesContractSpec, FuturesDirection, FuturesOrderIntent, Instrument,
|
||||
IntradayExecutionQuote, OpenOrderView, OrderIntent, OrderSide, OrderStatus, PortfolioState,
|
||||
PriceField, ProcessEventKind, ScheduleRule, ScheduleStage, ScheduleTimeRule, Strategy,
|
||||
StrategyContext, StrategyDecision,
|
||||
FuturesAccountState, FuturesCommissionType, FuturesContractSpec, FuturesDirection,
|
||||
FuturesOrderIntent, FuturesTradingParameter, Instrument, IntradayExecutionQuote, OpenOrderView,
|
||||
OrderIntent, OrderSide, OrderStatus, PortfolioState, PriceField, ProcessEventKind,
|
||||
ScheduleRule, ScheduleStage, ScheduleTimeRule, Strategy, StrategyContext, StrategyDecision,
|
||||
};
|
||||
|
||||
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
|
||||
@@ -97,6 +97,147 @@ fn single_day_anchor_data(date: NaiveDate) -> DataSet {
|
||||
.expect("dataset")
|
||||
}
|
||||
|
||||
fn market_row(date: NaiveDate, symbol: &str, open: f64, close: f64) -> DailyMarketSnapshot {
|
||||
DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: Some(format!("{date} 10:18:00")),
|
||||
day_open: open,
|
||||
open,
|
||||
high: open.max(close),
|
||||
low: open.min(close),
|
||||
close,
|
||||
last_price: close,
|
||||
bid1: close,
|
||||
ask1: close,
|
||||
prev_close: open,
|
||||
volume: 1_000_000,
|
||||
tick_volume: 1_000_000,
|
||||
bid1_volume: 1_000_000,
|
||||
ask1_volume: 1_000_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: open * 1.1,
|
||||
lower_limit: open * 0.9,
|
||||
price_tick: 0.2,
|
||||
}
|
||||
}
|
||||
|
||||
fn factor_row(
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
extra_factors: BTreeMap<String, f64>,
|
||||
) -> DailyFactorSnapshot {
|
||||
DailyFactorSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
market_cap_bn: 100.0,
|
||||
free_float_cap_bn: 80.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: Some(1.0),
|
||||
effective_turnover_ratio: Some(1.0),
|
||||
extra_factors,
|
||||
}
|
||||
}
|
||||
|
||||
fn candidate_row(date: NaiveDate, symbol: &str) -> CandidateEligibility {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
fn benchmark_row(date: NaiveDate) -> BenchmarkSnapshot {
|
||||
BenchmarkSnapshot {
|
||||
date,
|
||||
benchmark: "000300.SH".to_string(),
|
||||
open: 100.0,
|
||||
close: 100.0,
|
||||
prev_close: 99.0,
|
||||
volume: 1_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
fn two_day_futures_data() -> DataSet {
|
||||
let d1 = d(2025, 1, 2);
|
||||
let d2 = d(2025, 1, 3);
|
||||
DataSet::from_components_with_actions_quotes_and_futures(
|
||||
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(),
|
||||
},
|
||||
Instrument {
|
||||
symbol: "IF2501".to_string(),
|
||||
name: "IF".to_string(),
|
||||
board: "FUTURE".to_string(),
|
||||
round_lot: 1,
|
||||
listed_at: Some(d(2024, 1, 1)),
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
},
|
||||
],
|
||||
vec![
|
||||
market_row(d1, "000001.SZ", 10.0, 10.0),
|
||||
market_row(d2, "000001.SZ", 10.0, 10.0),
|
||||
market_row(d1, "IF2501", 4000.0, 4000.0),
|
||||
market_row(d2, "IF2501", 3988.0, 3990.0),
|
||||
],
|
||||
vec![
|
||||
factor_row(
|
||||
d1,
|
||||
"000001.SZ",
|
||||
BTreeMap::from([
|
||||
("custom_alpha".to_string(), 7.0),
|
||||
("margin_all".to_string(), 1.0),
|
||||
("yield_curve_1y".to_string(), 0.02),
|
||||
]),
|
||||
),
|
||||
factor_row(
|
||||
d2,
|
||||
"000001.SZ",
|
||||
BTreeMap::from([
|
||||
("custom_alpha".to_string(), 8.0),
|
||||
("margin_all".to_string(), 1.0),
|
||||
("yield_curve_1y".to_string(), 0.021),
|
||||
]),
|
||||
),
|
||||
],
|
||||
vec![
|
||||
candidate_row(d1, "000001.SZ"),
|
||||
candidate_row(d2, "000001.SZ"),
|
||||
],
|
||||
vec![benchmark_row(d1), benchmark_row(d2)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![FuturesTradingParameter {
|
||||
symbol: "IF2501".to_string(),
|
||||
effective_date: Some(d1),
|
||||
contract_multiplier: 300.0,
|
||||
long_margin_rate: 0.12,
|
||||
short_margin_rate: 0.14,
|
||||
commission_type: FuturesCommissionType::ByVolume,
|
||||
open_commission_ratio: 2.5,
|
||||
close_commission_ratio: 2.0,
|
||||
close_today_commission_ratio: 3.0,
|
||||
price_tick: 0.2,
|
||||
}],
|
||||
)
|
||||
.expect("futures dataset")
|
||||
}
|
||||
|
||||
struct HookProbeStrategy {
|
||||
log: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
@@ -234,6 +375,73 @@ impl Strategy for FuturesOrderStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
struct FuturesLimitOrderStrategy;
|
||||
|
||||
impl Strategy for FuturesLimitOrderStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"futures-limit-order"
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
if ctx.execution_date != d(2025, 1, 2) {
|
||||
return Ok(StrategyDecision::default());
|
||||
}
|
||||
Ok(StrategyDecision {
|
||||
order_intents: vec![OrderIntent::Futures {
|
||||
intent: FuturesOrderIntent::limit_open(
|
||||
"IF2501",
|
||||
FuturesDirection::Long,
|
||||
FuturesContractSpec::new(1.0, 0.0, 0.0),
|
||||
2,
|
||||
3990.0,
|
||||
0.0,
|
||||
"wait for pullback",
|
||||
),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AdvancedDataApiProbeStrategy {
|
||||
observed: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl Strategy for AdvancedDataApiProbeStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"data-api-probe"
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
let factors = ctx.get_factor(
|
||||
"000001.SZ",
|
||||
ctx.execution_date,
|
||||
ctx.execution_date,
|
||||
"custom_alpha",
|
||||
);
|
||||
let margin_stocks = ctx.get_margin_stocks("all");
|
||||
let yield_curve = ctx.get_yield_curve(ctx.execution_date, ctx.execution_date, Some("1y"));
|
||||
let dominant = ctx.get_dominant_future("IF").unwrap_or_default();
|
||||
let dominant_prices =
|
||||
ctx.get_dominant_future_price("IF", ctx.execution_date, ctx.execution_date, "1d");
|
||||
self.observed.borrow_mut().push(format!(
|
||||
"factor={:.0};margin={};yield={:.3};dominant={};prices={}",
|
||||
factors.first().map(|row| row.value).unwrap_or_default(),
|
||||
margin_stocks.join(","),
|
||||
yield_curve.first().map(|row| row.value).unwrap_or_default(),
|
||||
dominant,
|
||||
dominant_prices.len()
|
||||
));
|
||||
Ok(StrategyDecision::default())
|
||||
}
|
||||
}
|
||||
|
||||
struct ScheduledProbeStrategy {
|
||||
log: Rc<RefCell<Vec<String>>>,
|
||||
process_log: Rc<RefCell<Vec<String>>>,
|
||||
@@ -1098,6 +1306,126 @@ fn engine_settles_configured_futures_expiration_at_settlement() {
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_aggregates_futures_account_into_nav_and_metrics() {
|
||||
let date = d(2025, 1, 2);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
single_day_anchor_data(date),
|
||||
FuturesOrderStrategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_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::Open,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(500_000.0);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert_eq!(result.metrics.initial_cash, 600_000.0);
|
||||
assert!((result.equity_curve[0].total_equity - 599_988.0).abs() < 1e-6);
|
||||
assert!((result.metrics.total_assets - 599_988.0).abs() < 1e-6);
|
||||
assert_eq!(result.analyzer_report().trades.len(), result.fills.len());
|
||||
assert!(
|
||||
result
|
||||
.analyzer_report_json()
|
||||
.expect("report json")
|
||||
.contains("\"trades\"")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_matches_pending_futures_limit_order_with_data_driven_costs() {
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
two_day_futures_data(),
|
||||
FuturesLimitOrderStrategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_000.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(d(2025, 1, 2)),
|
||||
end_date: Some(d(2025, 1, 3)),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Open,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(1_000_000.0);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert!(
|
||||
result
|
||||
.order_events
|
||||
.iter()
|
||||
.any(|event| { event.symbol == "IF2501" && event.status == OrderStatus::Pending })
|
||||
);
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::Filled
|
||||
&& event.filled_quantity == 2
|
||||
}));
|
||||
let fill = result
|
||||
.fills
|
||||
.iter()
|
||||
.find(|fill| fill.symbol == "IF2501")
|
||||
.expect("futures fill");
|
||||
assert!((fill.price - 3988.0).abs() < 1e-6);
|
||||
assert!((fill.commission - 5.0).abs() < 1e-6);
|
||||
let futures_account = engine.futures_account().expect("future account");
|
||||
let position = futures_account
|
||||
.position("IF2501", FuturesDirection::Long)
|
||||
.expect("long futures position");
|
||||
assert_eq!(position.quantity, 2);
|
||||
assert!((position.contract_multiplier - 300.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strategy_context_exposes_advanced_rqdata_helpers() {
|
||||
let observed = Rc::new(RefCell::new(Vec::new()));
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
two_day_futures_data(),
|
||||
AdvancedDataApiProbeStrategy {
|
||||
observed: observed.clone(),
|
||||
},
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_000.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(d(2025, 1, 2)),
|
||||
end_date: Some(d(2025, 1, 2)),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Open,
|
||||
},
|
||||
);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert_eq!(
|
||||
observed.borrow().as_slice(),
|
||||
&["factor=7;margin=000001.SZ;yield=0.020;dominant=IF2501;prices=1"]
|
||||
);
|
||||
assert!(result.analyzer_report().positions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_runs_subscribed_tick_hooks_and_executes_tick_orders() {
|
||||
let date = d(2025, 1, 2);
|
||||
|
||||
Reference in New Issue
Block a user