Open-source personal finance manager. Self-hosted, privacy-first.
fix(assets): keep sold assets in portfolio trend history (#120) (#133)
Tássio Noronha18a01130f9f4
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex 77fd7fc8..ffc07af7 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -501,12 +501,14 @@ async def get_portfolio_trend(session: AsyncSession, user_id: uuid.UUID) -> dict:"""Get portfolio trend data for stacked area chart.- Returns asset metadata + pivoted trend with fill-forward values."""+ Returns asset metadata + pivoted trend with fill-forward values.+ Sold assets are included so their pre-sell history still contributes+ to the historical total; their contribution drops to 0 the day after+ sell_date."""result = await session.execute(select(Asset).where(Asset.user_id == user_id,Asset.is_archived == False,- Asset.sell_date.is_(None),).order_by(Asset.position, Asset.name))active_assets = list(result.scalars().all())@@ -517,6 +519,7 @@ async def get_portfolio_trend(# Collect all values per asset and all unique datesasset_meta = []asset_values_map: dict[str, list[tuple[date, float]]] = {}+ sell_date_by_aid: dict[str, date] = {}all_dates: set[date] = set()# Get user's primary currency for conversion@@ -544,6 +547,16 @@ async def get_portfolio_trend(if not vals or asset.purchase_date < vals[0][0]:vals.insert(0, (asset.purchase_date, float(asset.purchase_price)))+ # If the asset was sold and a sell_price is recorded, treat it as the+ # asset's terminal value on sell_date so the chart reflects the+ # realized value before dropping to 0.+ if asset.sell_date is not None:+ sell_date_by_aid[aid] = asset.sell_date+ if asset.sell_price is not None:+ vals = [(d, v) for d, v in vals if d <= asset.sell_date]+ if not vals or vals[-1][0] != asset.sell_date:+ vals.append((asset.sell_date, float(asset.sell_price)))+# Convert every value to the primary currency at its own date so the# stacked areas and the tooltip total are all in the same unit. Before# this, a USD-quoted asset like AAPL contributed its raw $ value to@@ -593,6 +606,11 @@ async def get_portfolio_trend(val = round(last_known[aid], 2)else:val = 0+ # After sell_date, the asset has been liquidated — drop to 0 so+ # it stops contributing to the portfolio total going forward.+ if aid in sell_date_by_aid and d > sell_date_by_aid[aid]:+ val = 0+ last_known[aid] = 0.0row[aid] = valdate_total += valrow["_total"] = round(date_total, 2)