Skip to main content

distributions.PredictiveDistribution

The joint result every model returns: draws for each simulation (row)

Usage

Source

distributions.PredictiveDistribution()

and component (column), keyed by dimension values.

The mean, quantile, var and tvar methods describe the total over all components, computed from row sums.

Parameters

dims: list of str

Dimension names, e.g. ["lob", "origin"].

components: list of tuple

One key per component, with one int or str per dimension.

draws: list of list of float
One row per simulation, one value per component.

Raises

ValueError
If the keys or the draws do not fit together.

Examples

>>> from prospicio.distributions import PredictiveDistribution
>>> pd = PredictiveDistribution(["line"], [("A",), ("B",)],
...                             [[0.0, 0.0], [0.0, 0.0], [0.0, 100.0], [100.0, 0.0]])
>>> pd.var(0.75)

100.0

>>> pd.marginal(("A",)).var(0.75)

0.0

Attributes

Name Description
dims Dimension names.
n_components Number of components (columns).
n_sims Number of simulations (rows).

dims

Dimension names.

dims: list[str]


n_components

Number of components (columns).

n_components: int


n_sims

Number of simulations (rows).

n_sims: int

Methods

Name Description
aggregate() Sums the components within each simulation over every dimension not
blend() Blends several models’ predictive distributions: simulation i is
blend_by_component() Blends models with weights that differ by component, as
components() Component keys, one tuple per column.
correlation_from_pairs() The correlation matrix between the groups of dim from a long
draw_matrix() All draws, one row per simulation.
from_gaussian() n_sims draws of a multivariate normal or lognormal joint.
from_json() A distribution from a document written by to_json.
group_spearman() Spearman’s rho between the totals of the groups of dim, ties
groups() The groups of dimension dim in order of first appearance: the
join() Joins distributions of different models into one portfolio, with a
marginal() One component’s draws, or None if no component has this key.
mean() Mean of the total.
provenance() Where this result came from: model, parameters, seed, stream scheme,
quantile() Quantile of the total.
reorder_groups() Sets the dependence between the groups of dimension dim by
reorder_groups_by_copula() Sets the dependence between the groups of dimension dim by a
scale_to_totals() Every simulation’s components rescaled pro rata to a new total.
select() The components whose value on dimension dim is one of keys,
to_json() The distribution as a JSON document: dimensions, component keys,
to_numpy() All draws as a read-only NumPy array, one row per simulation and one
total() The total over all components, one value per simulation.
tvar() Tail value at risk of the total at level p.
var() Value at risk of the total at level p.
variance() Variance of the total.

aggregate()

Sums the components within each simulation over every dimension not

Usage

Source

aggregate(keep)

in keep, keeping the joint structure.

Parameters
keep: list of str
Returns
PredictiveDistribution
Raises
ValueError
If keep names an unknown dimension or repeats one.

blend()

Blends several models’ predictive distributions: simulation i is

Usage

Source

blend(models, weights, seed)

simulation i of model k, with k drawn with probability weights[k] from stream i of seed. Rows stay whole, so sums across components remain coherent. Use weights from stacking_weights or pseudo_bma_weights.

Parameters
models: list of PredictiveDistribution

Same dimensions, components and number of simulations.

weights: list of float

Non-negative, not all zero; normalized.

seed: int
Returns
PredictiveDistribution
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> a = PredictiveDistribution(["lob"], [("x",)], [[0.0]] * 1000)
>>> b = PredictiveDistribution(["lob"], [("x",)], [[1.0]] * 1000)
>>> mix = PredictiveDistribution.blend([a, b], [0.25, 0.75], seed=7)
>>> abs(mix.mean() - 0.75) < 0.05

True


blend_by_component()

Blends models with weights that differ by component, as

Usage

Source

blend_by_component(models, weights, seed)

HierarchicalStacking gives them: in simulation i every component draws its model from the same uniform against its own cumulative weights, so components with equal weights take the same model and dependence is kept as far as the weights allow.

Parameters
models: list of PredictiveDistribution
weights: list of list of float

One weight vector per component (in components() order), one weight per model.

seed: int
Returns
PredictiveDistribution

components()

Component keys, one tuple per column.

Usage

Source

components()
Returns
list of tuple

correlation_from_pairs()

The correlation matrix between the groups of dim from a long

Usage

Source

correlation_from_pairs(dim, pairs)

pairwise table, in the order of groups(dim). Each pair of distinct groups appears once, in either order (both orders only with the same value); a diagonal entry may be given and must be 1.

Parameters
dim: str
pairs: list of tuple
(group, group, value) rows, values in [-1, 1].
Returns
list of list of float
Raises
ValueError
If a pair is missing, given twice with different values, names an unknown group, or a value is outside [-1, 1].
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> pd = PredictiveDistribution(["peril"], [("wind",), ("quake",)], [[0.0, 1.0]] * 3)
>>> pd.correlation_from_pairs("peril", [("quake", "wind", 0.2)])

[[1.0, 0.2], [0.2, 1.0]]


draw_matrix()

All draws, one row per simulation.

Usage

Source

draw_matrix()
Returns
list of list of float

from_gaussian()

n_sims draws of a multivariate normal or lognormal joint.

Usage

Source

from_gaussian(joint, n_sims, seed, keys=None, dims=None)

Simulation i draws only from stream i of seed, so the result reproduces by seed on any number of threads; the provenance records the model, its dimension, the seed and a hash of the mean and covariance.

Parameters
joint: MultivariateNormal or MultivariateLognormal
n_sims: int
seed: int
keys: list of tuple = None

One component key per component; defaults to (0,), (1,), ....

dims: list of str = ["component"]
Returns
PredictiveDistribution
Raises
TypeError

If joint is neither joint.

ValueError
If keys does not have one key per component.
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> from prospicio.risk import MultivariateNormal
>>> mvn = MultivariateNormal([100.0, 50.0], [[400.0, 120.0], [120.0, 100.0]])
>>> pd = PredictiveDistribution.from_gaussian(
...     mvn, 20_000, 1, keys=[("auto",), ("property",)], dims=["line"])
>>> abs(pd.mean() - 150.0) < 1.0

True


from_json()

A distribution from a document written by to_json.

Usage

Source

from_json(text)
Parameters
text: str
Returns
PredictiveDistribution
Raises
ValueError
If the text is not such a document, or is from a newer version.

group_spearman()

Spearman’s rho between the totals of the groups of dim, ties

Usage

Source

group_spearman(dim)

given their average rank as scipy.stats.spearmanr: what reorder_groups achieved.

Parameters
dim: str
Returns
tuple of (list, list of list of float)
The groups, as groups(dim), and the matrix.

groups()

The groups of dimension dim in order of first appearance: the

Usage

Source

groups(dim)

rows and columns of reorder_groups’ matrix.

Parameters
dim: str
Returns
list of int or str

join()

Joins distributions of different models into one portfolio, with a

Usage

Source

join(parts, dim, same_simulations=False)

leading dimension dim holding each part’s label, followed by the union of the parts’ dimensions ("" where a part lacks one). Simulation i of the result is simulation i of every part.

Parameters
parts: list of (str, PredictiveDistribution)
dim: str
same_simulations: bool = False
False: the parts were simulated separately, and two with the same seed and stream scheme (which would share random numbers) are refused. True: the parts come from the same scenarios (a cover applied to a reserve) and keep their pairing.
Returns
PredictiveDistribution
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> a = PredictiveDistribution(["origin"], [(2023,), (2024,)], [[10.0, 20.0], [12.0, 25.0]])
>>> b = PredictiveDistribution(["lob"], [("motor",)], [[50.0], [40.0]])
>>> p = PredictiveDistribution.join([("reserve", a), ("premium", b)], "risk")
>>> p.dims, p.total().draws

([‘risk’, ‘origin’, ‘lob’], [80.0, 77.0])


marginal()

One component’s draws, or None if no component has this key.

Usage

Source

marginal(key)

An origin period is named by its label, as a string or an integer: ("2021",) or (2021,) for a year, ("2021Q3",) for a quarter.

Parameters
key: tuple
Returns
Sampled or None

mean()

Mean of the total.

Usage

Source

mean()
Returns
float

provenance()

Where this result came from: model, parameters, seed, stream scheme,

Usage

Source

provenance()

samplers, crate versions and input hash.

stream_scheme names how simulations map to random-number streams; samplers lists (family, sampler id) pairs, e.g. [("gamma", "marsaglia-tsang/2026-10")]: the sampler table of the build that made the draws, so every sampler they may have used. A family not listed uses its first sampler (inverse transform for a distribution, the documented method for a copula’s frailty). A result replays only with the same seed, stream scheme and samplers. samplers is None when not recorded: a result without draws, one computed from draws made elsewhere, or one made by a build from before samplers were recorded (2026-10-08).

Returns
dict

quantile()

Quantile of the total.

Usage

Source

quantile(p)
Parameters
p: float
Returns
float
Raises
ValueError
If p is outside [0, 1].

reorder_groups()

Sets the dependence between the groups of dimension dim by

Usage

Source

reorder_groups(dim, correlation, seed, kind="pearson", return_index=False)

Iman–Conover on the groups’ totals, moving each group’s simulations as whole rows: every group keeps its distribution and internal joint structure, and the group totals take a rank correlation close to correlation.

Parameters
dim: str
correlation: list of list of float

One row and column per group, in order of first appearance (groups(dim)); correlation_from_pairs builds it from a long table.

seed: int
kind: str = "pearson"

"pearson" (the default: the normal scores’ correlation, so Spearman’s rho comes out near (6/π) asin(r/2)) or "spearman" (a Spearman target, converted to 2 sin(π ρ / 6) first).

return_index: bool = False
Also return where each simulation came from (see below).
Returns
PredictiveDistribution, or (PredictiveDistribution, dict)
With return_index, also a dict from each group to the list of input simulations its rows came from: simulation i of the result holds the group’s row of input simulation index[group][i]. EventSet.permute(index[group]) keeps a class’s events with its reordered totals, with no matching of values (which tied draws defeat).
Raises
ValueError
If the matrix (after conversion) is not a positive definite correlation matrix, or kind is unknown.
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> n = 4000
>>> pd = PredictiveDistribution(
...     ["seg"], [("a",), ("b",)], [[i, (i * 7919) % n] for i in range(n)])
>>> r = pd.reorder_groups("seg", [[1, 0.6], [0.6, 1]], 5, kind="spearman")
>>> groups, rho = r.group_spearman("seg")
>>> groups, abs(rho[0][1] - 0.6) < 0.02

([‘a’, ‘b’], True)

>>> r, index = pd.reorder_groups("seg", [[1, 0.6], [0.6, 1]], 5, return_index=True)
>>> before, after = pd.draw_matrix(), r.draw_matrix()
>>> all(after[i][0] == before[index["a"][i]][0] for i in range(n))

True


reorder_groups_by_copula()

Sets the dependence between the groups of dimension dim by a

Usage

Source

reorder_groups_by_copula(dim, copula, seed, return_index=False)

copula: n_sims draws of uniforms from copula (draw i on stream i of seed, as copula.sample), and each group’s simulations, whole rows sorted by the group’s total, take the ranks of its column. The group totals then have the copula’s rank pattern, so a t, Gumbel or Clayton copula gives its joint tails to results already simulated; every group keeps its distribution and internal joint structure, as under reorder_groups.

Parameters
dim: str
copula: (
    GaussianCopula,
    StudentTCopula,
    ArchimedeanCopula,
    NestedArchimedeanCopula or VineCopula,
)

One dimension per group, in order of first appearance (groups(dim)).

seed: int
return_index: bool = False
Also return where each simulation came from, as reorder_groups does.
Returns
PredictiveDistribution, or (PredictiveDistribution, dict)
Raises
ValueError
If the copula’s dimension is not the number of groups.
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> from prospicio.risk import ArchimedeanCopula
>>> n = 4000
>>> pd = PredictiveDistribution(
...     ["seg"], [("a",), ("b",)], [[i, (i * 7919) % n] for i in range(n)])
>>> clayton = ArchimedeanCopula("clayton", 2.0, 2)  # Spearman's rho near 0.68
>>> r = pd.reorder_groups_by_copula("seg", clayton, 5)
>>> abs(r.group_spearman("seg")[1][0][1] - 0.68) < 0.03

True


scale_to_totals()

Every simulation’s components rescaled pro rata to a new total.

Usage

Source

scale_to_totals(totals)

Component k in simulation s becomes c[s][k] * totals[s] / sum_k c[s][k] (unchanged when the components sum to 0). This carries a total computed from the components, a loss-ratio cap over several classes or a stop loss on a mix of perils, back onto them in proportion to their shares; it is not a capital allocation. The keys and dimensions are kept.

Parameters
totals: list of float
One total per simulation.
Returns
PredictiveDistribution
Raises
ValueError
Not one finite total per simulation, or a non-zero total where the components sum to 0.
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> pd = PredictiveDistribution(["class"], [("motor",), ("home",)], [[6.0, 9.0], [3.0, 1.0]])
>>> pd.scale_to_totals([10.0, 4.0]).draw_matrix()

[[4.0, 6.0], [3.0, 1.0]]


select()

The components whose value on dimension dim is one of keys,

Usage

Source

select(dim, keys)

with every dimension and the draws’ joint structure kept.

Take one part of a result this way before joining it to another: Tower.apply(...).select("kind", ["ceded"]) is a treaty’s cession, ready to add to a book. Aggregating over kind instead adds gross, ceded and net together.

Parameters
dim: str
keys: list of int or str
Returns
PredictiveDistribution
Raises
ValueError
An unknown dimension, no keys, or a key no component has.
Examples
>>> from prospicio.distributions import PredictiveDistribution
>>> pd = PredictiveDistribution(
...     ["kind", "layer"], [("gross", "ground_up"), ("ceded", "5x5"), ("net", "retained")],
...     [[10.0, 3.0, 7.0], [4.0, 0.0, 4.0]])
>>> pd.select("kind", ["ceded"]).mean()

1.5


to_json()

The distribution as a JSON document: dimensions, component keys,

Usage

Source

to_json()

provenance and draws, numbers bit for bit (#978). from_json reads it back; pickle uses the same document.

Returns
str
Examples
>>> import pickle
>>> from prospicio.distributions import PredictiveDistribution
>>> pd = PredictiveDistribution(["line"], [("A",), ("B",)], [[1.0, 2.0], [3.0, 4.5]])
>>> back = PredictiveDistribution.from_json(pd.to_json())
>>> back.draw_matrix() == pd.draw_matrix() and back.components() == pd.components()

True

>>> pickle.loads(pickle.dumps(pd)).draw_matrix() == pd.draw_matrix()

True


to_numpy()

All draws as a read-only NumPy array, one row per simulation and one

Usage

Source

to_numpy()

column per component, in the order of components(). The array is a view of the distribution’s own buffer: nothing is copied, and it keeps the distribution alive (#978). numpy.array(pd.to_numpy()) gives a writeable copy.

Returns
numpy.ndarray
Float64, of shape (n_sims, n_components).
Examples
>>> import numpy as np
>>> from prospicio.distributions import PredictiveDistribution
>>> pd = PredictiveDistribution(["line"], [("A",), ("B",)], np.array([[1.0, 2.0], [3.0, 4.5]]))
>>> pd.to_numpy()

array([[1. , 2. ], [3. , 4.5]])

>>> pd.to_numpy().flags.writeable

False


total()

The total over all components, one value per simulation.

Usage

Source

total()
Returns
Sampled

tvar()

Tail value at risk of the total at level p.

Usage

Source

tvar(p)
Parameters
p: float
Returns
float
Raises
ValueError
If p is outside [0, 1].

var()

Value at risk of the total at level p.

Usage

Source

var(p)
Parameters
p: float
Returns
float
Raises
ValueError
If p is outside [0, 1].

variance()

Variance of the total.

Usage

Source

variance()
Returns
float