Deductible, Limit and Residual Risk in Python
Buying cyber insurance means choosing three numbers at once: the deductible you absorb yourself, the coverage limit the insurer will pay, and the premium you can afford. A low deductible and a high limit feel safe, but the premium rises quickly. A high deductible keeps the bill small but leaves you exposed to a bad year. This article turns that tension into an optimization problem and solves it in Python.
1. The Example Problem
A mid-sized company faces the following cyber risk profile (all amounts in million USD).
- Incidents per year follow a Poisson distribution with mean $\lambda = 1.2$.
- Each incident causes a loss $X$ that follows a heavy-tailed lognormal distribution, $\ln X \sim \mathcal{N}(\mu, \sigma^2)$ with $\mu=\ln 0.5$ and $\sigma = 1.5$.
- The expected annual loss without insurance is about 1.84 M$, but a bad year can cost many times that.
The company can buy a per-incident policy with deductible $d$ and limit $L$. For one incident, the insurer pays
$$
I(X; d, L) = \min{(X-d)^+,; L},
$$
and the company keeps
$$
R(X; d, L) = X - I(X; d, L).
$$
Over a year, with $N \sim \mathrm{Poisson}(\lambda)$ incidents,
$$
S_{\text{pay}} = \sum_{i=1}^{N} I(X_i; d, L), \qquad S_{\text{ret}} = \sum_{i=1}^{N} R(X_i; d, L).
$$
The insurer prices the policy with an expected-value loading, a volatility loading and a capital charge on the limit:
$$
P(d, L) = (1+\theta),\mathbb{E}[S_{\text{pay}}] + \gamma,\mathrm{SD}[S_{\text{pay}}] + c,L + f,
$$
with $\theta = 0.30$, $\gamma = 0.20$, $c = 0.015$ and $f = 0.05$.
The total annual cost to the company is the premium plus the retained loss:
$$
C = P(d, L) + S_{\text{ret}}.
$$
Residual risk is measured by the Conditional Value at Risk. By the Rockafellar–Uryasev representation,

which is the average cost over the worst $(1-\alpha)$ fraction of years. Financial impact is measured by the probability that the annual cost exceeds a cash buffer $W = 8$ M$:
$$
\Pr(C > W).
$$
The optimization problem balances average cost against tail cost under a premium budget $B = 1.8$ M$:
$$
\min_{d,,L}; J(d, L) = (1-\rho),\mathbb{E}[C] + \rho,\mathrm{CVaR}_{0.95}(C)
\quad \text{s.t.} \quad P(d, L) \le B,;; 0 \le d \le 4,;; 0 < L \le 30,
$$
with risk weight $\rho = 0.5$.
For a lognormal severity, the expected annual payout has a closed form through the limited expected value $\mathrm{LEV}(u) = \mathbb{E}[\min(X, u)]$:
$$
\mathrm{LEV}(u) = e^{\mu + \sigma^2/2},\Phi!\left(\frac{\ln u - \mu - \sigma^2}{\sigma}\right) + u\left[1 - \Phi!\left(\frac{\ln u - \mu}{\sigma}\right)\right],
$$
$$
\mathbb{E}[S_{\text{pay}}] = \lambda,\big[\mathrm{LEV}(d+L) - \mathrm{LEV}(d)\big].
$$
The code uses this formula to validate the simulation.
2. Full Source Code
1 | import time |
3. Detailed Code Walkthrough
3.1 Parameters and the scenario set
All monetary values are in million USD. The incident loss has median $e^{\mu} = 0.5$ M$, but with $\sigma = 1.5$ its mean is $e^{\mu+\sigma^2/2} \approx 1.54$ M$ and its upper tail is very heavy. This is the typical shape of cyber losses: most incidents are small and a few are catastrophic.
The scenario set is generated once, at the top:
countsholds the number of incidents in each of the 40,000 simulated years.year_idxrepeats each year’s index once per incident, so every incident knows which year it belongs to.severityholds one lognormal loss per incident.
Every candidate policy is evaluated against exactly the same 40,000 simulated years. This is the common random numbers technique. Differences between policies then reflect the policies themselves rather than sampling noise, which makes the objective surface smooth enough to optimize reliably.
3.2 The speed-up: vectorization instead of loops
A naive implementation would loop over years and incidents for every candidate $(d, L)$, roughly 48,000 incidents times 900 grid points in pure Python. The code avoids this in four ways:
np.clip(severity - d, 0.0, L)computes $\min{(X-d)^+, L}$ for all incidents in a single vectorized call.np.bincount(year_idx, weights=..., minlength=N_YEARS)converts per-incident values into per-year totals in one pass. It replaces a Python-level group-by.np.partitioninsidecvarfinds the worst 5% of years in linear time, instead of sorting all 40,000 values.- The two-stage search uses a coarse 30 × 30 grid to find the global shape of the problem, then a zoom-in refinement on 15 × 15 local grids. The refinement needs only about 450 additional evaluations, and the full run takes only a few seconds.
3.3 Pricing and the objective
evaluate is the heart of the program. For an insured policy it computes the annual payout series, then applies the pricing formula: expected payout with loading $\theta$, plus a volatility charge $\gamma,\mathrm{SD}[S_{\text{pay}}]$, plus a capital charge $cL$ and a fixed fee $f$. The capital charge matters. It reflects that insurers hold capital against the limit they sell, so a higher limit costs more even when the extra layer is rarely hit. It also makes the choice of $L$ a genuine trade-off.
The retained loss is whatever the insurer does not pay, severity - payout. Adding the premium gives the total annual cost total, and from it the function returns the expected cost, the 95% VaR, the 95% CVaR and the exceedance probability $\Pr(C > W)$.
objective combines the mean and the tail as $J = (1-\rho),\mathbb{E}[C] + \rho,\mathrm{CVaR}_{0.95}(C)$. With $\rho = 0.5$, the company cares equally about its average bill and its worst-year bill.
3.4 Validation with the closed form
lev and expected_payout_analytic implement the lognormal formula from Section 1. The console report compares the simulated expected payout with the closed form for each insured strategy. A small relative gap confirms that the scenario set, the clipping logic and the bincount aggregation are all correct.
3.5 Grid search, budget and refinement
The first stage evaluates $J$, the premium and the residual tail loss on a $30 \times 30$ grid of $(d, L)$ pairs. Cells with a premium above the budget are set to infinity in J_feasible, so argmin returns the best feasible cell. A separate argmin on the raw J gives the unconstrained optimum for comparison.
The second stage zooms in around the best feasible cell twice, each time shrinking the search window by a factor of four. A candidate is accepted only if its premium respects the budget and it lowers $J$. This simple scheme is robust: it needs no gradients, handles the kinks that clipping creates in the objective, and cannot leave the feasible region.
3.6 Strategy comparison and plots
Four strategies are compared side by side: no insurance, a conventional mid-range policy ($d = 0.5$, $L = 10$), full cover ($d = 0.05$, $L = 30$) and the budget-constrained optimum. The figure uses a $2 \times 3$ layout: two 3D surfaces, one contour map, one scatter plot of the premium against residual risk, one exceedance-probability chart and one cost breakdown.
4. Console Output
==================================================================================================== Cyber insurance optimization: deductible d, limit L, premium ==================================================================================================== Scenario set: 40,000 years, 47,732 incidents Expected annual loss without insurance : 1.843 M$ Grid evaluations: 900 in 2.84 s (total with refinement 4.26 s) Premium budget: 1.80 M$ | Cash buffer: 8.0 M$ | CVaR level: 95% | rho = 0.50 ---------------------------------------------------------------------------------------------------- Unconstrained optimum : d = 0.050, L = 30.00, premium = 3.451, J = 4.528 Budget-constrained opt: d = 1.860, L = 16.29, premium = 1.800, J = 5.947 ---------------------------------------------------------------------------------------------------- Strategy d L Premium E[Ret] CVaR[Ret] E[Cost] VaR95 CVaR95 P(C>Buf) J No insurance 0.00 0.00 0.000 1.843 16.689 1.843 7.861 16.689 0.0486 9.266 Conventional 0.50 10.00 2.170 0.706 7.011 2.876 3.647 9.180 0.0129 6.028 Full cover 0.05 30.00 3.451 0.149 2.005 3.600 3.601 5.456 0.0030 4.528 Optimal (budget) 1.86 16.29 1.800 1.079 7.216 2.879 5.149 9.015 0.0081 5.947 ---------------------------------------------------------------------------------------------------- Validation of the simulated expected payout against the closed-form lognormal formula Conventional simulated = 1.1369 M$ | analytic = 1.1407 M$ | relative gap = 0.33% Full cover simulated = 1.6942 M$ | analytic = 1.7018 M$ | relative gap = 0.44% Optimal (budget) simulated = 0.7645 M$ | analytic = 0.7691 M$ | relative gap = 0.60% ====================================================================================================
5. Result Image

6. Reading the Results
Without a budget, the optimizer buys everything
The unconstrained optimum sits in the corner of the search space: the smallest deductible and the largest limit, with a premium of about 3.45 M$. Because the objective gives half its weight to the tail, and the tail of a lognormal severity is so expensive, insuring almost everything always lowers $J$. A premium that large is nearly double the expected annual loss of 1.84 M$, which is why a real company needs a budget constraint. The cyan diamond in the top-left of panel (3) marks this unconstrained corner.
Panels (1) and (2): the 3D surfaces
Panel (1) shows $J(d, L)$ as a smooth landscape. It falls toward low deductibles and high limits, which is the direction of heavy insurance, and rises steeply toward high deductibles and low limits, where the company carries most of the tail itself. Panel (2) shows the premium surface in the opposite shape: the premium is highest at low $d$ and high $L$. The translucent cyan plane is the budget. Where the premium surface rises above the plane, the policy is unaffordable. The optimal policy sits exactly on the intersection of the two.
Panel (3): the contour map and the budget frontier
The white curve is the set of policies whose premium equals the budget. Everything to its lower-right is affordable, and everything to its upper-left is not. The red star is the best point along that curve: a deductible of about 1.86 M$ and a limit of about 16.3 M$. The curve slopes upward, which shows the trade-off the company faces. Accepting a higher deductible frees premium budget that can be spent on a larger limit. The optimizer finds the point along this curve where the next unit of budget stops buying more tail protection than it costs.
Panel (4): premium versus residual risk
Every grid point is a dot, colored by its deductible. The cloud forms a clear lower-left frontier: for a given premium, some $(d, L)$ combinations leave far less tail risk than others. Without insurance, the CVaR of retained loss is about 16.7 M$. The optimal policy brings it down to about 7.2 M$ for a premium of 1.8 M$, and it sits on the efficient frontier just left of the dashed budget line. Spending the same premium on a poorly structured policy, such as a low deductible with a small limit, would leave visibly more residual risk.
Panel (5): exceedance curves and financial impact
The vertical axis is logarithmic, so the gaps between curves are large in relative terms. The probability that the annual cost exceeds the 8 M$ cash buffer is about 4.9% with no insurance, 1.3% with the conventional policy, 0.8% with the optimal policy and 0.3% with full cover. The optimal policy therefore cuts the chance of breaching the buffer by roughly a factor of six compared with doing nothing. It is also better than the conventional policy even though it costs less. Notice the vertical drops at the left of each insured curve: they are the premium floors, the minimum cost the company pays in a year with no incident.
Panel (6): the cost breakdown
Insurance increases the expected cost, because the insurer loads the price. The expected annual cost is 1.84 M$ without insurance, but about 2.88 M$ for both the conventional and the optimal policies. What the extra cost buys is a smaller worst case: the CVaR of the total cost drops from about 16.7 M$ to about 9.0 M$ for the optimal policy, and to about 5.5 M$ for full cover. The optimal policy and the conventional policy cost the same on average, yet the optimal one has lower CVaR and a lower probability of breaching the buffer. The gain comes entirely from restructuring the policy: a higher deductible in exchange for a much larger limit.
Validation
The simulated expected payouts agree with the closed-form lognormal values to within about one percent for all three insured strategies. This confirms that the vectorized pipeline is consistent with the analytic model.
7. Conclusion
Cyber insurance is best seen as buying protection against the heavy tail, not against everyday incidents. In this example, the budget-constrained optimum accepts a deductible of about 1.9 M$ so that it can afford a limit of about 16 M$. That structure removed most of the extreme-loss exposure and cut the probability of a cash-buffer breach from about 5% to under 1%, at the same premium as a conventional policy that protected less. The framework here is easy to extend: replace the lognormal with a fitted severity distribution, add an annual aggregate limit or a coinsurance share, or price the policy with a market-quoted rate curve. The same two-stage search will still apply.

















