Support dividend reinvestment

This commit is contained in:
boris
2026-04-23 02:11:06 -07:00
parent 0bc224f703
commit b6ddd14d94
2 changed files with 377 additions and 3 deletions

View File

@@ -94,6 +94,7 @@ pub struct BacktestEngine<S, C, R> {
strategy: S,
broker: BrokerSimulator<C, R>,
config: BacktestConfig,
dividend_reinvestment: bool,
}
impl<S, C, R> BacktestEngine<S, C, R> {
@@ -108,8 +109,14 @@ impl<S, C, R> BacktestEngine<S, C, R> {
strategy,
broker,
config,
dividend_reinvestment: false,
}
}
pub fn with_dividend_reinvestment(mut self, enabled: bool) -> Self {
self.dividend_reinvestment = enabled;
self
}
}
impl<S, C, R> BacktestEngine<S, C, R>
@@ -633,14 +640,106 @@ where
let mut report = BrokerExecutionReport::default();
let settled = portfolio.settle_cash_receivables(date);
for receivable in settled {
let note = format!(
let mut note = format!(
"cash_receivable_settled {} ex_date={} payable_date={} cash={:.2}",
receivable.symbol, receivable.ex_date, receivable.payable_date, receivable.amount
);
let cash_before = portfolio.cash() - receivable.amount;
if self.dividend_reinvestment
&& receivable.reason.starts_with("cash_dividend")
&& receivable.amount > 0.0
{
let reinvest_price = portfolio
.position(&receivable.symbol)
.map(|position| position.last_price)
.filter(|price| price.is_finite() && *price > 0.0)
.or_else(|| {
self.data
.calendar()
.previous_day(date)
.and_then(|prev_date| {
self.data.price_on_or_before(
prev_date,
&receivable.symbol,
PriceField::Close,
)
})
});
let round_lot = self
.data
.instrument(&receivable.symbol)
.map(|instrument| instrument.round_lot.max(1))
.unwrap_or(100);
if let Some(price) = reinvest_price {
let raw_quantity = (receivable.amount / price).floor() as u32;
let reinvest_quantity = (raw_quantity / round_lot) * round_lot;
if reinvest_quantity > 0 {
let reinvest_cash = reinvest_quantity as f64 * price;
let residual_cash = receivable.amount - reinvest_cash;
portfolio.apply_cash_delta(-reinvest_cash);
portfolio.position_mut(&receivable.symbol).buy(
date,
reinvest_quantity,
price,
);
note = format!(
"cash_receivable_reinvested {} ex_date={} payable_date={} cash={:.2} reinvest_qty={} reinvest_price={:.4} residual_cash={:.2}",
receivable.symbol,
receivable.ex_date,
receivable.payable_date,
receivable.amount,
reinvest_quantity,
price,
residual_cash
);
report.fill_events.push(FillEvent {
date,
order_id: None,
symbol: receivable.symbol.clone(),
side: OrderSide::Buy,
quantity: reinvest_quantity,
price,
gross_amount: reinvest_cash,
commission: 0.0,
stamp_tax: 0.0,
net_cash_flow: -reinvest_cash,
reason: "dividend_reinvestment".to_string(),
});
report.position_events.push(PositionEvent {
date,
symbol: receivable.symbol.clone(),
delta_quantity: reinvest_quantity as i32,
quantity_after: portfolio
.position(&receivable.symbol)
.map(|position| position.quantity)
.unwrap_or(0),
average_cost: portfolio
.position(&receivable.symbol)
.map(|position| position.average_cost)
.unwrap_or(0.0),
realized_pnl_delta: 0.0,
reason: "dividend_reinvestment".to_string(),
});
report.process_events.push(ProcessEvent {
date,
kind: ProcessEventKind::Trade,
order_id: None,
symbol: Some(receivable.symbol.clone()),
side: Some(OrderSide::Buy),
detail: format!(
"dividend_reinvestment quantity={} price={}",
reinvest_quantity, price
),
});
}
}
}
notes.push(note.clone());
report.account_events.push(AccountEvent {
date,
cash_before: portfolio.cash() - receivable.amount,
cash_before,
cash_after: portfolio.cash(),
total_equity: portfolio.total_equity(),
note,