Skip to main content

Crop index insurance with PostGIS

Crop index insurance with PostGIS

This tutorial builds one applied case from start to finish: crop index insurance for rice in Java. An index contract pays when a measured index, here a rainfall shortfall, crosses a threshold, instead of when a loss adjuster confirms the damage in the field. Over twelve chapters you load satellite rainfall and paddy-field maps into a spatial database, turn them into a drought index for each insured kabupaten/kota, set the trigger and exit of a contract, test what it would have paid since 1981, measure its basis risk against the drought damage the Ministry of Agriculture reported, and serve the payouts as a web map.

Every analysis step is SQL, run from Python against PostgreSQL with the PostGIS extension, so each result is a table, view or function you can read, query again and rebuild. The series shows what a spatial database adds to such work: rasters and polygons meeting in one query, results that later steps and other people can reuse, and a map served straight from the tables.

Who it is for. Analysts who are comfortable with Python and pandas, have used QGIS and some SQL, and are new to PostGIS. No background in insurance is assumed: Chapter 1 explains the parts of an index contract and the words used throughout.

What this tutorial is, and is not

This is a tutorial about PostGIS, not a guide to designing crop insurance. Crop index insurance is the case that carries the series because it uses much of what a spatial database offers: rasters and polygons in one query, time series per area, thresholds applied in SQL, and results served as a map. The insurance method follows the case only as far as the PostGIS lessons need it, and it may not match how such a product should be built in practice. The index is not calibrated against yields or insured losses, the rainfall is not checked against rain gauges or with farmers, and the contract is not priced. Each choice is documented with its alternatives (Chapter 1 and the sources page), but none is offered as best practice. The trigger, exit and payout rule are illustrative, nothing here is advice on buying or selling insurance, and the damage reports used to test the contract are reported areas, not measurements.

PostGIS at the centre, not alone. Every analysis step runs in the database, PostgreSQL with PostGIS for both vector and raster data, which is why PostGIS is in the title. Getting data in, drawing figures and serving the map use other open-source tools, all driven from Python: raster2pgsql (part of PostGIS) and rasterio for the rainfall rasters; geopandas, pyarrow and shapely for the boundaries and paddy fields; requests and BeautifulSoup for downloads and the damage pages; psycopg and SQLAlchemy to talk to the database; pyproj, pandas and matplotlib to check and show results; and MapLibre GL JS for the web map. GDAL works underneath several of them, inside PostGIS raster as well as rasterio. The chapters use 56 PostGIS functions: 31 for geometries, 22 for rasters and 3 for vector tiles (ledger L174).

The workflow

Each box is a source or a table in the database; each arrow is a step built with SQL, labelled with the chapter that builds it. Chapter 1 explains the case and the schemas the tables live in.

%%{init: {"theme": "neutral"}}%%
flowchart TB
  B["Boundaries<br/>BIG 2022"] -->|Ch 3| K["ref.kabupaten<br/>kabupaten/kota"]
  D["Damage reports<br/>datanonkom"] -->|Ch 3| DR["raw.datanonkom_damage<br/>damage per month"]
  C["Rainfall<br/>CHIRPS v3"] -->|Ch 4| CR["raw.chirps_rnl_daily<br/>one raster per day"]
  CR -->|Ch 4| DK["idx.chirps_dekad<br/>dekad rainfall"]
  P["Rice fields<br/>MoA 2015"] -->|Ch 5| PF["ref.paddy_moa2015<br/>paddy polygons"]
  K --> PF
  PF -->|Ch 5| U["idx.insured_unit<br/>99 insured units"]
  DK -->|Ch 6| W["idx.dekad_rain<br/>rain over paddy"]
  PF --> W
  U --> W
  W -->|Ch 7| CAL["idx.season_dekad<br/>crop calendar"]
  CAL -->|Ch 8| I["idx.season_index<br/>drought index"]
  I -->|Ch 9| CT["idx.contract<br/>trigger and exit"]
  CT -->|Ch 9| PO["out.payout<br/>payouts"]
  PO -->|Ch 10| BT["out.backtest_summary<br/>back-test"]
  PO -->|Ch 11| BR["out.basis_risk<br/>basis risk"]
  DR --> BR
  PO -->|Ch 12| MAP["Web map<br/>vector tiles"]

Chapters

Chapter What you build
1 Index insurance in one case Nothing in the database yet: the case, the parts of an index contract, basis risk, and the words used throughout
2 Setting up PostgreSQL, PostGIS and Python The tutorial database with PostGIS and PostGIS raster, its four schemas, and a tested connection from Python
3 Boundaries and reported crop damage Java’s 119 kabupaten/kota and 6 provinces, and the monthly flood, drought and pest damage reported for each, collected politely from the web
4 Daily rainfall as rasters One CHIRPS rainfall raster per day from 1981, summed to ten-day totals (dekads) in the database, with a record of which days are final
5 Paddy fields and insured units Nearly a million rice-field polygons, reprojected, repaired and joined to their kabupaten/kota, and the 99 insured units
6 Rainfall per insured unit A weight table linking paddy fields to rainfall cells, and paddy-weighted rainfall for every unit and dekad
7 A crop calendar from rainfall The start of the rainy and dry seasons in each unit, two planting dates, and every season of every crop year laid over the record
8 A drought index Rainfall deficits below normal per crop stage, ranked against a fixed reference period, and the season index
9 Trigger, exit and payout The payout rule as a SQL function, a trigger and exit per unit, and what the contract would have paid since 1981
10 Back-testing the contract Periods as ranges of crop years, views that keep provisional years apart, and bootstrap intervals in SQL
11 Basis risk: payouts against reported damage Payouts set against reported drought damage, the 2x2 table and its rates, and an exercise on flood
12 Serving payouts as a web map Vector tiles cut in SQL, a small tile server in Python, and a MapLibre web map

Each chapter opens with “At a glance”: what it builds, what it needs from the chapters before it, and how long it took to run when it was tested.

Before you start

  • Software: PostgreSQL with PostGIS, and the Python environment in environment.yml. Chapter 2 installs them on Windows, where the series was written and run with PostgreSQL 18 and PostGIS 3.7, with pointers for macOS and Linux. The database connection and the data folder are set in config.yml.
  • Data: the chapters download what they need on their first run. The boundaries, the rainfall and the paddy fields come as files released with this repository, each checked against a checksum (Chapters 3 to 5), about 1.4 GB in all; the damage reports are collected from the Ministry of Agriculture’s web pages, slowly and with a local copy, as Chapter 3 explains. Each chapter lists what it downloads and how long it takes at its top.
  • Space: keep the data and the database outside folders that a cloud client synchronises. The tutorial database grows to a few gigabytes, most of it the paddy polygons and the daily rainfall rasters (Chapter 12, section 8).
  • The notebooks: each chapter is shown with the outputs of the author’s run. The “View source” link at the foot of each page opens it on GitHub, where you can download it and run it yourself. Each chapter ends with a checkpoint that stops with an error if its results are not what the next chapter expects.

Where the numbers come from

Every number in the chapters comes from a cell output in the same chapter or from a row of the sources page, which says how it was measured or where it was read.

Bahasa Indonesia

The whole series is also available in Bahasa Indonesia.

Repository

Source, issues and history: github.com/osgeoid/postgis-crop-insurance. Maintainer: Benny Istanto. Part of the tutorials of OSGeo Indonesia.

Licence and citation

Code under the Mozilla Public License 2.0, text under CC BY 4.0. The data keep their own terms, listed in the source ledger. To cite the tutorial, use the citation file of the repository.