Add management fee callbacks

This commit is contained in:
boris
2026-04-23 20:18:31 -07:00
parent 85feee6dac
commit c843de078f
9 changed files with 241 additions and 10 deletions

View File

@@ -933,6 +933,12 @@ where
));
Ok(())
}
OrderIntent::SetManagementFeeRate { rate, reason } => {
report.diagnostics.push(format!(
"engine_account_intent_skipped kind=set_management_fee_rate rate={rate:.6} reason={reason}"
));
Ok(())
}
}
}

View File

@@ -396,6 +396,38 @@ where
},
)?;
}
crate::strategy::OrderIntent::SetManagementFeeRate { rate, reason } => {
portfolio
.set_management_fee_rate(rate)
.map_err(BacktestError::Execution)?;
decision
.diagnostics
.push(format!("account_management_fee_rate rate={rate:.6}"));
publish_custom_process_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&*portfolio,
open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
process_events,
ProcessEvent {
date: execution_date,
kind: ProcessEventKind::AccountManagementFee,
order_id: None,
symbol: None,
side: None,
detail: format!(
"reason={reason} rate={rate:.6} management_fees={:.2}",
portfolio.management_fees()
),
},
)?;
}
other => retained.push(other),
}
}
@@ -1283,6 +1315,21 @@ where
&mut settlement_decision,
&mut directive_report,
)?;
let dynamic_universe_snapshot = self.dynamic_universe.clone();
let subscriptions_snapshot = self.subscriptions.clone();
let management_fee_report = self.apply_management_fee(
execution_date,
decision_date,
decision_index,
&mut portfolio,
&post_close_open_orders,
dynamic_universe_snapshot.as_ref(),
&subscriptions_snapshot,
&mut process_events,
visible_order_events_after_close.as_slice(),
visible_fills_after_close.as_slice(),
)?;
merge_broker_report(&mut directive_report, management_fee_report);
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
@@ -1695,6 +1742,92 @@ where
report
}
fn apply_management_fee(
&mut self,
execution_date: NaiveDate,
decision_date: NaiveDate,
decision_index: usize,
portfolio: &mut PortfolioState,
open_orders: &[crate::strategy::OpenOrderView],
dynamic_universe: Option<&BTreeSet<String>>,
subscriptions: &BTreeSet<String>,
process_events: &mut Vec<ProcessEvent>,
order_events: &[OrderEvent],
fills: &[FillEvent],
) -> Result<BrokerExecutionReport, BacktestError> {
let rate = portfolio.management_fee_rate();
if rate <= 0.0 {
return Ok(BrokerExecutionReport::default());
}
let fee = self
.strategy
.management_fee(
&StrategyContext {
execution_date,
decision_date,
decision_index,
data: &self.data,
portfolio,
open_orders,
dynamic_universe,
subscriptions,
process_events: process_events.as_slice(),
active_process_event: None,
active_datetime: stage_datetime(
execution_date,
default_stage_time(ScheduleStage::Settlement),
),
order_events,
fills,
},
rate,
)?
.unwrap_or_else(|| portfolio.default_management_fee());
if fee <= 0.0 {
return Ok(BrokerExecutionReport::default());
}
let cash_before = portfolio.cash();
portfolio
.apply_management_fee(fee)
.map_err(BacktestError::Execution)?;
let mut report = BrokerExecutionReport::default();
report.account_events.push(AccountEvent {
date: execution_date,
cash_before,
cash_after: portfolio.cash(),
total_equity: portfolio.total_equity(),
note: format!("management_fee rate={rate:.6} fee={fee:.2}"),
});
publish_custom_process_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&*portfolio,
open_orders,
dynamic_universe,
subscriptions,
process_events,
ProcessEvent {
date: execution_date,
kind: ProcessEventKind::AccountManagementFee,
order_id: None,
symbol: None,
side: None,
detail: format!(
"rate={rate:.6} fee={fee:.2} cash_before={cash_before:.2} cash_after={:.2} management_fees={:.2}",
portfolio.cash(),
portfolio.management_fees()
),
},
)?;
Ok(report)
}
fn settle_delisted_positions(
&self,
date: NaiveDate,

View File

@@ -150,6 +150,7 @@ pub enum ProcessEventKind {
UniverseUnsubscribed,
AccountDepositWithdraw,
AccountFinanceRepay,
AccountManagementFee,
}
impl ProcessEventKind {
@@ -191,6 +192,7 @@ impl ProcessEventKind {
Self::UniverseUnsubscribed => "universe_unsubscribed",
Self::AccountDepositWithdraw => "account_deposit_withdraw",
Self::AccountFinanceRepay => "account_finance_repay",
Self::AccountManagementFee => "account_management_fee",
}
}
}

View File

@@ -118,6 +118,7 @@ pub enum PlatformUniverseActionKind {
pub enum PlatformAccountActionKind {
DepositWithdraw,
FinanceRepay,
SetManagementFeeRate,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -310,6 +311,8 @@ struct DayExpressionState {
trading_pnl: f64,
position_pnl: f64,
cash_liabilities: f64,
management_fee_rate: f64,
management_fees: f64,
current_exposure: f64,
position_count: i64,
max_positions: i64,
@@ -494,6 +497,8 @@ impl PlatformExprStrategy {
"daily_returns",
"total_returns",
"cash_liabilities",
"management_fee_rate",
"management_fees",
"current_exposure",
"position_count",
"max_positions",
@@ -1115,6 +1120,8 @@ impl PlatformExprStrategy {
trading_pnl: account.trading_pnl,
position_pnl: account.position_pnl,
cash_liabilities: account.cash_liabilities,
management_fee_rate: account.management_fee_rate,
management_fees: account.management_fees,
current_exposure,
position_count: ctx.portfolio.positions().len() as i64,
max_positions: self.config.max_positions as i64,
@@ -1294,6 +1301,8 @@ impl PlatformExprStrategy {
scope.push("trading_pnl", day.trading_pnl);
scope.push("position_pnl", day.position_pnl);
scope.push("cash_liabilities", day.cash_liabilities);
scope.push("management_fee_rate", day.management_fee_rate);
scope.push("management_fees", day.management_fees);
scope.push("current_exposure", day.current_exposure);
scope.push("position_count", day.position_count);
scope.push("max_positions", day.max_positions);
@@ -1428,6 +1437,11 @@ impl PlatformExprStrategy {
"cash_liabilities".into(),
Dynamic::from(day.cash_liabilities),
);
day_factors.insert(
"management_fee_rate".into(),
Dynamic::from(day.management_fee_rate),
);
day_factors.insert("management_fees".into(), Dynamic::from(day.management_fees));
day_factors.insert(
"current_exposure".into(),
Dynamic::from(day.current_exposure),
@@ -3125,6 +3139,12 @@ impl PlatformExprStrategy {
reason: reason.clone(),
});
}
PlatformAccountActionKind::SetManagementFeeRate => {
intents.push(OrderIntent::SetManagementFeeRate {
rate: amount,
reason: reason.clone(),
});
}
}
}
PlatformTradeAction::TargetPortfolioSmart {

View File

@@ -311,6 +311,8 @@ pub struct PortfolioState {
units: f64,
cash: f64,
cash_liabilities: f64,
management_fee_rate: f64,
management_fees: f64,
positions: IndexMap<String, Position>,
cash_receivables: Vec<CashReceivable>,
pending_cash_flows: Vec<PendingCashFlow>,
@@ -341,6 +343,8 @@ impl PortfolioState {
units: initial_cash,
cash: initial_cash,
cash_liabilities: 0.0,
management_fee_rate: 0.0,
management_fees: 0.0,
positions: IndexMap::new(),
cash_receivables: Vec::new(),
pending_cash_flows: Vec::new(),
@@ -367,6 +371,14 @@ impl PortfolioState {
self.cash_liabilities
}
pub fn management_fee_rate(&self) -> f64 {
self.management_fee_rate
}
pub fn management_fees(&self) -> f64 {
self.management_fees
}
pub fn positions(&self) -> &IndexMap<String, Position> {
&self.positions
}
@@ -484,6 +496,27 @@ impl PortfolioState {
Ok(())
}
pub fn set_management_fee_rate(&mut self, rate: f64) -> Result<(), String> {
if !rate.is_finite() || rate < 0.0 {
return Err("management fee rate must be finite and non-negative".to_string());
}
self.management_fee_rate = rate;
Ok(())
}
pub fn default_management_fee(&self) -> f64 {
self.total_equity().max(0.0) * self.management_fee_rate
}
pub fn apply_management_fee(&mut self, fee: f64) -> Result<(), String> {
if !fee.is_finite() || fee < 0.0 {
return Err("management fee must be finite and non-negative".to_string());
}
self.cash -= fee;
self.management_fees += fee;
Ok(())
}
pub fn settle_cash_receivables(&mut self, date: NaiveDate) -> Vec<CashReceivable> {
let mut settled = Vec::new();
let mut pending = Vec::new();

View File

@@ -17,6 +17,13 @@ use crate::universe::{DynamicMarketCapBandSelector, SelectionContext, UniverseSe
pub trait Strategy {
fn name(&self) -> &str;
fn management_fee(
&mut self,
_ctx: &StrategyContext<'_>,
_rate: f64,
) -> Result<Option<f64>, BacktestError> {
Ok(None)
}
fn on_process_event(
&mut self,
_ctx: &StrategyContext<'_>,
@@ -115,6 +122,8 @@ pub struct PortfolioRuntimeView {
pub trading_pnl: f64,
pub position_pnl: f64,
pub cash_liabilities: f64,
pub management_fee_rate: f64,
pub management_fees: f64,
}
pub struct StrategyContext<'a> {
@@ -368,6 +377,8 @@ impl StrategyContext<'_> {
trading_pnl: self.portfolio.trading_pnl(),
position_pnl: self.portfolio.position_pnl(),
cash_liabilities: self.portfolio.cash_liabilities(),
management_fee_rate: self.portfolio.management_fee_rate(),
management_fees: self.portfolio.management_fees(),
}
}
@@ -819,6 +830,10 @@ pub enum OrderIntent {
amount: f64,
reason: String,
},
SetManagementFeeRate {
rate: f64,
reason: String,
},
}
#[derive(Debug, Clone)]

View File

@@ -124,7 +124,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\") 指定执行阶段;需要模拟 rqalpha 的 tick 订阅保护时,可写 trading.subscription_guard(true),未订阅 symbol 的显式订单会被拦截TargetPortfolioSmart + AlgoOrder 会过滤未订阅标的。用 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\"])、account.deposit_withdraw(100000, receiving_days=0)、account.finance_repay(50000)。其中 order.target_shares(...) 对应 rqalpha 的 order_toorder.target_portfolio_smart(...) 对应 rqalpha 的 order_target_portfolio_smart 批量目标权重语义account.deposit_withdraw(...) 和 account.finance_repay(...) 对应 RQAlpha 账户出入金与融资/还款语义order_prices 既可以是逐标的限价映射,也可以是 VWAPOrder/TWAPOrder 这类全局 AlgoOrderorder.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\") 指定执行阶段;需要模拟 rqalpha 的 tick 订阅保护时,可写 trading.subscription_guard(true),未订阅 symbol 的显式订单会被拦截TargetPortfolioSmart + AlgoOrder 会过滤未订阅标的。用 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\"])、account.deposit_withdraw(100000, receiving_days=0)、account.finance_repay(50000)、account.set_management_fee_rate(0.001)。其中 order.target_shares(...) 对应 rqalpha 的 order_toorder.target_portfolio_smart(...) 对应 rqalpha 的 order_target_portfolio_smart 批量目标权重语义account.deposit_withdraw(...) 和 account.finance_repay(...) 对应 RQAlpha 账户出入金与融资/还款语义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(),
@@ -142,7 +142,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
ManualField { name: "benchmark_ma5/benchmark_ma10/benchmark_ma20/benchmark_ma30".to_string(), field_type: "float".to_string(), detail: "基准指数滚动均线。".to_string() },
ManualField { name: "cash/available_cash/frozen_cash/market_value/total_equity".to_string(), field_type: "float".to_string(), detail: "账户可用资金、挂单冻结资金、市值与总权益available_cash 会扣减当前买入挂单冻结估算。".to_string() },
ManualField { name: "total_value/portfolio_value/starting_cash/unit_net_value/static_unit_net_value".to_string(), field_type: "float".to_string(), detail: "组合总权益别名、初始资金、实时净值和昨日静态净值,对齐 RQAlpha Portfolio 常用字段。".to_string() },
ManualField { name: "daily_pnl/daily_returns/total_returns/transaction_cost/trading_pnl/position_pnl/cash_liabilities".to_string(), field_type: "float".to_string(), detail: "账户当日盈亏、日收益率、累计收益率、当日交易成本、交易盈亏、持仓盈亏现金负债;股票账户现金负债默认为 0".to_string() },
ManualField { name: "daily_pnl/daily_returns/total_returns/transaction_cost/trading_pnl/position_pnl/cash_liabilities/management_fee_rate/management_fees".to_string(), field_type: "float".to_string(), detail: "账户当日盈亏、日收益率、累计收益率、当日交易成本、交易盈亏、持仓盈亏现金负债、管理费率和累计管理费".to_string() },
ManualField { name: "position_count/max_positions/refresh_rate".to_string(), field_type: "int".to_string(), detail: "仓位计数与调仓周期。".to_string() },
ManualField { name: "has_open_orders/open_order_count/open_buy_order_count/open_sell_order_count".to_string(), field_type: "bool/int".to_string(), detail: "当前阶段挂单簿摘要。".to_string() },
ManualField { name: "open_buy_qty/open_sell_qty/latest_open_order_id".to_string(), field_type: "int".to_string(), detail: "当前阶段未成交买卖挂单的剩余数量汇总,以及最近一笔挂单 id。".to_string() },
@@ -208,7 +208,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
ManualFunction { name: "get_price".to_string(), signature: "ctx.get_price(symbol, start_date, end_date, \"1d\" | \"1m\" | \"tick\")".to_string(), detail: "按日期区间读取统一 PriceBar 序列。日线返回 open/high/low/close/last/volume/盘口字段;分钟或 tick 返回按 timestamp 排序的 last/bid1/ask1/volume_delta/amount_delta 映射,便于服务层转成表格或前端明细。".to_string() },
ManualFunction { name: "order/order_status/order_avg_price/order_transaction_cost".to_string(), signature: "ctx.order(order_id)".to_string(), detail: "按订单 id 查询运行时订单对象,支持已结束订单和当前挂单。返回字段包括 status、filled_quantity、unfilled_quantity、avg_price、transaction_cost、symbol、side、reason可用便捷函数读取状态、成交均价和费用对齐 RQAlpha Order 的核心属性。".to_string() },
ManualFunction { name: "account/portfolio_view".to_string(), signature: "ctx.account()".to_string(), detail: "返回当前股票账户/组合运行时视图,字段包括 cash、available_cash、frozen_cash、market_value、total_value、unit_net_value、daily_pnl、daily_returns、total_returns、transaction_cost、trading_pnl、position_pnl 等DSL 中同名字段可直接使用。".to_string() },
ManualFunction { name: "deposit_withdraw/finance_repay".to_string(), signature: "account.deposit_withdraw(amount, receiving_days=0)".to_string(), detail: "策略账户资金动作。deposit_withdraw 正数入金、负数出金receiving_days 大于 0 时按交易日延迟到账并保持净值口径不把外部资金流当成收益。finance_repay 正数融资、负数还款,会同步维护 cash_liabilities。".to_string() },
ManualFunction { name: "deposit_withdraw/finance_repay/management_fee".to_string(), signature: "account.deposit_withdraw(amount, receiving_days=0)".to_string(), detail: "策略账户资金动作。deposit_withdraw 正数入金、负数出金receiving_days 大于 0 时按交易日延迟到账并保持净值口径不把外部资金流当成收益。finance_repay 正数融资、负数还款,会同步维护 cash_liabilities。set_management_fee_rate 设置结算管理费率;普通策略可覆盖 management_fee(ctx, rate) 自定义计算器,对齐 RQAlpha 管理费回调能力。".to_string() },
ManualFunction { name: "rolling_mean".to_string(), signature: "rolling_mean(\"field\", lookback)".to_string(), detail: "任意字段滚动均值,支持 volume/amount/turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 等。任意成交量窗口推荐用它,比如 rolling_mean(\"volume\", 15)。".to_string() },
ManualFunction { name: "sma".to_string(), signature: "sma(\"field\", lookback)".to_string(), detail: "rolling_mean 的别名。任意价格均线窗口推荐用它,比如 sma(\"close\", 15)。".to_string() },
ManualFunction { name: "round/floor/ceil/abs/min/max/clamp".to_string(), signature: "round(x)".to_string(), detail: "常用数值函数。".to_string() },