Skip to content

About

Multi-currency group consolidation in DuckDB SQL whose CTA is proved analytically rather than plugged, with intercompany differences split into FX, timing and amount errors.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

groupclose

CI

groupclose

groupclose consolidates a five-entity, multi-currency group (a US parent with UK, German, Indian and Canadian subsidiaries) in layered DuckDB SQL. It translates each local trial balance to USD under the current-rate method, computes the cumulative translation adjustment (CTA) twice, once as the balancing figure and once analytically from opening net assets, income and dividends, and requires the two to agree to the cent for every entity and month. Intercompany documents are paired and each difference is split into an FX part, a timing error or an amount error, so only genuine booking mistakes surface as close issues. All data is synthetic and generated by a seeded script in this repository.

The problem

A mid-market engineering services group closes monthly in spreadsheets. Each entity's trial balance is in local currency, translation is done by hand, intercompany balances never agree between the two sides, and the CTA is whatever number makes the balance sheet balance. When auditors ask for a CTA roll-forward, or for the cause of an intercompany difference, nobody can produce one. A plugged CTA also hides translation errors: a wrong rate or a mistyped dividend moves the plug, and the balance sheet still balances.

How it works

flowchart TD
    A[Entity trial balances<br/>in local currency] --> B[20 mapping<br/>local to group accounts]
    B --> C[30 translation<br/>closing, average and historical rates<br/>dividends at spot, retained earnings rolled in USD]
    C --> D[40 CTA<br/>balancing figure and analytic roll-forward]
    L[IC document lines] --> E[50 IC match<br/>pair by document, classify<br/>fx, timing, amount]
    C --> F[60 eliminations<br/>IC balances, IC P&L, dividends, investment]
    E --> F
    D --> G[70 consolidated<br/>TB, BS, IS, CTA roll-forward]
    F --> G
    G --> H{Assertions<br/>zero rows = pass}
    H -->|all pass| I[Consolidated BS and IS CSVs<br/>and close memo]
    H -->|any fail| J[Exit code 1<br/>offending rows printed]
Loading

The SQL lives in sql/ and runs in filename order on an in-process DuckDB, with every amount held as DECIMAL so nothing is rounded until reporting. The assertion queries in sql/assertions/ each return the offending rows; zero rows is a pass.

Translation (layer 30) uses closing rates for assets and liabilities, the historical rate for share capital, each month's average rate for that month's P&L, the declaration-date spot rate for dividends, and rolls retained earnings forward in USD. The CTA movement for a month is

opening net assets (LC) x (closing - prior closing)
+ net income (LC)       x (closing - average)
- dividends (LC)        x (closing - spot)

and its sum from the opening balance must equal the balancing figure of the translated trial balance. The consolidated statements use the analytic figure.

Intercompany (layers 50 and 60): the parent invoices each subsidiary a monthly fee in USD, left unsettled. A subsidiary books at the transaction-date spot and remeasures the USD payable at each month-end. Each document is classified timing (the two sides book it in different months), amount (transaction amounts disagree) or fx (amounts agree and the USD difference comes from booking at spot but translating at the average). The document difference is then split into a booking part (timing or amount, parked in IC_SUSPENSE on the balance sheet and shown in IC_BOOKING_DIFF in the P&L) and an FX part (IC_FX_DIFF in the P&L, which also absorbs the remeasurement of the USD balances).

Quick start

uv venv --python 3.12 .venv   # any Python 3.11+ works
uv pip install --python .venv/bin/python -e ".[dev]"

.venv/bin/groupclose generate --seed 7 --out data       # inputs and truth.json
.venv/bin/groupclose run --data data                    # layers, then assertions
.venv/bin/groupclose cta --data data --month 2025-06    # CTA roll-forward per entity
.venv/bin/groupclose ic --data data --month 2025-10     # intercompany reconciliation
.venv/bin/groupclose report --data data --out out       # BS and IS CSVs, close memo

# the unmapped-account scenario
.venv/bin/groupclose generate --scenario unmapped --out data_unmapped
.venv/bin/groupclose run --data data_unmapped                    # exits 1, names IN / 6199
.venv/bin/groupclose run --data data_unmapped --allow-unmapped   # posts to SUSPENSE, lists 6199

pip install -e ".[dev]" followed by the groupclose command works the same way without uv.

Example output

Real output on the seeded data (--seed 7). Amounts are USD; the CTA is credit-positive.

Assertions (groupclose run):

assertion                                result  offending_rows
---------------------------------------  ------  --------------
tb_balances_lc                           PASS                 0
mapping_complete                         PASS                 0
opening_equity_balances                  PASS                 0
translated_tb_balances                   PASS                 0
cta_analytic_equals_balancing            PASS                 0
eliminations_net_zero                    PASS                 0
consolidated_bs_balances                 PASS                 0
ic_suspense_matches_booking_differences  PASS                 0

all assertions passed

CTA roll-forward, June 2025 (groupclose cta --month 2025-06):

entity      opening  net_asset_effect  income_effect  dividend_effect      closing
------  -----------  ----------------  -------------  ---------------  -----------
CA      -168,541.26        -63,375.20      -1,105.56             0.00  -233,022.02
DE      -476,650.84        -78,587.91      -1,688.30             0.00  -556,927.05
IN      -129,244.07        -38,106.90        -785.64             0.00  -168,136.61
UK       307,700.39       -251,343.83      -7,909.63             0.00    48,446.93
GROUP   -466,735.78       -431,413.84     -11,489.13             0.00  -909,638.75

December 2024, the month UK declares its dividend (--month 2024-12):

entity      opening  net_asset_effect  income_effect  dividend_effect      closing
------  -----------  ----------------  -------------  ---------------  -----------
CA      -195,963.50         -8,683.88        -230.43             0.00  -204,877.81
DE      -271,693.17        -78,871.32      -1,733.09             0.00  -352,297.57
IN      -207,550.39           -998.02         -14.90             0.00  -208,563.31
UK       240,056.92         13,249.13         320.22        -1,726.50   251,899.77
GROUP   -435,150.13        -75,304.09      -1,658.20        -1,726.50  -513,838.92

Intercompany reconciliation, October 2025 (groupclose ic --month 2025-10). Differences are seller minus buyer. The UK document is booked by UK in November, so it is a timing difference; its FX part appears in November. REMEASUREMENT rows are the subsidiary's month-end remeasurement of its USD balances.

entity  counterparty  ic_doc_id       classification  seller_usd   buyer_usd  difference_usd  note
------  ------------  --------------  --------------  ----------  ----------  --------------  --------------------------------------
CA      US            FEE-2025-10-CA  fx               35,000.00   35,011.25          -11.25  booked at spot, translated at average
CA      US            REMEASUREMENT   fx                    0.00   -4,144.81        4,144.81  USD balance remeasured at closing rate
DE      US            FEE-2025-10-DE  fx               50,000.00   50,114.12         -114.12  booked at spot, translated at average
DE      US            REMEASUREMENT   fx                    0.00  -16,685.63       16,685.63  USD balance remeasured at closing rate
IN      US            FEE-2025-10-IN  fx               40,000.00   39,949.77           50.23  booked at spot, translated at average
IN      US            INT-2025-10-IN  fx               15,000.00   14,923.69           76.31  booked at spot, translated at average
IN      US            REMEASUREMENT   fx                    0.00  -38,188.77       38,188.77  USD balance remeasured at closing rate
UK      US            FEE-2025-10-UK  timing           55,000.00        0.00       55,000.00  booked by buyer in 2025-11
UK      US            REMEASUREMENT   fx                    0.00   61,749.12      -61,749.12  USD balance remeasured at closing rate

classification  rows  difference_usd
--------------  ----  --------------
fx                 8       -2,728.73
timing             1       55,000.00

Consolidated balance sheet summary, December 2025 (from the close memo written by groupclose report):

section                    usd
-------------------------  --------------
Current assets             76,279,133.72
Non-current assets          1,973,359.97
Current liabilities        11,934,115.29
Non-current liabilities     2,984,147.46
Equity                     63,334,230.93

total_assets   total_liabilities   total_equity   difference
78,252,493.69  14,918,262.75       63,334,230.93  0.00

The memo also lists the two close issues found over the two years: the DE amount error in March 2025 (FEE-2025-03-DE, USD 45,000.00, still in IC_SUSPENSE at December) and the UK timing difference in October 2025 (FEE-2025-10-UK, USD 55,000.00, reversed in November).

Design decisions

  • Exact arithmetic, no plug. Rates have six decimals, amounts two, and every product is a DECIMAL that is never rounded in SQL, so the analytic CTA equals the balancing CTA exactly rather than approximately. The opening balances in the generator are multiples of 10,000 local units so that the opening translated equity is exact to the cent too. The cost is that the generated opening data is stylised; a real opening position would carry a sub-cent residual and need the $0.01 tolerance the assertion allows.
  • Two CTA computations, one used. The consolidated statements take the analytic CTA, which makes the balance-sheet check a real test; the balancing figure is the control. If a dividend is translated at the wrong rate, a rate is wrong in one place, or the opening CTA is mistyped, the two diverge and cta_analytic_equals_balancing names the entity and month. The trade-off is that the analytic formula needs net assets, income and dividends in local currency to be consistent with the ledger, which is exactly what it is meant to check.
  • Booking differences and FX differences are separate account families. Timing and amount errors are balance-sheet items in IC_SUSPENSE (cumulative, so a timing error returns to zero when the buyer books the document and an amount error stays) and flow through the P&L as IC_BOOKING_DIFF, so the reported group result visibly carries the distortion. FX differences go to IC_FX_DIFF. Keeping them apart means the FX line is never a dumping ground for errors, at the price of two extra consolidation accounts.
  • Eliminations are built from the ledger and balanced from the documents. Removal lines come from the translated trial balances; the balancing lines come from the document reconciliation built from ic_lines. If the document lines and the ledger disagree, the elimination does not net to zero and the assertion fails. The balance-sheet leg is the exception: its residual goes straight to IC_SUSPENSE, and a separate assertion compares it with the document-based booking balance within $0.05, the allowance for rounding remeasured balances to two decimals.
  • SQL layers and assertion queries instead of dbt. Plain numbered files run by a small runner keep the dependency set to DuckDB, sqlglot, pandas and typer, and every file parses in a test. The cost is no lineage graph and no incremental builds, which does not matter at this size.
  • Scope limits. Intercompany transaction amounts are assumed to be in the seller's currency (USD), one retained-earnings account per entity, one dividend per entity-month at a single spot rate, and a two-level group (a parent and wholly owned subsidiaries, no goodwill).

Testing

.venv/bin/python -m pytest -q

The 60 tests check the generator (balanced trial balances, deterministic output, FX paths, opening equity exact to the cent), a hand-computed fixture (USD parent, EUR subsidiary, two months, with and without a dividend), the CTA proof and roll-forward continuity for all 120 entity-months, the intercompany classification against truth.json (one timing, one amount, every other row fx within $1) (truth.json is derived from the generator's own flows, the same decomposition the SQL applies, so this checks consistency, not independent truth), eliminations and the consolidated balance sheet for all 24 months, the unmapped-account scenario through the CLI, sqlglot parsing of every SQL file, and byte-identical output across two runs. One test deliberately corrupts the opening CTA and expects the proof to fail for that entity.

Project layout

sql/
  10_staging_masters.sql   entities, charts, mapping, FX rates, calendar
  11_staging_ledger.sql    trial balances, opening equity, dividends
  12_staging_ic.sql        intercompany document lines
  20_mapping.sql           local to group accounts, unmapped handling
  30_translation.sql       current-rate translation, retained earnings roll
  40_cta.sql               balancing and analytic CTA, roll-forward
  50_ic_match.sql          document pairing and classification
  60_eliminations.sql      IC, dividend and investment eliminations
  70_consolidated.sql      consolidated TB, BS, IS, CTA roll-forward
  assertions/              eight queries; zero rows = pass
src/groupclose/
  chart.py                 group and local charts, entity parameters
  fx.py                    seeded closing, average and spot rates
  ledger.py                double-entry ledger in integer cents
  generate.py              seeded books, intercompany documents, truth.json
  runner.py                layer and assertion runner on DuckDB
  reports.py               tables, CSV exports, close memo
  cli.py                   generate, run, cta, ic, report
tests/                     60 tests and a hand-sized fixture

License

MIT, see LICENSE.

About

Multi-currency group consolidation in DuckDB SQL whose CTA is proved analytically rather than plugged, with intercompany differences split into FX, timing and amount errors.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages