69 lines
2.5 KiB
Python
69 lines
2.5 KiB
Python
"""Holdings, cost basis (average-cost method) and profit/loss."""
|
|
from decimal import Decimal
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session, selectinload
|
|
|
|
from models import Asset
|
|
|
|
ZERO = Decimal("0")
|
|
|
|
|
|
def position(asset: Asset) -> dict:
|
|
qty = cost = realized = ZERO
|
|
for t in asset.trades:
|
|
if t.side == "buy":
|
|
qty += t.quantity
|
|
cost += t.quantity * t.price + (t.fees or ZERO)
|
|
else:
|
|
avg = cost / qty if qty else ZERO
|
|
sold = min(t.quantity, qty)
|
|
realized += sold * t.price - (t.fees or ZERO) - avg * sold
|
|
cost -= avg * sold
|
|
qty -= sold
|
|
price = asset.manual_price if asset.manual_price is not None else asset.last_price
|
|
value = (qty * price) if price is not None else None
|
|
pnl = (value - cost) if value is not None else None
|
|
return {
|
|
"asset": asset,
|
|
"qty": qty,
|
|
"cost": cost.quantize(Decimal("0.01")),
|
|
"avg": (cost / qty) if qty else None,
|
|
"price": price,
|
|
"value": value.quantize(Decimal("0.01")) if value is not None else None,
|
|
"pnl": pnl.quantize(Decimal("0.01")) if pnl is not None else None,
|
|
"pnl_pct": float(pnl / cost * 100) if pnl is not None and cost else None,
|
|
"realized": realized.quantize(Decimal("0.01")),
|
|
"grams": (qty * (Decimal("31.1034768") if asset.unit == "oz" else 1) * (asset.purity or 1))
|
|
if asset.kind == "gold" else None,
|
|
}
|
|
|
|
|
|
def holdings(db: Session, kind: str | None = None) -> list[dict]:
|
|
q = select(Asset).options(selectinload(Asset.trades)).order_by(Asset.kind, Asset.name)
|
|
if kind:
|
|
q = q.where(Asset.kind == kind)
|
|
return [position(a) for a in db.scalars(q)]
|
|
|
|
|
|
def totals(rows: list[dict]) -> dict:
|
|
out: dict[str, dict] = {}
|
|
for r in rows:
|
|
for k in (r["asset"].kind, "all"):
|
|
t = out.setdefault(k, {"cost": ZERO, "value": ZERO, "realized": ZERO, "missing_price": 0})
|
|
if r["qty"] <= 0 and not r["realized"]:
|
|
continue
|
|
t["realized"] += r["realized"]
|
|
if r["qty"] <= 0:
|
|
continue
|
|
t["cost"] += r["cost"]
|
|
if r["value"] is None:
|
|
t["missing_price"] += 1
|
|
t["value"] += r["cost"] # fall back to cost so totals stay meaningful
|
|
else:
|
|
t["value"] += r["value"]
|
|
for t in out.values():
|
|
t["pnl"] = t["value"] - t["cost"]
|
|
t["pnl_pct"] = float(t["pnl"] / t["cost"] * 100) if t["cost"] else None
|
|
return out
|