aggregate.EventSet
Simulated years of individual losses, for applying per-loss terms such
Usage
aggregate.EventSet()as reinsurance layers.
Created by simulate_events. Year i was drawn from stream i of the generator keyed by seed, so results do not depend on the number of threads.
Attributes
| Name | Description |
|---|---|
| aggregate_part_labels | Each column of the aggregate part’s labels, one value per label |
| has_aggregate_part | Whether the years carry an aggregate part. |
| has_labels | Whether the losses carry labels. |
| has_sums_insured | Whether the losses carry sums insured. |
| has_times | Whether the losses carry times. |
| input_hash | A hash of the years’ source (a year loss table’s file), which |
| label_combinations | The distinct combinations of label values, one value per dimension, |
| label_dims | The label dimensions, empty without labels. |
| n_sims | Number of simulated years. |
| seed | The seed the years were drawn from. |
aggregate_part_labels
Each column of the aggregate part’s labels, one value per label
aggregate_part_labels: list[list[str]] | None
dimension, or None without a part.
has_aggregate_part
Whether the years carry an aggregate part.
has_aggregate_part: bool
has_labels
Whether the losses carry labels.
has_labels: bool
has_sums_insured
Whether the losses carry sums insured.
has_sums_insured: bool
has_times
Whether the losses carry times.
has_times: bool
input_hash
A hash of the years’ source (a year loss table’s file), which
input_hash: str | None
results record as their provenance’s input hash, or None.
label_combinations
The distinct combinations of label values, one value per dimension,
label_combinations: list[list[str]]
sorted: the labels of Tower.apply’s components.
label_dims
The label dimensions, empty without labels.
label_dims: list[str]
n_sims
Number of simulated years.
n_sims: int
seed
The seed the years were drawn from.
seed: int
Methods
| Name | Description |
|---|---|
| __eq__() |
Whether other is an event set with the same years, losses and
|
| aggregate_part() |
Year sim’s aggregate part, one amount per column in the order of
|
| calibrate_year_correlation() |
The correlation between every pair of n_years years for which
|
| contract_years() |
The events regrouped into contract years starting at start, a
|
| correlated_years() |
A term of n_years underwriting years whose yearly totals (each
|
| counts() | Number of losses in each year. |
| events() |
Year sim’s individual losses, in the order they were drawn.
|
| filter() | The losses whose label label takes one of values, every |
| from_json() | An event set from a document written by to_json. |
| from_long() | Years of losses in long form, as a year loss table lists them: one |
| from_years() | Years of losses from elsewhere (your own simulation, or a |
| from_ylt() | Years of losses from a year loss table’s columns, checked and |
| grouped() | Each year’s losses grouped into occurrences by an hours clause. |
| labels() |
Year sim’s labels, a list per dimension with a value per loss,
|
| maxima() | Each year’s largest loss (0 in a year with none): its survival |
| merge() | Both sets’ losses in each year: a catastrophe event set with a |
| permute() |
The years in another order: year i of the result is year
|
| sums_insured() |
Year sim’s sums insured, one per loss, or None.
|
| term_years() |
Splits the simulations into a term of n_years consecutive
|
| times() |
Year sim’s times, one per loss, or None.
|
| to_json() | The years as a JSON document: losses, and their sums insured, |
| to_numpy() | Every year’s losses as read-only NumPy arrays, without copying |
| totals() | Each year’s total loss. |
| with_aggregate_part() | The same events with an aggregate part: amounts in each year that |
| with_labels() | The same events with labels, a peril or a class say. |
| with_seasonal_times() | The same events at times drawn from a seasonal density. |
| with_uniform_times() | The same events at times spread uniformly over the year. |
__eq__()
Whether other is an event set with the same years, losses and
Usage
__eq__(other)everything they carry.
aggregate_part()
Year sim’s aggregate part, one amount per column in the order of
Usage
aggregate_part(sim)aggregate_part_labels, or None.
Parameters
sim: int
Returns
list of float or None
calibrate_year_correlation()
The correlation between every pair of n_years years for which
Usage
calibrate_year_correlation(
n_years, ratio, *, kind="spearman", draws="same", seed=0
)correlated_years gives a term whose mean yearly total has ratio times the standard deviation of one year’s total, found by bisection on these simulations. With the same premium each year, that is the ratio of the term’s loss ratio’s spread to one year’s. Independent years give 1 / sqrt(n_years), identical ones 1.
Parameters
n_years: intratio: float-
In
[0, 1]. kind: str = "spearman"-
As correlated_years.
draws: str = "spearman"-
As correlated_years.
seed: str = "spearman"- As correlated_years.
Returns
tuple of (float, float, list of EventSet)- The correlation, the ratio it achieves and the years under it.
Examples
>>> from prospicio.aggregate import EventSet
>>> from prospicio.distributions import Lognormal, Poisson
>>> from prospicio.aggregate import simulate_events
>>> e = simulate_events(Poisson(2.0), Lognormal.from_mean_cv(100.0, 1.0), 4000, seed=7)
>>> rho, achieved, years = e.calibrate_year_correlation(3, 0.75, seed=11)
>>> abs(achieved - 0.75) < 1e-3, 0 < rho < 1, len(years)(True, True, 3)
contract_years()
The events regrouped into contract years starting at start, a
Usage
contract_years(start, partial="drop")fraction of the simulated year, for a treaty whose year is not the simulation’s (#586). The simulated years are read as consecutive years of one timeline: a loss of year i at time t happens at i + t, contract year j runs from j + start to j + 1 + start, and each loss moves to its contract year with its time rebased to it, keeping its sum insured and labels. The first and last contract years are partial: partial="drop" (the default) leaves them out with their losses, so n - 1 whole years remain; "keep" keeps them, n + 1 years. start=0 returns the set as it is.
Parameters
start: float-
In
[0, 1). partial: str = "drop"-
"drop"or"keep".
Returns
EventSet
Raises
ValueError-
Without times, for
startoutside[0, 1), with an aggregate part, or when no whole contract year is left.
Examples
>>> from prospicio.aggregate import EventSet
>>> cal = EventSet.from_years([[1.0, 2.0], [3.0]], times=[[0.25, 0.75], [0.25]])
>>> july = cal.contract_years(0.5)
>>> july.n_sims, july.events(0), july.times(0)(1, [2.0, 3.0], [0.25, 0.75])
counts()
Number of losses in each year.
Usage
counts()Returns
list of int
events()
Year sim’s individual losses, in the order they were drawn.
Usage
events(sim)Parameters
sim: int
Returns
list of float
Raises
IndexError-
If
simis not a simulated year.
filter()
Usage
filter(label, values)year kept (a year with none of them is empty), with their sums insured, times and labels, and the aggregate part’s columns with one of the values: what a layer scoped to those values (Layer.with_scope) sees.
Parameters
label: strvalues: list of str
Returns
EventSet
Raises
ValueError- Without labels, without the dimension, or with no values.
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[20.0, 15.0], [8.0]]).with_labels(
... {"peril": ["quake", "wind", "quake"]})
>>> w = e.filter("peril", ["wind"])
>>> w.n_sims, w.events(0), w.events(1)(2, [15.0], [])
from_json()
An event set from a document written by to_json.
Usage
from_json(text)Parameters
text: str
Returns
EventSet
Raises
ValueError- If the text is not such a document, or is from a newer version.
from_long()
Years of losses in long form, as a year loss table lists them: one
Usage
from_long(years, losses, n_years, seed=0, labels=None)row per loss with its year, an index from 0 to n_years - 1.
Within a year the losses keep their order; years with no row are empty.
Parameters
years: list of intlosses: list of floatn_years: int-
The number of simulated years, including those with no loss.
seed: int = 0labels: dict of str to list of str = None-
Each row’s labels, a list per label dimension (
{"peril": [...], "class": [...]}), as with_labels takes them.
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_long([2, 0, 2], [5.0, 1.0, 7.0], 4)
>>> e.counts(), e.events(2)([1, 0, 2, 0], [5.0, 7.0])
>>> e = EventSet.from_long([2, 0, 2], [5.0, 1.0, 7.0], 4, labels={"peril": ["wind", "quake", "wind"]})
>>> e.labels(0){‘peril’: [‘quake’]}
from_years()
Years of losses from elsewhere (your own simulation, or a
Usage
from_years(years, sums_insured=None, seed=0, times=None)catastrophe model’s event loss table by year), optionally with the sum insured of the risk each loss hit, which a surplus treaty needs.
Parameters
years: list of list of float-
Each year’s losses, in order.
sums_insured: list of list of float = None-
The same shape: each loss’s sum insured, at least the loss.
seed: int = 0-
Recorded in results’ provenance; the samplers are not, since the losses were not drawn here.
times: list of list of float = None-
The same shape: each loss’s time, as the fraction of the year elapsed (in
[0, 1], non-decreasing within a year), which reinstatements pro rata as to time need.
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[5.0, 2.0], [], [9.0]], [[10.0, 2.0], [], [50.0]])
>>> e.counts(), e.sums_insured(2)([2, 0, 1], [50.0])
from_ylt()
Years of losses from a year loss table’s columns, checked and
Usage
from_ylt(
years,
losses,
*,
slots=None,
times=None,
labels=None,
n_years=None,
n_sims=None,
expand="tile",
seed=0,
unique_by=None,
expected=None,
source_hash=None,
losses_negative=False
)expanded to a run’s simulations.
Rows are ordered by year, then slot (the given order breaking ties), and each row is one loss: rows sharing a slot, an event hitting several classes, stay separate losses, so an occurrence layer sees each of them. prospicio.aggregate.read_ylt reads the columns from a CSV or Parquet file.
Parameters
years: list of int or numpy.ndarray-
Each row’s year, from 1.
losses: list of float or numpy.ndarray-
Finite and non-negative.
slots: list of int or numpy.ndarray = None-
Each row’s event slot, which orders a year’s rows.
times: list of float or numpy.ndarray = None-
Each row’s time of loss, the fraction of its year elapsed, in
[0, 1]. Rows are then ordered by time within a year, the slot (or the given order) breaking ties, and the events carry the times (has_times), for an hours clause (grouped) and reinstatements pro rata as to time. labels: dict of str to list of str = None-
Each row’s labels, a list per dimension (
{"peril": [...], "class": [...]}). n_years: int = None-
The table’s years, at least its largest year; by default the largest year.
n_sims: int = None-
The simulations to expand to, by default
n_years. expand: (tile, resample) = "tile"-
"tile": simulationi(from 0) takes yeari % n_years, so n_sims must be a multiple ofn_years."resample": each simulation takes a year drawn uniformly with replacement from its own stream of seed. seed: int = 0unique_by: list of str = None-
With slots, no two rows may share a year, a slot and their values in these label dimensions (
["peril"]: one slot may hit several classes, not repeat a peril); by default every label dimension. expected: dict of str to list of str = None-
The values allowed in each named dimension (
{"peril": ["WS", "EQ"]}). source_hash: str = None-
A hash of the source, recorded as results’ input hash.
losses_negative: bool = False- The losses are stored as negative numbers, money going out: each must be at most 0 and is read with its sign flipped.
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_ylt([2, 1, 2], [5.0, 1.0, 7.0], slots=[9, 1, 3], n_sims=4)
>>> e.events(1), e.events(3)([7.0, 5.0], [7.0, 5.0])
grouped()
Each year’s losses grouped into occurrences by an hours clause.
Usage
grouped(window_hours, *, labels="drop", by=None)Losses within window_hours of the first loss of a window are one occurrence, whose loss is their sum and whose time is the window’s start; the next loss after the window opens the next one. A year is 8,760 hours. Windows open at each first loss in turn, not where they would recover most. Needs times; sums insured are not carried.
Parameters
window_hours: float-
Such as 72 for a windstorm, 168 for a flood.
labels: (drop, agree, largest) = "drop"-
What the occurrences carry of the losses’ labels: none (
"drop"), their losses’ labels, which must agree within an occurrence ("agree", an error otherwise), or the labels of the largest loss in the occurrence, the earliest of equal ones ("largest"). An aggregate part keeps its labels unless they are dropped. by: str = None-
A label dimension,
"peril"say: the clause applies within each of its values, so losses of two perils are never one occurrence, and the occurrences keep the labels (labels then decides the other dimensions,"drop"read as"agree"). Occurrences are listed by the time each window opens.
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> h = 1 / 8760
>>> e = EventSet.from_years([[10.0, 20.0, 5.0]], times=[[0.5, 0.5 + 30 * h, 0.5 + 80 * h]])
>>> e.grouped(72.0).events(0)[30.0, 5.0]
>>> p = EventSet.from_years([[10.0, 20.0, 5.0]], times=[[0.5, 0.5 + 30 * h, 0.5 + 40 * h]])
>>> g = p.with_labels({"peril": ["wind", "flood", "wind"]}).grouped(72.0, by="peril")
>>> g.events(0), g.labels(0)([15.0, 20.0], {‘peril’: [‘wind’, ‘flood’]})
labels()
Year sim’s labels, a list per dimension with a value per loss,
Usage
labels(sim)or None.
Parameters
sim: int
Returns
dict of str to list of str or None
maxima()
Each year’s largest loss (0 in a year with none): its survival
Usage
maxima()function is the simulated occurrence exceedance (OEP) curve, and its quantiles the occurrence PMLs.
Returns
PredictiveDistribution
merge()
Both sets’ losses in each year: a catastrophe event set with a
Usage
merge(other)non-catastrophe one, say.
The sets need the same number of years. With times on both, each year’s losses are merged in time order (this set’s first on a tie); with times on neither, this set’s losses come first. Sums insured are kept when both sets carry them. Labels are kept when either carries them: this set’s dimensions, then the other’s new ones, with "" for a loss without a value in a dimension.
Parameters
other: EventSet
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> cat = EventSet.from_years([[100.0], []], times=[[0.5], []])
>>> other = EventSet.from_years([[3.0, 4.0], [5.0]], times=[[0.2, 0.7], [0.1]])
>>> cat.merge(other).events(0)[3.0, 100.0, 4.0]
permute()
The years in another order: year i of the result is year
Usage
permute(index)index[i] of this set, with its losses, sums insured, times and labels. Pass the index PredictiveDistribution.reorder_groups returns for a class (return_index=True) to keep the class’s events with its reordered totals; any index into the years works, so a resample with repeats does too.
Parameters
index: list of int- 0-based years of this set.
Returns
EventSet
Raises
ValueError- If the index is empty or names a year past the last.
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[], [50.0], [5.0, 60.0]])
>>> [e.permute([2, 0, 1]).events(i) for i in range(3)][[5.0, 60.0], [], [50.0]]
sums_insured()
Year sim’s sums insured, one per loss, or None.
Usage
sums_insured(sim)Parameters
sim: int
Returns
list of float or None
term_years()
Splits the simulations into a term of n_years consecutive
Usage
term_years(n_years)blocks, for Tower.apply_term: year t (from 0) holds simulations t * n to (t + 1) * n - 1, with n = n_sims // n_years, so path j’s year t is simulation t * n + j. Sums insured and times go with their losses.
Parameters
n_years: int- Must divide n_sims.
Returns
list of EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[1.0], [2.0], [3.0], [4.0]])
>>> [y.events(1) for y in e.term_years(2)][[2.0], [4.0]]
times()
Year sim’s times, one per loss, or None.
Usage
times(sim)Parameters
sim: int
Returns
list of float or None
to_json()
The years as a JSON document: losses, and their sums insured,
Usage
to_json()times, labels and aggregate parts when present, with the seed and provenance, numbers bit for bit (#978). from_json reads it back; pickle uses the same document.
Returns
str
Examples
>>> import pickle
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[5.0, 2.0], [], [9.0]], seed=3)
>>> EventSet.from_json(e.to_json()) == eTrue
>>> pickle.loads(pickle.dumps(e)) == eTrue
to_numpy()
Every year’s losses as read-only NumPy arrays, without copying
Usage
to_numpy()(#978): losses, all the losses year after year, and offsets, where each year starts, so year i’s losses are losses[offsets[i]:offsets[i + 1]]. Both are views of the event set’s own buffers and keep it alive.
Returns
tuple of numpy.ndarray-
(losses, offsets): float64 of lengthoffsets[-1], and uint64 of lengthn_sims + 1, from 0.
Examples
>>> import numpy as np
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[1.0, 2.0], [], [3.5]])
>>> losses, offsets = e.to_numpy()
>>> losses, offsets(array([1. , 2. , 3.5]), array([0, 2, 2, 3], dtype=uint64))
>>> np.add.reduceat(losses, offsets[:-1].astype(np.intp))[np.diff(offsets) > 0]array([3. , 3.5])
totals()
Each year’s total loss.
Usage
totals()Returns
PredictiveDistribution
with_aggregate_part()
The same events with an aggregate part: amounts in each year that
Usage
with_aggregate_part(part)are no event and have no time, attritional losses say, one column per component of part.
part needs as many simulations as the set has years; simulation i goes with year i. Its dimensions are label dimensions, so the part can be given by peril or class: the set’s labels get the part’s dimensions not among them, with "" for every loss. A part with no dimensions is one unlabelled amount a year. Replaces any aggregate part the set had; label the events first.
Tower.apply counts the part in gross and net, and only layers that see it (Layer.sees_aggregate_part: quota shares and stop losses) cede from it. In each year it comes before the events, so a binding annual deductible is used up on it first, unless the layer shares annual terms pro rata. totals includes it; maxima and counts do not.
Parameters
part: PredictiveDistribution
Returns
EventSet
Raises
ValueError-
If
parthas another number of simulations, a negative or non-finite amount, or a dimension"kind"or"layer", or if labels are given after the part.
Examples
>>> from prospicio.aggregate import EventSet
>>> from prospicio.distributions import PredictiveDistribution
>>> from prospicio.reinsurance import Layer, Tower
>>> attritional = PredictiveDistribution([], [()], [[10.0], [40.0], [30.0]])
>>> e = EventSet.from_years([[], [50.0], [5.0, 60.0]]).with_aggregate_part(attritional)
>>> r = Tower([Layer("30x25", 30.0, 25.0)]).apply(e)
>>> list(r.marginal(("ceded", "30x25")).draws)[0.0, 25.0, 30.0]
with_labels()
The same events with labels, a peril or a class say.
Usage
with_labels(labels)Tower.apply then gives gross, each layer’s ceded loss and net by label, with the label dimensions after kind and layer; merge keeps the labels of either set. Replaces any labels the set had.
Parameters
labels: dict of str to list of str-
One list per label dimension, a value per loss, years in order as events lists them. The names may not be
"kind"or"layer".
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[5.0, 2.0], [9.0]]).with_labels({"peril": ["wind", "flood", "wind"]})
>>> e.label_dims, e.label_combinations([‘peril’], [[‘flood’], [‘wind’]])
with_seasonal_times()
The same events at times drawn from a seasonal density.
Usage
with_seasonal_times(weights)The year is cut into len(weights) equal periods (12 for months, 52 for weeks) starting at the contract’s inception, and a loss falls in period k with probability weights[k] / sum(weights), uniformly within it. A zero weight means no losses in that period. The draws are those of with_uniform_times, mapped through the season’s quantile, so equal weights give the uniform times.
Parameters
weights: list of float- Each period’s relative weight: non-negative, not all zero.
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[5.0, 2.0, 7.0]], seed=3)
>>> t = e.with_seasonal_times([0.0, 1.0]).times(0)
>>> all(x >= 0.5 for x in t) and t == sorted(t)True
with_uniform_times()
The same events at times spread uniformly over the year.
Usage
with_uniform_times()Year i‘s losses take sorted uniform draws, in their order, from a stream of the generator keyed by the set’s seed apart from the losses’ own, so the losses are unchanged and any year replays alone.
Returns
EventSet
Examples
>>> from prospicio.aggregate import EventSet
>>> e = EventSet.from_years([[5.0, 2.0, 7.0]], seed=3).with_uniform_times()
>>> t = e.times(0)
>>> t == sorted(t) and e.has_timesTrue