pytracemodel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,645 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytracemodel
3
+ Version: 0.1.0
4
+ Summary: Traced, checked financial models in Python: every number has an address, a source and rules that check it.
5
+ Project-URL: Homepage, https://github.com/datayoga-io/tracemodel
6
+ Project-URL: Repository, https://github.com/datayoga-io/tracemodel
7
+ Project-URL: Issues, https://github.com/datayoga-io/tracemodel/issues
8
+ Author-email: DataYoga <oren@datayoga.io>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ai agents,data quality,financial modeling,three-statement model,xbrl
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Office/Business :: Financial
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.12
21
+ Description-Content-Type: text/markdown
22
+
23
+ # tracemodel
24
+
25
+ tracemodel lets you build a financial model in Python in which every number has a fixed address,
26
+ a source you can open, and rules that check it.
27
+
28
+ **What it is.** tracemodel is a Python library for financial and business models. A model holds
29
+ items (revenue, cash, a balance sheet line) over named dimensions (period, region, line). Each
30
+ number is entered with its source, or calculated by a formula. Checks state what must hold, such
31
+ as "total = sum of the parts".
32
+
33
+ **Why we built it.** Financial models usually live in spreadsheets. In a spreadsheet, a cell has
34
+ no source, a person can overwrite a formula with no trace, and a broken total can stay hidden. A
35
+ DataFrame does not solve this: it has no declared definition, no per-cell formulas and no record
36
+ of where a number came from. tracemodel keeps the definition, the values, their sources and the
37
+ checks in one model. A person or an AI agent fills it in, and a reviewer can trace each number.
38
+
39
+ **Why financial modeling is different.**
40
+
41
+ - Reported and calculated numbers mix. A subtotal in a report is an input, not a formula: you
42
+ enter it and check the arithmetic.
43
+ - Actuals override forecasts. Past periods are entered; later periods are calculated from the
44
+ period before.
45
+ - Balances roll forward. Each opening balance is the previous ending; the first one comes from
46
+ outside the model.
47
+ - Reports round their numbers. A total can differ from its parts by a small amount, so checks
48
+ need a tolerance.
49
+ - Some cells follow their own terms, such as one contract with a different escalator.
50
+ - Every number must tie back to a page in a filing, report or contract.
51
+
52
+ **What it is good for.**
53
+
54
+ Above all, tracemodel gives AI a **financial brain**. A language model can read a filing, but it
55
+ does not reliably keep hundreds of linked numbers consistent, roll balances forward or notice that
56
+ a total does not tie. tracemodel gives the agent that structure: a declared model to fill,
57
+ formulas that calculate the rest, and checks that catch its errors. The agent writes values; the
58
+ model keeps them consistent, and each value traces back to its source.
59
+
60
+ - Building an operating or three-statement model from filings and reports, with a source on each
61
+ number.
62
+ - Letting AI agents extract values into a fixed definition that rejects values that do not fit.
63
+ - Reviewing a model: `explain()` shows the cells each check and formula read, back to the entered
64
+ values.
65
+
66
+ ## Install
67
+
68
+ Python 3.12 or later. No dependencies.
69
+
70
+ ```bash
71
+ pip install pytracemodel
72
+ ```
73
+
74
+ ```python
75
+ import tracemodel as tm
76
+ ```
77
+
78
+ ## Concepts
79
+
80
+ | Concept | What it is |
81
+ | --- | --- |
82
+ | **Dimension** | A named axis with an ordered list of coordinate labels, e.g. `period`: `Q1`, `Q2`. |
83
+ | **Coords** | The labels along a dimension. A value is addressed by one label per dimension: `{"region": "/north", "period": "Q1"}`. |
84
+ | **Hierarchy** | A dimension whose labels are paths: `/`, `/north`, `/north/boston`. A path's parent is the path minus its last segment. |
85
+ | **Item** | A named measure (e.g. `revenue`) declared over some dimensions, with a data type and attributes such as units. Holds no numbers until values are set. |
86
+ | **Check** | A data quality rule: a condition over items (comparisons joined with and / or / not), run once for each label of the dimensions you choose. |
87
+ | **Value** | One number for one item at full coords, with a `source` saying where it came from. |
88
+
89
+ ## Workflow
90
+
91
+ A model is built in four steps, in this order:
92
+
93
+ 1. **Dimensions** — `model.add_dimension(...)`
94
+ 2. **Items scaffold** — `model.add_item(...)`
95
+ 3. **Data quality** — `model.add_check(...)`
96
+ 4. **Values** — `model.set_value(...)`, then `model.check()`
97
+
98
+ Steps 1–3 are the *definition*: what can exist and what must hold. Step 4 fills it in.
99
+ They can be done by different people or agents: whoever writes values only calls
100
+ `set_value`, and every call is validated against the definition.
101
+
102
+ To run steps 1–3 and step 4 as two AI agents, see [docs/agents.md](docs/agents.md).
103
+
104
+ ## Example
105
+
106
+ A retail chain's sales by region and quarter.
107
+
108
+ ```python
109
+ import tracemodel as tm
110
+
111
+ model = tm.Model()
112
+
113
+ # 1. Dimensions
114
+ model.add_dimension("period", [
115
+ ("Q1", "First quarter", {"end": "2026-03-31"}), # (code, description, attrs)
116
+ ("Q2", "Second quarter", {"end": "2026-06-30"}),
117
+ ])
118
+ model.add_dimension("region", tm.Hierarchy([
119
+ ("/", "All regions"), # (code, description)
120
+ "/north", # code only
121
+ "/north/boston",
122
+ "/north/portland",
123
+ ("/south", "South"),
124
+ ]))
125
+ model.add_dimension("channel", tm.Hierarchy(["/store", "/online"]))
126
+
127
+ # 2. Items scaffold
128
+ USD_K = {"units": "USD", "scale": "thousands"}
129
+ model.add_item("revenue", dims=("region", "period"), dtype=float, attrs=USD_K)
130
+ model.add_item("returns", dims=("channel", "period"), dtype=float, attrs=USD_K)
131
+ model.add_item("stores", dims=("period",), dtype=int, attrs={"units": "stores"})
132
+
133
+ # 3. Data quality: total revenue equals north plus south, in every period
134
+ model.add_check("DQ-1",
135
+ coords={"period": tm.ANY},
136
+ expect=abs(
137
+ model["revenue"]["/"] - (model["revenue"]["/north"] + model["revenue"]["/south"])
138
+ ) <= 0.5, # within 0.5 (USD thousands) for rounding
139
+ description="Total revenue = North + South",
140
+ )
141
+
142
+ # 4. Values
143
+ SRC = {"document": "Q2 sales report", "url": "https://example.com/q2.pdf", "section": "Table 1"}
144
+ model.set_value("revenue", coords={"region": "/", "period": "Q1"}, value=1_200, source=SRC)
145
+ model.set_value("revenue", coords={"region": "/north", "period": "Q1"}, value=700, source=SRC)
146
+ model.set_value("revenue", coords={"region": "/south", "period": "Q1"}, value=500, source=SRC)
147
+ model.set_value("stores", coords={"period": "Q1"}, value=42, source=SRC)
148
+
149
+ model.check() # DQ-1 passes for Q1; Q2 fails because its values are missing
150
+ model.table("revenue") # regions down, periods across
151
+ ```
152
+
153
+ ## API reference
154
+
155
+ ### Model
156
+
157
+ ```python
158
+ model = tm.Model()
159
+ ```
160
+
161
+ **Definition**
162
+
163
+ | Call | Does |
164
+ | --- | --- |
165
+ | `add_dimension(name, coords)` | `coords` is a list of coord entries (see Coord entries) or a `tm.Hierarchy`. Re-adding an identical dimension is a no-op; a different one under the same name raises `DefinitionError`. |
166
+ | `add_coords(name, entries)` | Appends labels to a dimension, e.g. forecast periods (entries as in Coord entries; a hierarchy path needs its parent). Items get the new cells, not entered. Checks given `tm.ANY` for that dimension are re-expanded to cover the new labels; checks with listed labels keep them. A function check loaded from a file can't build conditions for new labels of its parameter's dimension: `add_coords` raises and changes nothing, and you re-add the check with its function. Labels already there with the same entry are a no-op. Labels can't be removed or reordered. |
167
+ | `remove_dimension(name)` | Removes a dimension that no item uses; raises `DefinitionError` naming the items that do. |
168
+ | `add_item(name, dims, dtype=float, attrs=None, formula=None)` | `dims`: tuple of declared dimension names. `dtype`: `int` or `float`. `attrs`: free-form dict; `units` and `scale` are shown in tables. By convention `period_type` is `"duration"` (a flow over the period) or `"instant"` (a balance at its end), for whoever reads the model; the library doesn't act on it. `formula`: an expression that calculates the item's cells, or a Python function of the cell (see Formulas). Re-adding an identical item is a no-op. |
169
+ | `add_check(id, expect, coords=None, description=None, severity="error")` | `expect`: a condition, a function of dims that returns one, or a value check: a function of `x` that returns `True` or `False` (see Data quality). `coords`: `{dim: tm.ANY \| tm.filter_by_attrs(...) \| label \| [labels]}` — the check runs once per combination. Every dimension a cell leaves open must appear here, and every dimension here must be left open by some cell (otherwise `DefinitionError`). When every cell fixes all its coords, omit `coords`: the check runs once. `severity`: `"error"` or `"warning"`; a failing warning is reported but doesn't make `report.ok` false. An existing `id` is replaced. |
170
+ | `model[item]` | An expression for the whole item; see Expressions. |
171
+ | `model.item(name)` | The declared `Item`; raises `UnknownItem`. |
172
+ | `model.dimensions`, `model.items`, `model.checks` | Dicts by name/id of `Dimension`, `Item` and `Check` objects (below). |
173
+ | `print(model)` | A summary: each dimension with every label and its description and attrs, each item with its dims, dtype, attrs and formula, each check with its condition and the dims it runs over, and the number of values. |
174
+
175
+ **Declared objects** (read-only)
176
+
177
+ | Object | Fields |
178
+ | --- | --- |
179
+ | `Dimension` | `name`, `coords` (tuple of labels), `hierarchy` (the `tm.Hierarchy`, or `None` for a plain list), `description(label)`, `attrs(label)` |
180
+ | `Item` | `name`, `dims`, `dtype`, `attrs`, `formula` (or `None`), `unit_label` (`units` and `scale` joined) |
181
+ | `Check` | `id`, `expect`, `coords` (dim → labels it runs over), `description`, `severity`, `runs()` (the coords of each run), `params` (the dims a function `expect` takes), `condition(at)` (the condition a run tests) |
182
+
183
+ **Values**
184
+
185
+ | Call | Does |
186
+ | --- | --- |
187
+ | `set_value(line_item, coords, value, source)` | `coords` must give exactly one declared label for each of the item's dims. `value` must match the item's `dtype` (`int` items reject non-integers), or `tm.NIL` (see below), or an expression: a formula for this one cell (see Formulas). The last write wins: setting a cell again replaces its value and source, and the old ones are kept in the entry's `history`. |
188
+ | `get(line_item, **coords)` | The number at full coords (0 for a nil cell). |
189
+ | `entry(line_item, **coords)` | With full coords: an `Entry` (`value`, `source`, `history`). With fewer coords: a `Table` of matching entries. |
190
+ | `table(line_item)` | The item as a grid: `period` across (if the item has it), other dims down. Cells not entered are blank; nil cells show `—`. |
191
+ | `evaluate(expr)` | Evaluates an expression for every combination of its open dims: a `Table`, or a number when no dim is open. |
192
+ | `check()` | Runs every check; returns a `Report`. |
193
+ | `transaction()` | Groups changes; see Transactions. |
194
+ | `to_jsonl(path)` / `load_jsonl(path)` | Save / load values, one JSON object per value. Loading validates like `set_value`, in one transaction: a bad row loads nothing. |
195
+
196
+ **Saving the definition**
197
+
198
+ | Call | Does |
199
+ | --- | --- |
200
+ | `save(path)` | Writes the definition (dimensions, items, formulas, checks) to a JSON file. Values are not included; save them with `to_jsonl`. |
201
+ | `tm.load(path, allow_code=False)` | A model from a file written by `save`. Formulas saved as Python functions are code: they load only with `allow_code=True`. |
202
+ | `to_dict()` / `tm.Model.from_dict(data, allow_code=False)` | The same, as plain data. |
203
+
204
+ **Source.** Every value needs a `source` dict with `document`, `url` and `section`;
205
+ `page` and `quote` are optional. Other keys are rejected.
206
+
207
+ ### Coord entries
208
+
209
+ Every dimension, plain or hierarchy, lists its coords as entries of one of three forms:
210
+
211
+ | Entry | Example |
212
+ | --- | --- |
213
+ | `"code"` | `"Q1"`, `"/north"` |
214
+ | `(code, description)` | `("Q1", "First quarter")` |
215
+ | `(code, description, attrs)` | `("Q1", "First quarter", {"end": "2026-03-31"})` |
216
+
217
+ `attrs` is a free-form dict. Use `None` as the description to give attrs only.
218
+ `dim.description(label)` returns the description, falling back to the code (for a hierarchy,
219
+ the last path segment); `dim.attrs(label)` returns the attrs, or `{}`.
220
+
221
+ ### Hierarchy
222
+
223
+ ```python
224
+ tm.Hierarchy(["/", "/a", ("/a/x", "Description"), ("/b", "B", {"note": "..."})])
225
+ ```
226
+
227
+ - Entries as above; each code is a path.
228
+ - Every path's parent must also be declared, except the root `/`: top-level paths such as
229
+ `/a` and `/b` may stand alone.
230
+ - `h.parent(path)`, `h.children(path)`, `h.description(path)` (falls back to the last path segment).
231
+ - Reach it with `model.dimensions["region"].hierarchy`.
232
+
233
+ ### Expressions
234
+
235
+ `model["revenue"]` is the whole item. Fix coords by label or by name:
236
+
237
+ ```python
238
+ model["revenue"]["/north"] # the label must belong to exactly one of the item's dims
239
+ model["revenue"].sel(region="/north", period="Q1")
240
+ ```
241
+
242
+ Expressions combine with `+ - * /`, unary `-` and numbers, and `sum([...])` adds a list of them.
243
+ Dimensions broadcast by name, as in xarray: the result has one value per combination of the dims
244
+ its cells leave open.
245
+
246
+ ```python
247
+ model["revenue"] / model["revenue"]["/"] # each region's share, by region and period
248
+ model["revenue"]["/"] / model["stores"] # revenue per store, by period
249
+ sum(model["revenue"][r] for r in ["/north", "/south"]) # displays as revenue['/north'] + revenue['/south']
250
+ ```
251
+
252
+ **Earlier and later labels.** `lag` and `lead` (named as in SQL's window functions) read the
253
+ same item a number of labels earlier or later along a plain dimension; `shift` is the
254
+ xarray / pandas spelling of the same thing.
255
+
256
+ | Write | Reads |
257
+ | --- | --- |
258
+ | `x.lag("period")`, `x.lag("period", 2)` | the previous period, two periods back |
259
+ | `x.lead("period")` | the next period |
260
+ | `x.shift(period=1)`, `x.shift(period=-1)` | the same as `lag` and `lead` |
261
+
262
+ A check that lags must leave the first label out of its coords, because it has nothing before
263
+ it; a lead leaves out the last. Slice the dimension's labels, like any Python tuple:
264
+
265
+ ```python
266
+ rev = model["revenue"]
267
+ model.add_check("GROWTH-1",
268
+ coords={"period": model.dimensions["period"].coords[1:]}, # every period but the first
269
+ expect=rev["/"] >= rev["/"].lag("period"),
270
+ description="Total revenue doesn't shrink",
271
+ )
272
+ # runs once, period=Q2: revenue['/'] at Q2 >= revenue['/'] at Q1
273
+ ```
274
+
275
+ With `coords={"period": tm.ANY}` instead, `add_check` raises `DefinitionError`: there is no
276
+ period before Q1, and the message suggests `coords[1:]`. Displayed, a lag shows the first
277
+ period blank. Lag and lead work on plain dimensions only: a hierarchy has no previous line.
278
+
279
+ Nothing is computed when an expression is built. It is evaluated when a check runs, when
280
+ you call `model.evaluate(expr)`, or when you display it in IPython/Jupyter (shown as a table).
281
+ A missing value or a division by zero shows as blank.
282
+
283
+ ### Data quality
284
+
285
+ A check's `expect` is a condition: a comparison of expressions, or comparisons joined together.
286
+
287
+ | Write | Holds when |
288
+ | --- | --- |
289
+ | `a < b`, `a <= b`, `a > b`, `a >= b`, `a != b` | the comparison is true |
290
+ | `a == b` | equal |
291
+ | `cond1 & cond2`, `cond1 \| cond2`, `~cond` | both hold / at least one holds / it does not hold |
292
+ | `x.is_nil()` | the cell was entered as `tm.NIL`, not as a number such as 0 (not entered: missing) |
293
+
294
+ A tolerance is an expression too: `abs(a - b) <= 0.5` allows a difference of 0.5 in the
295
+ item's units, and `abs(a - b) <= 0.001 * abs(a)` allows 0.1%. Comparisons allow for float
296
+ rounding (about one part in a billion), so `abs(1_000.2 - 1_000) <= 0.2` holds.
297
+
298
+ ```python
299
+ model.add_check("SIGN-1", coords={"region": tm.ANY, "period": tm.ANY},
300
+ expect=model["revenue"] >= 0)
301
+
302
+ share = model["revenue"]["/north"] / model["revenue"]["/"]
303
+ model.add_check("MIX-1", coords={"period": tm.ANY},
304
+ expect=(share >= 0.4) & (share <= 0.7))
305
+ ```
306
+
307
+ Python can't redefine `and`, `or`, `not` or chained comparisons, so they raise an error:
308
+ write `(x >= 0) & (x <= 1)`, not `0 <= x <= 1` or `x >= 0 and x <= 1`. The parentheses are
309
+ required, because `&` and `|` bind tighter than comparisons.
310
+
311
+ A value check allows them. Pass a function of `x`, as in formulas. It runs once per run, with
312
+ numbers. `x["item"]` reads an item at the run's coords; `x.coords` and `x.attrs(dim)` work. It
313
+ returns `True` or `False`. `and`, `or`, `not`, chained comparisons, `max`, `min` and `if`/`else`
314
+ all work:
315
+
316
+ ```python
317
+ model.add_check("MARGIN-1", coords={"period": tm.ANY},
318
+ expect=lambda x: 0 <= x["margin"] <= 1)
319
+ ```
320
+
321
+ - The cells it reads are traced. A missing cell fails the run and is listed in `missing`.
322
+ - An error, or a return value that isn't `True` or `False`, fails the run. The result's `error`
323
+ says why.
324
+ - A function that only uses expressions (`lambda x: x["margin"] >= 0`) is stored as a condition,
325
+ so it keeps left, right and diff.
326
+ - Saving stores the function's source, as for formula functions. Loading needs
327
+ `allow_code=True`.
328
+ - The parameter `x` makes a value check, so a dim named `x` can't be a function check parameter.
329
+
330
+ Displayed, a comparison shows left, right, diff and the result for each combination of its open
331
+ dims; a joined condition shows each part's result and the whole. A condition has no single truth
332
+ value, so `if a == b:` raises. A missing value or a division by zero fails the check.
333
+
334
+ `tm.ANY` in check coords means "every label of that dimension".
335
+ `tm.filter_by_attrs(kind="forecast")` (named after xarray's `Dataset.filter_by_attrs`) means
336
+ "every label whose attrs match": `kind` is `"forecast"` in the label's attrs, and with several
337
+ attrs, all of them match. Both are resolved again when `add_coords` adds labels, so a check
338
+ over `filter_by_attrs(kind="forecast")` covers forecast periods added later:
339
+
340
+ ```python
341
+ FORECAST = tm.filter_by_attrs(kind="forecast")
342
+ model.add_dimension("year", [("FY2024", None, {"kind": "actual"}),
343
+ ("FY2025", None, {"kind": "actual"}),
344
+ ("FY2026", None, {"kind": "forecast"})])
345
+ model.add_item("sales", dims=("year",), formula=lambda s: s.lag("year") * 1.03)
346
+ model.add_check("FC-SALES", coords={"year": FORECAST}, expect=model["sales"] > 0)
347
+ model.add_coords("year", [("FY2027", None, {"kind": "forecast"})]) # FC-SALES now runs FY2026, FY2027
348
+ model.check().filter(year=FORECAST).ok # only the forecast years
349
+ ```
350
+
351
+ **Function checks.** When the rule itself depends on a label, such as "a region equals the sum
352
+ of *its* children", pass a function as `expect`. Name each parameter after a dimension in
353
+ `coords`; the check calls it once per combination of those labels and tests the condition it
354
+ returns. Dimensions you don't name run as usual, with their cells left open.
355
+
356
+ ```python
357
+ rev = model["revenue"]
358
+ regions = model.dimensions["region"].hierarchy
359
+
360
+ model.add_check("ROLLUP-1",
361
+ coords={"region": ["/", "/north"], "period": tm.ANY},
362
+ expect=lambda region: abs(rev[region] - sum(rev[c] for c in regions.children(region))) <= 0.5,
363
+ description="Each region = the sum of its children",
364
+ )
365
+ # region="/": abs(revenue['/'] - (revenue['/north'] + revenue['/south'])) <= 0.5
366
+ # region="/north": abs(revenue['/north'] - (revenue['/north/boston'] + revenue['/north/portland'])) <= 0.5
367
+ ```
368
+
369
+ The functions are called when the check is added, so every run still has a formula, the cells it
370
+ reads, and left and right in the report. A parameter that isn't a dimension in `coords`, or a
371
+ return value that isn't a condition, raises `DefinitionError` there. Parameters with a default
372
+ value (`lambda region, h=regions: ...`) are not dimensions; use them to bind values in a loop.
373
+
374
+ ### Results and display
375
+
376
+ - `Report`: `ok` (no failing error check), `filter(check=None, **coords)` (the runs of one check and/or on some labels: a label, a list, `tm.ANY` or `tm.filter_by_attrs(...)`; returns a `Report`), `results`, `failures` (every run that didn't pass), `errors` and `warnings` (failures by severity), `explain(check_id=None)` (each run with every cell it read), `table()`, `show()`.
377
+ - Each result: `check`, `at` (the coords of the run), `lhs`, `rhs`, `diff`, `passed`, `cells`, `missing`, `error`.
378
+ - For a value check, `lhs`, `rhs` and `diff` are `None`. `error` holds the error text when the function raised or didn't return a bool.
379
+ - A run fails with `error` set, instead of `check()` raising, when a cell it reads can't be calculated: say a formula's `lag` before the first period, or an `int` formula that gives a fraction.
380
+ - A missing value fails the check that reads it; it is never treated as 0.
381
+ - Each run's result: `pass`, `FAIL`, `missing`, or for a warning check `warn` / `warn: missing`.
382
+ - `Table`: `columns`, `rows`, `title`, `to_records()`, `show()`. Renders as HTML in Jupyter and as aligned text elsewhere.
383
+
384
+ ### Formulas
385
+
386
+ An item with `formula=` is calculated, not entered: each cell evaluates the formula at the
387
+ cell's coords. Use it for numbers the source doesn't report, such as ratios, growth or
388
+ recomputed figures:
389
+
390
+ ```python
391
+ model.add_item("avg_revenue_per_store", dims=("period",), attrs=USD_K,
392
+ formula=model["revenue"]["/"] / model["stores"])
393
+ ```
394
+
395
+ A cell is either **entered** with `set_value` (the last write wins) or **calculated** by its
396
+ item's formula. An entered cell overrides the formula for that one cell, with a source, as in
397
+ Anaplan; the entry has `overrides_formula=True`.
398
+
399
+ **Formulas as Python functions.** A formula can be a function of `x`, the cell being
400
+ calculated. It is called once per cell, with numbers, so any Python works: `max`, `min`,
401
+ `if`/`else`, `math`:
402
+
403
+ ```python
404
+ FLOOR = 25_000 # minimum cash
405
+ model.add_item("cash", dims=("period",), attrs=USD_K)
406
+ model.add_item("revolver_draw", dims=("period",), attrs=USD_K,
407
+ formula=lambda x: max(0, FLOOR - x["cash"]))
408
+ # cash 40,000 → draw 0; cash 18,000 → draw 7,000
409
+ ```
410
+
411
+ | In the function | Reads |
412
+ | --- | --- |
413
+ | `x["cash"]` | item `cash` at this cell's coords (a label of the item itself if no item has that name) |
414
+ | `x["cash"]["/north"]`, `x["cash"].sel(region="/north")` | `cash` with a coord fixed |
415
+ | `x.lag("period")`, `x["cash"].lag("period")` | this item / `cash` one period earlier |
416
+ | `x.coords` | this cell's labels, e.g. `{"period": "Q2"}` |
417
+ | `x.attrs("period")` | the attrs of this cell's period label, e.g. `{"kind": "forecast"}` |
418
+ | `x.is_nil()` | whether the cell read was entered as `tm.NIL` |
419
+
420
+ **One formula for many lines.** When an item spans lines that each need their own formula (a
421
+ balance sheet over a `bs_line` hierarchy), give the item one function that picks by label.
422
+ Entered actuals still win; returning `None` leaves a cell missing:
423
+
424
+ ```python
425
+ LINES = {
426
+ "/current/receivables": lambda x: x["sales"] * x["dso"] / 365,
427
+ "/current/inventory": lambda x: x["cogs"] * x["dio"] / 365,
428
+ "/current": lambda x: x["/current/receivables"] + x["/current/inventory"],
429
+ }
430
+ model.add_item("balance_sheet", dims=("bs_line", "period"),
431
+ formula=lambda x: LINES[x.coords["bs_line"]](x)
432
+ if x.attrs("period").get("kind") == "forecast" and x.coords["bs_line"] in LINES
433
+ else None)
434
+ ```
435
+
436
+ Forecast periods added later with `add_coords` are calculated too. (`x["/current/receivables"]`
437
+ reads a line of the item itself, since no item has that name.)
438
+
439
+ - `x` and what it reads behave as numbers. A cell that isn't entered makes the whole cell
440
+ missing, as for expressions; a division by zero too.
441
+ - If the function only uses expressions (`lambda x: x["cash"] - FLOOR`), it is stored as an
442
+ expression: `print(model)` shows `cash - 25000`, and circular formulas are rejected when it is
443
+ added. Otherwise `print(model)` shows the function's source, the cells each cell read are
444
+ traced when it runs, and a formula that reads itself raises `DefinitionError` when calculated.
445
+ - Saving stores the function's source and the values of the names it uses (`FLOOR`, modules,
446
+ numbers, strings, lists, dicts). A function typed at a plain `python` prompt has no source and
447
+ can't be saved. Loading runs the code, so it needs `tm.load(path, allow_code=True)` and
448
+ `load_jsonl(path, allow_code=True)`; run files you don't trust in a sandbox.
449
+
450
+ **Projections: reading the item's own earlier cells.** Pass the formula as a function of the
451
+ item's cells. Entered actuals win; the later periods are calculated, each from the one before:
452
+
453
+ ```python
454
+ model.add_dimension("year", ["FY2024", "FY2025", "FY2026", "FY2027"])
455
+ model.add_item("sales", dims=("year",), attrs=USD_K,
456
+ formula=lambda sales: sales.lag("year") * 1.03) # 3% growth
457
+ model.set_value("sales", coords={"year": "FY2024"}, value=4_800, source=SRC)
458
+ model.set_value("sales", coords={"year": "FY2025"}, value=5_100, source=SRC)
459
+ model.table("sales")
460
+ # year value
461
+ # FY2024 4,800 entered
462
+ # FY2025 5,100 entered
463
+ # FY2026 5,253 = 5,100 × 1.03
464
+ # FY2027 5,410.59 = 5,253 × 1.03
465
+ ```
466
+
467
+ **Opening balances.** A balance that rolls forward has one number from outside the model: the
468
+ balance before the first period. It's a single value, not a column, so it needs no extra period.
469
+ Give the beginning line a formula that reads the previous period's ending, and enter the first
470
+ period's beginning; entered cells win over the formula:
471
+
472
+ ```python
473
+ model.add_dimension("period", ["FY2024", "FY2025", "FY2026"])
474
+ model.add_item("cash_end", dims=("period",), attrs=USD_K,
475
+ formula=lambda x: x["cash_begin"] + x["cash_flow"])
476
+ model.add_item("cash_begin", dims=("period",), attrs=USD_K,
477
+ formula=lambda x: x["cash_end"].lag("period"))
478
+ model.add_item("cash_flow", dims=("period",), attrs=USD_K)
479
+ model.set_value("cash_begin", coords={"period": "FY2024"}, value=29_943, source=SRC) # the opening balance
480
+ # cash_begin FY2024 29,943 entered; FY2025, FY2026 = cash_end one period earlier
481
+ ```
482
+
483
+ When the source reports every period's beginning balance (a cash flow statement does), they are
484
+ inputs: enter each one, with no formula, and check that it ties to the previous ending from the
485
+ second period on (`coords={"period": PERIODS[1:]}`). The first period's beginning ties to
486
+ nothing in the model; that is expected. When several items read the opening balance, make it
487
+ an item with no dims (`dims=()`), entered once.
488
+
489
+ **A formula for one cell.** `set_value` also takes an expression, or a function of the item's
490
+ cells, as the value: that cell is calculated by its own formula, sourced like any value. Use it
491
+ when one cell follows different terms, such as a contract with its own escalator:
492
+
493
+ ```python
494
+ model.add_dimension("contract", ["C-101", "C-104"])
495
+ model.add_item("fee", dims=("contract", "year"), attrs=USD_K,
496
+ formula=lambda fee: fee.lag("year") * 1.02) # the standard 2% escalator
497
+ for c in ["C-101", "C-104"]:
498
+ model.set_value("fee", coords={"contract": c, "year": "FY2024"}, value=100, source=SRC)
499
+ MSA = {"document": "MSA C-104", "url": "https://example.com/msa-c104.pdf", "section": "4.2"}
500
+ model.set_value("fee", coords={"contract": "C-104", "year": "FY2026"},
501
+ value=lambda fee: fee.lag("year") * 1.10, source=MSA) # a 10% step-up in FY2026
502
+ model.table("fee")
503
+ # contract year value
504
+ # C-101 FY2026 104.04 the item's 2%
505
+ # C-104 FY2026 112.2 = 102 × 1.10, this cell's formula
506
+ # C-104 FY2027 114.444 = 112.2 × 1.02, back on the item's 2%
507
+ # ...
508
+ ```
509
+
510
+ When only the terms differ (rate, start year), prefer entering the terms as items of their
511
+ own under one item formula; a cell formula is for a cell whose formula really is different.
512
+
513
+ - A formula may leave open only dims the item has; fix the rest with `["label"]` / `.sel()`.
514
+ - On an `int` item, a formula's result must be a whole number (float noise such as
515
+ `9.999999999999998` is rounded); otherwise reading the cell raises `DefinitionError`. Round in
516
+ the formula: `formula=lambda x: round(x["buyback"] / x["price"])`.
517
+ - A formula that would make a cell depend on itself is rejected when it is added, e.g.
518
+ `lambda x: x.lag("year") + x.lead("year")` (`DefinitionError: circular formula: ...`).
519
+ - A cell is missing when any cell its formula reads is missing; the first period of a lag
520
+ has nothing before it, so enter it.
521
+ - Checks read calculated cells like any other; `explain()` lists the cells each formula read,
522
+ back to the entered ones.
523
+ - `entry()` shows a cell formula as `= fee.lag('year') * 1.1`; the values file saves it as
524
+ `"formula"` text instead of `"value"`.
525
+
526
+ A number the source reports is an input, even when it equals other numbers' arithmetic (a
527
+ subtotal, gross margin on the income statement): enter it with its source and add a check
528
+ for the arithmetic. A formula on it would hide the reported number.
529
+
530
+ ### Transactions
531
+
532
+ Filling in a model takes many calls, and some states in between aren't valid yet: a cell
533
+ formula can read a cell that, for now, reads it back. Group the calls in a transaction:
534
+
535
+ ```python
536
+ with model.transaction():
537
+ for year in ["FY2026", "FY2027"]:
538
+ model.set_value("fee", coords={"contract": "C-101", "year": year},
539
+ value=lambda fee: fee.lag("year") * 1.05, source=MSA)
540
+ # committed here
541
+ ```
542
+
543
+ - Checks that need the whole picture (circular formulas) run once, at commit.
544
+ - If the commit fails, or an exception leaves the block, every change made inside it is undone:
545
+ values, items, labels and checks.
546
+ - Reads inside the transaction (`get`, `table`, `check`) see the changes so far; reading a cell
547
+ that loops for now raises `DefinitionError`.
548
+ - Without `with`: `tx = model.transaction()`, then `tx.commit()` or `tx.rollback()`. One
549
+ transaction at a time.
550
+
551
+ Calculated cells are cached and the cache is cleared on any change, so a long chain of
552
+ formulas (years of monthly periods, each reading the one before) is calculated once per cell.
553
+
554
+ ### Not entered vs nil
555
+
556
+ A cell is either **not entered** (the default: no `set_value` yet) or has a value. When the
557
+ source reports a cell as nil ("—" or blank in a table that has numbers elsewhere), enter it
558
+ explicitly, with a source like any value:
559
+
560
+ ```python
561
+ model.set_value("cost", coords={"segment": "/corporate", "period": "FY2025"}, value=tm.NIL, source=SRC)
562
+ ```
563
+
564
+ | | Not entered | `tm.NIL` |
565
+ | --- | --- | --- |
566
+ | Meaning | Nobody has entered it yet | The source shows nothing here |
567
+ | In checks | `missing`: the check doesn't pass | Counts as 0 |
568
+ | In tables and `explain()` | blank / `MISSING` | `—` |
569
+ | `get()` | raises `MissingValue` | 0 (the entry's `value` is `tm.NIL`) |
570
+ | Values file | no row | `"value": null` |
571
+ | In a condition | `x.is_nil()` is missing | `x.is_nil()` holds |
572
+
573
+ Don't enter 0 for a "—": a real 0 and a nil cell are different facts.
574
+
575
+ Not entered is normal, not an error. A model's dims are a grid, and a source rarely fills all of
576
+ it: a three-year income statement next to a two-year balance sheet, or a segment that has no
577
+ costs. The library can't know which cells a source was meant to fill, so it never reports empty
578
+ cells by themselves. Only a check that reads a cell reports it as `missing`; to leave cells out
579
+ of a check, give the check `coords` (a list of labels, or `tm.filter_by_attrs(...)`). Don't add
580
+ lines or skip a period to avoid empty cells, and don't enter nil for a cell the source doesn't
581
+ show at all.
582
+
583
+ ### Errors
584
+
585
+ All derive from `tm.TraceModelError`.
586
+
587
+ | Error | Raised when |
588
+ | --- | --- |
589
+ | `DefinitionError` | A dimension, item or check is invalid or conflicts with an existing one. |
590
+ | `UnknownItem` | The item name is not declared. |
591
+ | `UnknownCoord` | A label or dimension name is not declared. |
592
+ | `DimMismatch` | Coords miss one of the item's dims or add one it doesn't have. |
593
+ | `MissingValue` | No value at these coords. |
594
+ | `InvalidValue` | Wrong type for the item's `dtype`, or a bad `source`. |
595
+
596
+ ## Saving a model
597
+
598
+ The code that builds a model runs once. Save the definition, and from then on load it:
599
+
600
+ ```python
601
+ model.save("retail.model.json") # dimensions, items, formulas, checks
602
+ model.to_jsonl("retail.values.jsonl") # values, kept apart
603
+
604
+ model = tm.load("retail.model.json")
605
+ model.load_jsonl("retail.values.jsonl")
606
+ ```
607
+
608
+ - The definition and the values are separate files, as in XBRL (taxonomy vs instance): one
609
+ agent defines the model, another enters values against it.
610
+ - Expressions are saved as the text `print(model)` shows, e.g.
611
+ `"expect": "abs(revenue['/'] - (revenue['/north'] + revenue['/south'])) <= 0.5"`.
612
+ Loading parses that text with Python's `ast` and accepts only the expression grammar (item
613
+ names, `["label"]`, `.sel()`, `.lag()`, `.lead()`, `.shift()`, `.is_nil()`, `abs()`, numbers,
614
+ `+ - * /`, one comparison, `& | ~`). Nothing is evaluated as code, so a model file from
615
+ anyone is safe to load.
616
+ - A function check is saved as the condition it built for each label (`expect_by_label`); the
617
+ function itself isn't needed again. `tm.ANY` is saved as `"ANY"`.
618
+ - Item names must be Python identifiers (`add_item` checks), and attrs must hold JSON values.
619
+ - Loading validates everything, as building the model in code does.
620
+ - A formula written as a Python function is saved as `{"python": "<source>", "env": {...}}`;
621
+ loading it runs it, so it needs `allow_code=True`.
622
+
623
+ ## Values file format
624
+
625
+ `to_jsonl` writes one object per value:
626
+
627
+ ```json
628
+ {"line_item": "revenue", "coords": {"region": "/north", "period": "Q1"}, "value": 700, "source": {"document": "Q2 sales report", "url": "https://example.com/q2.pdf", "section": "Table 1"}}
629
+ ```
630
+
631
+ A nil cell is written with `"value": null`; a cell formula with `"formula": "<expression>"` instead of `"value"`. A value that overrides a formula adds `"overrides_formula": true`.
632
+
633
+ ## Development
634
+
635
+ ```
636
+ uv run pytest
637
+ ```
638
+
639
+ ## Appendix: Inspiration
640
+
641
+ | Project | What we take from it |
642
+ | --- | --- |
643
+ | [xarray](https://docs.xarray.dev/) | Named dimensions, coordinate labels, selection by label (`.sel`), broadcasting by dimension name. |
644
+ | [Great Expectations](https://docs.greatexpectations.io/) | Data quality rules as declared *expectations*, grouped into suites and run against the data; `severity` (critical / warning / info) and `mostly` (pass when a share of rows passes). |
645
+ | [XBRL Formula](https://www.xbrl.org/specification/validation/REC-2009-06-22/validation-REC-2009-06-22.html) | Value and consistency *assertions* over reported financial facts, with absolute and proportional acceptance radii; satisfied / unsatisfied with a severity. |
@@ -0,0 +1,14 @@
1
+ tracemodel/__init__.py,sha256=h2pXn2iP_Y99kUSvV__9Yc0wO6zweSjdEHrOjwu3tcI,1411
2
+ tracemodel/cellfn.py,sha256=4udxw9osDuDtpBdM-3SkPozbaO9gsd6dfc_UZ9BGNNc,14077
3
+ tracemodel/dimensions.py,sha256=6zcKQr9uviblQDDfBvbJsPOmpN8QCPbH_eH6TpWIwTo,6609
4
+ tracemodel/errors.py,sha256=9x7vu0RYziITM1rWw7ZxPTvazfGkcvm3CYetCdnH6-A,798
5
+ tracemodel/expr.py,sha256=6kZyypPqUbYTFLMWxYCudQLOwLMu3CKKPNvuix_-6NA,16609
6
+ tracemodel/model.py,sha256=QJFo1PJ-bCoH3Q_hS_UPuO8tEq5QT1whuDL9EYPrse4,54855
7
+ tracemodel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ tracemodel/table.py,sha256=wHALa-I-FiQv4lJtmTCO-F7_VVB680zVKTIfnqYJil8,2814
9
+ tracemodel/text.py,sha256=_ibShldqX8MdA-siUuOFucy2HrFWV39kHd9wb40EF2I,3989
10
+ tracemodel/values.py,sha256=MS_TdwdbmnuF3ZlunWbUIw4fdccFb6RwUWW2wEgzJ7Q,6034
11
+ pytracemodel-0.1.0.dist-info/METADATA,sha256=CUn1TiR6l-73quaxYm5ZDG7fsTI1QoJF0lUclrjWOEw,34897
12
+ pytracemodel-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
13
+ pytracemodel-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
14
+ pytracemodel-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any