Metadata-Version: 2.5
Name: tieback
Version: 0.2.1
Summary: Reconcile insurance extracts: join any number of files, correct mistyped keys, find what is wrong, and prove the result ties back to the totals.
Project-URL: Homepage, https://actuariallabs.com
Project-URL: Source, https://github.com/actuariallabs/tieback
Project-URL: Issues, https://github.com/actuariallabs/tieback/issues
Project-URL: Changelog, https://github.com/actuariallabs/tieback/blob/main/CHANGELOG.md
Author: Actuarial Labs
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: actuarial,data-quality,insurance,polars,pricing,reconciliation
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.9
Requires-Dist: numpy>=1.24
Requires-Dist: polars>=1.0
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# tieback

**Reconcile insurance extracts. `tieback` joins any number of files, corrects the mistyped keys the data can vouch for, reports everything else that is wrong, and proves the result ties back to the totals.**

A pricing or reserving project rarely starts from one clean file. It starts from several, produced by systems that were never designed to agree:

| Extract            | Grain                                                    | Policy written as |
| ------------------ | -------------------------------------------------------- | ----------------- |
| Policy admin       | One row per policy **term**                              | `ON-0482113`      |
| Vehicle schedule   | One row per vehicle per term, with the exposure          | `482113`          |
| Claims             | One row per claim per **coverage**, a loss date, no term | `P0482113`        |
| Finance premium    | One row per policy term                                  | `0482113/1`       |
| Driver convictions | One row per conviction, per **policy**, dated            | `0482113`         |

The files also carry the errors real extracts carry: a policy number typed `P0428113`, a vehicle exported twice, a region spelt `Toronto`, `TORONTO` and `Otawa`, a claim reported before the loss, paid above incurred, exposure longer than the term.

A naive join absorbs each of these into the rates without raising an error. `tieback` performs the join, records what it did and why, and lists each problem with the amounts it affects.

```
$ pip install tieback
$ tieback demo sample          # five extracts with the problems real ones have
$ tieback sample/*.csv -o book.parquet --plan plan.json --findings findings.json
```

```
base: vehicles.csv (22,067 rows), exposure EARNED_CAR_YRS

claims.csv  [rollup]  on POLICY_REF = POL_NUM + VEHICLE = UNIT_NO, LOSS_DATE within [TERM_START, TERM_EXP)
    POLICY_REF ↔ POL_NUM: 'P0123423' and '123423' are the same policy once the prefix and leading zeros are dropped.
    claims has no term, only dates: LOSS_DATE between TERM_START and TERM_EXP places each row in one term.
    7 mistyped key values corrected first (9 rows). Chance check: a key that is missing, not mistyped,
    finds a convincing near match 0.5% of the time on this book, so about 0.2 of them could be wrong.
    CLAIM_NO: 2,144 in file = 2,074 attached + 35 no matching key + 35 outside every term + 0 ambiguous  ok
    INCURRED: 31,394,525 in file = 30,315,213 in table + 1,079,312 unattached  ok

premium.csv  [per group]  on GL_POLICY_TERM (part 1) = POL_NUM + BOOKED_FROM = TERM_START
    Each row belongs to a group of 1.49 vehicles rows on average (the rows sharing POL_NUM and TERM_START).
    Split across each group's rows by EARNED_CAR_YRS, so the total still ties: WRITTEN_PREMIUM.
    WRITTEN_PREMIUM: 29,034,341 in file = 29,013,424 in table + 20,917 unattached  ok

exposure: 21,125 in, 21,125 out  ok

findings: 4 errors, 9 to review, 10 fixed
  ERROR   claims.csv has 4 rows that repeat another row exactly.
          affects INCURRED 52,299, PAID 33,787
  ERROR   3 vehicles.csv rows overlap an earlier period of the same POL_NUM and UNIT_NO: exposure counted twice.
  ERROR   2 vehicles.csv rows carry more EARNED_CAR_YRS than their period is long.
  REVIEW  policies.csv.REGION spells 2 values two ways: 'TORONTO' (20) looks like 'Toronto' (3,182); 'Otawa' (5) looks like 'Ottawa' (1,711).
  REVIEW  6 claims.csv rows have PAID above INCURRED.
  REVIEW  3 claims.csv rows were reported before the loss happened (REPORTED_DATE < LOSS_DATE).
  REVIEW  claims.csv.POLICY_REF: 8 values match nothing but sit one character from a real key whose other columns
          and dates fit, and only that one. Not applied: a policy missing from the extract can sit one digit from a real one by chance.
  FIXED   claims.csv.POLICY_REF: 'P9016838' read as 'P0916838' (swapped neighbours; its other keys and dates match only this one).
```

This is real output on the sample book, trimmed: five files, 22,000 exposure rows, about two seconds.

## What it does

### Joins any number of files

`tieback` starts from the file that carries exposure and attaches each other file in the order the data allows.

- **Keys are matched on values, not names.** `POLICY_NO` and `POL_NUM` join because their values overlap. `ON-0482113`, `482113` and `P0482113` are recognised as the same policy.
- **Compound identifiers are split.** `0482113/1` is split into policy and term, and each part is matched.
- **Keys are refined until each row has one partner.** Renewals repeat the policy number, so the key is narrowed by another column, then by a date window: a loss belongs to the term it falls inside.
- **There are three ways to attach.** Attributes look up one row each. Events such as claims roll up, counted once per claim id with amounts summed. Events at a coarser grain than the exposure, such as convictions per policy term or premium per term, attach to the whole group: counts become a per-group attribute, and money is split across the group by exposure so it still sums to the file total.

### Corrects mistyped keys, and reports how far to trust each correction

For each key that matches nothing, `tieback` looks for real keys one keystroke away, of three kinds: case and spacing, swapped neighbours, and one changed character.

- A candidate counts only if the rest of the row supports it: with the corrected number, the claim's vehicle and loss date fall in exactly one term. If two candidates fit, nothing is changed.
- Case, spacing and swapped neighbours are applied by default. A single changed character is listed as a likely correction and applied only with `--repair all`, because a policy missing from the extract often sits one digit from a real one.
- **The chance check.** `tieback` gives real rows random keys that exist nowhere and counts how often they would still be "corrected". That rate, measured on your own book, becomes the expected number of wrong corrections and is printed next to the corrections. If it is too high, none are applied.
- A key that appears in another of your files is a real policy missing from this one, not a typo, and is left alone.

### Reports what else is wrong, with its effect on the numbers

| Check                                 | Why it matters                                     |
| ------------------------------------- | -------------------------------------------------- |
| Rows exported twice                   | Double exposure or double losses                   |
| Overlapping periods for the same unit | Exposure counted twice                             |
| Exposure longer than its period       | Inflated exposure                                  |
| Periods that end before they start    | Broken terms                                       |
| Negative amounts                      | Sign errors, or recoveries to treat on purpose     |
| Paid above incurred                   | Stale reserves or mis-keyed amounts                |
| Reported before the loss date         | Swapped dates that move a claim to the wrong term  |
| One category spelt several ways       | Each spelling becomes its own rating level         |
| Fields that disagree between files    | Which system is the source of truth                |
| Events with no exposure to sit on     | Losses outside the book                            |
| Totals that do not tie to finance     | `--control EARNED_CAR_YRS=21130`                   |

### Accounts for everything

Base rows and exposure are unchanged. Every claim and every dollar is either in the output table or listed as unattached, with its reason.

### Saves its decisions

The plan is a JSON file holding the keys, the windows and every correction. Replay it on next quarter's extracts with `tieback --replay plan.json`, and it lists every row that did not make it in.

## In Python

```python
import tieback

tables = tieback.read(["policies.csv", "vehicles.csv", "claims.csv", "premium.csv", "convictions.csv"])
book, plan = tieback.assemble(tables, controls={"EARNED_CAR_YRS": 21_130})
print(tieback.report(plan))

for f in plan.findings:              # dicts: check, severity, table, column, count, impact, examples, action
    if f["severity"] == "error":
        print(f["message"])

tieback.save_plan(plan, "plan.json")
result = tieback.replay(next_quarter_tables, tieback.load_plan("plan.json"))
```

Options:

- `repair=False` changes no key.
- `repair="all"` also applies single-character corrections.
- `exposure_hints={"vehicles.csv": "EARNED_CAR_YRS"}` names the exposure column if it is not detected.

## What it does not do

- **It does not guess.** Ambiguous keys, ambiguous rows and tables it cannot join are listed with the reason, never forced.
- **It does not change your rating variables.** Misspelt categories are reported with the mapping to use. Applying it is your decision.
- **It does not decide what to do with orphan claims.** Whether losses with no exposure are kept or dropped is an actuarial judgment.
- **It does not send anything anywhere.** No network access and no telemetry: Polars and NumPy, on your machine.

## How we test it

The demo book is generated with every problem above planted, and the tests check `tieback` against what was planted, not against its own report.

Over 30 random books of 300 to 5,000 policies, every book tied: rows, exposure, claim counts and amounts. `tieback` corrected 300 of 449 planted typos, and 3 of the 303 corrections it applied were wrong, against 8.2 the chance check expected. The typos it did not correct were listed as likely typos or as unmatched. A wrong correction is a claim on a missing policy that sits, by chance, one keystroke from a real policy whose vehicle and dates fit.

On a book ten times denser (60,000 policies), coincidental matches are common (12.5%), and `tieback` declined to correct and listed the 41 candidates instead. That is the intended behaviour: on dense numbering, keys and dates alone cannot vouch for a correction.

On a real public book, freMTPL2 (678,013 policies and 26,639 claim rows, French motor), `tieback`'s join matches an independent join exactly: 26,444 claim rows attached for 59,909,216.50, and 195 listed because their policy is not in the file. It takes about 10 seconds.

## Status

Version 0.2, alpha. The API may change before 1.0, and every change is listed in [CHANGELOG.md](CHANGELOG.md). CI runs on Python 3.9 to 3.13. Five files with 377,000 exposure rows (985,000 rows in all) take about 25 seconds on a laptop. It reads CSV or Parquet; text files may be comma, semicolon (with decimal commas), tab or pipe separated, in UTF-8 or Windows-1252. If `tieback` gets a join wrong on your data, the most useful report is an issue describing the column shapes, not the data.

## Why it is open source

In our experience, most of the time on an actuarial project goes into getting the data right, long before a model is fit: joining extracts from systems that disagree, and proving that nothing was lost or counted twice. Every team rebuilds that work, and a mistake made there passes into the rates without raising an error.

We release as open source the parts of the actuarial workflow that every team needs and no team should have to rebuild. Reconciliation is the first.

## Who made this

[Actuarial Labs](https://actuariallabs.com) is an actuarial science research lab. `tieback` is the reconciliation step from [Workspace](https://actuariallabs.com/workspace), released on its own because every pricing, reserving and data team needs it.

Apache 2.0.
