Support successor conversions for delisted holdings
This commit is contained in:
@@ -231,6 +231,12 @@ pub struct CorporateAction {
|
||||
pub issue_price: f64,
|
||||
pub reform: bool,
|
||||
pub adjust_factor: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub successor_symbol: Option<String>,
|
||||
#[serde(default)]
|
||||
pub successor_ratio: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub successor_cash: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -284,6 +290,26 @@ impl CorporateAction {
|
||||
|| (self.split_ratio() - 1.0).abs() > f64::EPSILON
|
||||
|| self.issue_quantity.abs() > f64::EPSILON
|
||||
|| self.reform
|
||||
|| self.has_successor_conversion()
|
||||
}
|
||||
|
||||
pub fn has_successor_conversion(&self) -> bool {
|
||||
self.successor_symbol
|
||||
.as_ref()
|
||||
.is_some_and(|symbol| !symbol.trim().is_empty())
|
||||
&& self.successor_ratio_value() > 0.0
|
||||
}
|
||||
|
||||
pub fn successor_ratio_value(&self) -> f64 {
|
||||
self.successor_ratio
|
||||
.filter(|ratio| ratio.is_finite() && *ratio > 0.0)
|
||||
.unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn successor_cash_value(&self) -> f64 {
|
||||
self.successor_cash
|
||||
.filter(|cash| cash.is_finite())
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,7 +355,10 @@ impl SymbolPriceSeries {
|
||||
let closes = sorted.iter().map(|row| row.close).collect::<Vec<_>>();
|
||||
let prev_closes = sorted.iter().map(|row| row.prev_close).collect::<Vec<_>>();
|
||||
let last_prices = sorted.iter().map(|row| row.last_price).collect::<Vec<_>>();
|
||||
let volumes = sorted.iter().map(|row| row.volume as f64).collect::<Vec<_>>();
|
||||
let volumes = sorted
|
||||
.iter()
|
||||
.map(|row| row.volume as f64)
|
||||
.collect::<Vec<_>>();
|
||||
let open_prefix = prefix_sums(&opens);
|
||||
let close_prefix = prefix_sums(&closes);
|
||||
let prev_close_prefix = prefix_sums(&prev_closes);
|
||||
@@ -513,7 +542,12 @@ impl BenchmarkPriceSeries {
|
||||
self.moving_average_for(date, lookback, PriceField::Close)
|
||||
}
|
||||
|
||||
fn moving_average_for(&self, date: NaiveDate, lookback: usize, field: PriceField) -> Option<f64> {
|
||||
fn moving_average_for(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
lookback: usize,
|
||||
field: PriceField,
|
||||
) -> Option<f64> {
|
||||
if lookback == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -875,12 +909,7 @@ impl DataSet {
|
||||
.and_then(|series| series.decision_volume_moving_average(date, lookback))
|
||||
}
|
||||
|
||||
pub fn factor_numeric_value(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
symbol: &str,
|
||||
field: &str,
|
||||
) -> Option<f64> {
|
||||
pub fn factor_numeric_value(&self, date: NaiveDate, symbol: &str, field: &str) -> Option<f64> {
|
||||
self.factor(date, symbol)
|
||||
.and_then(|snapshot| factor_numeric_value(snapshot, field))
|
||||
}
|
||||
@@ -922,16 +951,14 @@ impl DataSet {
|
||||
lookback: usize,
|
||||
) -> Option<f64> {
|
||||
match field {
|
||||
"close" | "prev_close" | "stock_close" | "price" => {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.decision_close_rolling_average(date, lookback))
|
||||
}
|
||||
"volume" | "stock_volume" => {
|
||||
self.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.decision_volume_rolling_average(date, lookback))
|
||||
}
|
||||
"close" | "prev_close" | "stock_close" | "price" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.decision_close_rolling_average(date, lookback)),
|
||||
"volume" | "stock_volume" => self
|
||||
.market_series_by_symbol
|
||||
.get(symbol)
|
||||
.and_then(|series| series.decision_volume_rolling_average(date, lookback)),
|
||||
"open" => self.market_moving_average(date, symbol, lookback, PriceField::Open),
|
||||
"last" | "last_price" => {
|
||||
self.market_moving_average(date, symbol, lookback, PriceField::Last)
|
||||
@@ -1178,6 +1205,13 @@ fn read_corporate_actions(path: &Path) -> Result<Vec<CorporateAction>, DataSetEr
|
||||
issue_price: row.parse_optional_f64(6 + offset).unwrap_or(0.0),
|
||||
reform: row.parse_optional_bool(7 + offset).unwrap_or(false),
|
||||
adjust_factor: row.parse_optional_f64(8 + offset),
|
||||
successor_symbol: row
|
||||
.fields
|
||||
.get(9 + offset)
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty()),
|
||||
successor_ratio: row.parse_optional_f64(10 + offset),
|
||||
successor_cash: row.parse_optional_f64(11 + offset),
|
||||
});
|
||||
}
|
||||
Ok(snapshots)
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::broker::{BrokerExecutionReport, BrokerSimulator};
|
||||
use crate::cost::CostModel;
|
||||
use crate::data::{BenchmarkSnapshot, DataSet, DataSetError, PriceField};
|
||||
use crate::events::{AccountEvent, FillEvent, OrderEvent, OrderSide, OrderStatus, PositionEvent};
|
||||
use crate::metrics::{BacktestMetrics, compute_backtest_metrics};
|
||||
use crate::metrics::{compute_backtest_metrics, BacktestMetrics};
|
||||
use crate::portfolio::{CashReceivable, HoldingSummary, PortfolioState};
|
||||
use crate::rules::EquityRuleHooks;
|
||||
use crate::strategy::{Strategy, StrategyContext};
|
||||
@@ -177,18 +177,18 @@ where
|
||||
&mut corporate_action_notes,
|
||||
)?;
|
||||
self.extend_result(&mut result, receivable_report);
|
||||
let delisting_report = self.settle_delisted_positions(
|
||||
execution_date,
|
||||
&mut portfolio,
|
||||
&mut corporate_action_notes,
|
||||
)?;
|
||||
self.extend_result(&mut result, delisting_report);
|
||||
let corporate_action_report = self.apply_corporate_actions(
|
||||
execution_date,
|
||||
&mut portfolio,
|
||||
&mut corporate_action_notes,
|
||||
)?;
|
||||
self.extend_result(&mut result, corporate_action_report);
|
||||
let delisting_report = self.settle_delisted_positions(
|
||||
execution_date,
|
||||
&mut portfolio,
|
||||
&mut corporate_action_notes,
|
||||
)?;
|
||||
self.extend_result(&mut result, delisting_report);
|
||||
|
||||
let decision = execution_idx
|
||||
.checked_sub(self.config.decision_lag_trading_days)
|
||||
@@ -396,6 +396,58 @@ where
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if action.has_successor_conversion() {
|
||||
let successor_symbol = action
|
||||
.successor_symbol
|
||||
.as_deref()
|
||||
.expect("successor symbol checked");
|
||||
let Some(outcome) = portfolio.apply_successor_conversion(
|
||||
&action.symbol,
|
||||
successor_symbol,
|
||||
action.successor_ratio_value(),
|
||||
action.successor_cash_value(),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let reason = format!(
|
||||
"successor_conversion {}->{} ratio={:.6} cash_per_share={:.6}",
|
||||
outcome.old_symbol,
|
||||
outcome.new_symbol,
|
||||
action.successor_ratio_value(),
|
||||
action.successor_cash_value()
|
||||
);
|
||||
notes.push(reason.clone());
|
||||
report.position_events.push(PositionEvent {
|
||||
date,
|
||||
symbol: outcome.old_symbol.clone(),
|
||||
delta_quantity: -(outcome.old_quantity as i32),
|
||||
quantity_after: 0,
|
||||
average_cost: 0.0,
|
||||
realized_pnl_delta: 0.0,
|
||||
reason: reason.clone(),
|
||||
});
|
||||
report.position_events.push(PositionEvent {
|
||||
date,
|
||||
symbol: outcome.new_symbol.clone(),
|
||||
delta_quantity: outcome.new_quantity_delta,
|
||||
quantity_after: outcome.new_quantity_after,
|
||||
average_cost: outcome.new_average_cost_after,
|
||||
realized_pnl_delta: 0.0,
|
||||
reason: reason.clone(),
|
||||
});
|
||||
if outcome.cash_delta.abs() > f64::EPSILON {
|
||||
let cash_before = portfolio.cash();
|
||||
portfolio.apply_cash_delta(outcome.cash_delta);
|
||||
report.account_events.push(AccountEvent {
|
||||
date,
|
||||
cash_before,
|
||||
cash_after: portfolio.cash(),
|
||||
total_equity: portfolio.total_equity(),
|
||||
note: format!("{} cash={:.2}", reason, outcome.cash_delta),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
portfolio.prune_flat_positions();
|
||||
|
||||
@@ -181,6 +181,17 @@ pub struct PortfolioState {
|
||||
cash_receivables: Vec<CashReceivable>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct SuccessorConversionOutcome {
|
||||
pub old_symbol: String,
|
||||
pub new_symbol: String,
|
||||
pub old_quantity: u32,
|
||||
pub new_quantity_delta: i32,
|
||||
pub new_quantity_after: u32,
|
||||
pub new_average_cost_after: f64,
|
||||
pub cash_delta: f64,
|
||||
}
|
||||
|
||||
impl PortfolioState {
|
||||
pub fn new(initial_cash: f64) -> Self {
|
||||
Self {
|
||||
@@ -290,6 +301,80 @@ impl PortfolioState {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn apply_successor_conversion(
|
||||
&mut self,
|
||||
old_symbol: &str,
|
||||
new_symbol: &str,
|
||||
ratio: f64,
|
||||
cash_per_old_share: f64,
|
||||
) -> Option<SuccessorConversionOutcome> {
|
||||
if !ratio.is_finite() || ratio <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let old_symbol_owned = old_symbol.to_string();
|
||||
let old_position = self.positions.shift_remove(old_symbol)?;
|
||||
if old_position.quantity == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let old_quantity = old_position.quantity;
|
||||
let last_price = old_position.last_price;
|
||||
let realized_pnl = old_position.realized_pnl;
|
||||
let mut converted_lots = old_position
|
||||
.lots
|
||||
.into_iter()
|
||||
.map(|lot| PositionLot {
|
||||
acquired_date: lot.acquired_date,
|
||||
quantity: round_half_up_u32(lot.quantity as f64 * ratio),
|
||||
price: lot.price / ratio,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let expected_total = round_half_up_u32(old_quantity as f64 * ratio);
|
||||
let scaled_total = converted_lots.iter().map(|lot| lot.quantity).sum::<u32>();
|
||||
if let Some(last_lot) = converted_lots.last_mut() {
|
||||
if scaled_total < expected_total {
|
||||
last_lot.quantity += expected_total - scaled_total;
|
||||
} else if scaled_total > expected_total {
|
||||
last_lot.quantity = last_lot
|
||||
.quantity
|
||||
.saturating_sub(scaled_total - expected_total);
|
||||
}
|
||||
}
|
||||
converted_lots.retain(|lot| lot.quantity > 0);
|
||||
let converted_quantity = converted_lots.iter().map(|lot| lot.quantity).sum::<u32>();
|
||||
let converted_last_price = if last_price > 0.0 {
|
||||
last_price / ratio
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let successor = self
|
||||
.positions
|
||||
.entry(new_symbol.to_string())
|
||||
.or_insert_with(|| Position::new(new_symbol));
|
||||
successor.lots.extend(converted_lots);
|
||||
successor.quantity = successor.lots.iter().map(|lot| lot.quantity).sum();
|
||||
successor.realized_pnl += realized_pnl;
|
||||
if converted_last_price > 0.0 {
|
||||
successor.last_price = converted_last_price;
|
||||
}
|
||||
successor.recalculate_average_cost();
|
||||
|
||||
Some(SuccessorConversionOutcome {
|
||||
old_symbol: old_symbol_owned,
|
||||
new_symbol: new_symbol.to_string(),
|
||||
old_quantity,
|
||||
new_quantity_delta: converted_quantity as i32,
|
||||
new_quantity_after: successor.quantity,
|
||||
new_average_cost_after: successor.average_cost,
|
||||
cash_delta: if cash_per_old_share.is_finite() {
|
||||
old_quantity as f64 * cash_per_old_share
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user