Plots

vecxt_re can plot its distributions, fit diagnostics, indices and scenarios. Every plot is a Vega-Lite spec, shown through a plot target that you bring into scope:

Target Use
viz.PlotTargets.desktopBrowser open in the default browser
viz.PlotTargets.almond inline in an Almond (Jupyter) notebook
viz.PlotTargets.tempHtmlFile, viz.PlotTargets.png write to a file

The examples below assume:

import vecxt_re.all.*
import viz.PlotTargets.desktopBrowser

Each example is type-checked against the library on every docs build, but not run. Values written ??? are your own inputs.

Every plot also accepts mods: Seq[SpecMod], which edits the Vega-Lite JSON after the plot's own settings are applied. The one you will most often want is fixedSize(width, height). Both come from vecxt_re.Plots, and vecxt_re.all.* exports them. Plots size themselves to their container by default, which can grow without limit in a notebook:

NegativeBinomial(4.0, 2.0).plot(Seq(fixedSize(600, 400)))

Distributions

NegativeBinomial, Poisson, Pareto, Empirical and Mixed all have plot (the probability mass or density function) and plotCdf:

NegativeBinomial(a = 4.0, b = 2.0).plot
Poisson(6.5).plotCdf
Pareto(scale = 10.0e6, shape = 1.4).plot

Fit diagnostics for count models

NegativeBinomial and Poisson have three plots comparing a fitted distribution with the counts it was fitted to. These are the natural follow-up to mle / volweightedMle.

val counts: Array[Int] = ???
val fitted = NegativeBinomial.mle(counts).dist

fitted match
  case nb: NegativeBinomial =>
    nb.plotEcdfVsCdf(counts.toIndexedSeq)
    nb.plotRootogram(counts.toIndexedSeq)
    nb.plotPearsonResiduals(counts.toIndexedSeq)
  case p: Poisson =>
    p.plotRootogram(counts.toIndexedSeq)
Plot Shows Look for
plotEcdfVsCdf empirical CDF against the fitted CDF, both as step functions systematic gaps between the two curves
plotRootogram bars hanging from √expected down to √observed, for each count value k bar ends far from zero. Below zero means the model under-predicts that count; above zero means it over-predicts. The grey band marks ±1.
plotPearsonResiduals (Ok − Ek)/√Ek for each count value k residuals beyond ±2 (red), and systematic patterns. For a Poisson fit, a U shape suggests overdispersion.

With only 10–30 years of counts, all three plots are noisy. Treat them as a check for gross misfit, not as a test.

Trend in counts

plotTrend fits a Poisson regression log(count) = β₀ + β₁·year by iteratively reweighted least squares, and plots the observations, the fitted trend and a 95% confidence band. The title shows β₀ and β₁ with their standard errors.

val years: IndexedSeq[Int] = ???
val counts: IndexedSeq[Int] = ???

Poisson(1.0).plotTrend(years, counts)

plotTrend is defined on a Poisson value, but it fits its own model from years and counts; the value's λ is not used. Use it for the stationarity check in the frequency recipe: a clearly non-zero β₁ means the years are not draws from one distribution. With a short history the confidence band is wide, so the check catches only large trends, such as a change in reporting or event definition. It cannot confirm that frequency is stable.

Trend in severity

With small data volumes, no statistical test of severity trend is robust. The trend in the forecast should come from the normalisation index and from outside evidence: market inflation, industry losses, similar portfolios. The portfolio's own losses can only check whether that index is consistent with them. Use two plots for that check:

Expect either to catch only clear problems: a missing normalisation step, an index applied twice or in the wrong direction, mixed currencies, a wrong date.

Look: losses over time

plotLossStems draws each loss at its date: the amount as reported (blue), the normalised amount (orange, joined to the reported amount by a stem), and a rolling average of the normalised amounts (green).

import java.time.LocalDate

val dates: IndexedSeq[LocalDate] = ???
val amounts: IndexedSeq[Double] = ???    // as reported
val normalised: IndexedSeq[Double] = ??? // on-levelled to the current year

plotLossStems(dates, amounts, normalised, rollingYears = 3)

The rolling average for end year Y is the mean normalised loss dated in years Y − rollingYears + 1 to Y. It is drawn at 31 December of Y, and only for windows that lie inside the data. With few losses per window it moves a lot from year to year; look at its overall direction, not at individual steps. Look for:

Check: regression on log severity

plotSeverityTrend fits log(loss) = β₀ + β₁·year by ordinary least squares. It plots each loss on a log scale, with the fitted median severity and a confidence band.

val years: IndexedSeq[Int] = ???
val losses: IndexedSeq[Double] = ??? // on-levelled, above a fixed threshold

plotSeverityTrend(years, losses)

val fit = fitSeverityTrend(years, losses)
fit.annualTrendCI() // 95% interval for exp(β₁) − 1
println(fit.summary)

// trend with each loss left out in turn
val withoutEach = fitSeverityTrendLeaveOneOut(years, losses).map(_.map(_.annualTrend))

Read the confidence interval against the trend you expect the index to have removed:

The p-value and the interval carry the same information: the interval excludes zero exactly when p < alpha. The p-value is a continuous measure of how compatible the data is with no trend. Read it as a degree of confidence, not as a pass or fail at 0.05. With small data volumes, how much it moves when a single loss is left out matters as much as its value. fit.pValueSlope and fit.summary give it outside the plot.

Reading the result

Tails

val losses: Array[Double] = ???

HillEstimator.hillPlot(losses).plotHill
HillEstimator.hillPlot(losses, convention = HillConvention.Embrechts).plotHill
HillEstimator.hillPlot(losses, convention = HillConvention.Unbiased).plotHill
PickandsEstimator.pickandsPlot(losses).plotPickands
PickandsEstimator.pickandsPlot(losses).plotPickandsGamma
Plot Shows Look for
plotHill the Hill estimate of the Pareto tail index α̂ against k / n, the empirical exceedance probability of its threshold, as points with a 95% interval that is exact for Pareto data. A red sawtooth shows the estimate with the threshold sliding continuously between losses: it jumps as each loss enters and decays until the next one does. The curve and the band are the same whatever the convention; only the points move, and the subtitle says where. HillConvention.MaxLikelihood (default) puts the threshold at the (k+1)-th largest loss, so the points are the bottoms of the teeth; it is biased high by k / (k − 1) for Pareto data, 25% at k = 5. HillConvention.Embrechts (Embrechts, Klüppelberg & Mikosch) puts it at the k-th largest, so the points are the tops of the teeth; biased high by k / (k − 2), and so starting at k = 3 by default, which keeps the thresholds the same as the other conventions. HillConvention.Unbiased uses (k − 1) / k times the maximum likelihood estimate, exactly unbiased for Pareto data. The y-axis stops just above the highest estimate (plotHill(mods, yMax) to set it) a stable plateau. The left end uses only the largest losses and is noisy; further right, losses from outside the tail pull the estimate away. With small data volumes the interval is wide at every threshold, so no plateau can be pinned down.
plotPickands the Pickands estimate α̂(k) = 1/γ̂(k) a plateau, as for Hill. Pickands is more robust to misspecification than Hill but noisier.
plotPickandsGamma the Pickands extreme value index γ̂(k) γ > 0 is a heavy tail, γ ≈ 0 exponential-like, γ < 0 bounded

For a fitted Mixed distribution (empirical body with a Pareto tail), plotLogLogVsSample compares the model's survival function with the sample's on log-log axes. A Pareto tail is a straight line there:

val mixed: Mixed = ???
val samples: IndexedSeq[Double] = ???

mixed.plotLogLogVsSample(samples, threshold = 10.0e6)

threshold sets where the x-axis starts.

Indices

val tivIndex: CalendarYearLevels = ???
tivIndex.plotLevels()

val rateChanges: CalendarYearRateChanges = ???
rateChanges.plotIndex(reportingThreshold = 10.0e6, thresholdYear = 2016)

Scenarios

val scenario: Scenarr = ???

scenario.plotSeasonality()
scenario.plotSeasonality(highlight = Some((year = 2024, month = 9)))

plotSeasonality plots the scenario's losses summed by calendar month, as a share of the total. highlight picks out one month.

Exceedance curves (OEP / AEP)

plotOep and plotAep plot the occurrence or aggregate exceedance curves of a set of scenarios on one chart: loss along x, return period (log scale) up y. With more than one scenario, their combination (Scenarr.combineAll) is added as a thick line. Click a legend entry to pick out one curve.

val perils: Seq[Scenarr] = ???
val layers: Seq[Layer] = Seq(Layer(limit = 50e6, ret = 50e6), Layer(limit = 100e6, ret = 100e6))

perils.plotOep(layers, unit = AmountUnit.Mn)
perils.plotAep(total = None)
Seq(perils.head).plotOep(maxLoss = Some(500e6))

plotExceedance(
  perils,
  ExceedanceType.OEP,
  attachments = Seq((label = "Board appetite", loss = 75e6)),
  minReturnPeriod = 5,
  title = Some("Net OEP by peril")
)

The loss axis on an OEP plot with layers or attachments stops at 1.2 × the highest line, usually the top layer's exhaustion point, to leave 20% headroom without letting the tail squash everything else. Set maxLoss to choose the end yourself; on an AEP, or a plot with no lines, the axis covers every curve unless maxLoss is set.

Each layer adds dashed lines at its attachment (retention) and exhaustion (retention + limit): the occurrence terms on an OEP, the aggregate terms on an AEP. A dot marks where each curve reaches each line; hover it for the return period. The layer terms are compared with the scenario losses as they are, so plot the losses to the layer (ground up, or net of inuring cover).

The same numbers are available without plotting. Scenarr.oep and Scenarr.aep are ExceedanceCurves:

val scenario: Scenarr = ???

scenario.oep.lossAt(200)              // the 1-in-200 occurrence loss
scenario.aep.returnPeriodAt(100e6)    // Some(rp), or None if no iteration reaches 100m
scenario.oep.points                   // (returnPeriod, amount), largest first

The k-th largest of n iterations sits at return period n / k. Between those points the curve is a step: lossAt takes the next point up the curve, so it never understates the loss, and it refuses return periods beyond n.