Support algo order pricing in smart portfolio rebalances

This commit is contained in:
boris
2026-04-23 18:48:14 -07:00
parent ac308c8d68
commit 58836a1c37
7 changed files with 427 additions and 28 deletions

View File

@@ -12,7 +12,9 @@ use crate::events::{
};
use crate::portfolio::PortfolioState;
use crate::rules::EquityRuleHooks;
use crate::strategy::{AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision};
use crate::strategy::{
AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision, TargetPortfolioOrderPricing,
};
#[derive(Debug, Default)]
pub struct BrokerExecutionReport {
@@ -547,6 +549,7 @@ where
execution_cursors,
global_execution_cursor,
commission_state,
None,
report,
),
OrderIntent::LimitShares {
@@ -1567,7 +1570,7 @@ where
portfolio: &mut PortfolioState,
data: &DataSet,
target_weights: &BTreeMap<String, f64>,
order_prices: Option<&BTreeMap<String, f64>>,
order_prices: Option<&TargetPortfolioOrderPricing>,
valuation_prices: Option<&BTreeMap<String, f64>>,
reason: &str,
intraday_turnover: &mut BTreeMap<String, u32>,
@@ -1584,6 +1587,25 @@ where
valuation_prices,
)?;
report.diagnostics.extend(diagnostics);
let limit_prices = match order_prices {
Some(TargetPortfolioOrderPricing::LimitPrices(prices)) => Some(prices),
_ => None,
};
let algo_request = match order_prices {
Some(TargetPortfolioOrderPricing::AlgoOrder {
style,
start_time,
end_time,
}) => Some(AlgoExecutionRequest {
style: match style {
AlgoOrderStyle::Vwap => AlgoExecutionStyle::Vwap,
AlgoOrderStyle::Twap => AlgoExecutionStyle::Twap,
},
start_time: *start_time,
end_time: *end_time,
}),
_ => None,
};
let mut symbols = BTreeSet::new();
symbols.extend(portfolio.positions().keys().cloned());
@@ -1601,7 +1623,7 @@ where
let sell_qty = current_qty - target_qty;
let mut local_report = BrokerExecutionReport::default();
if let Some(limit_price) =
self.required_custom_order_price(date, symbol, order_prices)?
self.required_custom_order_price(date, symbol, limit_prices)?
{
self.process_limit_shares(
date,
@@ -1629,6 +1651,7 @@ where
execution_cursors,
global_execution_cursor,
commission_state,
algo_request.as_ref(),
&mut local_report,
)?;
}
@@ -1647,7 +1670,7 @@ where
let buy_qty = target_qty - current_qty;
let mut local_report = BrokerExecutionReport::default();
if let Some(limit_price) =
self.required_custom_order_price(date, symbol, order_prices)?
self.required_custom_order_price(date, symbol, limit_prices)?
{
self.process_limit_shares(
date,
@@ -1675,6 +1698,7 @@ where
execution_cursors,
global_execution_cursor,
commission_state,
algo_request.as_ref(),
&mut local_report,
)?;
}
@@ -3189,6 +3213,7 @@ where
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
global_execution_cursor: &mut Option<NaiveDateTime>,
commission_state: &mut BTreeMap<u64, f64>,
algo_request: Option<&AlgoExecutionRequest>,
report: &mut BrokerExecutionReport,
) -> Result<(), BacktestError> {
if quantity == 0 {
@@ -3216,7 +3241,7 @@ where
None,
false,
true,
None,
algo_request,
report,
)
} else {
@@ -3235,7 +3260,7 @@ where
None,
false,
true,
None,
algo_request,
report,
)
}
@@ -3273,6 +3298,7 @@ where
execution_cursors,
global_execution_cursor,
commission_state,
None,
report,
)
}

View File

@@ -45,8 +45,9 @@ pub use scheduler::{
ScheduleFrequency, ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time,
};
pub use strategy::{
CnSmallCapRotationConfig, CnSmallCapRotationStrategy, JqMicroCapConfig, JqMicroCapStrategy,
AlgoOrderStyle, OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision,
AlgoOrderStyle, CnSmallCapRotationConfig, CnSmallCapRotationStrategy, JqMicroCapConfig,
JqMicroCapStrategy, OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision,
TargetPortfolioOrderPricing,
};
pub use strategy_ai::{
ManualExample, ManualFactorSource, ManualField, ManualFieldGroup, ManualFunction,

View File

@@ -11,7 +11,10 @@ use crate::portfolio::PortfolioState;
use crate::scheduler::{
ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time,
};
use crate::strategy::{AlgoOrderStyle, OrderIntent, Strategy, StrategyContext, StrategyDecision};
use crate::strategy::{
AlgoOrderStyle, OrderIntent, Strategy, StrategyContext, StrategyDecision,
TargetPortfolioOrderPricing,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlatformScheduleFrequency {
@@ -2229,6 +2232,10 @@ impl PlatformExprStrategy {
expr
)));
};
Self::parse_time_string(raw.trim())
}
fn parse_time_string(raw: &str) -> Result<NaiveTime, BacktestError> {
NaiveTime::parse_from_str(raw.trim(), "%H:%M")
.or_else(|_| NaiveTime::parse_from_str(raw.trim(), "%H:%M:%S"))
.map_err(|_| {
@@ -2239,6 +2246,49 @@ impl PlatformExprStrategy {
})
}
fn parse_numeric_time_code(code: i64, expr: &str) -> Result<NaiveTime, BacktestError> {
let value = code.abs();
let (hour, minute, second) = if value >= 10_000 {
(
(value / 10_000) as u32,
((value / 100) % 100) as u32,
(value % 100) as u32,
)
} else {
((value / 100) as u32, (value % 100) as u32, 0)
};
NaiveTime::from_hms_opt(hour, minute, second).ok_or_else(|| {
BacktestError::Execution(format!(
"platform expr did not produce a valid HHMM/HHMMSS time code: {}",
expr
))
})
}
fn eval_time_code_expr(
&self,
ctx: &StrategyContext<'_>,
expr: &str,
day: &DayExpressionState,
stock: Option<&StockExpressionState>,
position: Option<&PositionExpressionState>,
) -> Result<NaiveTime, BacktestError> {
let value = self.eval_dynamic(ctx, expr, day, stock, position)?;
if let Some(raw) = value.clone().try_cast::<String>() {
return Self::parse_time_string(raw.trim());
}
if let Some(number) = value.clone().try_cast::<f64>() {
return Self::parse_numeric_time_code(number.round() as i64, expr);
}
if let Some(number) = value.try_cast::<i64>() {
return Self::parse_numeric_time_code(number, expr);
}
Err(BacktestError::Execution(format!(
"platform expr did not produce a time string or HHMM/HHMMSS time code: {}",
expr
)))
}
fn eval_float_map_expr(
&self,
ctx: &StrategyContext<'_>,
@@ -2273,6 +2323,75 @@ impl PlatformExprStrategy {
Ok(output)
}
fn eval_target_portfolio_order_pricing_expr(
&self,
ctx: &StrategyContext<'_>,
expr: &str,
day: &DayExpressionState,
stock: Option<&StockExpressionState>,
position: Option<&PositionExpressionState>,
) -> Result<TargetPortfolioOrderPricing, BacktestError> {
let trimmed = expr.trim();
if trimmed.is_empty() {
return Err(BacktestError::Execution(
"target_portfolio_smart order_prices expr cannot be empty".to_string(),
));
}
if trimmed.starts_with('{') {
return Ok(TargetPortfolioOrderPricing::LimitPrices(
self.eval_float_map_expr(ctx, trimmed, day, stock, position)?,
));
}
self.eval_algo_order_pricing_expr(ctx, trimmed, day, stock, position)
}
fn eval_algo_order_pricing_expr(
&self,
ctx: &StrategyContext<'_>,
expr: &str,
day: &DayExpressionState,
stock: Option<&StockExpressionState>,
position: Option<&PositionExpressionState>,
) -> Result<TargetPortfolioOrderPricing, BacktestError> {
let Some(open_paren) = expr.find('(') else {
return Err(BacktestError::Execution(format!(
"target_portfolio_smart order_prices must be a {{...}} map or AlgoOrder(...) call: {expr}"
)));
};
let Some(args_src) = expr
.strip_suffix(')')
.map(|trimmed| &trimmed[open_paren + 1..])
else {
return Err(BacktestError::Execution(format!(
"target_portfolio_smart order_prices must end with ')': {expr}"
)));
};
let name = expr[..open_paren].trim().to_ascii_lowercase();
let style = match name.as_str() {
"vwap" | "vwaporder" => AlgoOrderStyle::Vwap,
"twap" | "twaporder" => AlgoOrderStyle::Twap,
_ => {
return Err(BacktestError::Execution(format!(
"unsupported target_portfolio_smart AlgoOrder style: {}",
expr[..open_paren].trim()
)));
}
};
let args = Self::split_top_level_args(args_src);
if args.len() != 2 {
return Err(BacktestError::Execution(format!(
"target_portfolio_smart AlgoOrder expects start and end time arguments: {expr}"
)));
}
let start_time = self.eval_time_code_expr(ctx, &args[0], day, stock, position)?;
let end_time = self.eval_time_code_expr(ctx, &args[1], day, stock, position)?;
Ok(TargetPortfolioOrderPricing::AlgoOrder {
style,
start_time: Some(start_time),
end_time: Some(end_time),
})
}
fn eval_symbol_set_expr(
&self,
ctx: &StrategyContext<'_>,
@@ -2788,7 +2907,11 @@ impl PlatformExprStrategy {
}
let order_prices = order_prices_expr
.as_deref()
.map(|expr| self.eval_float_map_expr(ctx, expr, day, None, None))
.map(|expr| {
self.eval_target_portfolio_order_pricing_expr(
ctx, expr, day, None, None,
)
})
.transpose()?;
let valuation_prices = valuation_prices_expr
.as_deref()
@@ -3466,7 +3589,7 @@ mod tests {
AlgoOrderStyle, BenchmarkSnapshot, CandidateEligibility, DailyFactorSnapshot,
DailyMarketSnapshot, DataSet, Instrument, OpenOrderView, PortfolioState, ProcessEvent,
ProcessEventKind, ScheduleStage, ScheduleTimeRule, Strategy, StrategyContext,
TradingCalendar, default_stage_time,
TargetPortfolioOrderPricing, TradingCalendar, default_stage_time,
};
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
@@ -4037,12 +4160,12 @@ mod tests {
assert_eq!(reason, "platform_target_portfolio_smart");
assert_eq!(target_weights.get("000001.SZ").copied(), Some(0.30));
assert_eq!(target_weights.get("000002.SZ").copied(), Some(0.20));
assert_eq!(
order_prices
.as_ref()
.and_then(|map| map.get("000001.SZ").copied()),
Some(1010.0)
);
match order_prices {
Some(TargetPortfolioOrderPricing::LimitPrices(map)) => {
assert_eq!(map.get("000001.SZ").copied(), Some(1010.0));
}
other => panic!("unexpected order pricing: {other:?}"),
}
assert_eq!(
valuation_prices
.as_ref()
@@ -4054,6 +4177,104 @@ mod tests {
}
}
#[test]
fn platform_strategy_emits_target_portfolio_smart_algo_order_style() {
let date = d(2025, 2, 3);
let data = DataSet::from_components(
vec![],
vec![DailyMarketSnapshot {
date,
symbol: "000001.SH".to_string(),
timestamp: Some("2025-02-03 10:18:00".to_string()),
day_open: 1000.0,
open: 1000.0,
high: 1002.0,
low: 998.0,
close: 1001.0,
last_price: 1001.0,
bid1: 1000.5,
ask1: 1001.5,
prev_close: 999.0,
volume: 100_000,
tick_volume: 5_000,
bid1_volume: 2_500,
ask1_volume: 2_500,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 1098.9,
lower_limit: 899.1,
price_tick: 0.01,
}],
vec![],
vec![],
vec![BenchmarkSnapshot {
date,
benchmark: "000852.SH".to_string(),
open: 1000.0,
close: 1001.0,
prev_close: 999.0,
volume: 100_000,
}],
)
.expect("dataset");
let portfolio = PortfolioState::new(1_000_000.0);
let subscriptions = BTreeSet::new();
let ctx = StrategyContext {
execution_date: date,
decision_date: date,
decision_index: 0,
data: &data,
portfolio: &portfolio,
open_orders: &[],
dynamic_universe: None,
subscriptions: &subscriptions,
process_events: &[],
active_process_event: None,
};
let mut cfg = PlatformExprStrategyConfig::microcap_rotation();
cfg.signal_symbol = "000001.SH".to_string();
cfg.rotation_enabled = false;
cfg.benchmark_short_ma_days = 1;
cfg.benchmark_long_ma_days = 1;
cfg.explicit_actions = vec![PlatformTradeAction::TargetPortfolioSmart {
target_weights_expr: "{\"000001.SZ\": 0.30}".to_string(),
order_prices_expr: Some("VWAPOrder(930, 940)".to_string()),
valuation_prices_expr: Some("{\"000001.SZ\": signal_close}".to_string()),
when_expr: None,
reason: "platform_target_portfolio_smart_algo".to_string(),
}];
let mut strategy = PlatformExprStrategy::new(cfg);
let decision = strategy.on_day(&ctx).expect("platform decision");
assert_eq!(decision.order_intents.len(), 1);
match &decision.order_intents[0] {
crate::strategy::OrderIntent::TargetPortfolioSmart {
order_prices,
reason,
..
} => {
assert_eq!(reason, "platform_target_portfolio_smart_algo");
match order_prices {
Some(TargetPortfolioOrderPricing::AlgoOrder {
style,
start_time,
end_time,
}) => {
assert_eq!(*style, AlgoOrderStyle::Vwap);
assert_eq!(
*start_time,
Some(NaiveTime::from_hms_opt(9, 30, 0).unwrap())
);
assert_eq!(*end_time, Some(NaiveTime::from_hms_opt(9, 40, 0).unwrap()));
}
other => panic!("unexpected order pricing: {other:?}"),
}
}
other => panic!("unexpected explicit target portfolio intent: {other:?}"),
}
}
#[test]
fn platform_strategy_emits_explicit_actions_in_open_auction_stage() {
let date = d(2025, 2, 3);

View File

@@ -334,6 +334,16 @@ pub enum AlgoOrderStyle {
Twap,
}
#[derive(Debug, Clone)]
pub enum TargetPortfolioOrderPricing {
LimitPrices(BTreeMap<String, f64>),
AlgoOrder {
style: AlgoOrderStyle,
start_time: Option<NaiveTime>,
end_time: Option<NaiveTime>,
},
}
#[derive(Debug, Clone)]
pub enum OrderIntent {
Shares {
@@ -431,7 +441,7 @@ pub enum OrderIntent {
},
TargetPortfolioSmart {
target_weights: BTreeMap<String, f64>,
order_prices: Option<BTreeMap<String, f64>>,
order_prices: Option<TargetPortfolioOrderPricing>,
valuation_prices: Option<BTreeMap<String, f64>>,
reason: String,
},

View File

@@ -120,7 +120,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
},
ManualSection {
title: "trading.rotation / order.* / cancel.* / update_universe / subscribe".to_string(),
detail: "支持显式下单、撤单、AlgoOrder 和动态 universe 管理。可以用 trading.rotation(false) 关闭默认轮动链路,再用 trading.stage(\"open_auction\" | \"on_day\") 指定执行阶段,用 trading.schedule.daily().at([\"10:18\"]) / trading.schedule.weekly(weekday=5).at([\"10:18\"]) / trading.schedule.weekly(tradingday=-1).at([\"10:18\"]) / trading.schedule.monthly(tradingday=1).at([\"10:18\"]) 指定触发频率和分钟级 time_rule然后写 order.shares(\"600000.SH\", 1000)、order.target_shares(\"600000.SH\", 2000)、order.value(\"600000.SH\", cash * 0.25)、order.target_percent(\"600000.SH\", 0.05)、order.limit_value(\"600000.SH\", cash * 0.25, open * 0.99)、order.vwap_value(\"600000.SH\", cash * 0.25, \"09:31\", \"09:40\")、order.twap_percent(\"600000.SH\", 0.05, \"10:00\", \"10:30\")、order.target_portfolio_smart(weights={\"600000.SH\": 0.3, \"000001.SZ\": 0.2}, order_prices={\"600000.SH\": open * 0.99}, valuation_prices={\"600000.SH\": prev_close})、cancel.order(12345)、cancel.symbol(\"600000.SH\")、cancel.all()、update_universe([\"600000.SH\", \"000001.SZ\"])、subscribe([\"000001.SZ\"])、unsubscribe([\"000001.SZ\"])。其中 order.target_shares(...) 对应 rqalpha 的 order_toorder.target_portfolio_smart(...) 对应 rqalpha 的 order_target_portfolio_smart 批量目标权重语义order.vwap_* / order.twap_* 对应 rqalpha 的 AlgoOrder 时间窗订单风格,而 update_universe/subscribe/unsubscribe 对应 rqalpha 的动态 universe 与订阅接口。symbol 使用标准证券代码数量、金额、仓位、时间窗、限价、order_id 和 symbol 列表都支持表达式;这些语句也支持放进 when/unless 条件块。".to_string(),
detail: "支持显式下单、撤单、AlgoOrder 和动态 universe 管理。可以用 trading.rotation(false) 关闭默认轮动链路,再用 trading.stage(\"open_auction\" | \"on_day\") 指定执行阶段,用 trading.schedule.daily().at([\"10:18\"]) / trading.schedule.weekly(weekday=5).at([\"10:18\"]) / trading.schedule.weekly(tradingday=-1).at([\"10:18\"]) / trading.schedule.monthly(tradingday=1).at([\"10:18\"]) 指定触发频率和分钟级 time_rule然后写 order.shares(\"600000.SH\", 1000)、order.target_shares(\"600000.SH\", 2000)、order.value(\"600000.SH\", cash * 0.25)、order.target_percent(\"600000.SH\", 0.05)、order.limit_value(\"600000.SH\", cash * 0.25, open * 0.99)、order.vwap_value(\"600000.SH\", cash * 0.25, \"09:31\", \"09:40\")、order.twap_percent(\"600000.SH\", 0.05, \"10:00\", \"10:30\")、order.target_portfolio_smart(weights={\"600000.SH\": 0.3, \"000001.SZ\": 0.2}, order_prices=VWAPOrder(930, 940), valuation_prices={\"600000.SH\": prev_close})、order.target_portfolio_smart(weights={\"600000.SH\": 0.3, \"000001.SZ\": 0.2}, order_prices={\"600000.SH\": open * 0.99}, valuation_prices={\"600000.SH\": prev_close})、cancel.order(12345)、cancel.symbol(\"600000.SH\")、cancel.all()、update_universe([\"600000.SH\", \"000001.SZ\"])、subscribe([\"000001.SZ\"])、unsubscribe([\"000001.SZ\"])。其中 order.target_shares(...) 对应 rqalpha 的 order_toorder.target_portfolio_smart(...) 对应 rqalpha 的 order_target_portfolio_smart 批量目标权重语义order_prices 既可以是逐标的限价映射,也可以是 VWAPOrder/TWAPOrder 这类全局 AlgoOrderorder.vwap_* / order.twap_* 对应 rqalpha 的 AlgoOrder 时间窗订单风格,而 update_universe/subscribe/unsubscribe 对应 rqalpha 的动态 universe 与订阅接口。symbol 使用标准证券代码数量、金额、仓位、时间窗、限价、order_id 和 symbol 列表都支持表达式;这些语句也支持放进 when/unless 条件块。".to_string(),
},
ManualSection {
title: "when / unless / else".to_string(),