Can We Quantify Indonesia’s Political Temperature? I Built a Daily GPR Index to Find Out
From the publisher’s feed, collected in the ZeroLabs newsroom.
How scraping five news sources, a keyword model, Prefect Cloud, and GitHub Actions turned Indonesian newspaper headlines into a quantified daily risk signal1. Introduction: Can You Measure Political Tension With Headlines?Geopolitical risk is something everyone feels but almost no one measures — at least not for Indonesia.If you’ve worked in finance, banking, or any sector where macro conditions matter, you’ve probably heard of the GPR Index. It’s a framework originally developed by economists Dario Caldara and Matteo Iacoviello to quantify how much geopolitical tension is in the air on any given day, based on newspaper coverage. The idea is elegant: politics shows up in language before it shows up in data. A spike in words like sanctions, military buildup, or terror attack across major newspapers is a leading signal — not a lagging one.The original Caldara & Iacoviello framework does include country-specific GPR indexes, including one for Indonesia. But those country indexes are built from English-language global newspapers like the New York Times or Financial Times, filtered by mentions of the country name. What you get is an index of how much the international press is talking about Indonesia’s political risk — not what’s actually being reported on the ground, in Indonesian, by Indonesian journalists.That distinction matters. Local political tension often surfaces in Bahasa Indonesia media days before it reaches international coverage, if it ever does at all. So I built a version sourced entirely from local outlets.2. The Problem Worth SolvingThe business question at the heart of this project is deceptively simple: what was Indonesia’s geopolitical temperature yesterday, and how has it trended over time?Answering that properly requires three things working together.First, a reliable daily data collection process. Indonesian political news is spread across dozens of sources. I needed to pick the most representative ones — a state news agency, independent outlets, and mainstream papers — and scrape them consistently, every single day, without manual intervention.Second, a principled methodology for converting text into a number. “Geopolitical risk” isn’t something you can just COUNT(*). You need a definition of what counts as a risk signal, what dimensions it covers, and how to aggregate them into an index that’s comparable across days.Third, a production system that doesn’t break. A GPR index that works for three weeks and then silently fails is worse than no index at all. It creates false confidence. The pipeline had to be robust enough to run unattended with observable failures.Those three constraints shaped every architecture decision in this project.3. Architecture OverviewThe pipeline follows a clean, linear flow:The stack: Python for scraping, Prefect Cloud for pipeline orchestration and observability, DuckDB as the analytical warehouse, dbt for transformation and index calculation, Google Sheets as the human-readable output layer, and GitHub Actions for scheduling and CI/CD.It runs every day at 08:00 WIB (Jakarta time), collecting and processing the previous day’s articles. The pipeline targets T-1 by design — yesterday’s news cycle is complete and stable, whereas scraping mid-day would give a partial, unrepresentative picture. No servers, no cloud bills, no manual steps.4. From Raw HTML to Clean News: The Scraping LayerPicking the Right SourcesSource selection was as much an editorial decision as a technical one. I chose five outlets that together cover the full spectrum of Indonesian political discourse: Antara as the state news agency for official framing of political events, Kompas and Detik as mainstream nationals with broad coverage and high volume, Tempo as the independent outlet known for investigative political reporting, and Tribunnews for wide regional reach across the archipelago.Between them, these five sources produce hundreds of articles per day across categories like politik, hukum (law), ekonomi, internasional, and nasional. That’s the raw material for the index.The Parser Architecture: Designing for ExtensibilityHere’s where the engineering got interesting. Each news source has a completely different HTML structure, a different URL pattern, and different anti-scraping behavior. Naive scraping — just writing five separate scripts — would have worked initially and become a maintenance nightmare within months.Instead, I built a polymorphic scraper architecture using Python Abstract Base Classes. Every parser inherits from a BaseParser ABC that defines the contract:class BaseParser(ABC): @abstractmethod def fetch_articles(self) -> list[dict]: ... @abstractmethod def parse_article(self, url: str) -> dict: ...Each site gets its own parser class that implements that contract. AntaraParser, KompasParser, TempoParser — they all look the same from the outside, which means the orchestrator (main_scraper.py) doesn't care which source it's dealing with. It just calls .fetch_articles() and gets back a list of article dictionaries.The practical payoff: adding a sixth news source later requires writing exactly one new class and registering it in two places. The rest of the pipeline is untouched.Keeping It Simple: Plain HTTP All the WayAll five parsers use Python requests for fetching — no headless browsers, no JavaScript rendering. This was a deliberate simplicity choice. The scraping targets article listing pages and individual article URLs, all of which return fully-formed HTML via standard HTTP responses. There's no need to spin up a browser engine when requests gets the job done in milliseconds.The practical payoff: the pipeline is fast, resource-light, and has no Playwright dependencies to install or maintain on the CI runner. Simpler is better when simpler works.5. From Clean Articles to a Risk Score: The Transformation LayerThe Data Cleaning ProblemRaw scraped articles are messy. The same article can appear twice if a source re-publishes it with a slightly different URL. Titles sometimes contain HTML artifacts. Timestamps are inconsistent across sources.The dbt staging model (stg_scraped_news) handles all of this: title normalization, duplicate detection via URL-based deduplication, null filtering, and timestamp standardization. By the time data leaves staging, every row is a distinct, clean article with a consistent schema.The GPR Index MethodologyThis is the analytical core of the project, and it’s worth spending time on.The GPR index operates on a simple but powerful idea: geopolitical risk leaves linguistic fingerprints. Words and phrases cluster around five distinct dimensions of risk. The first two cover the threat landscape: idx_war_threat captures conflict rhetoric, sanctions, and diplomatic pressure, while idx_peace_threat picks up signals of diplomatic collapse — failed negotiations, ceasefire breakdowns, and similar. The third dimension, idx_military_buildup, flags coverage of arms procurement, troop movements, and defense spending — tension that hasn't erupted yet but is visibly escalating. The final two capture actual events on the ground: idx_war_act covers active clashes, airstrikes, casualties, and territorial seizures, while idx_terror_act tracks terrorism, extremism, and counter-terror operations.Each article title is matched against keyword dictionaries for each dimension. If an article title contains words associated with war_threat, it flags that dimension. The index for each dimension is then calculated as:component_index = (articles_flagged_for_dimension / total_articles_that_day) × 100The result is normalized by article volume, so a day with 200 articles and 20 flags produces the same index as a day with 100 articles and 10 flags. This prevents the index from simply rising on days when news outlets publish more.The components then roll up into two composite indexes:GPR Threats Index = war_threat + peace_threat + military_buildup (tensions building)GPR Acts Index = war_act + terror_act (events actually happening)Total GPR Index = all five componentsThe distinction between threats and acts is deliberate. A period of escalating rhetoric without actual events looks very different from a period of active conflict, and the composite structure makes that difference visible.All of this lives inside a single dbt mart model, mart_gpr_daily, using a reusable match_keywords macro that keeps the keyword matching logic DRY across all five dimensions.6. Data Quality & ObservabilityA daily index is only as trustworthy as the pipeline underneath it. Several layers of quality checking keep the data honest.Parser-level tests in tests/test_parsers.py verify that each scraper returns well-formed output — non-empty article lists, expected fields present, no null titles. These run in CI before every pipeline execution.dbt tests on the staging model check for uniqueness violations and null values in critical fields. If a duplicate slips through the scraping layer, dbt catches it before it reaches the mart.The try_parser.py script is a manual inspection tool — not automated, but valuable. Before running the full pipeline on a new parser or after a source changes its HTML structure, this script lets you test a single parser in isolation and inspect the raw output. It's the "look before you leap" check that saved me several full pipeline runs.Environment separation via APP_ENV means the development and production databases are entirely isolated. Running the pipeline locally in dev mode writes to data/dev/ and a separate dev DuckDB file. Production data never gets contaminated by testing.7. Pipeline Orchestration: Why Prefect Cloud Changed EverythingThere’s a category of problem that dbt and GitHub Actions can’t solve on their own: what happens when one step fails halfway through?Early versions of the pipeline ran as a single Python script triggered by GitHub Actions. If the scraper succeeded but the DuckDB load timed out, the entire workflow showed as failed — but you had no idea which step broke, what the error was, or whether the raw JSON was safely saved before the crash.That’s where Prefect Cloud came in.The pipeline is now structured as a proper Prefect flow (run_pipeline.py) with four explicit tasks wired together in dependency order:@flow(name="Indo GPR Index Pipeline")def gpr_pipeline(target_date: str | None = None): scrape_future = scrape_task(target_date) load_future = load_task(target_date, wait_for=[scrape_future]) dbt_future = dbt_task(wait_for=[load_future]) export_future = export_task(wait_for=[dbt_future])Each @task decorator brings real operational benefits. The scrape task has retries=2 with a 60-second delay — if Antara or Kompas returns a transient error, Prefect retries it automatically without failing the entire flow. Each task streams its stdout to the Prefect Cloud UI in real time, so when something goes wrong at 08:00 WIB, the error is visible immediately with full context — not buried in GitHub Actions log output.GitHub Actions still handles the scheduling trigger and the uv run pytest gate before the pipeline runs. But once the pipeline starts, Prefect owns the execution graph. The raw JSON artifact is also uploaded to GitHub Actions with if: always() — meaning even if a downstream step (dbt, export) fails, the scraped data is preserved and can be replayed locally without touching the API again.The combination of the two tools is the right division of labor: GitHub Actions for scheduling and CI gates, Prefect for runtime orchestration and visibility.Why Abstract Base Classes instead of duck typing? Python doesn’t require ABCs — you could just write five functions and call it done. But ABCs make the contract explicit and enforce it at import time. Any parser that doesn’t implement fetch_articles and parse_article raises a TypeError immediately, not at 02:00 when the CI run silently fails. For a system that runs unattended, fail-fast is a feature.Why DuckDB for text-based article data? The articles table is wide — title, URL, source, timestamp, category, multiple keyword flags. DuckDB’s columnar storage makes aggregations across these fields extremely fast, and the LIKE-based keyword matching in the dbt mart runs on the full daily corpus in under a second. It's also completely serverless, which keeps the entire pipeline free to run.Why Google Sheets as the export target? An alternative would be a Looker Studio dashboard connected directly to DuckDB. But Google Sheets has a specific advantage for this use case: it’s accessible without any credentials, can be embedded in reports or shared with collaborators instantly, and makes the daily index values trivially easy to download, chart, or feed into other tools. It’s not the most sophisticated visualization layer — but it’s the most interoperable one.Why uv instead of pip? uv is a Rust-based Python package manager that's dramatically faster than pip and produces fully deterministic lockfiles via uv.lock. For a pipeline that runs in a fresh GitHub Actions environment every day, installation speed matters. uv sync on a cold runner completes in seconds vs. the 30–60 seconds that pip install -r requirements.txt often takes.Why Prefect Cloud instead of just GitHub Actions? GitHub Actions is excellent for scheduling and CI gates. But it’s not an orchestration tool — it has no concept of task dependencies, no retry logic per step, and no real-time task visibility. When a scraper fails at step 2 of 4, GitHub Actions shows one red job. Prefect shows exactly which task failed, with full logs, retry history, and the ability to replay from that task without re-running upstream steps. For an unattended daily pipeline, that observability is non-negotiable.Why normalize by article volume? This one took some thought. Early versions of the index produced higher scores on days when the news cycle was simply busier — election day coverage, for instance, floods every category with articles. Normalizing by total_articles ensures the index measures proportion of coverage dedicated to risk topics, not raw count. That's a more meaningful signal.8. Key Technical Decisions9. What the Data Tells UsThe index is designed to answer questions that a simple news search can’t:Is this week’s political tension elevated compared to last month? The total GPR index gives you a dated, reproducible score for each completed news day — comparable across any time window, rather than requiring you to read and interpret dozens of articles manually.Is the risk driven by threats or actual events? The split between gpr_threats_index and gpr_acts_index tells a different story depending on the political moment. A pre-election period typically shows rising threat rhetoric without a corresponding spike in acts. A security incident inverts that pattern.Which dimension is driving the index? Breaking down the composite reveals whether a spike comes from military-related coverage, diplomatic breakdown, or terrorism — which have very different implications for economic and market risk.Are there leading indicators in the data? Historically in global GPR research, the threats component tends to lead the acts component by days or weeks. Whether that pattern holds in Indonesian data is an open empirical question — and one this pipeline makes answerable.10. Lessons LearnedA pipeline without task-level observability is a black box. The single-script version of this pipeline was fine until it wasn’t. When it failed, the only signal was a red GitHub Actions job and a wall of interleaved log output. Moving to Prefect didn’t change the logic at all — same Python, same tasks — but it turned debugging from archaeology into diagnosis. Task-level retries, real-time streaming logs, and a run history UI are worth the extra setup time.ABCs are worth the extra typing. I initially wrote the first two parsers as plain functions. When I added the third, I refactored to ABCs. That refactor paid for itself immediately: the test suite became trivial to write because every parser promised the same interface, and the orchestrator became three lines instead of fifteen.Audit your sources before picking your scraping tool. It’s tempting to reach for a headless browser early because it handles everything. But requests is dramatically faster and cheaper to run in CI. Before adding Playwright or Selenium to a project, verify that the target pages actually require JavaScript rendering — in most cases, a plain HTTP request is all you need.Keyword lists are never finished. The initial keyword dictionaries were drafted once and then immediately felt incomplete. Indonesian political language evolves — new terms enter circulation, abbreviations become common, and regional vocabulary matters. Treating the keyword lists as living configuration (stored in config/) rather than hardcoded constants makes them much easier to extend.Separate dev from prod from day one. The APP_ENV environment variable split sounds like premature engineering for a solo project. It's not. Twice during development I accidentally populated the production DuckDB with test data and had to manually clean it up. The separation eliminated that problem entirely.Google Sheets is underrated as a data product. The stakeholder for this project is potentially anyone analyzing Indonesian political risk — investors, researchers, journalists. Not all of them can query a DuckDB file. A Google Sheet with a total_gpr_index column and a date column is something anyone can open, chart, and use in under thirty seconds. The engineering is the hard part. The output should be as frictionless as possible.11. Future ImprovementsSentiment analysis as a signal enrichment layer. Right now the index is purely keyword-based — a title either contains a flagged word or it doesn’t. Adding a lightweight sentiment model would allow weighting by intensity: an article with strongly negative sentiment around a flagged keyword contributes more to the index than a neutral mention of the same term.Full article body, not just titles. The current pipeline matches keywords against headlines only, which is fast and low-noise but misses context buried in article bodies. Extending the scraper to fetch and parse full text would make the index more comprehensive — at the cost of significantly more storage and processing time.Historical backfill. The pipeline starts accumulating data from launch date. To make the index analytically useful, a historical backfill using news archives would contextualize the current readings against years of baseline data — especially around major events like elections, natural disasters, and diplomatic incidents.Volatility metrics. A single daily score is useful. A 7-day rolling average and a standard deviation band would be more useful. These are simple dbt model additions, but they transform the index from a point estimate into a trend line with statistical context.Expanding to regional sources. The current five sources are all national. Indonesia has 38 provinces and rich regional political dynamics. Adding regional news sources would enable province-level GPR tracking, which would be genuinely novel for Indonesian political analysis.Closing ThoughtsThis project sits at an interesting intersection — data engineering infrastructure on the outside, quantitative political analysis on the inside. The pipeline is the enabler; the index is the product.What made it work wasn’t any single technical decision. It was the combination of things: a scraper architecture that’s actually maintainable, a methodology that’s principled enough to defend, and an output format that people can use without asking for help.If I had to pick one thing that surprised me most: how much the framing of the problem matters. “Scrape news and count keywords” is a trivial weekend project. “Build an automated geopolitical risk index for an underserved market, with a defensible methodology and a production-grade pipeline” is a portfolio piece worth explaining in a job interview.The data is the same. The story is completely different.Source code: github.com/billycemerson/indo-gpr-indexTags: #DataEngineering #Python #dbt #DuckDB #WebScraping #Prefect #Indonesia #GeopoliticalRisk #NLP #GitHubActionsCan We Quantify Indonesia’s Political Temperature? I Built a Daily GPR Index to Find Out was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.