Align order costs and rebalance priority with rqalpha
This commit is contained in:
@@ -29,9 +29,11 @@ struct ExecutionFill {
|
|||||||
struct TargetConstraint {
|
struct TargetConstraint {
|
||||||
symbol: String,
|
symbol: String,
|
||||||
current_qty: u32,
|
current_qty: u32,
|
||||||
|
desired_qty: u32,
|
||||||
min_target_qty: u32,
|
min_target_qty: u32,
|
||||||
max_target_qty: u32,
|
max_target_qty: u32,
|
||||||
provisional_target_qty: u32,
|
provisional_target_qty: u32,
|
||||||
|
target_weight: f64,
|
||||||
price: f64,
|
price: f64,
|
||||||
minimum_order_quantity: u32,
|
minimum_order_quantity: u32,
|
||||||
order_step_size: u32,
|
order_step_size: u32,
|
||||||
@@ -263,6 +265,8 @@ where
|
|||||||
let mut intraday_turnover = BTreeMap::<String, u32>::new();
|
let mut intraday_turnover = BTreeMap::<String, u32>::new();
|
||||||
let mut execution_cursors = BTreeMap::<String, NaiveDateTime>::new();
|
let mut execution_cursors = BTreeMap::<String, NaiveDateTime>::new();
|
||||||
let mut global_execution_cursor = None::<NaiveDateTime>;
|
let mut global_execution_cursor = None::<NaiveDateTime>;
|
||||||
|
let mut commission_state = BTreeMap::<u64, f64>::new();
|
||||||
|
let mut next_order_id = 1_u64;
|
||||||
if !decision.order_intents.is_empty() {
|
if !decision.order_intents.is_empty() {
|
||||||
for intent in &decision.order_intents {
|
for intent in &decision.order_intents {
|
||||||
self.process_order_intent(
|
self.process_order_intent(
|
||||||
@@ -273,6 +277,8 @@ where
|
|||||||
&mut intraday_turnover,
|
&mut intraday_turnover,
|
||||||
&mut execution_cursors,
|
&mut execution_cursors,
|
||||||
&mut global_execution_cursor,
|
&mut global_execution_cursor,
|
||||||
|
&mut commission_state,
|
||||||
|
&mut next_order_id,
|
||||||
&mut report,
|
&mut report,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
@@ -316,10 +322,12 @@ where
|
|||||||
data,
|
data,
|
||||||
&symbol,
|
&symbol,
|
||||||
requested_qty,
|
requested_qty,
|
||||||
|
Self::reserve_order_id(&mut next_order_id),
|
||||||
sell_reason(decision, &symbol),
|
sell_reason(decision, &symbol),
|
||||||
&mut intraday_turnover,
|
&mut intraday_turnover,
|
||||||
&mut execution_cursors,
|
&mut execution_cursors,
|
||||||
&mut global_execution_cursor,
|
&mut global_execution_cursor,
|
||||||
|
&mut commission_state,
|
||||||
&mut report,
|
&mut report,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
@@ -339,10 +347,12 @@ where
|
|||||||
data,
|
data,
|
||||||
&symbol,
|
&symbol,
|
||||||
requested_qty,
|
requested_qty,
|
||||||
|
Self::reserve_order_id(&mut next_order_id),
|
||||||
"rebalance_buy",
|
"rebalance_buy",
|
||||||
&mut intraday_turnover,
|
&mut intraday_turnover,
|
||||||
&mut execution_cursors,
|
&mut execution_cursors,
|
||||||
&mut global_execution_cursor,
|
&mut global_execution_cursor,
|
||||||
|
&mut commission_state,
|
||||||
None,
|
None,
|
||||||
&mut report,
|
&mut report,
|
||||||
)?;
|
)?;
|
||||||
@@ -363,6 +373,8 @@ where
|
|||||||
intraday_turnover: &mut BTreeMap<String, u32>,
|
intraday_turnover: &mut BTreeMap<String, u32>,
|
||||||
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
||||||
global_execution_cursor: &mut Option<NaiveDateTime>,
|
global_execution_cursor: &mut Option<NaiveDateTime>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
|
next_order_id: &mut u64,
|
||||||
report: &mut BrokerExecutionReport,
|
report: &mut BrokerExecutionReport,
|
||||||
) -> Result<(), BacktestError> {
|
) -> Result<(), BacktestError> {
|
||||||
match intent {
|
match intent {
|
||||||
@@ -376,10 +388,12 @@ where
|
|||||||
data,
|
data,
|
||||||
symbol,
|
symbol,
|
||||||
*target_value,
|
*target_value,
|
||||||
|
next_order_id,
|
||||||
reason,
|
reason,
|
||||||
intraday_turnover,
|
intraday_turnover,
|
||||||
execution_cursors,
|
execution_cursors,
|
||||||
global_execution_cursor,
|
global_execution_cursor,
|
||||||
|
commission_state,
|
||||||
report,
|
report,
|
||||||
),
|
),
|
||||||
OrderIntent::Value {
|
OrderIntent::Value {
|
||||||
@@ -392,15 +406,23 @@ where
|
|||||||
data,
|
data,
|
||||||
symbol,
|
symbol,
|
||||||
*value,
|
*value,
|
||||||
|
next_order_id,
|
||||||
reason,
|
reason,
|
||||||
intraday_turnover,
|
intraday_turnover,
|
||||||
execution_cursors,
|
execution_cursors,
|
||||||
global_execution_cursor,
|
global_execution_cursor,
|
||||||
|
commission_state,
|
||||||
report,
|
report,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn reserve_order_id(next_order_id: &mut u64) -> u64 {
|
||||||
|
let order_id = *next_order_id;
|
||||||
|
*next_order_id = next_order_id.saturating_add(1);
|
||||||
|
order_id
|
||||||
|
}
|
||||||
|
|
||||||
fn target_quantities(
|
fn target_quantities(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
@@ -409,6 +431,7 @@ where
|
|||||||
target_weights: &BTreeMap<String, f64>,
|
target_weights: &BTreeMap<String, f64>,
|
||||||
) -> Result<BTreeMap<String, u32>, BacktestError> {
|
) -> Result<BTreeMap<String, u32>, BacktestError> {
|
||||||
let equity = self.total_equity_at(date, portfolio, data, self.execution_price_field)?;
|
let equity = self.total_equity_at(date, portfolio, data, self.execution_price_field)?;
|
||||||
|
let target_weight_sum = target_weights.values().copied().sum::<f64>();
|
||||||
let mut desired_targets = BTreeMap::new();
|
let mut desired_targets = BTreeMap::new();
|
||||||
for (symbol, weight) in target_weights {
|
for (symbol, weight) in target_weights {
|
||||||
let price = data
|
let price = data
|
||||||
@@ -477,22 +500,66 @@ where
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
constraints.push(TargetConstraint {
|
constraints.push(TargetConstraint {
|
||||||
symbol,
|
symbol: symbol.clone(),
|
||||||
current_qty,
|
current_qty,
|
||||||
|
desired_qty,
|
||||||
min_target_qty,
|
min_target_qty,
|
||||||
max_target_qty,
|
max_target_qty,
|
||||||
provisional_target_qty,
|
provisional_target_qty,
|
||||||
|
target_weight: *target_weights.get(&symbol).unwrap_or(&0.0),
|
||||||
price,
|
price,
|
||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let safety = if target_weight_sum > 0.95 { 1.2 } else { 1.0 };
|
||||||
let mut targets = BTreeMap::new();
|
let mut targets = BTreeMap::new();
|
||||||
for constraint in &constraints {
|
for constraint in &constraints {
|
||||||
let mut target_qty = constraint.provisional_target_qty;
|
if constraint.provisional_target_qty > constraint.current_qty {
|
||||||
if target_qty > constraint.current_qty {
|
continue;
|
||||||
let desired_additional = target_qty - constraint.current_qty;
|
}
|
||||||
|
if constraint.provisional_target_qty > 0 {
|
||||||
|
targets.insert(constraint.symbol.clone(), constraint.provisional_target_qty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut buy_constraints = constraints
|
||||||
|
.iter()
|
||||||
|
.filter(|constraint| constraint.provisional_target_qty > constraint.current_qty)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
buy_constraints.sort_by(|lhs, rhs| {
|
||||||
|
rhs.target_weight
|
||||||
|
.partial_cmp(&lhs.target_weight)
|
||||||
|
.unwrap_or(std::cmp::Ordering::Equal)
|
||||||
|
.then_with(|| {
|
||||||
|
let lhs_gap = (lhs.provisional_target_qty.saturating_sub(lhs.current_qty))
|
||||||
|
as f64
|
||||||
|
* lhs.price;
|
||||||
|
let rhs_gap = (rhs.provisional_target_qty.saturating_sub(rhs.current_qty))
|
||||||
|
as f64
|
||||||
|
* rhs.price;
|
||||||
|
rhs_gap
|
||||||
|
.partial_cmp(&lhs_gap)
|
||||||
|
.unwrap_or(std::cmp::Ordering::Equal)
|
||||||
|
})
|
||||||
|
.then_with(|| lhs.symbol.cmp(&rhs.symbol))
|
||||||
|
});
|
||||||
|
|
||||||
|
for constraint in buy_constraints {
|
||||||
|
let mut target_qty = if safety > 1.0 {
|
||||||
|
let scaled_desired_qty = ((constraint.desired_qty as f64) * safety).floor() as u32;
|
||||||
|
self.round_buy_quantity(
|
||||||
|
scaled_desired_qty,
|
||||||
|
constraint.minimum_order_quantity,
|
||||||
|
constraint.order_step_size,
|
||||||
|
)
|
||||||
|
.clamp(constraint.current_qty, constraint.max_target_qty)
|
||||||
|
} else {
|
||||||
|
constraint.provisional_target_qty
|
||||||
|
};
|
||||||
|
target_qty = target_qty.max(constraint.current_qty);
|
||||||
|
let desired_additional = target_qty.saturating_sub(constraint.current_qty);
|
||||||
let affordable_additional = self.affordable_buy_quantity(
|
let affordable_additional = self.affordable_buy_quantity(
|
||||||
date,
|
date,
|
||||||
projected_cash,
|
projected_cash,
|
||||||
@@ -511,7 +578,6 @@ where
|
|||||||
target_qty - constraint.current_qty,
|
target_qty - constraint.current_qty,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if target_qty > 0 {
|
if target_qty > 0 {
|
||||||
targets.insert(constraint.symbol.clone(), target_qty);
|
targets.insert(constraint.symbol.clone(), target_qty);
|
||||||
@@ -631,10 +697,12 @@ where
|
|||||||
data: &DataSet,
|
data: &DataSet,
|
||||||
symbol: &str,
|
symbol: &str,
|
||||||
requested_qty: u32,
|
requested_qty: u32,
|
||||||
|
order_id: u64,
|
||||||
reason: &str,
|
reason: &str,
|
||||||
intraday_turnover: &mut BTreeMap<String, u32>,
|
intraday_turnover: &mut BTreeMap<String, u32>,
|
||||||
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
||||||
global_execution_cursor: &mut Option<NaiveDateTime>,
|
global_execution_cursor: &mut Option<NaiveDateTime>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
report: &mut BrokerExecutionReport,
|
report: &mut BrokerExecutionReport,
|
||||||
) -> Result<(), BacktestError> {
|
) -> Result<(), BacktestError> {
|
||||||
let snapshot = data.require_market(date, symbol)?;
|
let snapshot = data.require_market(date, symbol)?;
|
||||||
@@ -659,6 +727,7 @@ where
|
|||||||
};
|
};
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -684,6 +753,7 @@ where
|
|||||||
Err(limit_reason) => {
|
Err(limit_reason) => {
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -697,6 +767,7 @@ where
|
|||||||
if filled_qty == 0 {
|
if filled_qty == 0 {
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -734,9 +805,13 @@ where
|
|||||||
(filled_qty, self.sell_price(snapshot))
|
(filled_qty, self.sell_price(snapshot))
|
||||||
};
|
};
|
||||||
let gross_amount = execution_price * filled_qty as f64;
|
let gross_amount = execution_price * filled_qty as f64;
|
||||||
let cost = self
|
let cost = self.cost_model.calculate_with_order_state(
|
||||||
.cost_model
|
date,
|
||||||
.calculate(date, OrderSide::Sell, gross_amount);
|
OrderSide::Sell,
|
||||||
|
gross_amount,
|
||||||
|
Some(order_id),
|
||||||
|
commission_state,
|
||||||
|
);
|
||||||
let net_cash = gross_amount - cost.total();
|
let net_cash = gross_amount - cost.total();
|
||||||
|
|
||||||
let realized_pnl = portfolio
|
let realized_pnl = portfolio
|
||||||
@@ -755,6 +830,7 @@ where
|
|||||||
|
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -764,6 +840,7 @@ where
|
|||||||
});
|
});
|
||||||
report.fill_events.push(FillEvent {
|
report.fill_events.push(FillEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
quantity: filled_qty,
|
quantity: filled_qty,
|
||||||
@@ -806,10 +883,12 @@ where
|
|||||||
data: &DataSet,
|
data: &DataSet,
|
||||||
symbol: &str,
|
symbol: &str,
|
||||||
target_value: f64,
|
target_value: f64,
|
||||||
|
next_order_id: &mut u64,
|
||||||
reason: &str,
|
reason: &str,
|
||||||
intraday_turnover: &mut BTreeMap<String, u32>,
|
intraday_turnover: &mut BTreeMap<String, u32>,
|
||||||
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
||||||
global_execution_cursor: &mut Option<NaiveDateTime>,
|
global_execution_cursor: &mut Option<NaiveDateTime>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
report: &mut BrokerExecutionReport,
|
report: &mut BrokerExecutionReport,
|
||||||
) -> Result<(), BacktestError> {
|
) -> Result<(), BacktestError> {
|
||||||
let price = data
|
let price = data
|
||||||
@@ -838,10 +917,12 @@ where
|
|||||||
data,
|
data,
|
||||||
symbol,
|
symbol,
|
||||||
current_qty - target_qty,
|
current_qty - target_qty,
|
||||||
|
Self::reserve_order_id(next_order_id),
|
||||||
reason,
|
reason,
|
||||||
intraday_turnover,
|
intraday_turnover,
|
||||||
execution_cursors,
|
execution_cursors,
|
||||||
global_execution_cursor,
|
global_execution_cursor,
|
||||||
|
commission_state,
|
||||||
report,
|
report,
|
||||||
)?;
|
)?;
|
||||||
} else if target_qty > current_qty {
|
} else if target_qty > current_qty {
|
||||||
@@ -851,16 +932,19 @@ where
|
|||||||
data,
|
data,
|
||||||
symbol,
|
symbol,
|
||||||
target_qty - current_qty,
|
target_qty - current_qty,
|
||||||
|
Self::reserve_order_id(next_order_id),
|
||||||
reason,
|
reason,
|
||||||
intraday_turnover,
|
intraday_turnover,
|
||||||
execution_cursors,
|
execution_cursors,
|
||||||
global_execution_cursor,
|
global_execution_cursor,
|
||||||
|
commission_state,
|
||||||
None,
|
None,
|
||||||
report,
|
report,
|
||||||
)?;
|
)?;
|
||||||
} else if (current_value - target_value).abs() <= f64::EPSILON {
|
} else if (current_value - target_value).abs() <= f64::EPSILON {
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: None,
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: if current_qty > 0 {
|
side: if current_qty > 0 {
|
||||||
OrderSide::Sell
|
OrderSide::Sell
|
||||||
@@ -884,10 +968,12 @@ where
|
|||||||
data: &DataSet,
|
data: &DataSet,
|
||||||
symbol: &str,
|
symbol: &str,
|
||||||
value: f64,
|
value: f64,
|
||||||
|
next_order_id: &mut u64,
|
||||||
reason: &str,
|
reason: &str,
|
||||||
intraday_turnover: &mut BTreeMap<String, u32>,
|
intraday_turnover: &mut BTreeMap<String, u32>,
|
||||||
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
||||||
global_execution_cursor: &mut Option<NaiveDateTime>,
|
global_execution_cursor: &mut Option<NaiveDateTime>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
report: &mut BrokerExecutionReport,
|
report: &mut BrokerExecutionReport,
|
||||||
) -> Result<(), BacktestError> {
|
) -> Result<(), BacktestError> {
|
||||||
if value.abs() <= f64::EPSILON {
|
if value.abs() <= f64::EPSILON {
|
||||||
@@ -928,10 +1014,12 @@ where
|
|||||||
data,
|
data,
|
||||||
symbol,
|
symbol,
|
||||||
requested_qty,
|
requested_qty,
|
||||||
|
Self::reserve_order_id(next_order_id),
|
||||||
reason,
|
reason,
|
||||||
intraday_turnover,
|
intraday_turnover,
|
||||||
execution_cursors,
|
execution_cursors,
|
||||||
global_execution_cursor,
|
global_execution_cursor,
|
||||||
|
commission_state,
|
||||||
Some(value.abs()),
|
Some(value.abs()),
|
||||||
report,
|
report,
|
||||||
)
|
)
|
||||||
@@ -948,10 +1036,12 @@ where
|
|||||||
data,
|
data,
|
||||||
symbol,
|
symbol,
|
||||||
requested_qty,
|
requested_qty,
|
||||||
|
Self::reserve_order_id(next_order_id),
|
||||||
reason,
|
reason,
|
||||||
intraday_turnover,
|
intraday_turnover,
|
||||||
execution_cursors,
|
execution_cursors,
|
||||||
global_execution_cursor,
|
global_execution_cursor,
|
||||||
|
commission_state,
|
||||||
report,
|
report,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -980,10 +1070,12 @@ where
|
|||||||
data: &DataSet,
|
data: &DataSet,
|
||||||
symbol: &str,
|
symbol: &str,
|
||||||
requested_qty: u32,
|
requested_qty: u32,
|
||||||
|
order_id: u64,
|
||||||
reason: &str,
|
reason: &str,
|
||||||
intraday_turnover: &mut BTreeMap<String, u32>,
|
intraday_turnover: &mut BTreeMap<String, u32>,
|
||||||
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
|
||||||
global_execution_cursor: &mut Option<NaiveDateTime>,
|
global_execution_cursor: &mut Option<NaiveDateTime>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
value_budget: Option<f64>,
|
value_budget: Option<f64>,
|
||||||
report: &mut BrokerExecutionReport,
|
report: &mut BrokerExecutionReport,
|
||||||
) -> Result<(), BacktestError> {
|
) -> Result<(), BacktestError> {
|
||||||
@@ -996,6 +1088,7 @@ where
|
|||||||
if !rule.allowed {
|
if !rule.allowed {
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Buy,
|
side: OrderSide::Buy,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -1020,6 +1113,7 @@ where
|
|||||||
Err(limit_reason) => {
|
Err(limit_reason) => {
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Buy,
|
side: OrderSide::Buy,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -1069,6 +1163,7 @@ where
|
|||||||
if filled_qty == 0 {
|
if filled_qty == 0 {
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Buy,
|
side: OrderSide::Buy,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -1081,9 +1176,13 @@ where
|
|||||||
|
|
||||||
let cash_before = portfolio.cash();
|
let cash_before = portfolio.cash();
|
||||||
let gross_amount = execution_price * filled_qty as f64;
|
let gross_amount = execution_price * filled_qty as f64;
|
||||||
let cost = self
|
let cost = self.cost_model.calculate_with_order_state(
|
||||||
.cost_model
|
date,
|
||||||
.calculate(date, OrderSide::Buy, gross_amount);
|
OrderSide::Buy,
|
||||||
|
gross_amount,
|
||||||
|
Some(order_id),
|
||||||
|
commission_state,
|
||||||
|
);
|
||||||
let cash_out = gross_amount + cost.total();
|
let cash_out = gross_amount + cost.total();
|
||||||
|
|
||||||
portfolio.apply_cash_delta(-cash_out);
|
portfolio.apply_cash_delta(-cash_out);
|
||||||
@@ -1100,6 +1199,7 @@ where
|
|||||||
|
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Buy,
|
side: OrderSide::Buy,
|
||||||
requested_quantity: requested_qty,
|
requested_quantity: requested_qty,
|
||||||
@@ -1109,6 +1209,7 @@ where
|
|||||||
});
|
});
|
||||||
report.fill_events.push(FillEvent {
|
report.fill_events.push(FillEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: Some(order_id),
|
||||||
symbol: symbol.to_string(),
|
symbol: symbol.to_string(),
|
||||||
side: OrderSide::Buy,
|
side: OrderSide::Buy,
|
||||||
quantity: filled_qty,
|
quantity: filled_qty,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
|
|
||||||
use crate::events::OrderSide;
|
use crate::events::OrderSide;
|
||||||
@@ -18,6 +20,17 @@ impl TradingCost {
|
|||||||
|
|
||||||
pub trait CostModel {
|
pub trait CostModel {
|
||||||
fn calculate(&self, date: NaiveDate, side: OrderSide, gross_amount: f64) -> TradingCost;
|
fn calculate(&self, date: NaiveDate, side: OrderSide, gross_amount: f64) -> TradingCost;
|
||||||
|
|
||||||
|
fn calculate_with_order_state(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
side: OrderSide,
|
||||||
|
gross_amount: f64,
|
||||||
|
_order_id: Option<u64>,
|
||||||
|
_commission_state: &mut BTreeMap<u64, f64>,
|
||||||
|
) -> TradingCost {
|
||||||
|
self.calculate(date, side, gross_amount)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
@@ -67,6 +80,43 @@ impl ChinaAShareCostModel {
|
|||||||
}
|
}
|
||||||
gross_amount * self.stamp_tax_rate_for(date)
|
gross_amount * self.stamp_tax_rate_for(date)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn commission_for_order_fill(
|
||||||
|
&self,
|
||||||
|
gross_amount: f64,
|
||||||
|
order_id: Option<u64>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
|
) -> f64 {
|
||||||
|
if gross_amount <= 0.0 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let raw_commission = gross_amount * self.commission_rate;
|
||||||
|
let Some(order_id) = order_id else {
|
||||||
|
return raw_commission.max(self.minimum_commission);
|
||||||
|
};
|
||||||
|
|
||||||
|
let remaining_minimum = commission_state
|
||||||
|
.entry(order_id)
|
||||||
|
.or_insert(self.minimum_commission);
|
||||||
|
if raw_commission > *remaining_minimum {
|
||||||
|
let charged = if (*remaining_minimum - self.minimum_commission).abs() < 1e-12 {
|
||||||
|
raw_commission
|
||||||
|
} else {
|
||||||
|
raw_commission - *remaining_minimum
|
||||||
|
};
|
||||||
|
*remaining_minimum = 0.0;
|
||||||
|
charged
|
||||||
|
} else {
|
||||||
|
let charged = if (*remaining_minimum - self.minimum_commission).abs() < 1e-12 {
|
||||||
|
self.minimum_commission
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
*remaining_minimum -= raw_commission;
|
||||||
|
charged
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CostModel for ChinaAShareCostModel {
|
impl CostModel for ChinaAShareCostModel {
|
||||||
@@ -86,4 +136,28 @@ impl CostModel for ChinaAShareCostModel {
|
|||||||
stamp_tax,
|
stamp_tax,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn calculate_with_order_state(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
side: OrderSide,
|
||||||
|
gross_amount: f64,
|
||||||
|
order_id: Option<u64>,
|
||||||
|
commission_state: &mut BTreeMap<u64, f64>,
|
||||||
|
) -> TradingCost {
|
||||||
|
if gross_amount <= 0.0 {
|
||||||
|
return TradingCost {
|
||||||
|
commission: 0.0,
|
||||||
|
stamp_tax: 0.0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let commission = self.commission_for_order_fill(gross_amount, order_id, commission_state);
|
||||||
|
let stamp_tax = self.stamp_tax_for(date, side, gross_amount);
|
||||||
|
|
||||||
|
TradingCost {
|
||||||
|
commission,
|
||||||
|
stamp_tax,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use crate::broker::{BrokerExecutionReport, BrokerSimulator};
|
|||||||
use crate::cost::CostModel;
|
use crate::cost::CostModel;
|
||||||
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, PriceField};
|
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, PriceField};
|
||||||
use crate::events::{AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent};
|
use crate::events::{AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent};
|
||||||
use crate::metrics::{compute_backtest_metrics, BacktestMetrics};
|
use crate::metrics::{BacktestMetrics, compute_backtest_metrics};
|
||||||
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
|
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
|
||||||
use crate::rules::EquityRuleHooks;
|
use crate::rules::EquityRuleHooks;
|
||||||
use crate::strategy::{Strategy, StrategyContext};
|
use crate::strategy::{Strategy, StrategyContext};
|
||||||
@@ -574,6 +574,7 @@ where
|
|||||||
notes.push(reason.clone());
|
notes.push(reason.clone());
|
||||||
report.order_events.push(OrderEvent {
|
report.order_events.push(OrderEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: None,
|
||||||
symbol: symbol.clone(),
|
symbol: symbol.clone(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
requested_quantity: quantity,
|
requested_quantity: quantity,
|
||||||
@@ -583,6 +584,7 @@ where
|
|||||||
});
|
});
|
||||||
report.fill_events.push(FillEvent {
|
report.fill_events.push(FillEvent {
|
||||||
date,
|
date,
|
||||||
|
order_id: None,
|
||||||
symbol: symbol.clone(),
|
symbol: symbol.clone(),
|
||||||
side: OrderSide::Sell,
|
side: OrderSide::Sell,
|
||||||
quantity,
|
quantity,
|
||||||
|
|||||||
@@ -41,6 +41,8 @@ pub enum OrderStatus {
|
|||||||
pub struct OrderEvent {
|
pub struct OrderEvent {
|
||||||
#[serde(with = "date_format")]
|
#[serde(with = "date_format")]
|
||||||
pub date: NaiveDate,
|
pub date: NaiveDate,
|
||||||
|
#[serde(default)]
|
||||||
|
pub order_id: Option<u64>,
|
||||||
pub symbol: String,
|
pub symbol: String,
|
||||||
pub side: OrderSide,
|
pub side: OrderSide,
|
||||||
pub requested_quantity: u32,
|
pub requested_quantity: u32,
|
||||||
@@ -53,6 +55,8 @@ pub struct OrderEvent {
|
|||||||
pub struct FillEvent {
|
pub struct FillEvent {
|
||||||
#[serde(with = "date_format")]
|
#[serde(with = "date_format")]
|
||||||
pub date: NaiveDate,
|
pub date: NaiveDate,
|
||||||
|
#[serde(default)]
|
||||||
|
pub order_id: Option<u64>,
|
||||||
pub symbol: String,
|
pub symbol: String,
|
||||||
pub side: OrderSide,
|
pub side: OrderSide,
|
||||||
pub quantity: u32,
|
pub quantity: u32,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
use fidc_core::cost::CostModel;
|
use fidc_core::cost::CostModel;
|
||||||
use fidc_core::rules::EquityRuleHooks;
|
use fidc_core::rules::EquityRuleHooks;
|
||||||
@@ -74,6 +76,46 @@ fn china_cost_model_switches_stamp_tax_rate_after_2023_08_28() {
|
|||||||
assert!((after.stamp_tax - 50.0).abs() < 1e-9);
|
assert!((after.stamp_tax - 50.0).abs() < 1e-9);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn china_cost_model_tracks_minimum_commission_per_order_id() {
|
||||||
|
let model = ChinaAShareCostModel::default();
|
||||||
|
let mut commission_state = BTreeMap::new();
|
||||||
|
|
||||||
|
let first = model.calculate_with_order_state(
|
||||||
|
d(2024, 1, 3),
|
||||||
|
OrderSide::Buy,
|
||||||
|
1_000.0,
|
||||||
|
Some(7),
|
||||||
|
&mut commission_state,
|
||||||
|
);
|
||||||
|
let second = model.calculate_with_order_state(
|
||||||
|
d(2024, 1, 3),
|
||||||
|
OrderSide::Buy,
|
||||||
|
1_000.0,
|
||||||
|
Some(7),
|
||||||
|
&mut commission_state,
|
||||||
|
);
|
||||||
|
let third = model.calculate_with_order_state(
|
||||||
|
d(2024, 1, 3),
|
||||||
|
OrderSide::Buy,
|
||||||
|
20_000.0,
|
||||||
|
Some(7),
|
||||||
|
&mut commission_state,
|
||||||
|
);
|
||||||
|
let another_order = model.calculate_with_order_state(
|
||||||
|
d(2024, 1, 3),
|
||||||
|
OrderSide::Buy,
|
||||||
|
1_000.0,
|
||||||
|
Some(8),
|
||||||
|
&mut commission_state,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!((first.commission - 5.0).abs() < 1e-9);
|
||||||
|
assert!(second.commission.abs() < 1e-9);
|
||||||
|
assert!((third.commission - 1.6).abs() < 1e-9);
|
||||||
|
assert!((another_order.commission - 5.0).abs() < 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn china_rule_hooks_block_same_day_sell_under_t_plus_one() {
|
fn china_rule_hooks_block_same_day_sell_under_t_plus_one() {
|
||||||
let hooks = ChinaEquityRuleHooks;
|
let hooks = ChinaEquityRuleHooks;
|
||||||
@@ -107,11 +149,13 @@ fn china_rule_hooks_block_buy_at_limit_up_and_sell_at_limit_down() {
|
|||||||
PriceField::Open,
|
PriceField::Open,
|
||||||
);
|
);
|
||||||
assert!(!buy_check.allowed);
|
assert!(!buy_check.allowed);
|
||||||
assert!(buy_check
|
assert!(
|
||||||
|
buy_check
|
||||||
.reason
|
.reason
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.contains("upper limit"));
|
.contains("upper limit")
|
||||||
|
);
|
||||||
|
|
||||||
let sell_check = hooks.can_sell(
|
let sell_check = hooks.can_sell(
|
||||||
d(2024, 1, 3),
|
d(2024, 1, 3),
|
||||||
@@ -121,11 +165,13 @@ fn china_rule_hooks_block_buy_at_limit_up_and_sell_at_limit_down() {
|
|||||||
PriceField::Open,
|
PriceField::Open,
|
||||||
);
|
);
|
||||||
assert!(!sell_check.allowed);
|
assert!(!sell_check.allowed);
|
||||||
assert!(sell_check
|
assert!(
|
||||||
|
sell_check
|
||||||
.reason
|
.reason
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.contains("lower limit"));
|
.contains("lower limit")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -477,6 +477,179 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rebalance_optimizer_prioritizes_higher_target_weight_when_cash_is_tight() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
vec![
|
||||||
|
Instrument {
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
name: "LowerWeight".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
},
|
||||||
|
Instrument {
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
name: "HigherWeight".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
timestamp: Some("2024-01-10 10:18:00".to_string()),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.1,
|
||||||
|
low: 9.9,
|
||||||
|
close: 10.0,
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 100_000,
|
||||||
|
tick_volume: 100_000,
|
||||||
|
bid1_volume: 80_000,
|
||||||
|
ask1_volume: 80_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 11.0,
|
||||||
|
lower_limit: 9.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
},
|
||||||
|
DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
timestamp: Some("2024-01-10 10:18:00".to_string()),
|
||||||
|
day_open: 10.0,
|
||||||
|
open: 10.0,
|
||||||
|
high: 10.1,
|
||||||
|
low: 9.9,
|
||||||
|
close: 10.0,
|
||||||
|
last_price: 10.0,
|
||||||
|
bid1: 9.99,
|
||||||
|
ask1: 10.01,
|
||||||
|
prev_close: 10.0,
|
||||||
|
volume: 100_000,
|
||||||
|
tick_volume: 100_000,
|
||||||
|
bid1_volume: 80_000,
|
||||||
|
ask1_volume: 80_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: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: "000002.SZ".to_string(),
|
||||||
|
market_cap_bn: 60.0,
|
||||||
|
free_float_cap_bn: 50.0,
|
||||||
|
pe_ttm: 18.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: "000002.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,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(10_000.0);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Open,
|
||||||
|
);
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: true,
|
||||||
|
target_weights: BTreeMap::from([
|
||||||
|
("000001.SZ".to_string(), 0.2),
|
||||||
|
("000002.SZ".to_string(), 0.8),
|
||||||
|
]),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: Vec::new(),
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
portfolio
|
||||||
|
.position("000002.SZ")
|
||||||
|
.map(|position| position.quantity)
|
||||||
|
.unwrap_or(0),
|
||||||
|
900
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
portfolio.position("000001.SZ").is_none(),
|
||||||
|
"higher target weight should consume the limited rebalance cash first"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
report
|
||||||
|
.order_events
|
||||||
|
.iter()
|
||||||
|
.any(|event| event.symbol == "000002.SZ" && event.side == fidc_core::OrderSide::Buy)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn broker_uses_board_specific_min_quantity_and_step_size_for_buy_sizing() {
|
fn broker_uses_board_specific_min_quantity_and_step_size_for_buy_sizing() {
|
||||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user