Files
BTC-Portfolio/btc-portfolio/backend/app/routes/stats.py
T
Jonathan 5bb67d6663 Add purchase date picker and sells feature
- Purchase form now includes a date picker (defaults to today)
- New Sell model, CRUD endpoints (/sells), and stats integration
- AddSell and SellList components added to dashboard
- Portfolio chart updated to reflect sells over time

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 19:52:24 +02:00

41 lines
1.4 KiB
Python

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..database import get_db
from .. import models
from ..dependencies import get_current_user
from ..services.btc import get_btc_price_eur
router = APIRouter()
@router.get("/stats")
def get_stats(
db: Session = Depends(get_db),
current_user: models.User = Depends(get_current_user),
):
purchases = db.query(models.Purchase).filter(models.Purchase.user_id == current_user.id).all()
sells = db.query(models.Sell).filter(models.Sell.user_id == current_user.id).all()
total_invested = sum(p.amount_eur for p in purchases)
total_btc_bought = sum(p.amount_eur / p.price_eur for p in purchases) if purchases else 0.0
total_btc_sold = sum(s.btc_amount for s in sells)
proceeds_eur = sum(s.btc_amount * s.price_eur for s in sells)
net_btc = total_btc_bought - total_btc_sold
net_invested = total_invested - proceeds_eur
average_price = net_invested / net_btc if net_btc > 0 else 0.0
current_price = get_btc_price_eur()
portfolio_value = net_btc * current_price
profit_loss = portfolio_value - net_invested
return {
"total_invested": round(net_invested, 2),
"total_btc": round(net_btc, 8),
"average_price": round(average_price, 2),
"current_price": round(current_price, 2),
"portfolio_value": round(portfolio_value, 2),
"profit_loss": round(profit_loss, 2),
}