Clip portfolio targets before rebalance orders
This commit is contained in:
@@ -25,6 +25,17 @@ struct ExecutionFill {
|
||||
next_cursor: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TargetConstraint {
|
||||
symbol: String,
|
||||
current_qty: u32,
|
||||
min_target_qty: u32,
|
||||
max_target_qty: u32,
|
||||
provisional_target_qty: u32,
|
||||
price: f64,
|
||||
round_lot: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MatchingType {
|
||||
CurrentBarClose,
|
||||
@@ -396,9 +407,8 @@ where
|
||||
data: &DataSet,
|
||||
target_weights: &BTreeMap<String, f64>,
|
||||
) -> Result<BTreeMap<String, u32>, BacktestError> {
|
||||
let equity = self.total_equity_at(date, portfolio, data, PriceField::Open)?;
|
||||
let mut targets = BTreeMap::new();
|
||||
|
||||
let equity = self.total_equity_at(date, portfolio, data, self.execution_price_field)?;
|
||||
let mut desired_targets = BTreeMap::new();
|
||||
for (symbol, weight) in target_weights {
|
||||
let price = data
|
||||
.price(date, symbol, self.execution_price_field)
|
||||
@@ -408,13 +418,188 @@ where
|
||||
field: price_field_name(self.execution_price_field),
|
||||
})?;
|
||||
let raw_qty = ((equity * weight) / price).floor() as u32;
|
||||
let rounded_qty = self.round_buy_quantity(raw_qty, self.round_lot(data, symbol));
|
||||
targets.insert(symbol.clone(), rounded_qty);
|
||||
desired_targets.insert(
|
||||
symbol.clone(),
|
||||
self.round_buy_quantity(raw_qty, self.round_lot(data, symbol)),
|
||||
);
|
||||
}
|
||||
|
||||
let mut symbols = BTreeSet::new();
|
||||
symbols.extend(portfolio.positions().keys().cloned());
|
||||
symbols.extend(desired_targets.keys().cloned());
|
||||
|
||||
let mut constraints = Vec::new();
|
||||
let mut projected_cash = portfolio.cash();
|
||||
for symbol in symbols {
|
||||
let current_qty = portfolio
|
||||
.position(&symbol)
|
||||
.map(|pos| pos.quantity)
|
||||
.unwrap_or(0);
|
||||
let desired_qty = *desired_targets.get(&symbol).unwrap_or(&0);
|
||||
let price = data
|
||||
.price(date, &symbol, self.execution_price_field)
|
||||
.ok_or_else(|| BacktestError::MissingPrice {
|
||||
date,
|
||||
symbol: symbol.clone(),
|
||||
field: price_field_name(self.execution_price_field),
|
||||
})?;
|
||||
let round_lot = self.round_lot(data, &symbol);
|
||||
let min_target_qty = self.minimum_target_quantity(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
&symbol,
|
||||
current_qty,
|
||||
round_lot,
|
||||
);
|
||||
let max_target_qty = self.maximum_target_quantity(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
&symbol,
|
||||
current_qty,
|
||||
round_lot,
|
||||
);
|
||||
let provisional_target_qty = desired_qty.clamp(min_target_qty, max_target_qty);
|
||||
if current_qty > provisional_target_qty {
|
||||
projected_cash += self.estimated_sell_net_cash(
|
||||
price,
|
||||
current_qty.saturating_sub(provisional_target_qty),
|
||||
);
|
||||
}
|
||||
constraints.push(TargetConstraint {
|
||||
symbol,
|
||||
current_qty,
|
||||
min_target_qty,
|
||||
max_target_qty,
|
||||
provisional_target_qty,
|
||||
price,
|
||||
round_lot,
|
||||
});
|
||||
}
|
||||
|
||||
let mut targets = BTreeMap::new();
|
||||
for constraint in &constraints {
|
||||
let mut target_qty = constraint.provisional_target_qty;
|
||||
if target_qty > constraint.current_qty {
|
||||
let desired_additional = target_qty - constraint.current_qty;
|
||||
let affordable_additional = self.affordable_buy_quantity(
|
||||
projected_cash,
|
||||
None,
|
||||
constraint.price,
|
||||
desired_additional,
|
||||
constraint.round_lot,
|
||||
);
|
||||
target_qty = (constraint.current_qty + affordable_additional)
|
||||
.clamp(constraint.min_target_qty, constraint.max_target_qty);
|
||||
if target_qty > constraint.current_qty {
|
||||
projected_cash -= self.estimated_buy_cash_out(
|
||||
constraint.price,
|
||||
target_qty - constraint.current_qty,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if target_qty > 0 {
|
||||
targets.insert(constraint.symbol.clone(), target_qty);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
fn minimum_target_quantity(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
portfolio: &PortfolioState,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
current_qty: u32,
|
||||
round_lot: u32,
|
||||
) -> u32 {
|
||||
if current_qty == 0 {
|
||||
return 0;
|
||||
}
|
||||
let Some(position) = portfolio.position(symbol) else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(snapshot) = data.require_market(date, symbol) else {
|
||||
return current_qty;
|
||||
};
|
||||
let Ok(candidate) = data.require_candidate(date, symbol) else {
|
||||
return current_qty;
|
||||
};
|
||||
let rule = self.rules.can_sell(
|
||||
date,
|
||||
snapshot,
|
||||
candidate,
|
||||
position,
|
||||
self.execution_price_field,
|
||||
);
|
||||
if !rule.allowed {
|
||||
return current_qty;
|
||||
}
|
||||
let sellable = position.sellable_qty(date);
|
||||
let sell_limit = match self.market_fillable_quantity(
|
||||
snapshot,
|
||||
OrderSide::Sell,
|
||||
sellable.min(current_qty),
|
||||
round_lot,
|
||||
0,
|
||||
) {
|
||||
Ok(quantity) => quantity.min(sellable).min(current_qty),
|
||||
Err(_) => 0,
|
||||
};
|
||||
current_qty.saturating_sub(sell_limit)
|
||||
}
|
||||
|
||||
fn maximum_target_quantity(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
_portfolio: &PortfolioState,
|
||||
data: &DataSet,
|
||||
symbol: &str,
|
||||
current_qty: u32,
|
||||
round_lot: u32,
|
||||
) -> u32 {
|
||||
let Ok(snapshot) = data.require_market(date, symbol) else {
|
||||
return current_qty;
|
||||
};
|
||||
let Ok(candidate) = data.require_candidate(date, symbol) else {
|
||||
return current_qty;
|
||||
};
|
||||
let rule = self
|
||||
.rules
|
||||
.can_buy(date, snapshot, candidate, self.execution_price_field);
|
||||
if !rule.allowed {
|
||||
return current_qty;
|
||||
}
|
||||
let additional_limit =
|
||||
match self.market_fillable_quantity(snapshot, OrderSide::Buy, u32::MAX, round_lot, 0) {
|
||||
Ok(quantity) => quantity,
|
||||
Err(_) => 0,
|
||||
};
|
||||
current_qty.saturating_add(additional_limit)
|
||||
}
|
||||
|
||||
fn estimated_sell_net_cash(&self, price: f64, quantity: u32) -> f64 {
|
||||
if quantity == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let gross = price * quantity as f64;
|
||||
let cost = self.cost_model.calculate(OrderSide::Sell, gross);
|
||||
gross - cost.total()
|
||||
}
|
||||
|
||||
fn estimated_buy_cash_out(&self, price: f64, quantity: u32) -> f64 {
|
||||
if quantity == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let gross = price * quantity as f64;
|
||||
let cost = self.cost_model.calculate(OrderSide::Buy, gross);
|
||||
gross + cost.total()
|
||||
}
|
||||
|
||||
fn process_sell(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
|
||||
Reference in New Issue
Block a user