fix(portfolios): replay corporate-action cost basis (#38)
This commit is contained in:
+37
-16
@@ -1282,27 +1282,48 @@ def get_holdings_cost_basis(
|
||||
finally:
|
||||
_close_repo(repo)
|
||||
|
||||
# Build rows for domain function
|
||||
rows = [
|
||||
{
|
||||
"side": e.side,
|
||||
"quantity": e.quantity,
|
||||
"price": e.price,
|
||||
"fee_amount": e.fee_amount,
|
||||
"executed_at": e.executed_at,
|
||||
# Build rows for domain function, preserving joined corporate-action metadata.
|
||||
rows = []
|
||||
corporate_action_fields = (
|
||||
"corporate_action_id",
|
||||
"action_type",
|
||||
"quantity_before",
|
||||
"quantity_after",
|
||||
"average_price_after",
|
||||
"total_cost_basis",
|
||||
)
|
||||
for entry in ledger_entries:
|
||||
row = {
|
||||
"side": entry.side,
|
||||
"quantity": entry.quantity,
|
||||
"price": entry.price,
|
||||
"fee_amount": entry.fee_amount,
|
||||
"executed_at": entry.executed_at,
|
||||
"ledger_entry_id": entry.ledger_entry_id,
|
||||
}
|
||||
for e in ledger_entries
|
||||
]
|
||||
if entry.corporate_action:
|
||||
row.update(
|
||||
{
|
||||
field: entry.corporate_action.get(field)
|
||||
for field in corporate_action_fields
|
||||
}
|
||||
)
|
||||
rows.append(row)
|
||||
|
||||
wac_result = calculate_current_wac(rows)
|
||||
|
||||
current_quantity = portfolio.asset_quantity
|
||||
cost_basis_per_unit = wac_result.current_wac if current_quantity > 0 else None
|
||||
total_cost_basis = (
|
||||
cost_basis_per_unit * current_quantity
|
||||
if cost_basis_per_unit is not None and current_quantity > 0
|
||||
else None
|
||||
)
|
||||
if wac_result.total_cost_basis is not None and wac_result.current_quantity > 0:
|
||||
current_quantity = wac_result.current_quantity
|
||||
total_cost_basis = wac_result.total_cost_basis
|
||||
cost_basis_per_unit = total_cost_basis / current_quantity
|
||||
else:
|
||||
cost_basis_per_unit = wac_result.current_wac if current_quantity > 0 else None
|
||||
total_cost_basis = (
|
||||
cost_basis_per_unit * current_quantity
|
||||
if cost_basis_per_unit is not None and current_quantity > 0
|
||||
else None
|
||||
)
|
||||
|
||||
return HoldingsCostBasisResponse(
|
||||
portfolio_id=portfolio_id,
|
||||
|
||||
Reference in New Issue
Block a user