feat(investments): add investment tracker

Investments are accounts flagged as investments; performance is derived from their transactions. Linked transfers are contributions and withdrawals (average cost, realized gains), unlinked transactions are gains or losses, and income comes from the accounts' income entities.

- Unit-priced (exchange currency) or value-tracked accounts
- Money-weighted return (XIRR), annualized after a year
- Totals converted along each currency's exchange chain, with currency effect
- Investments list and detail pages; buy/sell/income use the transfer and transaction forms
- GET /api/accounts/<id>/performance/
This commit is contained in:
Herculino Trotta committed 2026-11-05 11:07:32 -03:00
1 parent 1b9ea452d9
commit 359e5880cc
23 files changed
+1366 -3

No files matched your search

+45
View File
@@ -1,3 +1,5 @@
from decimal import Decimal
from django.db.models import Q
from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
@@ -50,6 +52,8 @@ class AccountSerializer(serializers.ModelSerializer):
"exchange_currency",
"exchange_currency_id",
"is_asset",
"is_investment",
"income_entities",
]
def __init__(self, *args, **kwargs):
@@ -76,3 +80,44 @@ class AccountBalanceSerializer(serializers.Serializer):
projected_balance = serializers.DecimalField(max_digits=20, decimal_places=10)
currency = CurrencySerializer()
class InvestmentPerformanceSerializer(serializers.Serializer):
"""Serializer for an investment account's performance."""
currency = CurrencySerializer()
priced = serializers.BooleanField()
quantity = serializers.DecimalField(max_digits=42, decimal_places=30)
price = serializers.DecimalField(max_digits=42, decimal_places=30, allow_null=True)
price_date = serializers.DateTimeField(allow_null=True)
average_cost = serializers.DecimalField(
max_digits=42, decimal_places=30, allow_null=True
)
cost_basis = serializers.DecimalField(max_digits=42, decimal_places=30)
market_value = serializers.DecimalField(
max_digits=42, decimal_places=30, allow_null=True
)
unrealized = serializers.DecimalField(
max_digits=42, decimal_places=30, allow_null=True
)
realized = serializers.DecimalField(max_digits=42, decimal_places=30)
income = serializers.DecimalField(max_digits=42, decimal_places=30)
contributed = serializers.DecimalField(max_digits=42, decimal_places=30)
withdrawn = serializers.DecimalField(max_digits=42, decimal_places=30)
total_return = serializers.DecimalField(max_digits=42, decimal_places=30)
return_percentage = serializers.DecimalField(
max_digits=42, decimal_places=30, allow_null=True
)
estimated = serializers.BooleanField()
money_weighted_return = serializers.SerializerMethodField(
help_text="Return weighted by when money went in and out, in percent: "
"annual (XIRR) when the first contribution is a year old or more, "
"otherwise over the period held."
)
money_weighted_annualized = serializers.SerializerMethodField()
def get_money_weighted_return(self, perf) -> Decimal | None:
return perf.money_weighted and perf.money_weighted["percentage"]
def get_money_weighted_annualized(self, perf) -> bool | None:
return perf.money_weighted and perf.money_weighted["annualized"]
+16
View File
@@ -11,7 +11,9 @@ from apps.api.serializers import (
AccountGroupSerializer,
AccountSerializer,
AccountBalanceSerializer,
InvestmentPerformanceSerializer,
)
from apps.investments.services import get_holding_performance
class AccountGroupViewSet(viewsets.ModelViewSet):
@@ -38,6 +40,11 @@ class AccountGroupViewSet(viewsets.ModelViewSet):
description="Returns the current and projected balance for the account, along with currency data.",
responses={200: AccountBalanceSerializer},
),
performance=extend_schema(
summary="Get investment performance",
description="Returns quantity, cost basis, market value, realized/unrealized gains, income and total return, in the account's exchange currency (or its own currency when it has none).",
responses={200: InvestmentPerformanceSerializer},
),
)
class AccountViewSet(viewsets.ModelViewSet):
"""ViewSet for managing accounts."""
@@ -51,6 +58,7 @@ class AccountViewSet(viewsets.ModelViewSet):
"currency": ["exact"],
"exchange_currency": ["exact", "isnull"],
"is_asset": ["exact"],
"is_investment": ["exact"],
"is_archived": ["exact"],
"owner": ["exact"],
}
@@ -80,3 +88,11 @@ class AccountViewSet(viewsets.ModelViewSet):
)
return Response(serializer.data)
@action(detail=True, methods=["get"], permission_classes=[IsAuthenticated])
def performance(self, request, pk=None):
"""Get investment performance (cost basis, value, returns) for an account."""
account = self.get_object()
return Response(
InvestmentPerformanceSerializer(get_holding_performance(account)).data
)