Skip to main content

Chapter 9: Trigger, exit and payout

Chapter 9: Trigger, exit and payout

TipAt a glance
  • You will build: idx.payout (the payout function), idx.contract (trigger and exit of each insured unit and season) and out.payout (the payout of every unit, season and crop year 1981-2025)
  • You need: Chapter 8
  • Time to run: Under a minute (the checkpoint prints the time)
  • Level: Intermediate

Chapter 8 gave every insured unit, season and crop year a drought index between 0 and 1. This chapter turns the index into a contract (Chapter 1, section 2): for each unit and season a trigger, the index at which the contract starts to pay, and an exit, the index at which it pays the full sum insured, with a payout that rises in a straight line between them. It writes the payout rule once, as a SQL function, sets the thresholds from each unit’s own index over 1991-2020, and applies the contract to every season of the record: a back-test of what the contract would have paid. The thresholds and payouts are illustrative, not a priced insurance product.

NoteLearning objectives

By the end of this chapter you will be able to:

  • write a SQL function with CREATE FUNCTION ... RETURN and say what IMMUTABLE and STRICT promise;
  • set thresholds from a reference period with percentile_cont(...) WITHIN GROUP;
  • apply a contract to a long record with one join, and read payouts as shares and hectare-equivalents;
  • find the crop years in which many units pay at once;
  • show that adding a year to the record leaves past payouts unchanged.

Before running this chapter:

  • complete Chapter 8, which builds the index idx.season_index, and the chapters before it;
  • allow under a minute for the whole chapter. No downloads are needed. A step whose table already exists is skipped on a second run (the function is replaced).

1. Setup

The setup cell reads config.yml, defines connect() and ENGINE as in the earlier chapters, checks the tables of the earlier chapters (and that the index column of Chapter 8 is there), creates the schema out for results, and reads the date to which the rainfall is final (idx.data_status, Chapter 4). The settings of the contract are the chapter’s own:

  • REF, the reference period 1991-2020, the same as for the index (Chapter 8);
  • TRIGGER_RP and EXIT_RP, the return periods of trigger and exit, 5 and 20 years. A return period of N years means “reached on average once in N years”, so the threshold is the (1 - 1/N) percentile of the unit’s reference index: the 80th for the trigger, the 95th for the exit, the design of Chapter 1, section 2;
  • UNIT, the unit looked at closely: Garut, as before.
import os
os.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL")   # before numpy is imported (ledger L128)

import datetime as dt
import math
import time
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import psycopg
import yaml
from psycopg import sql
from sqlalchemy import URL, create_engine

T0 = time.perf_counter()
REF = {"ref_first": 1991, "ref_last": 2020}    # reference period of the thresholds
TRIGGER_RP, EXIT_RP = 5, 20                    # return periods: trigger 1-in-5, exit 1-in-20
SETTINGS = {**REF, "trigger_rp": TRIGGER_RP, "exit_rp": EXIT_RP}
UNIT = "3205"                                  # BPS code of Kabupaten Garut

ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
CONFIG = yaml.safe_load((ROOT / "config.yml").read_text(encoding="utf-8"))
DB = CONFIG["database"]


def connect(**kwargs):
    """A new session in the tutorial database (Chapter 2)."""
    return psycopg.connect(**DB, **kwargs)


ENGINE = create_engine(URL.create("postgresql+psycopg", username=DB["user"], host=DB["host"],
                                  port=DB["port"], database=DB["dbname"]))

with connect() as conn:
    print("connected |", conn.execute("SELECT postgis_full_version()").fetchone()[0][:60], "...")
    for table in ["idx.insured_unit", "idx.chirps_dekad", "idx.data_status", "idx.season_dekad", "idx.season_index"]:
        if not conn.execute("SELECT to_regclass(%s)", [table]).fetchone()[0]:
            raise RuntimeError(f"{table} is missing: run Chapters 3 to 8 first")
    if not conn.execute("""SELECT 1 FROM information_schema.columns WHERE table_schema = 'idx'
                           AND table_name = 'season_index' AND column_name = 'stage_mean_prank'""").fetchone():
        raise RuntimeError("idx.season_index has no stage_mean_prank: run section 6 of Chapter 8")
    found = conn.execute("SELECT name FROM idx.insured_unit WHERE code = %s", [UNIT]).fetchone()
    if found is None:
        raise ValueError(f"UNIT {UNIT} is not an insured unit: pick a code from idx.insured_unit")
    unit_name = found[0]
    conn.execute("CREATE SCHEMA IF NOT EXISTS out")
    first_year, last_year = conn.execute("SELECT min(crop_year), max(crop_year) FROM idx.season_index").fetchone()
    final_through = conn.execute("SELECT final_through FROM idx.data_status WHERE source = 'chirps_rnl'").fetchone()[0]
print(f"unit: {UNIT} {unit_name} | index crop years {first_year}-{last_year} | trigger 1-in-{TRIGGER_RP} "
      f"({100 * (1 - 1 / TRIGGER_RP):.0f}th percentile), exit 1-in-{EXIT_RP} ({100 * (1 - 1 / EXIT_RP):.0f}th) | "
      f"rainfall final through {final_through}")
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
unit: 3205 Garut | index crop years 1981-2025 | trigger 1-in-5 (80th percentile), exit 1-in-20 (95th) | rainfall final through 2025-09-30

2. The payout rule as a SQL function

The payout, as a share of the sum insured, is 0 at or below the trigger, 1 at or above the exit, and a straight line between:

payout = min(max((index - trigger) / (exit - trigger), 0), 1)

Every later query needs this rule, and later chapters read the payouts from the database, so it is written once, as a function in the database rather than in Python. CREATE FUNCTION ... RETURN expression defines a SQL function whose body is a single expression (ledger L78). Three promises go with it:

  • IMMUTABLE: the result depends only on the arguments, never on a table or the clock, so PostgreSQL may compute a call whose arguments are all constants once, while it plans the query;
  • STRICT: if any argument is NULL, the result is NULL without running the body;
  • PARALLEL SAFE: PostgreSQL may run it in several processes at once on large queries.

STRICT matters more here than it seems. least and greatest skip NULL arguments, so the bare formula turns a missing index into a payout of 0, a silent “no payout”; with STRICT the payout is NULL and the gap stays visible. The cell creates the function (CREATE OR REPLACE lets it run again) and tests it with made-up thresholds, a trigger of 0.75 and an exit of 0.85; the real ones come in section 3.

PAYOUT_FUNCTION = """
CREATE OR REPLACE FUNCTION idx.payout(index_value double precision, trigger_value double precision,
                                      exit_value double precision)
RETURNS double precision
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE
RETURN least(greatest((index_value - trigger_value) / (exit_value - trigger_value), 0), 1)"""

with connect() as conn:
    conn.execute(PAYOUT_FUNCTION)
    conn.execute("COMMENT ON FUNCTION idx.payout(double precision, double precision, double precision) IS "
                 "'Linear payout share of the sum insured: 0 at or below the trigger, 1 at or above the exit (Chapter 9)'")
    tests = conn.execute("""SELECT x, idx.payout(x, 0.75, 0.85)
                            FROM unnest(ARRAY[0.70, 0.75, 0.80, 0.85, 0.90]::double precision[]) AS x""").fetchall()
    with_strict, bare = conn.execute("""SELECT idx.payout(NULL, 0.75, 0.85),
                                               least(greatest((NULL::double precision - 0.75) / (0.85 - 0.75), 0), 1)""").fetchone()
    curve = pd.DataFrame(conn.execute("""SELECT x, idx.payout(x, 0.75, 0.85) AS payout
                                         FROM generate_series(0.6, 1.0, 0.005) AS x""").fetchall(), columns=["x", "payout"])
print("index -> payout with trigger 0.75, exit 0.85:", [(x, round(p, 3)) for x, p in tests])
print(f"NULL index -> payout: {with_strict} with the function (STRICT), {bare} from the bare formula")
index -> payout with trigger 0.75, exit 0.85: [(0.7, 0.0), (0.75, 0.0), (0.8, 0.5), (0.85, 1.0), (0.9, 1.0)]
NULL index -> payout: None with the function (STRICT), 0.0 from the bare formula
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(curve.x.astype(float), curve.payout)
ax.axvline(0.75, color="0.6", linestyle=":"); ax.axvline(0.85, color="0.6", linestyle=":")
ax.text(0.75, 1.03, "trigger", ha="center", fontsize=8); ax.text(0.85, 1.03, "exit", ha="center", fontsize=8)
ax.set_xlabel("index"); ax.set_ylabel("payout share of the sum insured"); ax.set_ylim(-0.05, 1.12)
plt.show()

Line chart of the payout share against the index for a made-up trigger of 0.75 and exit of 0.85, zero up to the trigger, a straight rise to one at the exit, and one beyond.

Look before moving on. The payout should be 0 at and below the trigger, 0.5 halfway, 1 at the exit and stay 1 beyond it: the exit is where the payout reaches the full sum insured, not where cover ends (Chapter 1, section 2). A NULL index gives None from the function and 0 from the bare formula.

3. Trigger and exit from the reference years

The thresholds of a unit and season are percentiles of its own index over the reference years. Chapter 8 showed that the index, a mean of three ranks, gathers towards the middle, so a fixed value such as 0.8 would mean a different return period in every unit; taking percentiles of the index itself gives every unit a trigger it reaches in about one reference year in five (ledger L70).

percentile_cont(f) WITHIN GROUP (ORDER BY v) returns the value at fraction f of the ordered values, interpolating between the two nearest when f falls between them. With the 30 reference values sorted, the 80th percentile lies 0.8 x 29 = 23.2 steps above the lowest: between the 24th and 25th values, a fifth of the way from one to the other. So at most 6 of the 30 reference seasons lie above a unit’s trigger, fewer when the 24th and 25th are equal. The exit, at 0.95 x 29 = 27.55 steps, lies between the 28th and 29th values: “1-in-20” is nominal with 30 years. Chapter 7 used percentile_disc for a median that had to be a real dekad; a threshold can lie between two observed values, so here the continuous form fits.

The choice has alternatives the series tested and set aside: a trigger fitted to reported damage pays more often and costs more (ledger L76), and with only 30 reference years the trigger itself is uncertain: its 90% range is about 28% (MK1) to 36% (MH) of its value wide (ledger L72).

idx.contract holds one row per unit and season, with the settings it was built from, so that a reader of the table later knows which reference and return periods produced the thresholds. The parameters selected into the table are cast with ::integer; psycopg passes small Python integers as smallint, and the columns would get that type (ledger L167). The sum insured, the money per hectare a full payout is worth, stays empty, as in Chapter 1 (ledger L80): no source for it has been checked yet.

CONTRACT = """
CREATE TABLE idx.contract AS
SELECT kabupaten_code, season,
       %(ref_first)s::integer AS ref_first, %(ref_last)s::integer AS ref_last,
       %(trigger_rp)s::integer AS trigger_rp, %(exit_rp)s::integer AS exit_rp,
       percentile_cont(1 - 1.0 / %(trigger_rp)s::integer) WITHIN GROUP (ORDER BY stage_mean_prank) AS trigger_value,
       percentile_cont(1 - 1.0 / %(exit_rp)s::integer) WITHIN GROUP (ORDER BY stage_mean_prank) AS exit_value,
       NULL::numeric AS sum_insured_idr_per_ha
FROM idx.season_index
WHERE stage = 'season' AND crop_year BETWEEN %(ref_first)s AND %(ref_last)s
GROUP BY kabupaten_code, season"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('idx.contract')").fetchone()[0]:
        print("idx.contract already exists: left as it is")
    else:
        conn.execute(CONTRACT, SETTINGS)
        conn.execute("""ALTER TABLE idx.contract
                        ADD PRIMARY KEY (kabupaten_code, season),
                        ADD FOREIGN KEY (kabupaten_code, season) REFERENCES idx.crop_calendar (kabupaten_code, season),
                        ALTER COLUMN trigger_value SET NOT NULL,
                        ALTER COLUMN exit_value SET NOT NULL,
                        ADD CHECK (exit_value > trigger_value)""")
        conn.execute(sql.SQL("COMMENT ON TABLE idx.contract IS {}").format(sql.Literal(
            "Contract: trigger and exit on the equal-weight index (idx.season_index.stage_mean_prank) per insured unit "
            "and season, percentile_cont(1 - 1/return period) over crop years ref_first-ref_last; sum insured empty "
            f"until sourced; illustrative, not a priced product; built {dt.date.today()} by Chapter 9")))
        conn.execute("ANALYZE idx.contract")
        print("idx.contract built")
    contract = pd.DataFrame(conn.execute("""
        SELECT season, count(*) AS units,
               round(min(trigger_value)::numeric, 3) AS trigger_min, round(max(trigger_value)::numeric, 3) AS trigger_max,
               round(min(exit_value)::numeric, 3) AS exit_min, round(max(exit_value)::numeric, 3) AS exit_max,
               round(percentile_cont(0.5) WITHIN GROUP (ORDER BY exit_value - trigger_value)::numeric, 3) AS width_median,
               round(min(exit_value - trigger_value)::numeric, 3) AS width_min,
               count(*) FILTER (WHERE exit_value - trigger_value < 0.05) AS width_under_005
        FROM idx.contract GROUP BY season ORDER BY season""").fetchall(),
                            columns=["season", "units", "trigger_min", "trigger_max", "exit_min", "exit_max",
                                     "width_median", "width_min", "width_under_005"])
    unit_contract = conn.execute("""SELECT season, round(trigger_value::numeric, 3), round(exit_value::numeric, 3)
                                    FROM idx.contract WHERE kabupaten_code = %s ORDER BY season""", [UNIT]).fetchall()
print(f"{unit_name}:", "; ".join(f"{s} trigger {t}, exit {e}" for s, t, e in unit_contract))
contract
idx.contract built
Garut: MH trigger 0.620, exit 0.773; MK1 trigger 0.711, exit 0.767
season units trigger_min trigger_max exit_min exit_max width_median width_min width_under_005
0 MH 99 0.558 0.702 0.685 0.862 0.138 0.042 1
1 MK1 99 0.620 0.780 0.751 0.896 0.109 0.038 8

Look before moving on. Every unit should have both seasons, with the exit above the trigger, and the thresholds differ between units, since each comes from the unit’s own index. The width (exit minus trigger) matters for the insured. The index moves in steps of 1/90, about 0.011, since it is the mean of three ranks k/30, so a width under 0.05 spans only three or four steps: there the payout is close to all or nothing, and a small error in the rainfall decides a lot. Note how many units have such a narrow width.

4. The back-test: what the contract would have paid

out.payout applies the contract to every season of the index: one row per unit, season and crop year, with

  • season_label, a readable name such as MK1 2017/18 (the MK1 of crop year 2017, planted in 2018), joined together with ||;
  • index_value and payout_frac, the index and the payout share from idx.payout;
  • payout_ha_eq, the payout in hectare-equivalents: the share times the unit’s paddy hectares, the number of hectares that would be paid in full;
  • season_end, the last day of the season’s last dekad, from the subquery e, which takes the latest dekad_end of the season’s dekads (idx.season_dekad joined to idx.chirps_dekad). A season ending after the date to which the rainfall is final has a provisional payout; queries decide that from this column, so the table need not change when the Climate Hazards Center (CHC), which publishes CHIRPS, confirms a later date.

The payout is computed twice in the SELECT, once on its own and once times the hectares, because a SELECT cannot use the name of one of its own output columns in another.

PAYOUT_TABLE = """
CREATE TABLE out.payout AS
SELECT i.kabupaten_code, i.season, i.crop_year,
       i.season || ' ' || i.crop_year || '/' || right((i.crop_year + 1)::text, 2) AS season_label,
       i.stage_mean_prank AS index_value,
       idx.payout(i.stage_mean_prank, k.trigger_value, k.exit_value) AS payout_frac,
       idx.payout(i.stage_mean_prank, k.trigger_value, k.exit_value) * u.paddy_ha::double precision AS payout_ha_eq,
       e.season_end
FROM idx.season_index i
JOIN idx.contract k USING (kabupaten_code, season)
JOIN idx.insured_unit u ON u.code = i.kabupaten_code
JOIN (SELECT s.kabupaten_code, s.season, s.crop_year, max(d.dekad_end) AS season_end
      FROM idx.season_dekad s
      JOIN idx.chirps_dekad d USING (dekad_start)
      GROUP BY s.kabupaten_code, s.season, s.crop_year) e USING (kabupaten_code, season, crop_year)
WHERE i.stage = 'season'"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('out.payout')").fetchone()[0]:
        print("out.payout already exists: left as it is")
    else:
        t = time.perf_counter()
        conn.execute(PAYOUT_TABLE)
        conn.execute("""ALTER TABLE out.payout
                        ADD PRIMARY KEY (kabupaten_code, season, crop_year),
                        ADD FOREIGN KEY (kabupaten_code, season) REFERENCES idx.contract (kabupaten_code, season),
                        ALTER COLUMN payout_frac SET NOT NULL,
                        ADD CHECK (payout_frac BETWEEN 0 AND 1)""")
        conn.execute(sql.SQL("COMMENT ON TABLE out.payout IS {}").format(sql.Literal(
            "Back-tested payouts: payout_frac = idx.payout(index, trigger, exit), share of the sum insured; payout_ha_eq = "
            "payout_frac x paddy ha of idx.insured_unit; season_end = last day of the season (provisional when after "
            f"idx.data_status.final_through of chirps_rnl); illustrative, not a priced product; built {dt.date.today()} by Chapter 9")))
        conn.execute("ANALYZE out.payout")
        print(f"out.payout built in {time.perf_counter() - t:.1f} s")
garut = pd.read_sql("""SELECT season_label, round(index_value::numeric, 3) AS index_value,
                              round(payout_frac::numeric, 3) AS payout_frac, round(payout_ha_eq::numeric) AS payout_ha_eq,
                              season_end, season_end > %(f)s AS provisional
                       FROM out.payout WHERE kabupaten_code = %(u)s AND payout_frac > 0
                       ORDER BY crop_year, season""", ENGINE, params={"u": UNIT, "f": final_through})
print(f"{unit_name}: {len(garut)} paying seasons of {2 * (last_year - first_year + 1)}")
garut
out.payout built in 0.3 s
Garut: 16 paying seasons of 90
season_label index_value payout_frac payout_ha_eq season_end provisional
0 MH 1982/83 0.833 1.000 45097.0 1983-02-20 False
1 MH 1985/86 0.644 0.160 7216.0 1986-02-20 False
2 MH 1987/88 0.667 0.305 13775.0 1988-02-20 False
3 MK1 1990/91 0.878 1.000 45097.0 1991-08-31 False
4 MK1 1993/94 0.733 0.400 18039.0 1994-08-31 False
5 MH 1994/95 0.767 0.960 43293.0 1995-02-20 False
6 MK1 1996/97 0.744 0.600 27058.0 1997-08-31 False
7 MH 2000/01 0.656 0.233 10495.0 2001-02-20 False
8 MH 2002/03 0.778 1.000 45097.0 2003-02-20 False
9 MH 2006/07 0.800 1.000 45097.0 2007-02-20 False
10 MH 2010/11 0.689 0.451 20335.0 2011-02-20 False
11 MK1 2014/15 0.767 1.000 45097.0 2015-08-31 False
12 MK1 2017/18 0.800 1.000 45097.0 2018-08-31 False
13 MH 2018/19 0.744 0.815 36734.0 2019-02-20 False
14 MK1 2018/19 0.767 1.000 45097.0 2019-08-31 False
15 MK1 2025/26 0.878 1.000 45097.0 2026-08-31 True

Look before moving on. The table lists the paying seasons of UNIT. Compare each index with the unit’s trigger and exit printed in section 3: an index between them pays a share between 0 and 1, an index at or beyond the exit pays 1, which here is the unit’s whole paddy area in hectare-equivalents. Seasons marked provisional rest on rainfall that can still change.

The next query summarises the back-test for all units. The payout frequency is the share of unit-seasons with a payout. The paddy-weighted mean payout share is the average payout per unit of sum insured, if every hectare is insured for the same amount; this series calls it the pure premium (ledger L74). It is not a price: this series prices nothing. Inside 1991-2020 the frequency is set by the thresholds rather than tested, since the thresholds came from those years; Chapter 10 keeps the two apart.

SUMMARY = """
SELECT p.season,
       count(*) AS unit_seasons,
       round(avg((p.payout_frac > 0)::int), 3) AS frequency_all,
       round(avg((p.payout_frac > 0)::int) FILTER (WHERE p.crop_year BETWEEN %(ref_first)s AND %(ref_last)s), 3)
           AS frequency_reference,
       round((sum(p.payout_ha_eq) / sum(u.paddy_ha))::numeric, 3) AS pure_premium,
       round((sum(p.payout_ha_eq) FILTER (WHERE p.season_end <= %(f)s)
              / sum(u.paddy_ha) FILTER (WHERE p.season_end <= %(f)s))::numeric, 3) AS pure_premium_final
FROM out.payout p JOIN idx.insured_unit u ON u.code = p.kabupaten_code
GROUP BY p.season ORDER BY p.season"""
summary = pd.read_sql(SUMMARY, ENGINE, params={**REF, "f": final_through})
summary
season unit_seasons frequency_all frequency_reference pure_premium pure_premium_final
0 MH 4455 0.194 0.193 0.123 0.123
1 MK1 4455 0.176 0.190 0.119 0.116

Look before moving on. In the reference years the frequency is a little under 0.2: at most 6 of 30 seasons pay, and fewer where the 24th and 25th reference values tie. Compare it with the whole record, where MK1 pays less often than in the reference years and MH about as often. pure_premium_final leaves out the provisional seasons. These are illustrative numbers for an illustrative contract; Chapter 10 puts intervals on them.

5. When many units pay at once

An insurer that covers all of Java cares less about the average than about the bad years, when many units pay together. The query adds up, per season and crop year, the number of paying units, the number paying in full, and the payouts as a share of the paddy of all insured units, which is the share of Java’s total sum insured if every hectare were insured for the same amount. bool_or is true if any row of the group is true: here, if any unit’s season in that crop year is provisional.

BY_YEAR = """
SELECT p.season, p.crop_year, min(p.season_label) AS season_label,
       count(*) FILTER (WHERE p.payout_frac > 0) AS units_paying,
       count(*) FILTER (WHERE p.payout_frac >= 1) AS units_full,
       sum(p.payout_ha_eq) / (SELECT sum(paddy_ha) FROM idx.insured_unit)::double precision AS java_share,
       bool_or(p.season_end > %(f)s) AS provisional
FROM out.payout p
GROUP BY p.season, p.crop_year ORDER BY p.season, p.crop_year"""
by_year = pd.read_sql(BY_YEAR, ENGINE, params={"f": final_through})
fig, axes = plt.subplots(2, 1, figsize=(9, 4.6), sharex=True)
for ax, (season, g) in zip(axes, by_year.groupby("season")):
    ax.bar(g.crop_year, g.java_share, color=np.where(g.provisional, "tab:orange", "tab:blue"))
    ax.set_ylabel("share of Java\nsum insured"); ax.set_title(season, fontsize=9, loc="left")
axes[1].set_xlabel("crop year (orange: provisional)")
plt.tight_layout()
plt.show()


def at_least(k: int, n: int, p: float) -> float:
    """Chance that at least k of n units pay in a crop year if each paid on its own with probability p."""
    return sum(math.comb(n, j) * p ** j * (1 - p) ** (n - j) for j in range(k, n + 1))


rows = []
for season, g in by_year.groupby("season"):
    p = float(summary.set_index("season").frequency_all[season])
    rows.append({"season": season, "crop_years": len(g), "no_unit_paying": int((g.units_paying == 0).sum()),
                 "50_units_or_more": int((g.units_paying >= 50).sum()),
                 "expected_if_independent": f"{len(g) * at_least(50, 99, p):.1e}"})
print(pd.DataFrame(rows).to_string(index=False))
by_year.sort_values("java_share", ascending=False).head(5).round(3)

Bar chart of the payout share of Java's total sum insured in each crop year from 1981 to 2025, one panel for MH and one for MK1, with a few crop years paying far more than the rest, most of all in MK1.

season  crop_years  no_unit_paying  50_units_or_more expected_if_independent
    MH          45               2                 6                 1.9e-10
   MK1          45              24                 7                 4.1e-12
season crop_year season_label units_paying units_full java_share provisional
57 MK1 1993 MK1 1993/94 94 69 0.845 False
66 MK1 2002 MK1 2002/03 84 42 0.696 False
71 MK1 2007 MK1 2007/08 74 35 0.669 False
16 MH 1997 MH 1997/98 77 49 0.642 False
54 MK1 1990 MK1 1990/91 72 42 0.580 False

Look before moving on. MK1 pays in clusters: in many crop years no unit pays at all, and in a few most of the insured units pay at once. MH pays more evenly, with few crop years without any payout. The column expected_if_independent is how many crop years with 50 or more paying units one would expect if each unit paid on its own, with the average frequency: practically none, against the years counted. In those years the index is above the trigger in most units at once, so a contract on 99 units is far from 99 independent risks. The top of the table shows the worst seasons (season_label gives the planting years: MK1 1993/94 grew in 1994); the share of the total sum insured paid in one season is the loss an insurer of all of Java would have had to be able to pay in that season.

6. Does adding a year change past payouts?

Chapter 8 ranked the deficits against the fixed reference years so that the past would not move. This section shows what that means for payouts. The function below rebuilds the whole chain (stage ranks, index, thresholds, payouts) from the deficits of idx.season_index for a record ending in a given crop year, in two ways:

  • fixed: ranks against the reference years, as this series does: the hypothetical-set percent_rank of Chapter 8, written here as a correlated subquery that ranks one row at a time;
  • whole_record: ranks by the window function percent_rank() over every crop year of the record.

It compares the payouts of the past crop years with the record ending in the last crop year and a year earlier. For fixed no change is expected, by design; the cell also checks that its rebuild reproduces out.payout exactly, so the comparison runs on the real payouts. The query text is assembled in Python from two fixed strings of this notebook, not from values that come from outside.

RANK_EXPR = {
    "fixed": """(SELECT percent_rank(a.deficit_mm) WITHIN GROUP (ORDER BY f.deficit_mm) FROM idx.season_index f
                 WHERE f.kabupaten_code = a.kabupaten_code AND f.season = a.season AND f.stage = a.stage
                   AND f.crop_year BETWEEN %(ref_first)s AND %(ref_last)s)""",
    "whole_record": "percent_rank() OVER (PARTITION BY a.kabupaten_code, a.season, a.stage ORDER BY a.deficit_mm)",
}


def payouts_until(last: int, ranking: str) -> pd.DataFrame:
    """Payouts of every unit, season and crop year up to `last`, recomputed from the deficits."""
    query = f"""
    WITH r AS (SELECT a.kabupaten_code, a.season, a.crop_year, {RANK_EXPR[ranking]} AS pr
               FROM idx.season_index a WHERE a.stage <> 'season' AND a.crop_year <= %(last)s),
         i AS (SELECT kabupaten_code, season, crop_year,
                      round(avg(pr)::numeric, 12)::double precision AS index_value     -- as in Chapter 8
               FROM r GROUP BY 1, 2, 3),
         k AS (SELECT kabupaten_code, season,
                      percentile_cont(1 - 1.0 / %(trigger_rp)s) WITHIN GROUP (ORDER BY index_value) AS t,
                      percentile_cont(1 - 1.0 / %(exit_rp)s) WITHIN GROUP (ORDER BY index_value) AS e
               FROM i WHERE crop_year BETWEEN %(ref_first)s AND %(ref_last)s GROUP BY 1, 2)
    SELECT i.kabupaten_code, i.season, i.crop_year, idx.payout(i.index_value, k.t, k.e) AS payout
    FROM i JOIN k USING (kabupaten_code, season)"""
    return pd.read_sql(query, ENGINE, params={**SETTINGS, "last": last})


stored = pd.read_sql("SELECT kabupaten_code, season, crop_year, payout_frac FROM out.payout", ENGINE)
rebuilt = payouts_until(last_year, "fixed").merge(stored, on=["kabupaten_code", "season", "crop_year"])
assert len(rebuilt) == len(stored) and (rebuilt.payout == rebuilt.payout_frac).all(), "the rebuild does not match out.payout"
rows = []
for ranking in RANK_EXPR:
    a = payouts_until(last_year, ranking)
    b = payouts_until(last_year - 1, ranking)
    m = a.merge(b, on=["kabupaten_code", "season", "crop_year"], suffixes=("_now", "_before"))
    changed = (m.payout_now - m.payout_before).abs() > 1e-12
    rows.append({"ranking": ranking, "past_unit_seasons": len(m), "payout_changed": int(changed.sum()),
                 "largest_change": round(float((m.payout_now - m.payout_before).abs().max()), 3)})
pd.DataFrame(rows)
ranking past_unit_seasons payout_changed largest_change
0 fixed 8712 0 0.000
1 whole_record 8712 1057 0.444

Look before moving on. With ranks against the fixed reference years, no past payout changes when the last crop year is added. With whole-record ranks, adding that one crop year rewrote part of the payout history the insured had been paid on, by up to the share printed. That second line is the reason for the design of Chapter 8.

7. Check against pandas

The cell recomputes the thresholds and payouts of every unit in pandas from the index of Chapter 8: numpy.percentile with its default linear interpolation computes the same percentile as percentile_cont, and the payout rule is written out in numpy. It stops with an error if any value differs.

index = pd.read_sql("""SELECT kabupaten_code, season, crop_year, stage_mean_prank AS index_value
                       FROM idx.season_index WHERE stage = 'season'""", ENGINE)
ref = index[index.crop_year.between(REF["ref_first"], REF["ref_last"])]
thresholds = ref.groupby(["kabupaten_code", "season"]).index_value.agg(
    trigger=lambda v: np.percentile(v, 100 * (1 - 1 / TRIGGER_RP)),
    exit=lambda v: np.percentile(v, 100 * (1 - 1 / EXIT_RP))).reset_index()
by_pandas = index.merge(thresholds, on=["kabupaten_code", "season"])
by_pandas["payout"] = ((by_pandas.index_value - by_pandas.trigger) / (by_pandas.exit - by_pandas.trigger)).clip(0, 1)

db = pd.read_sql("""SELECT p.kabupaten_code, p.season, p.crop_year, p.payout_frac, k.trigger_value, k.exit_value
                    FROM out.payout p JOIN idx.contract k USING (kabupaten_code, season)""", ENGINE)
both = db.merge(by_pandas, on=["kabupaten_code", "season", "crop_year"], how="outer", indicator=True)
assert (both._merge == "both").all(), "rows on one side only"
for a, b in [("trigger_value", "trigger"), ("exit_value", "exit"), ("payout_frac", "payout")]:
    assert np.allclose(both[a], both[b], rtol=0, atol=1e-12), f"{a} differs"
print(f"{len(both):,} unit-seasons agree; largest differences: trigger {(both.trigger_value - both.trigger).abs().max():.1e}, "
      f"exit {(both.exit_value - both.exit).abs().max():.1e}, payout {(both.payout_frac - both.payout).abs().max():.1e}")
8,910 unit-seasons agree; largest differences: trigger 0.0e+00, exit 0.0e+00, payout 0.0e+00

Checkpoint

The cell below checks, in a new session, what Chapters 10 and 11 rely on:

  • the function idx.payout, immutable, strict and parallel safe;
  • a contract row for every insured unit and season, exit above trigger, built from the settings of this chapter;
  • a payout for every season row of the index, on the index as Chapter 8 stores it now, between 0 and 1, positive exactly where the index is above the trigger and 1 exactly where it reaches the exit;
  • no payout within a billionth of 0 or 1 except 0 and 1 themselves (the rounding noise of ledger L166);
  • labels of the form MK1 2017/18, and at most 6 paying reference seasons of 30 per unit and season (section 3).

It depends only on the setup cell.

with connect() as conn:
    first_row = lambda q, p=None: conn.execute(q, p).fetchone()
    fn = first_row("""SELECT provolatile, proisstrict, proparallel FROM pg_proc
                      WHERE oid = 'idx.payout(double precision, double precision, double precision)'::regprocedure""")
    n_units = first_row("SELECT count(*) FROM idx.insured_unit")[0]
    n_contract, settings = first_row("""SELECT count(*), array_agg(DISTINCT (ref_first, ref_last, trigger_rp, exit_rp)::text)
                                        FROM idx.contract WHERE exit_value > trigger_value""")
    n_index, n_payout, stale = first_row("""
        SELECT (SELECT count(*) FROM idx.season_index WHERE stage = 'season'),
               (SELECT count(*) FROM out.payout),
               (SELECT count(*) FROM out.payout p JOIN idx.season_index i USING (kabupaten_code, season, crop_year)
                WHERE i.stage = 'season' AND p.index_value IS DISTINCT FROM i.stage_mean_prank)""")
    wrong = first_row("""SELECT count(*) FROM out.payout p JOIN idx.contract k USING (kabupaten_code, season)
                         WHERE p.payout_frac NOT BETWEEN 0 AND 1
                            OR (p.payout_frac > 0) <> (p.index_value > k.trigger_value)
                            OR (p.payout_frac = 1) <> (p.index_value >= k.exit_value)""")[0]
    noise = first_row("""SELECT count(*) FROM out.payout
                         WHERE (payout_frac > 0 AND payout_frac < 1e-9) OR (payout_frac > 1 - 1e-9 AND payout_frac < 1)""")[0]
    bad_labels = first_row(r"SELECT count(*) FROM out.payout WHERE season_label !~ '^(MH|MK1) [0-9]{4}/[0-9]{2}$'")[0]
    ref_pay = first_row("""SELECT max(n) FROM (SELECT count(*) FILTER (WHERE payout_frac > 0) AS n FROM out.payout
                                               WHERE crop_year BETWEEN %(ref_first)s AND %(ref_last)s
                                               GROUP BY kabupaten_code, season) s""", REF)[0]

assert fn == ("i", True, "s"), f"idx.payout volatility, strictness, parallel safety: {fn}"
assert n_contract == 2 * n_units, f"{n_contract} contract rows with exit above trigger, expected {2 * n_units}"
assert settings == [f"({REF['ref_first']},{REF['ref_last']},{TRIGGER_RP},{EXIT_RP})"], f"contract settings {settings}"
assert n_payout == n_index and stale == 0, f"{n_payout} payout rows for {n_index} index rows; {stale} on an older index"
assert wrong == 0 and noise == 0 and bad_labels == 0, f"inconsistent {wrong}, near 0 or 1 {noise}, bad labels {bad_labels}"
assert ref_pay <= 6, f"a unit pays in {ref_pay} of 30 reference seasons"
print(f"checkpoint passed: {n_contract} contracts, {n_payout:,} payouts, at most {ref_pay} paying reference seasons per "
      f"unit; code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 198 contracts, 8,910 payouts, at most 6 paying reference seasons per unit; code cells took 7 s since the setup cell

Troubleshooting

Symptom Cause Fix
... is missing: run Chapters 3 to 8 first or ... has no stage_mean_prank an earlier chapter, or its last section, has not been run run it
UNIT ... is not an insured unit the setting in the setup cell changed use a code from idx.insured_unit
you changed REF, TRIGGER_RP or EXIT_RP, but the contract did not change the table was built earlier with the old settings (it records them in its columns) drop what later chapters built on these tables (Chapters 10 and 11), then DROP TABLE out.payout, idx.contract and run sections 3 and 4 again
check constraint "contract_check" of relation "contract" is violated by some row with other return periods, trigger and exit coincide for some unit choose return periods further apart, drop the table and run section 3 again
ProgrammingError mentioning placeholders, or a label showing $1 a % in a query sent with parameters: psycopg reads it as a placeholder write %% for a literal % in queries sent with parameters, or join text with \|\| as in section 4 (ledger L167)
the checkpoint reports payouts on an older index idx.season_index was rebuilt after this chapter ran drop what Chapters 10 and 11 built, then DROP TABLE out.payout, idx.contract, and run sections 3 and 4 again; never CASCADE (Chapter 7)

Summary

You now have:

  • idx.payout(index, trigger, exit): the linear payout rule as an IMMUTABLE, STRICT SQL function;
  • idx.contract: the trigger (1-in-5) and exit (nominally 1-in-20) of every insured unit and season, percentiles of its own index over 1991-2020, with the settings recorded and the sum insured left empty;
  • out.payout: the payout of every unit, season and crop year, as a share and in hectare-equivalents, with the season’s end date to tell final from provisional payouts.

The back-test showed MK1 payouts that come in clusters, and that ranks against a fixed reference keep past payouts fixed. All thresholds and payouts are illustrative.

What comes next

Chapter 10 reads the back-test with care: which crop years count as a test, how uncertain the averages are with a short record, and how to keep the provisional seasons apart.

References