Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 29 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ A modern, ESM-only TypeScript library that turns a DEGIRO account statement into

- 🧮 **Exact money** with [`big.js`](https://github.com/MikeMcl/big.js) — no float drift
- 🧩 **Extensible** dialects, classifiers and grouping strategies
- 🌐 **French and English exports** out of the box, and a layout-detecting fallback for every other language
- 🌐 **French, English, Dutch, German and Spanish exports** out of the box, Italian, Czech and Portuguese descriptions too, and a layout-detecting fallback for every other language
- 🧠 **Typed domain model** — discriminated unions for movements & transactions
- 🪶 **Lenient parsing** — per-row problems are collected, never thrown
- 🌊 **Streaming** parser for very large files
Expand Down Expand Up @@ -111,26 +111,35 @@ Parsing is **lenient**: a row with an unparseable date is dropped and reported a

## Supported exports

DEGIRO localizes the **header row** of `Account.csv` to the interface language. Two dialects recognise a header by its words, and a third recognises the file by its shape when neither does:
DEGIRO localizes the **header row** of `Account.csv` to the interface language. Five dialects recognise a header by its words, and a sixth recognises the file by its shape when none does:

| Dialect | `id` | Header |
| ---------------- | --------- | --------------------------------------------------------------------------------- |
| `frenchDialect` | `fr` | `Date,Heure,Date de,Produit,Code ISIN,Description,FX,Mouvements,,Solde,,ID Ordre` |
| `englishDialect` | `en` | `Date,Time,Value date,Product,ISIN,Description,FX,Change,,Balance,,Order Id` |
| `genericDialect` | `generic` | any header in DEGIRO's column layout, whatever the labels say |
| Dialect | `id` | Header |
| ---------------- | --------- | ---------------------------------------------------------------------------------------------- |
| `frenchDialect` | `fr` | `Date,Heure,Date de,Produit,Code ISIN,Description,FX,Mouvements,,Solde,,ID Ordre` |
| `englishDialect` | `en` | `Date,Time,Value date,Product,ISIN,Description,FX,Change,,Balance,,Order Id` |
| `dutchDialect` | `nl` | `Datum,Tijd,Valutadatum,Product,ISIN,Omschrijving,FX,Mutatie,,Saldo,,Order Id` |
| `germanDialect` | `de` | `Datum,Uhrzeit,Wertstellungsdatum,Produkt,ISIN,Beschreibung,FX,Änderung,,Saldo,,Auftrag ID` |
| `spanishDialect` | `es` | `Fecha,Hora,Fecha valor,Producto,ISIN,Descripción,Tipo,Variación,,Saldo,,ID Orden` |
| `genericDialect` | `generic` | any header in DEGIRO's column layout, whatever the labels say |

All three share the positional column layout, and the two language-aware ones share `DD-MM-YYYY` dates. They differ in how they read numbers: `frenchDialect` expects space thousands separators and a comma decimal mark, while `englishDialect` accepts either that or the US `1,060.20` form — DEGIRO does **not** switch the body of the file to English number formatting when you switch the interface language, so an English export can carry either. When a value contains both `,` and `.`, the last one is the decimal mark; a lone separator is a decimal mark unless the value is a run of exact 3-digit groups (`1,060,200`).
All six share the positional column layout, and the five language-aware ones share `DD-MM-YYYY` dates. They differ in how they read numbers: `frenchDialect` expects space thousands separators and a comma decimal mark, while the English, Dutch, German and Spanish dialects accept either that or the US `1,060.20` form — DEGIRO does **not** switch the body of the file to another number format when you switch the interface language, so an export can carry either. `dutchDialect` also accepts the header variant that says `Beschrijving` and `Order ID`. When a value contains both `,` and `.`, the last one is the decimal mark; a lone separator is a decimal mark unless the value is a run of exact 3-digit groups (`1,060,200`).

Descriptions are a separate axis: switching the interface language rewrites the header but leaves the description text alone, so an English-header export from a French account still says `Frais DEGIRO de courtage`. The built-in matchers therefore recognise both languages regardless of which dialect read the header. Anything they do not recognise becomes an `unknown` movement — never a dropped row.
Descriptions are a separate axis: switching the interface language rewrites the header but leaves the description text alone, so an English-header export from a French account still says `Frais DEGIRO de courtage`. The built-in matchers therefore recognise French, English, Dutch, German, Spanish, Italian, Czech and Portuguese wordings regardless of which dialect read the header. Anything they do not recognise becomes an `unknown` movement — never a dropped row.

A few wordings need more than a lookup:

- Dutch `Koop 15 @ 76,50 EUR` and German `Kauf 1 zu je 211 USD (US88160R1014)` name no product, and the Dutch form no ISIN either. The trade takes them from the row's `Product` and `ISIN` columns, and is only a trade when one of the two carries an ISIN.
- Czech calls both legs of a currency conversion `FX vyúčtování konverze měny`, so the sign of the amount decides between `fxCredit` and `fxDebit`.
- Rows that would need a new movement kind stay `unknown`: money-market fund price changes and conversions, corporate actions (splits, ISIN changes, delistings), promotions, transaction taxes, other fees (ADR/GDR, SOFORT, corporate-action fees), bond coupons and accrued interest, payments in lieu of a dividend, and deposit reservations.

### The fallback, for every other language

DEGIRO's column layout is the same in every language: twelve columns, where the mutation and the balance each pair a currency cell with an amount cell under a single header label — so the 9th and 11th header cells (0-based indices 8 and 10) are always empty. `genericDialect` recognises that shape and nothing else, reading no header text at all, and interprets dates (`DD-MM-YYYY`, `DD/MM/YYYY`, `YYYY-MM-DD`) and numbers by the same per-value rules as the English dialect. It is registered last, so a French or English export never reaches it.
DEGIRO's column layout is the same in every language: twelve columns, where the mutation and the balance each pair a currency cell with an amount cell under a single header label — so the 9th and 11th header cells (0-based indices 8 and 10) are always empty. `genericDialect` recognises that shape and nothing else, reading no header text at all, and interprets dates (`DD-MM-YYYY`, `DD/MM/YYYY`, `YYYY-MM-DD`) and numbers by the same per-value rules as the English dialect. It is registered last, so an export one of the language-aware dialects recognises never reaches it.

Because it is a guess, it says so: `dialect.heuristic` is `true` and a warning lands on `ParseResult.warnings` naming the line it was decided on. Nothing silently depends on it.

```ts
const result = parseDegiroCsv(dutchCsv);
const result = parseDegiroCsv(italianCsv);
result.dialect.id; // 'generic'
result.dialect.heuristic; // true
result.warnings[0].message; // 'No dialect recognised this header, so the "generic" fallback ...'
Expand All @@ -139,7 +148,7 @@ result.warnings[0].message; // 'No dialect recognised this header, so the "gener
Two smaller guesses ride along:

- If the header tokenizes to a single cell, `parseDegiroCsv` retries with `;` and then a tab before giving up. Passing `delimiter` explicitly turns this off.
- `structuralTradeMatcher` and `structuralFxTradeMatcher` recover trades from the _shape_ of a description — `<qty> <product>@<price> <CCY> (<ISIN>)` — and take the side from the sign of the mutation, money out being a buy. Both run at a negative priority, after every language-aware matcher has declined, so `Koop 1.060 SMI ETF@106,02 CHF (CH0019852802)` classifies as a buy without anyone teaching the library Dutch.
- `structuralTradeMatcher` and `structuralFxTradeMatcher` recover trades from the _shape_ of a description — `<qty> <product>@<price> <CCY> (<ISIN>)` — and take the side from the sign of the mutation, money out being a buy. Both run at a negative priority, after every language-aware matcher has declined, so `Acquisto 1.060 SMI ETF@106,02 CHF (CH0019852802)` classifies as a buy without anyone teaching the library the Italian verb.

Descriptions with no such shape — a dividend, a fee, a deposit in a language the matchers do not know — stay `unknown` with their amounts intact, so balances still reconcile and cash still adds up. Register a matcher for the wording to name them.

Expand Down Expand Up @@ -298,16 +307,16 @@ Every stage is pluggable. You rarely need to fork the library to support a new e

### Custom dialect (new locale / layout)

French and English are built in; here is a third locale — Dutch headers, dot thousands, comma decimals:
Five header languages are built in; here is a sixth — Italian headers, dot thousands, comma decimals:

```ts
import { parseDegiroCsv, DEGIRO_COLUMNS, parseDegiroDateTime, type Dialect } from 'libdegiro';

const dutchDialect: Dialect = {
id: 'nl',
label: 'DEGIRO Dutch',
const italianDialect: Dialect = {
id: 'it',
label: 'DEGIRO Italian',
columns: DEGIRO_COLUMNS, // the shared positional layout
matches: (header) => header.includes('Omschrijving') && header.includes('Mutatie'),
matches: (header) => header.includes('Descrizione') && header.includes('Variazioni'),
parseDecimal: (raw) => {
const n = raw.trim().replace(/\./g, '').replace(',', '.'); // 1.060,20
return /^-?\d+(\.\d+)?$/.test(n) ? n : null;
Expand All @@ -316,12 +325,12 @@ const dutchDialect: Dialect = {
parseDate: (d) => parseDegiroDateTime(d),
};

parseDegiroCsv(csv, { dialects: [dutchDialect] });
parseDegiroCsv(csv, { dialects: [italianDialect] });
// or force it, skipping detection:
parseDegiroCsv(csv, { dialect: dutchDialect });
parseDegiroCsv(csv, { dialect: italianDialect });
```

A dialect registered through `dialects` replaces the built-ins, including the fallback; pass `createDefaultDialectRegistry().register(dutchDialect, { prepend: true })` to keep them.
A dialect registered through `dialects` replaces the built-ins, including the fallback; pass `createDefaultDialectRegistry().register(italianDialect, { prepend: true })` to keep them.

### Custom classifier (new movement description)

Expand Down
3 changes: 2 additions & 1 deletion examples/dashboard/src/components/dropzone.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export function Dropzone() {
<div className="space-y-1">
<p className="font-medium">Drop your DEGIRO Account.csv here</p>
<p className="text-muted-foreground text-sm">
English and French statements are both recognised.
French, English, Dutch, German and Spanish headers are recognised, and
other languages by their column layout.
</p>
</div>

Expand Down
8 changes: 4 additions & 4 deletions examples/dashboard/test/positions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,12 +208,12 @@ describe('describeHealthProblems', () => {
})

it('warns when the layout fallback read the file, ahead of any rounding note', () => {
const dutchCsv = [
'Datum,Tijd,Valutadatum,Product,ISIN,Omschrijving,FX,Mutatie,,Saldo,,Order Id',
'18-11-2024,00:00,18-11-2024,,,Storting,,CHF,"9.000,00",CHF,"9.000,00",',
const italianCsv = [
'Data,Ora,Data Valore,Prodotto,ISIN,Descrizione,Borsa,Variazioni,,Saldo,,ID Ordine',
'18-11-2024,00:00,18-11-2024,,,Deposito,,CHF,"9.000,00",CHF,"9.000,00",',
'',
].join('\n')
const parsed = parseDegiroCsv(dutchCsv)
const parsed = parseDegiroCsv(italianCsv)
const report = withDiscrepancies(buildHealthReport(parsed, 0), [
discrepancy('rounding', '-0.01'),
])
Expand Down
101 changes: 70 additions & 31 deletions src/classify/descriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { Money } from '../money/money'
/** Leading quantity: digits, then any number of grouped thousands. */
const LEADING_QTY = /^[0-9]+(?:[ .,\u00a0\u202f][0-9]{3})*/
const QTY_GROUPING = /[ .,\u00a0\u202f]/g
/** `Achat|Vente|Buy|Sell` and the whitespace that follows it. */
const TRADE_VERB = /^(Achat|Vente|Buy|Sell)\s+/i
const BUY_SIDE = /^(achat|buy)$/i
/** `Achat|Vente|Buy|Sell|Koop|Verkoop|Kauf|Verkauf` and the whitespace that follows it. */
const TRADE_VERB = /^(Achat|Vente|Buy|Sell|Koop|Verkoop|Kauf|Verkauf)\s+/i
const BUY_SIDE = /^(achat|buy|koop|kauf)$/i
const UNLABELLED_PRICE_SEPARATORS = ['@'] as const
/** German trades read `Kauf 1 zu je 211 USD`. */
const LABELLED_PRICE_SEPARATORS = ['@', ' zu je '] as const
const CURRENCY = /^[A-Za-z]{3}$/
const DIGIT = /[0-9]/
const TRAILING_SPACE = /\s$/
Expand All @@ -15,9 +18,11 @@ const FX_SETTLEMENT_PREFIX =
/^(?:R[èe]glement transaction devise|(?:Currency|FX)\s+(?:transaction\s+)?settlement)\s*:\s*/i
/** Currency pair such as `EUR/CHF`. */
const FX_PAIR = /^[A-Za-z]{3}\/[A-Za-z]{3}$/
/** `Virement|Transfer|Deposit|Withdrawal vers|depuis|to|from ...`, up to the colon. */
const CASH_TRANSFER = /^(?:Virement|Transfer|Deposit|Withdrawal)\s+(vers|depuis|to|from)\b/i
const TO_CASH_ACCOUNT = /^(vers|to)$/i
const TO_CASH_ACCOUNT =
/^(?:(?:virement|transfer|deposit|withdrawal)\s+(?:vers|to)|overboeking\s+naar|überweisung\s+auf|transferir\s+a|trasferisci\s+sul)\b/i
const FROM_CASH_ACCOUNT =
/^(?:(?:virement|transfer|deposit|withdrawal)\s+(?:depuis|from)|overboeking\s+van|auszahlung\s+von|transferir\s+desde|trasferisci\s+dal)\b/i
const AMOUNT_CHAR = /[0-9.,\s]/

/** Parse a localized integer quantity (with space thousands separators). */
export function parseQuantity(raw: string, dialect: Dialect): number | null {
Expand Down Expand Up @@ -55,48 +60,68 @@ function splitTrailingCurrency(text: string): { head: string, currency: string }
function parsePriceTail(
priceTail: string,
dialect: Dialect,
isinRequired: boolean,
): { unitPrice: Money | null, isin: string | null } {
const trimmed = priceTail.trim()
const open = trimmed.lastIndexOf('(')
if (open < 0 || !trimmed.endsWith(')')) {
const hasIsin = open >= 0 && trimmed.endsWith(')')
if (!hasIsin && isinRequired) {
return { unitPrice: null, isin: null }
}

const priceAndCurrency = splitTrailingCurrency(trimmed.slice(0, open).trim())
const priceAndCurrency = splitTrailingCurrency(hasIsin ? trimmed.slice(0, open).trim() : trimmed)
if (!priceAndCurrency) {
return { unitPrice: null, isin: null }
}

const price = dialect.parseDecimal(priceAndCurrency.head)
return {
unitPrice: price === null ? null : new Money(price, priceAndCurrency.currency),
isin: trimmed.slice(open + 1, -1).trim() || null,
isin: hasIsin ? trimmed.slice(open + 1, -1).trim() || null : null,
}
}

function parseTradeBody(
qtyAndProduct: string,
priceTail: string,
dialect: Dialect,
isinRequired: boolean,
): ParsedTradeShape {
const qtyMatch = LEADING_QTY.exec(qtyAndProduct)
const quantity = qtyMatch ? parseQuantity(qtyMatch[0].replace(QTY_GROUPING, ''), dialect) : null
const rest = qtyMatch ? qtyAndProduct.slice(qtyMatch[0].length) : qtyAndProduct

return { quantity, product: rest.trim() || null, ...parsePriceTail(priceTail, dialect) }
return {
quantity,
product: rest.trim() || null,
...parsePriceTail(priceTail, dialect, isinRequired),
}
}

function splitAtPrice(text: string, from: number): { left: string, right: string } | null {
const at = text.indexOf('@', from)
if (at <= 0 || at === text.length - 1) {
function splitAtPrice(
text: string,
from: number,
separators: readonly string[],
): { left: string, right: string } | null {
let at = -1
let length = 0
for (const separator of separators) {
const index = text.indexOf(separator, from)
if (index >= 0 && (at < 0 || index < at)) {
at = index
length = separator.length
}
}
if (at <= 0 || at + length >= text.length) {
return null
}
return { left: text.slice(from, at), right: text.slice(at + 1) }
return { left: text.slice(from, at), right: text.slice(at + length) }
}

/**
* Parse a trade description such as
* `"Achat 42 iShares Core MSCI World UCITS ETF USD (Acc)@96,11 CHF (IE00B4L5Y983)"`.
* `"Achat 42 iShares Core MSCI World UCITS ETF USD (Acc)@96,11 CHF (IE00B4L5Y983)"`,
* `"Koop 15 @ 76,50 EUR"` or `"Kauf 1 zu je 211 USD (US88160R1014)"`.
* Returns `null` when the text is not a trade.
*/
export function parseTradeDescription(description: string, dialect: Dialect): ParsedTrade | null {
Expand All @@ -106,13 +131,13 @@ export function parseTradeDescription(description: string, dialect: Dialect): Pa
return null
}

const split = splitAtPrice(trimmed, verb[0].length)
const split = splitAtPrice(trimmed, verb[0].length, LABELLED_PRICE_SEPARATORS)
if (!split) {
return null
}

const side = BUY_SIDE.test(verb[1] ?? '') ? 'buy' : 'sell'
return { side, ...parseTradeBody(split.left, split.right, dialect) }
return { side, ...parseTradeBody(split.left, split.right, dialect, false) }
}

export interface ParsedUnlabelledTrade extends ParsedTradeShape {
Expand All @@ -129,14 +154,14 @@ export function parseUnlabelledTradeDescription(
return null
}

const split = splitAtPrice(trimmed, quantity)
const split = splitAtPrice(trimmed, quantity, UNLABELLED_PRICE_SEPARATORS)
if (!split) {
return null
}

return {
prefix: trimmed.slice(0, quantity).trim(),
...parseTradeBody(split.left, split.right, dialect),
...parseTradeBody(split.left, split.right, dialect, true),
}
}

Expand Down Expand Up @@ -184,32 +209,46 @@ export interface ParsedCashTransfer {
readonly amount: Money | null
}

function cashTransferDirection(text: string): ParsedCashTransfer['direction'] | null {
if (TO_CASH_ACCOUNT.test(text)) {
return 'toCashAccount'
}
if (FROM_CASH_ACCOUNT.test(text)) {
return 'fromCashAccount'
}
return null
}

function trailingAmount(text: string): string {
let start = text.length
while (start > 0 && AMOUNT_CHAR.test(text.charAt(start - 1))) {
start -= 1
}
return text.slice(start).trim()
}

/**
* Parse a cash-transfer description such as
* `"Virement depuis votre Compte Espèces à la flatexDEGIRO Bank: 213,25 EUR"`.
* `"Virement depuis votre Compte Espèces à la flatexDEGIRO Bank: 213,25 EUR"`, with
* or without the colon before the amount.
*/
export function parseCashTransferDescription(
description: string,
dialect: Dialect,
): ParsedCashTransfer | null {
const trimmed = description.trim()
const match = CASH_TRANSFER.exec(trimmed)
if (!match) {
return null
}

const colon = trimmed.lastIndexOf(':')
if (colon < 0) {
const direction = cashTransferDirection(trimmed)
if (direction === null) {
return null
}

const stated = splitTrailingCurrency(trimmed.slice(colon + 1).trim())
if (!stated || !DIGIT.test(stated.head.charAt(0))) {
const stated = splitTrailingCurrency(trimmed)
const amountText = stated ? trailingAmount(stated.head) : ''
if (!stated || !DIGIT.test(amountText.charAt(0))) {
return null
}

const direction = TO_CASH_ACCOUNT.test(match[1] ?? '') ? 'toCashAccount' : 'fromCashAccount'
const decimal = dialect.parseDecimal(stated.head)
const decimal = dialect.parseDecimal(amountText)
const amount = decimal === null ? null : new Money(decimal, stated.currency)

return { direction, amount }
Expand Down
Loading
Loading