Skip to content

Your first model

This page builds a small model end to end: gross losses simulated by class of business and underwriting year, a reinsurance layer, a copula correlating the classes, and the net result read out as statistics. Each step is covered in more depth in the user guide.

Declare the shape of your data

A collection's dimensions are declared as a zk.Dims class, one zk.Dim per dimension, with the type of its values: str, int or float. Value columns are typed by their kind and shape: zk.FloatA is an array of floats, one per simulation. Subscripting a column type with a name gives the column its name.

from typing import Literal as Lit

import numpy as np
import polars as pl
import zeki as zk


class Business(zk.Dims):
    class_of_business = zk.Dim(str)
    underwriting_year = zk.Dim(int)


Gross = zk.FloatA[Lit["gross"]]

Literal makes the name part of the type, so a type checker knows which columns a collection holds.

Simulate gross losses

Each row is simulated from its own lognormal parameters. Start from a Polars DataFrame with a column per dimension, including two float dimensions holding the parameters:

class Parameters(zk.Dims):
    class_of_business = zk.Dim(str)
    underwriting_year = zk.Dim(int)
    mu = zk.Dim(float)
    sigma = zk.Dim(float)


parameters = pl.DataFrame(
    {
        "class_of_business": ["motor", "motor", "property", "property"],
        "underwriting_year": [2025, 2026, 2025, 2026],
        "mu": [10.0, 10.1, 9.5, 9.6],
        "sigma": [0.4, 0.4, 0.8, 0.8],
    }
)

zk.Collection.of makes a collection with a row per row of the DataFrame, and with_columns adds value columns to it. zk.float calls a function once per row: here NumPy's lognormal, with zk.dim("mu") and zk.dim("sigma") replaced by that row's parameters.

rng = np.random.default_rng(2026)
gross = (
    zk.Collection.of(Parameters, parameters)
    .with_columns(gross=zk.float(rng.lognormal, zk.dim("mu"), zk.dim("sigma"), 10_000))
    .drop_dims("mu", "sigma")
    .validate(Business, Gross)
)

Once the values are simulated, the parameter dimensions have done their job, so drop_dims removes them. validate checks the collection has the dimensions and columns you expect, and types it as zk.Collection[Business, Gross].

Apply reinsurance

Arithmetic on collections works row by row and simulation by simulation, as it would on NumPy arrays. Here, a layer of 30,000 excess of 20,000:

recovery = (gross - 20_000.0).clamp(0.0, 30_000.0)  # 30k xs 20k, per row and simulation
net = (gross - recovery).rename({"gross": "net"})

A result takes the name of its left-hand column, so rename calls the net column net.

Correlate the classes

A copula reorders simulations so that rows are dependent. zk.Copula.gaussian takes a function giving the target correlation between any two rows, from their dimension values:

copula = zk.Copula.gaussian(lambda row_a, row_b: 1.0 if row_a == row_b else 0.5)
zk.correlate(gross, copula)

The copula is registered after net was built from gross, and it still applies to net. zeki tracks the inputs every value depends on, so everything built from gross, before or after the copula, reads the reordered simulations. See Dependency and copulas.

Read the results

So far, nothing has been computed: every collection records how its values are built, but holds no values. collect() evaluates a collection, and zk.collect_all evaluates several in one pass, doing shared work once:

total_net = net.sum()  # every row summed: one row, no dims
by_class = net.group_by(zk.dim("class_of_business")).sum()

total, classes = zk.collect_all(total_net, by_class)
net_values = total.to_numpy("net")[0]  # the row's 10,000 simulated values
print(f"mean {net_values.mean():,.0f}, 1-in-200 {np.quantile(net_values, 0.995):,.0f}")
print(classes.to_polars())
mean 67,032, 1-in-200 179,589
shape: (2, 2)
┌───────────────────┬─────────────────────────────────┐
│ class_of_business ┆ net                             │
│ ---               ┆ ---                             │
│ str               ┆ array[f64, 10000]               │
╞═══════════════════╪═════════════════════════════════╡
│ motor             ┆ [39647.552253, 31668.584361, …… │
│ property          ┆ [34496.260698, 28740.339254, …… │
└───────────────────┴─────────────────────────────────┘

net.sum() adds every row together, leaving one row with no dimensions. group_by(...).sum() adds up the rows within each class. A collected collection reads out as NumPy, Polars, pandas or plain Python: see Reading values out.