Skip to main content

Chapter 10: Back-testing the contract

Chapter 10: Back-testing the contract

TipAt a glance
  • You will build: idx.backtest_period (the periods reported, as ranges of crop years), the views out.backtest_year and out.backtest_summary, and the function out.backtest_bootstrap (bootstrap intervals over whole crop years)
  • You need: Chapter 9
  • Time to run: Under a minute (the checkpoint prints the time)
  • Level: Intermediate

Chapter 9 applied the contract to every season since 1981. This chapter reads that back-test with care. Three questions decide what its averages mean: which crop years can test the contract at all, since its thresholds were set on 1991-2020; how uncertain an average is when a few drought years carry a large share of the payouts; and which years rest on rainfall that is not final yet. The chapter answers them in the database, with periods stored as ranges of crop years, views that read the data status when they are queried, and a bootstrap written in SQL. Payouts and premiums remain illustrative.

NoteLearning objectives

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

  • store periods as int4multirange values and test membership with @>;
  • write views that combine stored results with a status table at query time;
  • tell an in-sample check from an out-of-sample test in a back-test;
  • compute bootstrap intervals over whole crop years in SQL with a PL/pgSQL function, setseed and random;
  • keep provisional results apart from the final record.

Before running this chapter:

  • complete Chapter 9, which builds out.payout, and the chapters before it;
  • allow under a minute for the whole chapter. No downloads are needed. The period table is skipped if it exists; the views and the function are replaced on every run.

1. Setup

The setup cell reads config.yml, defines connect() and ENGINE as in the earlier chapters, and checks the tables of Chapters 4 to 9. REPLICATES and SEED are the settings of the bootstrap in section 6, explained there.

import os
os.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL")   # before numpy is imported (ledger L128)

import datetime as dt
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()
REPLICATES = 2000                 # bootstrap replicates (section 6); the interval bounds then vary in the third decimal (section 7)
SEED = 0.20261201                 # any number from -1 to 1 for setseed(); this one is a date. Same seed, same intervals

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.data_status", "idx.insured_unit", "idx.contract", "out.payout"]:
        if not conn.execute("SELECT to_regclass(%s)", [table]).fetchone()[0]:
            raise RuntimeError(f"{table} is missing: run Chapters 4 to 9 first")
    status = pd.DataFrame(conn.execute("""SELECT source, first_day, available_through, final_through
                                          FROM idx.data_status ORDER BY source""").fetchall(),
                          columns=["source", "first_day", "available_through", "final_through"])
status
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
source first_day available_through final_through
0 chirps_rnl 1981-01-01 2026-09-30 2025-09-30
1 datanonkom_dpi 2016-01-01 2026-11-30 2025-12-31

2. What a back-test can and cannot show

A back-test applies today’s contract to past weather: the thresholds of Chapter 9 and the paddy map of 2015 to every crop year since 1981. It is an as-if exercise, not a record of what an insurer paid. (Weighting the units by another paddy map, or equally, changes the pure premium of all Java over 1981-2025 by less than 0.003, ledger L104.) Three groups of crop years play different roles:

  • reference (1991-2020), the in-sample years: the years the thresholds were set on. Each unit pays in at most 6 of its 30 reference seasons by construction (Chapter 9), so the frequency there is fixed by the rule, and the premium largely so through the trigger and exit fitted on the same years. These rows check the build; they are not evidence (ledger L95);
  • out-of-reference (1981-1990 and 2021 onward), the out-of-sample years: the years the thresholds never saw, the only test of how the contract behaves on new weather (section 5 counts them);
  • provisional: years whose rainfall can still change. The data status above says CHIRPS is final through the date in final_through; later days come from CHC’s newest release, which already replaced the rainfall of every season of crop year 2025 once (ledger L36, ledger L97), and that change moved 2025 payouts (ledger L98). They are reported on their own and never pooled with the final years.

The final record, every final crop year from 1981, is the headline: it is the longest record of what the rule does. Most of its years are reference years, so its frequency is partly fixed by design; the out-of-reference rows are the part that tests it.

3. One row per season and crop year: a view

The first summary sums out.payout per season and crop year: units paid, the payout frequency (share of units paid), the pure premium (Chapter 9: payout hectare-equivalents over paddy hectares) and whether the crop year is provisional. It is created as a view, a stored query that runs whenever it is read. A view reads idx.data_status at that moment, so when CHC confirms a later date and someone updates final_through by hand, every result that depends on it changes without rebuilding anything. bool_or marks a season and crop year provisional if any unit’s season ends after the final date.

CREATE OR REPLACE VIEW lets the cell run again. It keeps the existing columns (same names, order and types) and allows new columns only at the end.

BACKTEST_YEAR = """
CREATE OR REPLACE VIEW out.backtest_year AS
SELECT p.season, p.crop_year,
       bool_or(p.season_end > rain.final_through) AS provisional,
       count(*) AS units,
       count(*) FILTER (WHERE p.payout_frac > 0) AS units_paid,
       avg((p.payout_frac > 0)::int)::double precision AS frequency,
       sum(p.payout_ha_eq) / sum(u.paddy_ha::double precision) AS pure_premium
FROM out.payout p
JOIN idx.insured_unit u ON u.code = p.kabupaten_code
CROSS JOIN (SELECT final_through FROM idx.data_status WHERE source = 'chirps_rnl') rain
GROUP BY p.season, p.crop_year"""

with connect() as conn:
    conn.execute(BACKTEST_YEAR)
    conn.execute("COMMENT ON VIEW out.backtest_year IS 'Back-test per season and crop year: units paid, frequency, pure "
                 "premium, provisional (a unit season ending after idx.data_status.final_through of chirps_rnl); Chapter 10'")
years = pd.read_sql("SELECT * FROM out.backtest_year ORDER BY season, crop_year", ENGINE)
print(years.groupby("season").agg(crop_years=("crop_year", "size"), first=("crop_year", "min"), last=("crop_year", "max"),
                                  provisional=("provisional", "sum"), units_min=("units", "min"), units_max=("units", "max")))
years[years.provisional]
        crop_years  first  last  provisional  units_min  units_max
season                                                            
MH              45   1981  2025            1         99         99
MK1             45   1981  2025            1         99         99
season crop_year provisional units units_paid frequency pure_premium
44 MH 2025 True 99 16 0.161616 0.138202
89 MK1 2025 True 99 40 0.404040 0.262125

Look before moving on. Each season should have one row per crop year of the index, all with the same 99 units, and only the last crop year should be provisional: its MH ends in early 2026 and its MK1 in August 2026, after the final date. Its MK1 pays in many units, a large provisional payout that may move with the next release of the rainfall (ledger L98).

Frequency by decade

A first look at time: the frequency and premium by decade, from the final crop years. The CASE puts the crop years into groups; the last group, 2021-2024, has only 4 crop years.

DECADES = """
SELECT season,
       CASE WHEN crop_year <= 1990 THEN '1981-1990' WHEN crop_year <= 2000 THEN '1991-2000'
            WHEN crop_year <= 2010 THEN '2001-2010' WHEN crop_year <= 2020 THEN '2011-2020'
            ELSE '2021-2024' END AS decade,
       count(*) AS crop_years, round(avg(frequency)::numeric, 3) AS frequency,
       round(avg(pure_premium)::numeric, 3) AS pure_premium
FROM out.backtest_year
WHERE NOT provisional
GROUP BY 1, 2 ORDER BY 1, 2"""
decades = pd.read_sql(DECADES, ENGINE)
decades.pivot(index="decade", columns="season", values=["crop_years", "frequency", "pure_premium"])
crop_years frequency pure_premium
season MH MK1 MH MK1 MH MK1
decade
1981-1990 10.0 10.0 0.210 0.170 0.111 0.114
1991-2000 10.0 10.0 0.299 0.191 0.223 0.135
2001-2010 10.0 10.0 0.198 0.229 0.124 0.168
2011-2020 10.0 10.0 0.082 0.151 0.042 0.090
2021-2024 4.0 4.0 0.174 0.025 0.101 0.008

Look before moving on. Each decade row should count 10 crop years, the last 4. The decades differ, sometimes by a factor of two or more, with no change in the contract: a few drought years make or break a decade. The three reference decades together must average about one season in five, so a low one is balanced by a high one. For MH the low decade is 2011-2020, and MH rainfall rose over the record in some units (in 18 to 25 of the 99, depending on the measure, where about 5 would be expected by chance; ledger L71, ledger L103); whether that is a trend or chance is not settled here.

4. Periods as ranges of crop years

The periods of section 2 could be written into every query as BETWEEN conditions. Stored instead in a table, each as a multirange of crop years, they can be joined like any other data. An int4multirange is a set of integer ranges: '{[1981,1990],[2021,)}' holds 1981 to 1990 and every year from 2021 on, the open upper bound meaning “no end”, so new final years join the period without editing the table. The operator @> asks whether a range contains a value. The cell tries it first.

with connect() as conn:
    demo = conn.execute("""SELECT '{[1981,1990],[2021,)}'::int4multirange @> 1985,
                                  '{[1981,1990],[2021,)}'::int4multirange @> 2000,
                                  '{[1981,1990],[2021,)}'::int4multirange @> 2031,
                                  upper('[1991,2020]'::int4range)""").fetchone()
print(f"contains 1985: {demo[0]} | 2000: {demo[1]} | 2031: {demo[2]} | upper bound of [1991,2020]: {demo[3]}")
contains 1985: True | 2000: False | 2031: True | upper bound of [1991,2020]: 2021

The last value shows a detail of integer ranges: PostgreSQL stores [1991,2020] as [1991,2021), an inclusive lower and an exclusive upper bound, so upper() returns 2021. Containment works as written.

The table holds six periods. role says how each is to be read, sort_order only orders the rows for display, and the provisional period spans every year: what puts a crop year there is its provisional flag, not its number.

PERIODS = """
CREATE TABLE idx.backtest_period (
    period     text PRIMARY KEY,
    role       text NOT NULL CHECK (role IN ('final record', 'reference', 'out-of-reference', 'provisional')),
    years      int4multirange NOT NULL,
    sort_order int NOT NULL
)"""
PERIOD_ROWS = [
    ("final record", "final record", "{[1981,)}", 1),
    ("reference", "reference", "{[1991,2020]}", 2),
    ("out-of-reference", "out-of-reference", "{[1981,1990],[2021,)}", 3),
    ("before reference", "out-of-reference", "{[1981,1990]}", 4),
    ("after reference", "out-of-reference", "{[2021,)}", 5),
    ("provisional", "provisional", "{[1981,)}", 6),
]

with connect() as conn:
    if conn.execute("SELECT to_regclass('idx.backtest_period')").fetchone()[0]:
        print("idx.backtest_period already exists: left as it is")
    else:
        conn.execute(PERIODS)
        with conn.cursor() as cur:
            cur.executemany("INSERT INTO idx.backtest_period VALUES (%s, %s, %s::int4multirange, %s)", PERIOD_ROWS)
        conn.execute(sql.SQL("COMMENT ON TABLE idx.backtest_period IS {}").format(sql.Literal(
            "Back-test periods as int4multirange of crop years; role final record / reference / out-of-reference / "
            f"provisional; built {dt.date.today()} by Chapter 10")))
        print("idx.backtest_period built")
pd.read_sql("SELECT period, role, years::text AS years FROM idx.backtest_period ORDER BY sort_order", ENGINE)
idx.backtest_period built
period role years
0 final record final record {[1981,)}
1 reference reference {[1991,2021)}
2 out-of-reference out-of-reference {[1981,1991),[2021,)}
3 before reference out-of-reference {[1981,1991)}
4 after reference out-of-reference {[2021,)}
5 provisional provisional {[1981,)}

5. The summary by season and period

The summary view joins every season and crop year to every period that contains it, b.years @> y.crop_year, and keeps the provisional years in the provisional period only: y.provisional = (b.role = 'provisional') is true for a final year in a non-provisional period and for a provisional year in the provisional period. Per season and period it reports the crop years, the unit-seasons, the mean frequency and pure premium (each crop year weighs the same, which here equals weighting each unit-season the same, since all 99 units appear every year), the crop years with no unit paid and with at least 50 units paid (about half of them, as in Chapter 9), the worst crop year, and the share of all payouts held by the worst three crop years.

Three SQL details:

  • (array_agg(y.crop_year ORDER BY y.pure_premium DESC, y.crop_year))[1] collects the crop years ordered from the costliest (the earlier year first in a tie) and takes the first: the worst year;
  • [1:3] slices an array, here the three largest premiums, which unnest turns back into rows to add up;
  • nullif(x, 0) returns NULL when x is 0, so a period without any payout gives an empty share, not a division by zero.
BACKTEST_SUMMARY = """
CREATE OR REPLACE VIEW out.backtest_summary AS
SELECT y.season, b.period, b.role, b.sort_order,
       min(y.crop_year) AS first_crop_year, max(y.crop_year) AS last_crop_year,
       count(*) AS crop_years,
       sum(y.units)::bigint AS unit_seasons,
       avg(y.frequency) AS frequency,
       avg(y.pure_premium) AS pure_premium,
       count(*) FILTER (WHERE y.units_paid = 0) AS years_no_payout,
       count(*) FILTER (WHERE y.units_paid >= 50) AS years_50_units_paid,
       (array_agg(y.crop_year ORDER BY y.pure_premium DESC, y.crop_year))[1] AS worst_crop_year,
       max(y.pure_premium) AS worst_premium,
       (SELECT sum(t) FROM unnest((array_agg(y.pure_premium ORDER BY y.pure_premium DESC))[1:3]) AS t)
           / nullif(sum(y.pure_premium), 0) AS top3_share
FROM out.backtest_year y
JOIN idx.backtest_period b
  ON b.years @> y.crop_year
 AND y.provisional = (b.role = 'provisional')
GROUP BY y.season, b.period, b.role, b.sort_order"""

with connect() as conn:
    conn.execute(BACKTEST_SUMMARY)
    conn.execute("COMMENT ON VIEW out.backtest_summary IS 'Back-test per season and period: frequency, pure premium, "
                 "clustering and worst year; final years only except the provisional period; Chapter 10'")
summary = pd.read_sql("""SELECT season, period, role, first_crop_year AS first, last_crop_year AS last, crop_years,
                                unit_seasons, frequency, pure_premium, years_no_payout, years_50_units_paid,
                                worst_crop_year, worst_premium, top3_share
                         FROM out.backtest_summary ORDER BY season DESC, sort_order""", ENGINE)
summary.round(3)
season period role first last crop_years unit_seasons frequency pure_premium years_no_payout years_50_units_paid worst_crop_year worst_premium top3_share
0 MK1 final record final record 1981 2024 44 4356 0.171 0.116 24 7 1993 0.845 0.434
1 MK1 reference reference 1991 2020 30 2970 0.190 0.131 15 5 1993 0.845 0.563
2 MK1 out-of-reference out-of-reference 1981 2024 14 1386 0.128 0.083 9 2 1990 0.580 0.974
3 MK1 before reference out-of-reference 1981 1990 10 990 0.170 0.114 6 2 1990 0.580 1.000
4 MK1 after reference out-of-reference 2021 2024 4 396 0.025 0.008 3 0 2022 0.031 1.000
5 MK1 provisional provisional 2025 2025 1 99 0.404 0.262 0 0 2025 0.262 1.000
6 MH final record final record 1981 2024 44 4356 0.195 0.123 2 6 1997 0.642 0.304
7 MH reference reference 1991 2020 30 2970 0.193 0.130 2 4 1997 0.642 0.422
8 MH out-of-reference out-of-reference 1981 2024 14 1386 0.200 0.108 0 2 1982 0.398 0.616
9 MH before reference out-of-reference 1981 1990 10 990 0.210 0.111 0 1 1982 0.398 0.668
10 MH after reference out-of-reference 2021 2024 4 396 0.174 0.101 0 1 2023 0.340 1.000
11 MH provisional provisional 2025 2025 1 99 0.162 0.138 0 0 2025 0.138 1.000

Look before moving on. First the counts: in each season, the crop years of the final record should equal those of the reference plus the out-of-reference periods, and the provisional period should hold one. Then read the table by role:

  • the reference rows show frequencies a little under 0.2, the 1-in-5 trigger restated, not tested;
  • the out-of-reference rows are the test: compare their frequency and premium with the reference, and note how few crop years they rest on (crop_years); section 6 says whether the difference means anything;
  • the final-record row is the headline;
  • the provisional row stands alone, and its numbers may change with the next release of the rainfall.

Two columns show how the payouts cluster. years_no_payout counts crop years in which no unit paid at all: compare MK1 with MH in the final record. top3_share is the share of all payouts held by the three worst crop years; if payouts were spread evenly over 44 crop years, three would hold 3/44, about 0.07. In periods of three crop years or fewer it is 1 by construction and says nothing.

6. How uncertain are these averages?

A mean over 44 crop years looks precise, but the payouts of one crop year move together across Java (Chapter 9; 78-87% of the variance of the MK1 index is shared Java-wide, ledger L96), so the crop year, not the unit, is the independent piece of information. The bootstrap used here therefore draws whole crop years: draw as many crop years as the period has, with replacement, each with all its units; compute the mean frequency and premium of that draw, one replicate; repeat 2,000 times. The 5th and 95th percentiles of the replicates make a 90% interval: the range in which the mean falls over histories reshuffled from the crop years seen. It is not a 90% chance about the future premium. It assumes the crop years are independent and alike; a trend (section 3) or a run of related years would break that, and it leaves out other uncertainties: the trigger itself (ledger L72), and errors in the rainfall.

One replicate first, in plain SQL, for the MK1 out-of-reference period: the crop years are drawn by position in an array, ys[random(1, n)], where random(1, n) returns a whole number from 1 to n.

with connect() as conn:
    conn.execute("SELECT setseed(%s)", [SEED])
    one = conn.execute("""
        WITH yrs AS (SELECT array_agg(y.crop_year ORDER BY y.crop_year) AS ys
                     FROM out.backtest_year y JOIN idx.backtest_period b
                       ON b.years @> y.crop_year AND NOT y.provisional
                     WHERE y.season = 'MK1' AND b.period = 'out-of-reference'),
             draw AS (SELECT yrs.ys[random(1, cardinality(yrs.ys))] AS crop_year
                      FROM yrs, generate_series(1, (SELECT cardinality(ys) FROM yrs)))
        SELECT array_agg(d.crop_year ORDER BY d.crop_year), avg(y.pure_premium)
        FROM draw d JOIN out.backtest_year y ON y.season = 'MK1' AND y.crop_year = d.crop_year""").fetchone()
print(f"drawn crop years: {one[0]}\nmean premium of this replicate: {one[1]:.3f}")
drawn crop years: [1981, 1983, 1985, 1985, 1985, 1987, 1988, 1989, 1990, 2021, 2021, 2022, 2022, 2024]
mean premium of this replicate: 0.071

Some crop years come twice, others not at all: that is resampling with replacement. The function below repeats this for every season and period. It is written in PL/pgSQL, PostgreSQL’s procedural language, which makes the two steps explicit: set the seed of the random generator, then run the query that uses random().

  • The body sits between $$ signs, dollar quoting, so the quotes inside need no escaping.
  • PERFORM runs a query and discards its result (here setseed); RETURN QUERY returns the rows of a query.
  • RETURNS TABLE (...) makes it a function that returns rows; VOLATILE says it may give a different result on each call, as anything that calls random() does.
  • slots lists every draw to be made, one row per season, period, replicate and position, in a fixed order, and is MATERIALIZED so that it is computed once in that order; only then does draws call random(). Without this, the order in which rows meet random() could follow the query plan, and the same seed could give other intervals on another computer. COLLATE "C" makes the text order the same on every system.
  • #variable_conflict use_column tells PL/pgSQL that a name such as season, which is both an output column and a table column, means the table column. Every name in the queries is also qualified with its table, so the line only guards against later edits.

The function leaves the session’s random generator seeded.

BOOTSTRAP = """
CREATE OR REPLACE FUNCTION out.backtest_bootstrap(replicates int DEFAULT 2000, seed double precision DEFAULT 0.20261201)
RETURNS TABLE (season text, period text, crop_years bigint,
               frequency_p05 double precision, frequency_p95 double precision,
               premium_p05 double precision, premium_p95 double precision)
LANGUAGE plpgsql VOLATILE AS $$
#variable_conflict use_column
BEGIN
    PERFORM setseed(seed);
    RETURN QUERY
    WITH yrs AS (
        SELECT y.season, b.period, array_agg(y.crop_year ORDER BY y.crop_year) AS ys
        FROM out.backtest_year y
        JOIN idx.backtest_period b ON b.years @> y.crop_year AND y.provisional = (b.role = 'provisional')
        GROUP BY y.season, b.period
    ),
    slots AS MATERIALIZED (
        SELECT yrs.season, yrs.period, r.rep, k.i, yrs.ys
        FROM yrs
        CROSS JOIN generate_series(1, replicates) AS r(rep)
        CROSS JOIN LATERAL generate_series(1, cardinality(yrs.ys)) AS k(i)
        ORDER BY yrs.season COLLATE "C", yrs.period COLLATE "C", r.rep, k.i
    ),
    draws AS (
        SELECT slots.season, slots.period, slots.rep, slots.ys[random(1, cardinality(slots.ys))] AS crop_year
        FROM slots
    ),
    rep AS (
        SELECT d.season, d.period, d.rep, avg(y.frequency) AS frequency, avg(y.pure_premium) AS premium
        FROM draws d
        JOIN out.backtest_year y ON y.season = d.season AND y.crop_year = d.crop_year
        GROUP BY d.season, d.period, d.rep
    )
    SELECT rep.season, rep.period, (SELECT cardinality(ys) FROM yrs
                                    WHERE yrs.season = rep.season AND yrs.period = rep.period)::bigint,
           percentile_cont(0.05) WITHIN GROUP (ORDER BY rep.frequency),
           percentile_cont(0.95) WITHIN GROUP (ORDER BY rep.frequency),
           percentile_cont(0.05) WITHIN GROUP (ORDER BY rep.premium),
           percentile_cont(0.95) WITHIN GROUP (ORDER BY rep.premium)
    FROM rep
    GROUP BY rep.season, rep.period;
END
$$"""

with connect() as conn:
    conn.execute(BOOTSTRAP)
    conn.execute("COMMENT ON FUNCTION out.backtest_bootstrap(int, double precision) IS '90% bootstrap intervals over whole "
                 "crop years of frequency and pure premium per season and period; Chapter 10'")
    t = time.perf_counter()
    boot = pd.DataFrame(conn.execute("SELECT * FROM out.backtest_bootstrap(%s, %s)", [REPLICATES, SEED]).fetchall(),
                        columns=["season", "period", "crop_years", "frequency_p05", "frequency_p95", "premium_p05", "premium_p95"])
    seconds = time.perf_counter() - t
    again = pd.DataFrame(conn.execute("SELECT * FROM out.backtest_bootstrap(%s, %s)", [REPLICATES, SEED]).fetchall(),
                         columns=boot.columns)
a = boot.sort_values(["season", "period"]).reset_index(drop=True)
b = again.sort_values(["season", "period"]).reset_index(drop=True)
same = np.allclose(a.iloc[:, 3:].to_numpy(float), b.iloc[:, 3:].to_numpy(float), rtol=0, atol=1e-12)
print(f"{REPLICATES:,} replicates for {len(boot)} season-periods in {seconds:.1f} s; same seed, same intervals: {same}")
table = summary.merge(boot, on=["season", "period", "crop_years"])
reference = table[table.period == "reference"].set_index("season")
table["reference_inside"] = [reference.frequency[s] >= lo and reference.frequency[s] <= hi
                             for s, lo, hi in zip(table.season, table.frequency_p05, table.frequency_p95)]
table[["season", "period", "crop_years", "frequency", "frequency_p05", "frequency_p95", "reference_inside",
       "pure_premium", "premium_p05", "premium_p95"]].round(3)
2,000 replicates for 12 season-periods in 2.6 s; same seed, same intervals: True
season period crop_years frequency frequency_p05 frequency_p95 reference_inside pure_premium premium_p05 premium_p95
0 MK1 final record 44 0.171 0.107 0.237 True 0.116 0.068 0.171
1 MK1 reference 30 0.190 0.109 0.278 True 0.131 0.066 0.204
2 MK1 out-of-reference 14 0.128 0.036 0.242 True 0.083 0.017 0.165
3 MK1 before reference 10 0.170 0.040 0.316 True 0.114 0.020 0.225
4 MK1 after reference 4 0.025 0.000 0.076 False 0.008 0.000 0.023
5 MK1 provisional 1 0.404 0.404 0.404 False 0.262 0.262 0.262
6 MH final record 44 0.195 0.146 0.250 True 0.123 0.085 0.165
7 MH reference 30 0.193 0.131 0.259 True 0.130 0.080 0.183
8 MH out-of-reference 14 0.200 0.124 0.284 True 0.108 0.057 0.165
9 MH before reference 10 0.210 0.140 0.292 True 0.111 0.059 0.173
10 MH after reference 4 0.174 0.018 0.442 True 0.101 0.000 0.255
11 MH provisional 1 0.162 0.162 0.162 False 0.138 0.138 0.138

Look before moving on. The column reference_inside says whether the reference frequency lies inside each period’s interval. For the out-of-reference periods this is the test of section 2. Where it does, the years the thresholds never saw cannot be told apart from the reference years: the back-test neither confirms nor refutes the design, it lacks the years to do either. The exception is MK1 after the reference period, 2021-2024, whose interval lies below the reference frequency: in those four crop years MK1 paid far less often than the rule implies. Four seasons without a severe drought are thin evidence, and the next paragraph explains why their interval is too narrow; it is a pattern to watch as final years are added, not a finding about the contract (ledger L94).

Read the widths too. For the final record the 90% interval of the pure premium is wide compared with its value. The short periods need more care: a bootstrap can only reshuffle the crop years it has. With 4 crop years and no severe drought among them, the interval is narrow and low, because no replicate can contain a drought year that never occurred; for short periods the interval understates the uncertainty. A period of one crop year has nothing to reshuffle: its interval is a single value. The provisional row is one such year.

The figure puts the point values and intervals of the premium side by side for both seasons.

plot = table[table.period != "provisional"].copy()
order = ["final record", "reference", "out-of-reference", "before reference", "after reference"]
fig, ax = plt.subplots(figsize=(8, 3.4))
for k, (season, colour) in enumerate([("MH", "tab:blue"), ("MK1", "tab:orange")]):
    g = plot[plot.season == season].set_index("period").reindex(order)
    y = np.arange(len(order)) + (k - 0.5) * 0.25
    ax.errorbar(g.pure_premium, y, xerr=[g.pure_premium - g.premium_p05, g.premium_p95 - g.pure_premium],
                fmt="o", color=colour, capsize=3, label=season)
ax.set_yticks(np.arange(len(order)), order); ax.invert_yaxis()
ax.set_xlabel("pure premium (share of the sum insured), 90% interval"); ax.legend()
plt.tight_layout()
plt.show()

Dot and whisker chart of the pure premium with its 90% bootstrap interval for each back-test period, MH and MK1 side by side, with the widest intervals for the short out-of-reference periods relative to their values.

Look before moving on. Every whisker should contain its dot, as expected for a mean. A short whisker on a short period does not mean the premium is well known: it means the period’s few crop years were alike.

7. Check against pandas

The cell recomputes the point values of the summary in pandas from out.payout, idx.insured_unit and the final date of idx.data_status, and draws its own bootstrap over whole crop years with numpy, for the premium. The point values must agree to rounding; the intervals come from another random generator, so they agree only roughly. That is a measure of the bootstrap’s own noise: with 2,000 replicates, the interval bounds vary in the third decimal.

pay = pd.read_sql("""SELECT p.season, p.crop_year, p.payout_frac, p.payout_ha_eq, p.season_end, u.paddy_ha
                     FROM out.payout p JOIN idx.insured_unit u ON u.code = p.kabupaten_code""", ENGINE)
final_through = status.set_index("source").final_through["chirps_rnl"]
pay["paddy_ha"] = pay.paddy_ha.astype(float)
per_year = pay.groupby(["season", "crop_year"]).apply(lambda g: pd.Series({
    "provisional": bool((g.season_end > final_through).any()),
    "frequency": (g.payout_frac > 0).mean(),
    "pure_premium": g.payout_ha_eq.sum() / g.paddy_ha.sum()}), include_groups=False).reset_index()
periods = {"final record": (lambda y: y >= 1981, False), "reference": (lambda y: (y >= 1991) & (y <= 2020), False),
           "out-of-reference": (lambda y: (y <= 1990) | (y >= 2021), False), "before reference": (lambda y: y <= 1990, False),
           "after reference": (lambda y: y >= 2021, False), "provisional": (lambda y: y >= 1981, True)}
rng = np.random.default_rng(1)
rows = []
for season in ["MH", "MK1"]:
    for period, (inside, provisional) in periods.items():
        g = per_year[(per_year.season == season) & inside(per_year.crop_year) & (per_year.provisional == provisional)]
        if g.empty:                                  # no provisional year once the rainfall is final
            continue
        idx = rng.integers(0, len(g), size=(REPLICATES, len(g)))
        prem = g.pure_premium.to_numpy()[idx].mean(axis=1)
        rows.append({"season": season, "period": period, "frequency_pd": g.frequency.mean(),
                     "premium_pd": g.pure_premium.mean(), "premium_p05_np": np.percentile(prem, 5),
                     "premium_p95_np": np.percentile(prem, 95)})
check = table.merge(pd.DataFrame(rows), on=["season", "period"], how="outer", indicator=True)
assert (check._merge == "both").all(), "season-periods on one side only"
assert np.allclose(check.frequency, check.frequency_pd, rtol=0, atol=1e-12)
assert np.allclose(check.pure_premium, check.premium_pd, rtol=0, atol=1e-12)
print(f"{len(check)} season-periods: point values agree (largest difference "
      f"{max((check.frequency - check.frequency_pd).abs().max(), (check.pure_premium - check.premium_pd).abs().max()):.1e}); "
      f"premium interval bounds differ from numpy's by at most "
      f"{max((check.premium_p05 - check.premium_p05_np).abs().max(), (check.premium_p95 - check.premium_p95_np).abs().max()):.3f}")
12 season-periods: point values agree (largest difference 1.1e-16); premium interval bounds differ from numpy's by at most 0.004

Checkpoint

The cell below checks, in a new session, what this chapter built:

  • six periods, each role present, every multirange as defined in section 4;
  • one back-test row per season and crop year of out.payout, each with all insured units and a known season end, the provisional ones exactly those ending after the final date;
  • in the summary, every final crop year counted once in the final record and once in either the reference or the out-of-reference period, the provisional years nowhere else;
  • the bootstrap: one row per summary row with the same crop years, reproducible with the same seed, bounds in order, no spread for a single crop year, and every interval containing its mean.

It depends only on the setup cell.

EXPECTED = {"final record": "{[1981,)}", "reference": "{[1991,2021)}", "out-of-reference": "{[1981,1991),[2021,)}",
            "before reference": "{[1981,1991)}", "after reference": "{[2021,)}", "provisional": "{[1981,)}"}
with connect() as conn:
    first_row = lambda q, p=None: conn.execute(q, p).fetchone()
    periods_now = dict(conn.execute("SELECT period, years::text FROM idx.backtest_period").fetchall())
    n_roles = first_row("SELECT count(DISTINCT role) FROM idx.backtest_period")[0]
    year_rows, payout_years, wrong_flag, bad_units, no_end = first_row("""
        SELECT (SELECT count(*) FROM out.backtest_year),
               (SELECT count(DISTINCT (season, crop_year)) FROM out.payout),
               (SELECT count(*) FROM out.backtest_year y
                WHERE y.provisional IS DISTINCT FROM (
                    SELECT bool_or(p.season_end > d.final_through) FROM out.payout p, idx.data_status d
                    WHERE d.source = 'chirps_rnl' AND p.season = y.season AND p.crop_year = y.crop_year)),
               (SELECT count(*) FROM out.backtest_year WHERE units <> (SELECT count(*) FROM idx.insured_unit)),
               (SELECT count(*) FROM out.payout WHERE season_end IS NULL)""")
    counts = dict(conn.execute("SELECT season || ' ' || period, crop_years FROM out.backtest_summary").fetchall())
    finals = dict(conn.execute("SELECT season, count(*) FROM out.backtest_year WHERE NOT provisional GROUP BY season").fetchall())
    provisionals = dict(conn.execute("SELECT season, count(*) FROM out.backtest_year WHERE provisional GROUP BY season").fetchall())
    b1 = conn.execute("SELECT * FROM out.backtest_bootstrap(200, 0.5) ORDER BY season, period").fetchall()
    b2 = conn.execute("SELECT * FROM out.backtest_bootstrap(200, 0.5) ORDER BY season, period").fetchall()
    joined, mismatch = first_row("""
        SELECT count(*),
               count(*) FILTER (WHERE b.crop_years <> s.crop_years
                                   OR b.frequency_p05 > b.frequency_p95 OR b.premium_p05 > b.premium_p95
                                   OR (s.crop_years = 1 AND (b.frequency_p05 <> b.frequency_p95 OR b.premium_p05 <> b.premium_p95))
                                   OR s.frequency NOT BETWEEN b.frequency_p05 - 1e-12 AND b.frequency_p95 + 1e-12
                                   OR s.pure_premium NOT BETWEEN b.premium_p05 - 1e-12 AND b.premium_p95 + 1e-12)
        FROM out.backtest_summary s JOIN out.backtest_bootstrap(%s, %s) b USING (season, period)""", [REPLICATES, SEED])

assert periods_now == EXPECTED and n_roles == 4, f"periods {periods_now}"
assert year_rows == payout_years and wrong_flag == 0 and bad_units == 0 and no_end == 0, \
    f"{year_rows} rows for {payout_years}; wrong flags {wrong_flag}; years without all units {bad_units}; no season end {no_end}"
for s in ("MH", "MK1"):
    assert counts[f"{s} final record"] == finals[s] == counts[f"{s} reference"] + counts[f"{s} out-of-reference"], s
    assert counts[f"{s} out-of-reference"] == counts[f"{s} before reference"] + counts[f"{s} after reference"], s
    assert counts.get(f"{s} provisional", 0) == provisionals.get(s, 0), s
assert len(b1) == len(counts) and np.allclose(np.array([r[3:] for r in b1], float), np.array([r[3:] for r in b2], float),
                                              rtol=0, atol=1e-12), "bootstrap rows or reproducibility"
assert joined == len(counts) and mismatch == 0, f"bootstrap rows joined {joined} of {len(counts)}; inconsistent {mismatch}"
print(f"checkpoint passed: {year_rows} season-years, final record {finals}, provisional {provisionals}; "
      f"code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 90 season-years, final record {'MH': 44, 'MK1': 44}, provisional {'MH': 1, 'MK1': 1}; code cells took 11 s since the setup cell

Troubleshooting

Symptom Cause Fix
... is missing: run Chapters 4 to 9 first an earlier chapter has not been run run that chapter first
cannot change name of view column or cannot drop columns from view a view was changed in a way CREATE OR REPLACE VIEW does not allow DROP VIEW out.backtest_summary, out.backtest_year and run sections 3 and 5 again
cannot change return type of existing function the columns of RETURNS TABLE were changed DROP FUNCTION out.backtest_bootstrap(int, double precision) and run section 6 again
you changed PERIOD_ROWS, but the periods did not change idx.backtest_period was built earlier and is left as it is DROP VIEW out.backtest_summary, then DROP TABLE idx.backtest_period, and run sections 4 and 5 again
cannot drop table out.payout because other objects depend on it (Chapter 9) the views of this chapter, and of Chapter 11, read out.payout drop those views first (here DROP VIEW out.backtest_summary, out.backtest_year); the function needs no drop, never CASCADE
CHC has confirmed later dates, but nothing changed idx.data_status still holds the old final date update it by hand (UPDATE idx.data_status SET final_through = ... WHERE source = 'chirps_rnl'); the views follow at once
the bootstrap gives other intervals than before another seed or number of replicates, or another PostgreSQL version with another random generator keep SEED and REPLICATES; differences in the third decimal are the bootstrap’s own noise (section 7)

Summary

You now have:

  • idx.backtest_period: the periods of the back-test as int4multirange values with their roles;
  • out.backtest_year and out.backtest_summary: views of payouts per season and crop year and per period, which read the data status when they are queried;
  • out.backtest_bootstrap(replicates, seed): 90% bootstrap intervals over whole crop years, reproducible with a seed.

The back-test is as-if, its reference years restate the thresholds rather than test them, its test rests on 14 crop years, and its averages are uncertain because a few drought years carry a large share of the payouts. The provisional crop year stays apart until its rainfall is final. All payouts are illustrative. Chapter 11 reads out.payout and idx.data_status again, this time against the damage reported in the fields.

What comes next

Chapter 11 turns from rainfall to the fields: it compares the payouts with the drought damage reported for each unit and season, and measures the basis risk of the contract.

References