feat(allocations): portfolio allocation targets & rebalancing advisor
Summary
Hi 👋
This PR adds a full Allocation Targets system with a Rebalancing Advisor to Wealthfolio — letting users define target allocations per asset class and get actionable trade suggestions to reach those targets.
- Define target % per asset class (Equity, Bonds, Cash…) with optional per-holding breakdowns within each class
- Visual health strip showing portfolio alignment at a glance (on target / drift / amount to deploy)
- Rebalancing advisor generates a prioritized trade list given available cash, in Buy Only or Buy & Sell mode
- CSV export in importable format (compatible with the activity import flow, includes ISIN for European users)
- Allocation Strategy settings page to configure rebalancing mode per account
How it works
Overview tab
- Health strip: portfolio value, classes on target, worst drift, amount to deploy to reach targets
- Donut chart + deviation table (actual % vs target %, drift colored green/yellow/red)
- Click on a class → drilldown view opens inline: flat list of holdings on the left, target editor + holding-level targets on the right
Rebalancing tab
- Enter available cash → one click generates a trade plan
- Buy Only: deploys cash into underweight positions proportionally to their shortfall
- Buy & Sell: sells overweight positions first, redeploys proceeds + new cash
- Trade table with sortable columns (class, asset, action, shares, price, amount)
- BUDGET rows when a class has budget but no holding-level targets configured (with warning tooltip)
- Warning icons when holding targets are partial or missing
- CSV export ready to import as activities (symbol, activityType, quantity, unitPrice, isin…)
Technical changes
Rust / Backend
- New
portfolio/targetsmodule:PortfolioTarget,TargetAllocation,HoldingTargetwith full CRUD and SQLite repository - New
portfolio/rebalancingmodule: buy-only and buy-and-sell algorithms with 13+ unit tests has_partial_targetsdetection: compares portfolio holdings vs configured holding targetsisinfield propagated throughInstrument→HoldingSummary→TradeRecommendationfromasset.metadata- 3 new migrations:
portfolio_targets,holding_targets,rebalance_mode
Frontend
- New
/allocationspage with Overview and Rebalancing tabs - Components:
HealthStrip,AllocationDonut,DrilldownView,CategorySidePanel,HoldingTargetRow,RebalancingTab,TargetList - All colors use the app's semantic tokens (
success,warning,destructive) for consistency - Health strip is responsive (2 cols mobile → 4 cols desktop)
/settings/allocation-strategypage to configure rebalancing mode per account
Server (web mode)
- REST endpoints for portfolio targets mirroring the Tauri IPC commands
Known limitations / follow-up
| Item | Status |
|---|---|
| Mobile card views for trade table and target list | 🔜 Follow-up (same pattern as HoldingsTableMobile / ActivityTableMobile) |
| ISIN not editable in asset profile page | 🔜 Separate PR |
Test plan
- [ ] Create an allocation target for "All Portfolio" with Equity 70% / Bonds 15% / Cash 15%
- [ ] Click a class → verify drilldown opens with holdings list + target editor
- [ ] Set holding-level targets within a class, verify % auto-distribution
- [ ] Switch to Rebalancing tab, enter cash, calculate → verify trade list
- [ ] Toggle Buy & Sell mode, recalculate → verify sell recommendations appear
- [ ] Category with no holding targets → verify BUDGET row with warning
- [ ] Category with partial targets → verify ⚠ icon in Allocation Changes strip
- [ ] Export CSV → verify columns match import format (symbol, activityType, quantity, unitPrice, isin…)
- [ ] Switch account in dropdown → verify plan resets correctly
Checklist
- [x] I have read and agree to the Contributor License Agreement.
By submitting this PR, I agree to the CLA.
@codex review
Awesome feature, hope this gets shipped soon!
Hey @afadil , just wanted to give you a heads-up.
I'm also working on a related feature on my fork: Portfolio Grouping. The idea is to let users create named composite portfolios (e.g. "Retirement", "Growth") that group multiple accounts together, with their own consolidated snapshots and views.
It connects naturally with this PR: right now allocation targets are scoped per account — with grouping, you could scope them at the composite portfolio level and define a global allocation strategy across a set of accounts.
Not blocking this merge at all, just flagging it in case it's useful. I will be ready to have a PR for that next week I think, just need to correct and test few things on my side before.
And thanks @diogoap
Hey @afadil
A little heads up,
All review items are now addressed:
Blockers (1–4)
rebalanceMode: "buy_only"is now sent on first target creation- Buy & Sell mode accepts 0 additional cash (sells fund buys without new external cash)
- Phantom category-level SELLs removed — overweight categories without holding targets no longer generate non-actionable SELL orders or count as proceeds
- Portfolio value summary corrected — sell proceeds and redeployed cash are netted out from the "New Portfolio" figure
Other items
- Holding target upsert now conflicts on
(allocation_id, asset_id)instead ofid- 4 separate migrations consolidated into one clean script (
IF NOT EXISTSfor idempotency — dev environments that ran the previous separate migrations can restore without errors)- Unrelated
app-launcher.tsxchanges reverted (invalid Tailwind selectors + stray backtick)- Web adapter fixes already pushed in previous commit (
f608974)
I made also two small improvements:
Cash overweight auto-redeployment (both modes)
In buy_and_sell mode, an overweight cash category with no holding targets was generating a phantom SELL (which we removed). But cash is already liqui, it doesn't need a SELL order to be redeployed. The excess is now added directly to the buy budget in both buy-only and buy_and_sell modes. If a user transfers cash and forgets about it, the rebalancing plan will automatically deploy it into underweight positions without requiring a manual cash input.
"TO INVEST" shows actual deployed amount The column previously showed the category budget (ideal). It now shows the actual amount deployed (sum of individual buy orders), which is what the user will actually spend. The small gap between budget and deployed is due to whole-share rounding, already visible in the "Remaining" footer.
Happy to revert either if you'd prefer a different approach.
I am waiting your answers on the point 5 and 7 for working on those ones.
Thanks again for your inputs.
Hi @Jonjon-prog , I spent some time researching common allocation/rebalancing patterns and thinking through how this should fit Wealthfolio long term.
I wrote two docs from that work:
- North-star model:
docs/features/allocations/sota-target-model-spec.md - Scoped Wealthfolio v1:
docs/features/allocations/allocation-targets-v1-spec.md
The main conclusion is that the conceptual direction of this PR is good, but the first version should probably be smaller and more explicit. The important separation to keep is:
- target allocation
- rebalance trigger
- funding input
- execution constraints
For v1, I think we should center the implementation around the scoped spec: target profiles, target allocation nodes, drift calculation, cash-flow planning, optional simple sell planning, and optional saved drafts. I would defer holding-level targets, guardrails, value averaging, account groups, and tax-lot/disposal logic until those features actually ship.
Tax reporting and lot disposal are planned separately, so this feature should leave clean extension points for that work without baking tax-lot assumptions into the v1 schema.
My recommendation is to treat this PR as a strong prototype/product exploration, but not merge it as the final foundation. I think the next iteration should restart from the scoped v1 spec, reuse useful pieces where practical, and avoid locking us into rebalance_mode, holding targets, and “strategy/recommendation” terminology too early.
Curious to get your thoughts on this direction. Does this scoped v1 feel aligned with what you were aiming for, or do you think there are parts of the current PR that should stay in the first version?
Hi @afadil,
Thanks for the thorough research , both documents are well-structured and the v1 scoped spec reflects exactly the kind of discipline that keeps a first version shippable and extensible. I've spent time auditing the current PR against the v1 spec and want to share findings and a few questions before proceeding.
Audit: current PR vs v1-spec
I did a detailed diff. The conceptual direction is aligned, but several structural decisions diverge from the v1 spec:
account_idwith"PORTFOLIO"sentinel instead ofscope_type+scope_id— exactly the pattern the spec flags as problematic.target_percent(0–100 integer) instead oftarget_bps(0–10000) — loses precision, touches all math and display.rebalance_modeas a single enum ("buy_only"/"buy_and_sell") instead of the four inline fields (allow_sells,trigger_type,drift_band_bps,rebalance_to) — conflates concerns that should stay separate.holding_targetstable — fully implemented, but explicitly out of scope in v1. Needs to be dropped entirely.- Missing fields on the profile:
base_currency,status(draft/active/archived),min_trade_amount,whole_shares_only,is_requiredon nodes.
My proposal: rather than refactoring these divergences in-place (noisy diff, migration cruft), start a clean branch built directly from the v1 spec schema and salvage the parts that have real value, the drift calculation logic, the calculate_rebalancing_plan algorithm, and the frontend chart components.
The CRUD boilerplate is mechanical enough to rewrite clean in a day or two, and the result is a PR that's easy to review without carrying forward naming or structural debt.
PR #938 as a prerequisite
I'd like to make the case for merging the portfolio grouping PR (#938) before starting allocation targets work.
The v1 spec defines scope_type: "portfolio" | "account". The "portfolio" scope is currently ambiguous in Wealthfolio — there's no named, user-defined concept of a portfolio that groups multiple accounts.
Without #938 , scope_type: "portfolio" ends up meaning "all accounts combined" with no ability to distinguish, for example, a retirement group (RRSP + TFSA) from a taxable account.
Every serious portfolio management tool solves this at the portfolio/goal level rather than the account level. Betterment and Wealthfront work on goals — each goal groups accounts with its own target allocation. Personal Capital runs its Investment Checkup at the household level across all linked accounts. Morningstar Portfolio Manager has an explicit named-portfolio concept above the individual account.
The concrete case this addresses in Wealthfolio: a user with RRSP + TFSA + non-registered wants to target 70/30 across their retirement accounts combined, and a separate 60/40 for their taxable account. Without portfolio grouping, the scope selector in the Allocation Targets UI has no meaningful options beyond individual accounts or a blunt aggregate of everything. With #938, scope_type: "portfolio" maps to a real, user-defined concept — which also lays the groundwork for asset location optimization in later phases (directing bond-heavy allocations toward registered accounts).
On sell-to-rebalance in v1
The v1 spec leaves this as an open question (Milestone 3). My vote: include it in v1 behind an allow_sells flag. The algorithm is already implemented, it's cleanly gated, and the spec's copy guidance ("tax impact not estimated" warning) handles user expectations correctly. A planner that can only buy feels incomplete for users already overweight in a position.
Frontend: alignment check
One area I'd like your input on: the frontend direction.
Currently in the PR:
- A donut chart component (current allocation visualization)
- A drift table (current vs target rows with delta)
- An account selector
- A rebalancing tab with cash input and suggested trades
The v1 spec describes a single "Allocation Targets" page with a set-targets panel and a plan-rebalance drawer. The SOTA spec describes three separate screens (Allocation Advisor / Targets & Policy / Rebalance Plan).
For v1, does the single-page-with-panels direction match your vision? And are there specific UI patterns you want to establish early that should be designed toward, even if some screens only ship in later milestones? I want to make sure the v1 layout doesn't need to be restructured when Phase 2 ships.
Looking forward to your thoughts on #938 and the frontend direction.
Hi @Jonjon-prog, thanks for the detailed audit. I agree with your read.
I think the best next step is to focus first on the portfolio grouping PR (#938). I’ll review that one in detail and provide feedback there before we restart the allocation targets work.
One important point I want to resolve in #938 is how it relates to the existing accounts.group field. I’m leaning toward cleaning that up properly instead of keeping two grouping concepts. Ideally, we migrate existing account groups into real portfolios, stop exposing the free-text account group field in the UI, and use the new portfolio entity as the stable scope for future features like allocation targets.
For this PR, I agree that we should not keep refactoring the current branch in place. Once #938 is reviewed and the portfolio/grouping model is settled, we can start a clean allocation-targets branch from the scoped v1 spec and salvage the useful pieces from this prototype.
I’ll also prepare the frontend UI direction for the allocation targets flow so we have a clear target before implementation starts: likely a single “Allocation Targets” area with target setup and rebalance planning as panels/drawers rather than separate top-level screens.
Thanks again for pushing both pieces forward. I’ll move the detailed feedback to #938 first.
Hi @afadil,
Understood on the accounts.group → portfolios consolidation. Before you review, two quick questions to align on before implementation:
1. Join table vs JSON blob for account membership?
Currently portfolios.account_ids stores a JSON-encoded array as TEXT.
If you want proper relational queries later (e.g. "which portfolio does account X belong to?"), a join table portfolio_accounts(portfolio_id, account_id) would be cleaner.
Happy to change this before your review if you have a preference.
2. accounts.group migration scope
For the migration from accounts.group to real portfolios: are you thinking this happens in the same PR (data migration in a new SQL migration file), or as a separate cleanup PR after this one merges?
Ready to add either before your review if it helps move faster.
Hey @afadil — quick check-in on allocation targets. PR #995 (portfolio filters) is now merged, which unblocks the scope_type: "portfolio" path from the v1-spec. We've done the audit against the spec and have a clean restart plan ready.
You mentioned you'd prepare the frontend UI direction before we start implementation. Any update on that? Happy to get started on the schema/backend side in parallel if that's useful, or wait for the full UI picture first 🙂
@Jonjon-prog some design direction ideas:
Allocation
Target
Rebalance
Hey @afadil,
Thanks for sharing the UI mockups. The three-tab layout (Overview / Targets / Rebalance) is clean and gives me a great direction to work from. Before starting the greenfield implementation I wanted to share a quick audit of where things stand and ask a few questions to make sure I don't build the wrong thing.
Where things are — foundations audit
With #1011 + #1008 both merged, every prerequisite from the v1-spec is in place:
ResolvedAccountScope { scope_id, account_ids, base_currency }— scope engine live, TOTAL pseudo-account gone- All 8
*_basevaluation columns indaily_account_valuation FxContextenum, scoped flow classifier, Modified Dietz fieldsLotRecord/AssetLotViewwithcost_basis— from the lots module in #1011AllocationServicewith leaf-wins + active-set normalization — #1008portfolios+portfolio_accountsschema — #995- Desktop / web adapter parity
Backend foundations are solid. Ready to start the greenfield allocation targets module as soon as we align on scope.
V1-spec vs SOTA — how far I planned to go
To make sure we're on the same page, the v1-spec covers roughly Phase 1 + most of Phase 2 of the SOTA model:
| What | V1-spec | SOTA gap |
|---|---|---|
target_profiles + target_allocation_nodes |
✅ covered | Missing parent_node_id (nested sleeves), per-node min/max_bps, rebalance_priority |
RebalancePolicy |
⚡ inlined on target_profiles |
SOTA has a separate table with review_frequency, next_review_date, band_type |
ExecutionPolicy |
⚡ inlined (allow_sells, min_trade, whole_shares) | SOTA adds tax_mode, lot_selection, wash_sale_check, max_turnover_bps, blocked/preferred_asset_ids |
rebalance_drafts |
⚡ JSON blob | SOTA has structured rebalance_runs + trade_drafts tables (immutable, queryable) |
FundingPolicy |
❌ not in v1 | Recurring contributions, value averaging, DCA — full Phase 3 |
TargetGuardrail |
❌ not in v1 | Secondary constraints (sector max, cash reserve min, etc.) — Phase 3 |
HoldingTarget |
❌ not in v1 | Instrument-level targets within a sleeve — Phase 3 |
| Tax-aware planning | ❌ not in v1 | Lot selection (FIFO/HIFO), wash-sale, max realized gain cap — Phase 4 |
Happy to stick with v1-spec for the first milestone and extend toward SOTA progressively. But a couple of things in the mockups look like they might need Phase 2+ decisions baked in from the start — which leads to the questions below.
Questions on the mockups
1. Is this UI direction or a final spec? I want to make sure I'm implementing what you actually want, not a wireframe interpretation. Are the three screens a design reference to work from, or should I match them closely?
2. Scope selector — where is it? The v1-spec, SOTA, and the backend all support scoping by account or saved portfolio. The mockups show "PORTFOLIO $487,320 across 2 accounts" — which looks like the whole-portfolio scope But there's no visible scope or portfolio selector. Is scope selection handled somewhere outside these screens (e.g., a global page-level filter), or is allocation targets always whole-portfolio in v1?
3. "Drift drivers" explanatory panel The Overview tab shows narrative explanations like "Bonds underweight after equity rally. Bond sleeve fell to 24.9% (target 30%) as stocks appreciated faster". This level of narrative isn't in the v1-spec or SOTA spec. Is this AI-generated, a template system, or a v2 feature I should skip for now?
4. "Tax-loss candidate" in the Rebalance tab
V1-spec explicitly put tax-lot logic out of scope. But the mockup shows VWO flagged as a "Tax-loss candidate" with -$890 realized gain. The good news is this is computable from the lot data in #1011
It's just comparing remaining_cost_basis to the current market price to flag positions at a loss.
Should I include this in v1, or leave it to a later phase?
5. "Minimal trades" — third rebalance mode
V1-spec defines two modes: cash_flow_only and sell_to_rebalance.
The Rebalance tab shows a third: Minimal trades (fewest moves).
This maps to the SOTA "hybrid" scenario — use cash first, only sell what's needed to get back inside the band. Should this be in v1, or is Phase 1 just the two modes?
6. Account filter on holdings table (All / Taxable / IRA)
The "All holdings" table in Overview has a filter for All / Taxable / IRA.
Are "Taxable" and "IRA" account names in this example, or is there a tax_treatment / account_type field on accounts that I should filter by?
Once aligned on these I can kick off the schema and start with Milestone 1 (targets + drift) right away.
Hi @Jonjon-prog , my response:
-
Is this UI direction or a final spec? They're a design direction, not final spec, You can adjust if you got better ideas,
-
Scope selector — where is it? We should add it to the header of the page, like we did for the other insight pages
-
"Drift drivers" explanatory panel skip for now,
-
"Tax-loss candidate" in the Rebalance tab leave it to a later phases
-
"Minimal trades" — third rebalance mode Would be nice if you can added it. But we definitely could could start with two mode
-
Account filter on holdings table (All / Taxable / IRA) no need to add this filter, we just add the global scope selector at the header
Let me know if you have any other questions