diff --git a/app/apps/investments/services.py b/app/apps/investments/services.py
index 7546b3bd..259fc9c5 100644
--- a/app/apps/investments/services.py
+++ b/app/apps/investments/services.py
@@ -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}
diff --git a/app/apps/investments/tests/test_services.py b/app/apps/investments/tests/test_services.py
index 174d0494..20fd6c92 100644
--- a/app/apps/investments/tests/test_services.py
+++ b/app/apps/investments/tests/test_services.py
@@ -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
diff --git a/app/apps/investments/views.py b/app/apps/investments/views.py
index 417f0658..5ad80eb2 100644
--- a/app/apps/investments/views.py
+++ b/app/apps/investments/views.py
@@ -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,
diff --git a/app/templates/investments/fragments/_rebalance_move.html b/app/templates/investments/fragments/_rebalance_move.html
new file mode 100644
index 00000000..364e0dc4
--- /dev/null
+++ b/app/templates/investments/fragments/_rebalance_move.html
@@ -0,0 +1,8 @@
+{% load i18n %}
+{% if item.move > 0 %}
+ {% translate 'Buy' %}