Track investments as broker facts with a position leg

An account now has a kind, and an investment account holds positions as well as
cash. A broker row is not a new entity: it is a bank fact with an optional
position leg, so deduplication, the journal, fact immutability, the DuckDB
projection and the transactions view carry it unchanged. Facts.Amount stays the
cash leg and is zero on the rows that move only a position.

Scalable Capital exports are recognized locally as a fourth format, read by
their own parser because a column mapping cannot describe them: the amount
column is settled cash on a cash row, a gross to be netted on a trade, and a
position valuation that must never touch cash on a corporate action or a depot
transfer. A cash amount is already net of the tax the broker withheld or
refunded, so that tax is recorded on the fact and never subtracted a second
time; treating a corporate action's valuation as money conjures cash, and a
depot switch would do it once per instrument. The share column is signed only
for those two types, so buys and sells take their direction from the type. Every
security row is checked against shares times price at 128-bit width, because a
lost decimal separator survives every other check. An unknown status, type or
assetType, a foreign currency, a missing ISIN, or one failed check rejects the
whole file with the record number.

Instruments live in instruments.finance, keyed by ISIN with an ID derived from
it, so re-importing never registers a security twice. One ISIN appears under
several broker descriptions over the years and sometimes under the ISIN itself:
the most recent real description names it, and an import never renames one that
already exists. A broker also reuses a single reference across every leg of one
event, so transaction identity includes the event and its instrument.

domain.Fallback returns kind "investment" for any fact carrying a position leg,
so no broker row reaches the sign-based branch. That single rule is what stops
an unmatched deposit from counting as income and a broker fee from counting as
household spending; the monthly PRIME fee and its matching credit now cancel in
clearing:investments with no configuration at all. Investment rows are excluded
from spending analytics, from bulk reclassification and from the model, exactly
as transfers are.

Equal competing transfers are paired instead of skipped. Every connected
component of the candidate graph is a complete bipartite graph between two fixed
accounts at one amount and currency, so every pairing produces the same
accounts, kinds and postings and only the displayed counterpart differs.
Refusing to choose was the expensive option: both legs fell through to the
sign-based fallback and appeared as spending and income that never happened.
Pairing follows the nearest booking date, then the transaction ID, so iteration
order decides nothing. POST /api/transactions/{id}/transfer rewrites the old and
the new pair in one commit, because reciprocity is validated and a half-applied
link is an invalid dataset, and the matcher now skips any record classified
manually so a hand-made link or unlink outlives the next import.

Wealth reports each account's cash and positions from the journal rather than
the index, with named checks - row arithmetic, cash never negative, holdings
never negative - because it exists to be compared against the figures a broker
shows on its own screen. A negative holding means the imported history is
partial. Share counts are exact to eight places; a reinvested distribution
quoted to six is rounded to money's four and the residue is reported rather than
hidden. Market prices, market value, net worth over time, FIFO lot accounting,
realised gains and currency conversion are deliberately absent.
This commit is contained in:
Lars Nolden
2026-09-11 21:58:47 +02:00
parent 673cbf917b
commit 922ae507bd
27 changed files with 3071 additions and 157 deletions
+95
View File
@@ -3,10 +3,36 @@ export interface Account {
display_name: string;
institution: string;
currency: string;
// kind is "cash" or "investment"; an absent kind is a cash account.
kind?: string;
external_account_id?: string;
iban?: string;
// reference_iban is the counterpart an investment account settles cash
// against: a broker export carries no counterparty, so its deposits and
// withdrawals pair with the funding account through this IBAN.
reference_iban?: string;
active: boolean;
}
// Instrument is a security held in an investment account. The ISIN is the
// identity; the name is editable display text.
export interface Instrument {
id: string;
isin: string;
name: string;
currency: string;
}
// Investment is the broker-native leg of a fact. Cash movement always stays in
// Facts.amount, so a position-only event carries a zero amount. Quantity is an
// exact signed decimal, not money: negative removes from the holding.
export interface Investment {
event: string;
instrument_id?: string;
quantity?: string;
price?: string;
gross?: string;
fee?: string;
tax?: string;
}
export interface Facts {
id: string;
source: string;
@@ -20,6 +46,7 @@ export interface Facts {
fingerprint: string;
counterparty?: string;
counterparty_iban?: string;
investment?: Investment;
}
export interface Provenance {
source: string;
@@ -62,6 +89,7 @@ export interface Dataset {
categories: Category[];
tags: Tag[];
merchants: Merchant[];
instruments: Instrument[];
transactions: Transaction[];
}
export interface Connection {
@@ -161,6 +189,27 @@ export interface CSVColumn {
field: string;
column: string;
}
// BrokerReview is what the broker parser decided about an export that has not
// been imported yet: which securities it would register, which rows it skipped
// and which figures it deliberately did not apply.
export interface BrokerReview {
instruments: Instrument[];
// cancelled counts rows the broker did not execute.
cancelled: number;
// rounded counts rows whose money carried more than four decimal places;
// rounding is the exact total adjustment, to eight places.
rounded: number;
rounding: string;
// unapplied lists cash rows carrying a fee or tax. A broker cash amount is
// already net of both, so subtracting them again would double-count.
unapplied: {
record: number;
date: string;
description: string;
fee?: string;
tax?: string;
}[];
}
// PreparedImport is a parsed statement that has not been imported yet: the
// mapping and sample must be confirmed before any transaction is written.
export interface PreparedImport {
@@ -176,6 +225,51 @@ export interface PreparedImport {
new: number;
duplicates: number;
samples: Facts[];
broker?: BrokerReview;
}
// WealthHolding is one instrument's position in one account. quantity is an
// exact signed decimal and never money; invested and received are money.
export interface WealthHolding {
instrument_id: string;
isin: string;
name: string;
quantity: string;
invested: string;
received: string;
records: number;
}
// WealthCheck is one named verification with its evidence. failed marks a
// disagreement inside the journal; the rest are notes that explain a figure.
export interface WealthCheck {
name: string;
detail: string;
failed: boolean;
}
export interface WealthAccount {
account_id: string;
display_name: string;
institution: string;
currency: string;
kind: string;
active: boolean;
records: number;
first_booking?: string;
last_booking?: string;
// cash is every recorded movement summed. It equals the real balance only
// when the journal holds that account's complete history.
cash: string;
holdings: WealthHolding[];
checks: WealthCheck[];
}
export interface WealthTotal {
currency: string;
cash: string;
}
// Wealth is a reconciliation report computed from the journal rather than the
// analytics index, so it can be checked against a bank or broker's own screen.
export interface Wealth {
accounts: WealthAccount[];
totals: WealthTotal[];
}
export class APIError extends Error {
constructor(
@@ -244,6 +338,7 @@ export function normalizeState(state: State): State {
"categories",
"tags",
"merchants",
"instruments",
"transactions",
] as const) {
if (!(key in state.data))