Merge pull request #710 from eitchtee/feat/investments-asset-rebalance

feat(investments): show a per-asset breakdown in the rebalance
This commit is contained in:
Herculino Trotta authored and GitHub committed 2026-12-05 02:40:26 -03:00
commit e7b8e488e3
5 files changed
+141 -25

No files matched your search

+51 -7
View File
@@ -453,6 +453,7 @@ def portfolio_charts(performances):
{
"currency": figures["currency"],
"classes": {},
"assets": {},
"currencies": {},
"returns": [],
"history": {},
@@ -462,6 +463,7 @@ def portfolio_charts(performances):
if value:
key = perf.account.investment_class
chart["classes"][key] = chart["classes"].get(key, ZERO) + value
chart["assets"].setdefault(key, []).append((perf.account, value))
name = perf.currency.name
chart["currencies"][name] = chart["currencies"].get(name, ZERO) + value
chart["returns"].append((perf.account.name, figures["total_return"]))
@@ -486,18 +488,51 @@ def drift_limit(target):
return min(Decimal(5), target / 4)
def rebalance(classes, targeted):
def _fill(values, amount):
"""Split ``amount`` (positive) over ``values``, lowest first, raising them
toward a common level; returns what each value gets."""
order = sorted(values)
for k in range(1, len(order) + 1):
level = (amount + sum(order[:k])) / k
if k == len(order) or level <= order[k]:
break
return [max(ZERO, level - value) for value in values]
def _split(move, values):
"""Spread a class ``move`` over its assets in that direction only: a buy
goes to the lowest values, a sell comes from the highest."""
if move > 0:
return _fill(values, move)
return [-amount for amount in _fill([-value for value in values], -move)]
def rebalance(classes, targeted, assets=None, decimal_places=None):
"""What to buy or sell so the classes in ``targeted`` (InvestmentClass with a
target) match their targets, given ``classes`` as (class, value) from
portfolio_charts. Holdings without a class or target are left out and their
value is returned as ``left_out``. ``move`` is positive to buy."""
portfolio_charts. Holdings without a class or target are left out. ``move``
is positive to buy, rounded to ``decimal_places`` if given. With ``assets``
({class: [(account, value)]}, as in portfolio_charts), each row also gets its
holdings. Unless the class is on target, each gets an equal part of the
class target, and the class move is split toward it in its own direction
only (see _split). On target, ``target`` is None and ``move`` 0: the
spread among assets doesn't matter then."""
values = dict(classes)
assets = assets or {}
total = sum((values.get(cls, ZERO) for cls in targeted), ZERO)
def rounded(amount):
return amount if decimal_places is None else round(amount, decimal_places)
rows = []
for cls in targeted:
value = values.get(cls, ZERO)
share = value / total * 100 if total else ZERO
move = total * cls.target / 100 - value
move = rounded(total * cls.target / 100 - value)
off = abs(share - cls.target) > drift_limit(cls.target)
holdings = assets.get(cls, [])
part = cls.target / len(holdings) if move and holdings else None
moves = _split(move, [amount for _a, amount in holdings]) if part else []
rows.append(
{
"class": cls,
@@ -505,8 +540,17 @@ def rebalance(classes, targeted):
"share": share,
"target": cls.target,
"move": move,
"off": abs(share - cls.target) > drift_limit(cls.target),
"off": off,
"assets": [
{
"account": account,
"value": amount,
"share": amount / total * 100 if total else ZERO,
"target": part,
"move": rounded(moves[i]) if moves else ZERO,
}
for i, (account, amount) in enumerate(holdings)
],
}
)
left_out = sum(values.values(), ZERO) - total
return {"total": total, "rows": rows, "left_out": left_out}
return {"total": total, "rows": rows}
+64 -1
View File
@@ -261,7 +261,6 @@ class HoldingPerformanceTests(TestCase):
)
self.assertEqual(plan["total"], D("1000"))
self.assertEqual(plan["left_out"], D("75"))
moves = {row["class"].name: row["move"] for row in plan["rows"]}
self.assertEqual(moves, {"Stocks": D("-100"), "Bonds": D("0"), "Gold": D("100")})
self.assertEqual(sum(moves.values()), 0)
@@ -269,6 +268,70 @@ class HoldingPerformanceTests(TestCase):
off = {row["class"].name: row["off"] for row in plan["rows"]}
self.assertEqual(off, {"Stocks": True, "Bonds": False, "Gold": True})
def test_rebalance_splits_class_target_equally_per_asset(self):
from apps.investments.services import rebalance
stocks = InvestmentClass.objects.create(name="Stocks", target=D("60"))
bonds = InvestmentClass.objects.create(name="Bonds", target=D("40"))
plan = rebalance(
[(stocks, D("700")), (bonds, D("300"))],
[stocks, bonds],
{stocks: [("VWCE", D("500")), ("AAPL", D("200"))], bonds: [("CDB", D("300"))]},
)
stocks_row, bonds_row = plan["rows"]
# Each stock aims at 30%; the class sells 100, all from the largest one
self.assertEqual(
[(a["account"], a["target"], a["move"]) for a in stocks_row["assets"]],
[("VWCE", D("30"), D("-100")), ("AAPL", D("30"), D("0"))],
)
self.assertEqual(sum(a["move"] for a in stocks_row["assets"]), stocks_row["move"])
self.assertEqual(bonds_row["assets"][0]["move"], bonds_row["move"])
# A class on target (to the cent) doesn't care how its assets are spread;
# one merely within the drift band still gets the split
plan = rebalance(
[(stocks, D("600.004")), (bonds, D("399.996"))],
[stocks, bonds],
{stocks: [("VWCE", D("580.004")), ("AAPL", D("20"))], bonds: [("CDB", D("399.996"))]},
decimal_places=2,
)
for row in plan["rows"]:
self.assertEqual(row["move"], 0)
for asset in row["assets"]:
self.assertIsNone(asset["target"])
self.assertEqual(asset["move"], 0)
plan = rebalance(
[(stocks, D("620")), (bonds, D("380"))],
[stocks, bonds],
{stocks: [("VWCE", D("600")), ("AAPL", D("20"))]},
)
stocks_row = plan["rows"][0]
self.assertFalse(stocks_row["off"])
self.assertEqual([a["move"] for a in stocks_row["assets"]], [D("-20"), D("0")])
def test_rebalance_buy_goes_to_the_lowest_assets_only(self):
from apps.investments.services import rebalance
stocks = InvestmentClass.objects.create(name="Stocks", target=D("60"))
bonds = InvestmentClass.objects.create(name="Bonds", target=D("40"))
held = [("Apple", D("3863.88")), ("VWCE", D("3570.56")), ("Retirement", D("4670.00"))]
plan = rebalance(
[(stocks, D("12104.44")), (bonds, D("9698.73"))],
[stocks, bonds],
{stocks: held},
)
stocks_row = plan["rows"][0]
moves = [a["move"] for a in stocks_row["assets"]]
# The two lowest are raised to a common level; the one above it isn't sold
self.assertEqual(moves[2], 0)
self.assertEqual(D("3863.88") + moves[0], D("3570.56") + moves[1])
self.assertEqual(sum(moves), stocks_row["move"])
self.assertTrue(all(move >= 0 for move in moves))
def test_class_names_are_unique(self):
from apps.accounts.forms import InvestmentClassForm
+6 -4
View File
@@ -178,12 +178,14 @@ def investments_rebalance(request):
total_target = sum(cls.target for cls in targeted)
plans = []
for chart in portfolio_charts([get_holding_performance(a) for a in _holdings()]):
plan = rebalance(chart["classes"], targeted)
# Rounded so fractions of a cent don't show as "Buy 0.00"
plan = rebalance(
chart["classes"], targeted, chart["assets"], chart["currency"].decimal_places
)
plan["currency"] = chart["currency"]
for row in plan["rows"]:
# Fractions of a cent shouldn't show as "Buy 0.00"
row["move"] = round(row["move"], chart["currency"].decimal_places)
row["size"] = abs(row["move"])
for item in [row, *row["assets"]]:
item["size"] = abs(item["move"])
plans.append(plan)
return render(
request,
@@ -0,0 +1,8 @@
{% load i18n %}
{% if item.move > 0 %}
<span class="text-success">{% translate 'Buy' %}</span> <c-amount.display :amount="item.size" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
{% elif item.move < 0 %}
<span class="text-error">{% translate 'Sell' %}</span> <c-amount.display :amount="item.size" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
{% else %}
<span class="text-base-content/50">-</span>
{% endif %}
@@ -36,25 +36,24 @@
<td class="text-end tabular-nums {% if row.off %}text-warning{% endif %}">{{ row.share|floatformat:1 }}%</td>
<td class="text-end tabular-nums text-base-content/70">{{ row.target|floatformat:"-2" }}%</td>
<td class="text-end tabular-nums whitespace-nowrap">
{% if row.move > 0 %}
<span class="text-success">{% translate 'Buy' %}</span> <c-amount.display :amount="row.size" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
{% elif row.move < 0 %}
<span class="text-error">{% translate 'Sell' %}</span> <c-amount.display :amount="row.size" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
{% else %}
<span class="text-base-content/50">-</span>
{% endif %}
{% include "investments/fragments/_rebalance_move.html" with item=row %}
</td>
</tr>
{% for asset in row.assets %}
<tr class="text-sm text-base-content/70">
<td class="ps-8">{{ asset.account.name }}</td>
<td class="text-end tabular-nums whitespace-nowrap"><c-amount.display :amount="asset.value" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display></td>
<td class="text-end tabular-nums">{{ asset.share|floatformat:1 }}%</td>
<td class="text-end tabular-nums">{% if asset.target is not None %}{{ asset.target|floatformat:"-2" }}%{% else %}<span class="text-base-content/50">-</span>{% endif %}</td>
<td class="text-end tabular-nums whitespace-nowrap">
{% include "investments/fragments/_rebalance_move.html" with item=asset %}
</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
{% if plan.left_out %}
<div class="text-xs text-base-content/60 px-5 pb-4">
{% translate 'Left out: investments without an asset class or a target' %} ·
<c-amount.display :amount="plan.left_out" :prefix="c.prefix" :suffix="c.suffix" :decimal_places="c.decimal_places" divless></c-amount.display>
</div>
{% endif %}
</div>
{% endwith %}
{% endfor %}