How to Reconstruct a Portfolio From Broker Statements: Lots, FX and Corporate Actions

How to Reconstruct a Portfolio From Broker Statements: Lots, FX and Corporate Actions

A broker statement looks like it answers "what do I own, and what did it cost me?" It doesn't. It is a lossy, broker-specific view of a ledger you never get to see. Dividends and the tax withheld on them sit in different sections. Splits appear as free-text descriptions. Cash lines settle on different dates from the trades that caused them. The same trade can appear in two overlapping exports, with the price rounded differently in each. For the past few months I have been building an engine that takes these files (PDF, CSV, XLSX, even screenshots) and rebuilds holdings, cost basis under different tax systems, dividends net of withholding, and performance across accounts in different currencies. It is written in Go. It currently reads 15 brokers through 21 deterministic converters and has about 1,450 test functions. This article follows the data from upload to performance number, along with the bugs that forced most of the design. If you take away one thing, make it this: an unknown number is not zero. Nearly every bug below was a place where the system quietly made up a number instead of admitting it didn't have one. 1. Ingestion: deterministic parsers first, the model last Before anything else, every upload's first bytes are checked against its file extension. PDF, CSV/TXT/TSV, XLSX/XLSM, XLS, PNG, JPG and WEBP are accepted, and anything else is rejected. All spreadsheets are normalised into one internal "sheet JSON" shape, so the later stages see a single format. After that, parsing happens in two layers: Deterministic converters, one per broker report type, chosen by an exact match on the header set. Some brokers need several: Freedom24 has six (different report types in XLSX and PDF) and IBKR Flex has two. The other thirteen brokers (Trading 212, DEGIRO, eToro, Revolut, Trade Republic, Freetrade, XTB, Saxo, Schwab, Swissquote, Avanza, InvestEngine and Vanguard UK) have one each. An LLM, only for sheets that no converter claimed. If every sheet is claimed, the model is never called. That wasn't originally about cost. In testing, the model kept turning dividend rows into positions. To a language model asked to extract holdings, a line like "AAPL cash dividend USD 0.24 per share" looks a lot like a holding. A deterministic parser can be wrong too, but it is wrong the same way every time, and a test catches it. Model output is also never trusted for anything that changes the meaning of the ledger: Whether a row is a split is decided from the row's description text, not from the type the model returned. A split with no ratio, or a ratio of 1, is dropped. Rows with a quantity of zero or less are dropped. When a market close price is used to value an opening balance, it is checked against the execution prices in the same statement. If it is more than 3x off, it is rejected. Parsed rows don't go straight into the ledger. They are stored as pending, and the user reviews them: the trades, a ledger check, overlaps with existing data and any unmatched trades. Confirming keeps the selected rows and deletes only the rejected pending ones. 2. Deduplication: by content, never by file name Duplicates come in three kinds, and each needs its own key. The same files uploaded again. Each file is hashed with SHA-256, the hashes are sorted, and the sorted list is hashed again. File names and upload order don't affect the result. A repeat is rejected before any parsing quota is spent or the model is called, and an explicit force flag allows a deliberate re-import. Overlapping periods. Someone uploads January to June, then April to December. Three months of trades now appear twice, and the files differ, so file hashes don't help. Trades are matched on this key: type contributionDedupKey struct { tickerID string day string quantity string sell bool } func newContributionDedupKey(tickerID string, purchasedAt time.Time, quantity float64, contributionType string) contributionDedupKey { return contributionDedupKey{ tickerID: tickerID, day: purchasedAt.Format("2006-01-02"), quantity: strconv.FormatFloat(quantity, 'f', 6, 64), sell: contributionType == contributionsentity.TypeSell, } } Two details matter here. First, price is deliberately left out of the key, because brokers round prices differently across report types; with price in the key, the same trade would look like two. Second, the key is used as a multiset, not a set. Two identical buys on the same day are both real. If each file contains two of them, the result should be two, not four and not one. When earlier history arrives, any opening balances that were synthesised to fill the gap are deleted, because real trades now replace them. Platform feeds. For accounts synced through a data provider, each delivery's content hash classifies it as new, unchanged, changed or retry. A changed delivery of a transaction that is already recorded becomes an exception for a human to resolve. Confirmed rows are never silently overwritten. 3. The ledger and the lots The stored ledger is deliberately small. It has four transaction types (external_deposit, reinvestment, sell, split) and two flags (is_opening_balance and transfer_direction). Richer types exist only at the edges: the parser knows about income and transfers, and the replay knows about cost adjustments and corporate actions. A small stored model means every row has exactly one meaning. Cost basis is never stored. It is recomputed from scratch on every request by a single replay pass that keeps state per ticker (or per account and ticker, where the tax system pools by account). A full replay costs less than a stale cached basis after a late statement arrives. The lot method depends on the tax system Tax system Method Pooling Canada Average cost (ACB) Per person; re-valued on arrival; 30-day superficial loss US FIFO Per account UK Average Same day, then 30 days, then the Section 104 pool Australia FIFO (flagged as an assumption) Per account; re-valued on arrival The Australian row is marked as an assumption in the code. Australian rules let you identify which parcel you sold, so FIFO is a default, not the law. The UK matching rules are a good example of why the order of operations matters. Same-day acquisitions are matched first for every sale, and only then is each sale, in date order, matched against acquisitions in the following 30 days: // Same-day acquisitions first, for every sale (s.105(1)); then, sale by // sale in date order, the next `days` days, earliest first (s.106A(5)). for _, i := range sales { match(i, DisposalSameDay, func(d, sale time.Time) bool { return d.Equal(sale) }) } for _, i := range sales { match(i, DisposalThirtyDay, func(d, sale time.Time) bool { return d.After(sale) && !d.After(sale.AddDate(0, 0, days)) }) } Combine the two loops into one and you get a different answer whenever two sales fall close together. Unknown cost is never zero If you bought shares before the first statement you uploaded, the engine doesn't know what you paid. Showing $0 would make the whole sale proceeds look like a gain. Showing a plausible-looking guess is worse. So unknown cost has a type, and every unknown carries a reason: opening_balance, history_gap, transferred_in, spin_off_allocation, selection_mismatch and a few more. The screens show "unknown, because..." instead of a number. A test named TestHeldCosts_UnknownNeverZero keeps it that way. Opening balances: only the excess becomes a lot Say a statement opens with "you hold 120 shares", and later the user uploads the year before it, which contains buys of 100 shares. The opening balance must not add another 120. Only the 20 shares the earlier history can't explain become an opening lot, with unknown cost: func ReconcileOpenings(rows []CostLedgerRow) []CostLedgerRow { held := map[string]float64{} out := make([]CostLedgerRow, 0, len(rows)) for _, r := range rows { switch { case r.Opening: excess := r.Qty - held[r.Ticker] if excess <= 1e-9 { continue // earlier trades already explain this holding } r.Qty = excess held[r.Ticker] += excess case r.Type == contributionsentity.TypeSplit: held[r.Ticker] *= r.Ratio case r.Type == contributionsentity.TypeSell: held[r.Ticker] = math.Max(0, held[r.Ticker]-r.Qty) case r.Type == TypeACBAdjust: // cost-only adjustment, quantity unchanged default: held[r.Ticker] += r.Qty } out = append(out, r) } return out } 4. FX: fix the rate on the row Rates come from several sources: the broker's own rate printed in the statement, ECB reference rates, the Bank of Canada for Canadian tax, currency pegs, and a separate source for the one currency the ECB doesn't publish. The rules: Use the rate for the date of the event. That means the trade date for trades, the payment date for dividends, and the settlement date for IBKR cash lines. Weekend dates use Friday's fixing. Convert through USD, so the engine needs one rate per currency per day rather than one per pair. Freeze the rate on the row. The rate, its date and its source are written onto the transaction when it is recorded, with the broker's own rate taking priority. If no rate is available yet, the row is stored without one and a scheduled job fills it in later. Historical figures therefore don't move when a rate provider revises its data. No rate, no number. If a rate was never published for that day, the engine doesn't borrow a neighbouring day's. That last rule comes from a real bug. In August, a dividend projection summed euro and dollar amounts as if both were dollars. Nothing crashed and the number looked reasonable. It was just wrong. The fix was a dedicated "rate unavailable" error that travels up to the screen as "we can't show this yet", instead of a converted-ish figure. Canadian tax is stricter. The Canada Revenue Agency expects the Bank of Canada rate for the transaction date. The code separates two situations that look alike but aren't. A legitimate fallback, where the Bank doesn't cover that currency or the date is before its series starts, may use the ECB rate, and the result is labelled as a fallback. An outage, where the Bank's rate exists but couldn't be read just now, is not a reason to substitute anything. In simplified form: cadPer, rateDay, source, err := uc.bocRate(ctx, foreign, day) if err == nil { return amount.Mul(cadPer), TaxRate{Source: source, RateDay: rateDay}, nil } var reason string switch { case errors.Is(err, errBoCNotConfigured): reason = TaxFXFallbackNotConfigured case errors.Is(err, errBoCBeforeSeries): reason = TaxFXFallbackBeforeSeries case errors.Is(err, errBoCNotCovered): reason = TaxFXFallbackCurrency default: // The Bank's rate exists but couldn't be read right now. // An outage is not a fallback: the figure stays unknown. return decimal.Zero, TaxRate{}, err } v, d, ferr := uc.ConvertOn(ctx, amount, from, to, day) if ferr != nil { return decimal.Zero, TaxRate{}, ferr } return v, TaxRate{Source: fxReferenceSource(foreign), RateDay: d, Fallback: reason}, nil The version of the rate data is also part of the cache key for tax calculations, so a change in rate policy invalidates old results instead of mixing with them. 5. Corporate actions To be upfront: there is no market-wide corporate actions feed in this engine. Splits come only from statements and account feeds. When several accounts report the same split within seven days, they are merged into one event. Some things are handled automatically: Ticker changes. The same ISIN appearing under a new ticker is renamed, not treated as a sale and a new buy. Transfers between brokers. A transfer out and a transfer in are paired when they have the same ISIN and quantity, are in different accounts and are no more than ten days apart. If two candidates match equally well, no pair is made and a human decides. A wrong automatic pairing is harder to spot than a missing one. Other actions are entered by an adviser, because statements don't describe them reliably enough: An exchange with a ratio (for example, 1 old share for 1.5 new) keeps the original acquisition dates and cost. A spin-off requires a cost allocation for each tax system. If no allocation is entered, the cost of the new shares is unknown, not zero. A cash payment received as part of an exchange makes the cost unknown until someone resolves it. Each of these has a replay test built from a realistic scenario: a Schwab-to-Pershing transfer, a 1-for-1.5 share exchange, an 80/20 spin-off and specific-lot identification. 6. Dividends and withholding In uploaded statements, income rows aren't written to the ledger at all. They are used only as evidence when deciding whether a buy was a reinvested dividend or new money. For account feeds, withholding is matched to income in a fixed order: the same transaction; the nearest income in the same security and currency within seven days; an existing record from the platform. If nothing matches, the withholding stays unmatched and becomes an exception. If the broker doesn't report withholding, the field is nil, not 0. "Nothing was withheld" and "we don't know what was withheld" are different facts and lead to different tax outcomes. The bug here was mundane and instructive. The same withholding figure was calculated in more than one place, and the screens disagreed with one another, both on the weighted average withholding rate and on the net figure for an Irish-domiciled fund. Each calculation was reasonable on its own. The fix was one function used by every screen: US securities: the treaty rate for the investor's tax residence, or zero for US persons. Germany, France, Switzerland, the Netherlands, Spain and Italy: rate tables with cited sources. Securities from the investor's own country, and non-US funds: zero. Everything else: unknown, with no net figure shown. The foreign tax credit is capped at the smallest of three amounts: what was actually withheld, the treaty rate, and the home-country tax on that income. 7. Reconciliation: check against the broker, not against yourself The replayed ledger is checked against what the broker says the account holds: On import, each position is compared with the replayed ledger to within 1e-4 shares. A sale with no earlier purchase marks the ledger as incomplete, and that blocks money-weighted return (see below). On tax screens, a gap larger than 1e-6 sets history_gap, and cost basis isn't printed. For feeds, an account that matches with no open exceptions is confirmed automatically. Otherwise one position_mismatch exception is raised for the account, and it closes itself once the positions match again. 8. Performance: refuse rather than invent Money-weighted return (XIRR) uses Newton's method and falls back to bisection, on an actual/365 basis. It is shown only when the ledger is complete. With missing history, the cash flows are wrong, and an IRR on wrong cash flows can't be trusted. There is a test specifically for a large loss still converging, because Newton's method tends to fail exactly there. Time-weighted return (TWR) chains Modified Dietz periods between known valuations. If cash moves inside a sub-period, the result is labelled approximate. When TWR can't be computed it says why: flows before the first valuation, no valuations, or too short a period. Combining accounts is where interpolation is most tempting. The combined series includes only days on which every account that has started has a valuation. An account that hasn't started yet counts as zero. A day on which a started account has no valuation is skipped, never interpolated. Monthly snapshots are rebuilt by replaying the ledger. Valuations created on contribution dates are marked as flow valuations and kept off the chart, so a deposit doesn't show up as growth. 9. The pipeline The API accepts an upload and publishes a statement_uploaded event to Kafka (Redpanda). A consumer with three workers processes the statement: positions are synced, and transactions go through the converters first and the model second. The output is pending rows and a review. Confirmation publishes contributions_confirmed, which triggers the backfills: rates, snapshots and dividends. Scheduled jobs handle rate backfills, broker syncs, platform feeds, dividends and snapshots. Postgres holds transactions and file fingerprints, ClickHouse holds dividend history and processing statistics, and Redis caches quotes and rates (with request coalescing, so a hundred requests for the same day's rate become one fetch). The model is called only from the consumer, never from the request path. A design I reversed: stop fetching the whole world My first version of quotes was a cron job that ran every five minutes and fetched prices for every security in the reference catalogue, whether anyone held it or not. The reasoning was latency: I didn't want a user to wait even a second for a quote when they opened a screen. It ran straight into the data provider's rate limits. A catalogue that covers 67 exchanges is mostly securities nobody holds, so almost the entire request budget went on prices no one would ever look at. Now quotes are fetched only for securities that someone actually holds, and cached in Redis with a TTL. A quote that isn't cached yet is fetched on demand, which turned out to be fast, and after that it is served from the cache. The lesson I took from it: prefetch what you know someone needs, not everything someone might need. Precomputing the whole universe is a latency optimisation paid for out of someone else's quota. 10. What isn't solved yet A design write-up that lists only the good parts isn't much use, so here are the gaps: The lot replay uses float64. Postgres stores NUMERIC, and currency conversion and net tax use a decimal type, but the replay and the return calculations don't. Rounding happens at the edges (cents for money, 1e-6 for share counts). It is a known debt, and moving the replay to decimal is on the list. No wash-sale rule (US §1091), no cash in lieu, and spin-offs reported by account feeds become exceptions instead of being processed. Withholding reversals and corrections in uploaded statements aren't handled separately. The test fixtures are public sample exports from open-source projects (Export-To-Ghostfolio, Apache-2.0; capital-gains-calculator, MIT), not real client statements. Two converters were built from synthetic samples and still need checking against real exports. The rules, in short Unknown is not zero. Give it a type and a reason, and show the reason. Fix the exchange rate on the date of the event, store it with its source, and never fill a gap with a neighbouring day. One formula for every screen. If two screens can disagree, eventually they will. Deduplicate by content, not by file name, and use multisets so real duplicate trades survive. Don't mix countries' rules. Lot methods, rate sources and withholding are per tax system, with sources cited in the code. Let the model handle only what the parsers can't, and never let it decide anything that changes what the ledger means.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.