Open-source personal finance manager. Self-hosted, privacy-first.
fix(assets): plot value-trend points at every trade date (#331)
Tássio Noronha8e3732b3e9c2
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex 7a7f763a..c6991dda 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -197,15 +197,25 @@ async def _get_value_as_of(def build_market_value_series(value_rows: list[tuple[date, Decimal, Optional[Decimal]]],- txs: list[tuple[date, str, Decimal]],+ txs: list[tuple[date, str, Decimal, Optional[Decimal]]],) -> list[tuple[date, float]]:"""Rebuild a market-priced holding's value series from the ledger.value(date) = quantity_held_on(date) × price(date), where quantity is thecumulative buys − sells up to that date (from the ledger) and price is the- stored per-share price. This keeps the chart consistent with the ledger even- when past trades are entered after the fact. Falls back to the baked amount- when no per-share price is recorded. `value_rows` must be sorted by date.+ most recent stored per-share price. This keeps the chart consistent with the+ ledger even when past trades are entered after the fact. Falls back to the+ trade's own price on dates that predate any recorded market price (backdated+ trades entered before price tracking began), and to the baked amount when+ neither a price nor a later market price exists.++ A point is emitted at every stored-value date *and* every trade date, so a+ quantity change shows up on the chart at the date it happened. Without the+ trade-date points, a holding whose stored prices only start recently (the+ common case — prices are recorded daily from when the holding was added)+ collapses every backdated trade onto a single early anchor and renders one+ long straight interpolation across the gap. `value_rows` must be sorted by+ date.A holding with no ledger at all (e.g. a pre-ledger "no cost" position thatstill has a stored quantity) keeps its baked amounts — replaying an empty@@ -214,17 +224,44 @@ def build_market_value_series(if not txs:return [(d, float(amount)) for d, amount, _ in value_rows]- txs_sorted = sorted(txs, key=lambda t: t[0])+ # Net quantity change per trade date, plus a representative per-share price+ # (the day's last trade) used to value points that predate any market price.+ tx_delta: dict[date, Decimal] = {}+ tx_price: dict[date, Decimal] = {}+ for d, kind, q, p in sorted(txs, key=lambda t: t[0]):+ tx_delta[d] = tx_delta.get(d, Decimal("0")) + (q if kind == "buy" else -q)+ if p is not None:+ tx_price[d] = p++ # Stored value points by date (last write wins on duplicate dates).+ value_by_date: dict[date, tuple[Decimal, Optional[Decimal]]] = {+ d: (amount, price) for d, amount, price in value_rows+ }+out: list[tuple[date, float]] = []qty = Decimal("0")- i = 0- for d, amount, price in value_rows:- while i < len(txs_sorted) and txs_sorted[i][0] <= d:- _, kind, q = txs_sorted[i]- qty += q if kind == "buy" else -q- i += 1+ last_price: Optional[Decimal] = None # most recent known per-share price+ seen_market = False # has a stored market price been reached yet?+ for d in sorted(set(value_by_date) | set(tx_delta)):+ qty += tx_delta.get(d, Decimal("0"))held = qty if qty > 0 else Decimal("0")- out.append((d, float(Decimal(str(price)) * held) if price is not None else float(amount)))++ amount, price = value_by_date.get(d, (None, None))+ if price is not None:+ last_price = price # a recorded market price always wins+ seen_market = True+ elif not seen_market and d in tx_price:+ # Before any market price is recorded, value each trade at its own+ # price so backdated points aren't flattened onto a single anchor.+ # Once market prices begin they take over and carry forward.+ last_price = tx_price[d]++ if d in value_by_date and price is None:+ out.append((d, float(amount))) # stored point with no per-share price+ elif last_price is not None:+ out.append((d, float(last_price * held)))+ else:+ out.append((d, float(amount) if amount is not None else 0.0))return out@@ -264,12 +301,14 @@ async def _load_asset_native_values(if market_ids:tq = select(AssetTransaction.asset_id, AssetTransaction.date,- AssetTransaction.kind, AssetTransaction.quantity,+ AssetTransaction.kind, AssetTransaction.quantity, AssetTransaction.price,).where(AssetTransaction.asset_id.in_(market_ids))if up_to_date is not None:tq = tq.where(AssetTransaction.date <= up_to_date)- for aid, d, kind, qty in (await session.execute(tq)).all():- txs_by_aid.setdefault(str(aid), []).append((d, kind, Decimal(str(qty))))+ for aid, d, kind, qty, price in (await session.execute(tq)).all():+ txs_by_aid.setdefault(str(aid), []).append(+ (d, kind, Decimal(str(qty)), Decimal(str(price)) if price is not None else None)+ )values_map: dict[str, list[tuple[date, float]]] = {}for asset in assets:@@ -721,13 +760,16 @@ async def get_asset_value_trend(if asset.valuation_method == "market_price":txs = (await session.execute(- select(AssetTransaction.date, AssetTransaction.kind, AssetTransaction.quantity)+ select(+ AssetTransaction.date, AssetTransaction.kind,+ AssetTransaction.quantity, AssetTransaction.price,+ ).where(AssetTransaction.asset_id == asset_id))).all()series = build_market_value_series([(d, a, p) for d, a, p in rows],- [(d, k, Decimal(str(q))) for d, k, q in txs],+ [(d, k, Decimal(str(q)), Decimal(str(pr)) if pr is not None else None) for d, k, q, pr in txs],)return [{"date": d.isoformat(), "amount": v} for d, v in series]diff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.pyindex db8445fb..1c6619ee 100644--- a/backend/tests/test_asset_service.py+++ b/backend/tests/test_asset_service.py@@ -29,12 +29,17 @@ def test_build_market_value_series_reflects_quantity_over_time():(date(2026, 6, 11), Decimal("8330"), Decimal("41.65")),]txs = [- (date(2025, 12, 1), "buy", Decimal("200")),- (date(2026, 5, 15), "buy", Decimal("50")), # backdated, between the value points+ (date(2025, 12, 1), "buy", Decimal("200"), Decimal("40")),+ (date(2026, 5, 15), "buy", Decimal("50"), Decimal("46")), # backdated, between value points]out = dict(build_market_value_series(rows, txs))- assert round(out[date(2026, 5, 12)]) == round(200 * 46.43) # before the buy → 200 units- assert round(out[date(2026, 5, 17)]) == round(250 * 45.47) # after → 250 units+ # The trade dates get their own points so the chart isn't a flat line until+ # the first stored price. Before any market price, value at the trade price.+ assert round(out[date(2025, 12, 1)]) == round(200 * 40) # no market price yet → trade price+ assert round(out[date(2026, 5, 12)]) == round(200 * 46.43) # before the 05-15 buy → 200 units+ # A trade between two stored prices carries the last known market price.+ assert round(out[date(2026, 5, 15)]) == round(250 * 46.43) # 250 units at the carried price+ assert round(out[date(2026, 5, 17)]) == round(250 * 45.47) # after → 250 unitsassert round(out[date(2026, 6, 11)]) == round(250 * 41.65)@@ -45,15 +50,37 @@ def test_build_market_value_series_handles_sell_and_missing_price():(date(2026, 3, 1), Decimal("777"), None), # no price → fall back to amount]txs = [- (date(2026, 1, 1), "buy", Decimal("100")),- (date(2026, 1, 20), "sell", Decimal("40")),+ (date(2026, 1, 1), "buy", Decimal("100"), Decimal("10")),+ (date(2026, 1, 20), "sell", Decimal("40"), Decimal("11")),]out = dict(build_market_value_series(rows, txs))assert out[date(2026, 1, 1)] == 1000.0 # 100 × 10+ assert out[date(2026, 1, 20)] == 600.0 # mid-month sell point: 60 × 10 (carried price)assert out[date(2026, 2, 1)] == 720.0 # 60 × 12assert out[date(2026, 3, 1)] == 777.0 # fallback to stored amount+def test_build_market_value_series_backdated_trades_predating_prices():+ """The reported bug: trades years before price tracking each get a point.++ A market-priced holding records prices only from when it was added (recent+ dates), so every backdated buy must still produce a dated point — otherwise+ the chart collapses them onto one anchor and draws a single interpolation.+ """+ rows = [(date(2026, 6, 15), Decimal("5335.56"), Decimal("296.42"))]+ txs = [+ (date(2021, 1, 15), "buy", Decimal("10"), Decimal("50")),+ (date(2022, 2, 2), "buy", Decimal("5"), Decimal("80")),+ (date(2022, 4, 11), "buy", Decimal("3"), Decimal("120")),+ ]+ out = dict(build_market_value_series(rows, txs))+ assert round(out[date(2021, 1, 15)]) == round(10 * 50) # 10 units @ trade price+ assert round(out[date(2022, 2, 2)]) == round(15 * 80) # 15 units @ trade price+ assert round(out[date(2022, 4, 11)]) == round(18 * 120) # 18 units @ trade price+ assert round(out[date(2026, 6, 15)]) == round(18 * 296.42) # 18 units @ market price+ assert len(out) == 4 # a point per trade date plus the stored value++def test_build_market_value_series_no_ledger_keeps_amounts():"""A holding with no transactions must not be zeroed — keep stored amounts."""rows = [