Both describe the same model: the plain-language guide explains how the forecast works without the mathematics; the full specification is the technical paper the code implements.
On this page19 sections
- 1. Scope and principles
- 2. Data foundation
- 2.1 Sources
- 2.2 Notional results: re-bucketing history onto today's blocs
- 2.3 Data-quality gates
- 3. Model overview
- 4. Layer 1 — Baseline (electoral history)
- 5. Layer 2 — Swing (by-elections)
- 5a Contest structure — only the ballot can win a seat
- 6. Layer 3 — Polls
- 7. Layer 4 — Semantic (news, weekly)
- 8. The weekly analysis cycle
- 9. From shares to seats: simulation
- 9a Two seat counts: the median and the most-likely-winner tally
- 10. Backtesting and calibration
- 11. Assumptions and limitations
- 12. Academic anchors
- Appendix A — Parameter reference
- Appendix B — Reproducing a run
HitungKerusi Forecast Methodology
A layered Bayesian model for Malaysian parliamentary election forecasting
Last updated: 2026-11-08 (§9a the two seat counts — median vs most-likely-winner tally, and which the site shows where; the front-page headline is the one model-written sentence, number-checked; §9 Sarawak's horizon corrected to the SPR's 12 Dec 2026 polling day) · Version 0.1.7 · November 2026 · This document is the authoritative specification of the model implemented in backend/hitungkerusi/analysis_engine/. The public site renders this document — alongside a plain-language companion that explains the same model without the mathematics (methodology-plain.md) — on its Methodology page; if the code and this paper ever disagree, that is a bug.
Versioning note (2026-11-15). The complete methodology through engine v2 (
MODEL_VERSION 0.2.0, including §5a's pact transfer and §10's Melaka scorecard) is frozen atdocs/archive/methodology-v2-2026-11-15/with its calculation record and references. New methodology work happens in themethodology-v3working draft; this page continues to document the engine as built until a v3 change is ratified through the verification protocol.
1. Scope and principles
HitungKerusi ("count the chairs") forecasts Malaysian legislative elections under first-past-the-post:
- Dewan Rakyat — 222 federal constituencies (GE16 outlook).
- State assemblies (DUN) — chamber-specific forecasts with their own arithmetic: Melaka (28 seats, majority 15 — PRN polling day 14 November 2026), Sarawak (82, majority 42 — PRN polling day 12 December 2026, nomination 28 November), Johor (56 — next PRN ~2031), Negeri Sembilan (36 — ~2031), and Sabah (73 — ~2030; the 2025 PRN left a hung assembly). Each DUN chamber runs the same layered model on its own baseline (its latest PRN), own state-scoped polls, and own news window; the remaining states follow the same pattern as their PRNs approach.
Four principles govern the design:
- Reproducibility. Every published number comes from an immutable
forecast_runrow that stores the full parameter set and a SHA-256 hash over all input frames. Re-running with the same inputs reproduces the same output. - Layered evidence. Information enters in layers of decreasing reliability — electoral history first, then by-elections, then polls, then news — and each layer can only adjust what the previous layers established. No single layer, however loud, can dominate.
- Honesty about scarcity. Malaysian public polling is sparse, methodologically uneven, and concentrated in peninsular Malay-majority seats. The model must produce a defensible forecast from fundamentals alone, with polls and news as refinements.
- Bloc-level realism. Malaysian elections are contested by coalitions whose membership changes between and even during parliamentary terms (the Sheraton Move of 2020 redrew the entire chessboard without an election). The unit of forecasting is therefore the bloc — currently PH, BN, PN, GPS, GRS, WARISAN, and a residual OTHERS bucket — not the party. The bloc set is maintained as data (the
blocstable plus curated memberships), so a new bloc is a curation event, not a code change; see the development guide.
2. Data foundation
2.1 Sources
| Data | Source | Notes |
|---|---|---|
| GE15 candidate-level results (222 seats) | TindakMalaysia open dataset, cross-checked against SPR gazettes | Loaded via auditable transformer; QA gates reconcile every seat |
| GE14 party-level results (222 seats) | Wikipedia per-constituency results page, parsed from wikitext | Coalition totals reconcile exactly with the official result (BN 79, PH 113, PAS 18, WARISAN 8, STAR 1, IND 3) |
| PRN Melaka / Sarawak 2021 (28 + 82 seats) | Wikipedia results pages, parsed from wikitext | Exact actuals reproduced: BN 21 (Melaka), GPS 76 (Sarawak) |
| PRN Johor 2022/2026, N. Sembilan 2023/2026, Sabah 2025 | MECo results corpus (candidate-level) | Johor 2026: BN 48/56; NS 2026: BN+PN 25/36; Sabah 2025: GRS 34, WARISAN 20 — hung assembly |
| Six PRNs, August 2023 (Selangor, NS, Penang, Kedah, Kelantan, Terengganu) | MECo results corpus (aggregate state shares) | Swing-layer evidence only — no chambers built on them |
| By-elections since GE15 | Wikipedia by-election pages (Kuala Terengganu, Pulai, Kemaman 2023) | Like-for-like vote extraction; Padang Serai 2022 counted as part of GE15 |
| Electorates | SPR voter-roll demographics (Aug 2025 file, TindakMalaysia) | 169/222 seats updated; remainder keep GE15 values |
| Coalition membership history | Curated memberships.yaml in-repo | Human-reviewed, dated; editable as politics shifts |
| News | RSS (Google News queries, Malay Mail, FTM) | Headline + summary; paywalled content never scraped |
| Polls | Manual entry (Ilham Centre, Merdeka Center, EMIR Research) | Entered with field dates and sample size |
2.2 Notional results: re-bucketing history onto today's blocs
A vote cast at GE15 for Bersatu (then in PN) sits correctly in today's PN column. A vote for Pejuang under the Gerakan Tanah Air (GTA) banner belongs in today's OTHERS bucket, because GTA no longer exists as a competitive force. Notional results answer the question: given the votes actually cast at election E, how would they be distributed across today's blocs?
Two paths produce them:
- Bloc-aligned ingestion (used for GE15): the TindakMalaysia dataset already reports votes per today's blocs, so each candidacy carries its bloc directly and notional results are the straight aggregation of candidate votes into (seat, bloc) pairs.
- Party-history mapping (used for GE14): each 2018 candidacy's party is mapped to the bloc that party belongs to as of the load date, via the dated
coalition_membershiptable andcoalition_blocoverrides. A 2018 PPBM vote counts for PN today; a 2018 BN vote in Sarawak (PBB/PRS/PDP/SUPP) counts for GPS; a 2018 PAS vote counts for PN; PBS's 2018 BN seat counts for GRS. Parties with no current home (UPKO, PCS, BERJASA, ...) fall into OTHERS.
The result is a genuine realignment-aware history: GE14's notional seat allocation reads PH 100, PN 56, BN 34, GPS 19, WARISAN 8 — the PPBM+PAS votes that became the 2022 "green wave" were already visible inside the 2018 vote distribution once re-bucketed onto today's blocs.
The notional table is the only electoral input the model consumes. This isolates the realignment problem: when the coalition map changes, only notional results are recomputed, never the model.
The dated map answers "who belongs to whom", not "who is on this ballot" — and those diverge. Bersatu contested Melaka 2026 on its own logo after PN's registration was cancelled, yet the dated membership map still says PPBM → PN (it must, or every past Bersatu vote would leave PN). A per-election attribution override (data/seed/contest_blocs.csv: election, party, bloc) resolves the current contest without touching history: for Melaka 2026, PPBM counts as BERSATU, a bloc that appears in no formation and therefore earns no majority credit. Past elections keep their original attribution; only the field of the overridden election changes. This is the honest half of a deeper limitation — a bloc-level engine cannot express "one party alone" better than by giving that party a bloc of its own (§11).
2.3 Data-quality gates
Before any forecast runs, every election in the database passes QA: per-seat bloc vote totals must reconcile with official valid-vote counts (blocker if off by more than 0.1%), ballots cannot exceed electorate, recorded winners must hold the seat's maximum votes, and turnout must sit in a plausible band. Blockers abort the pipeline rather than poison the forecast.
3. Model overview
For each seat $s$ and bloc $b$ the model produces an expected vote share $\mu_{s,b}$, then a Monte Carlo simulation converts shares into seat outcomes. The expected share is built in four layers:
$$\mu_{s,b} = \underbrace{\text{baseline}{s,b}}{L1} \oplus \underbrace{\delta^{\text{nat}}b + \delta^{\text{state}}{s,b}}{L2\ \text{swing}} \oplus \underbrace{\text{poll-implied }\delta^{\text{nat}}b}{L3} \oplus \underbrace{\nu{s,b}}_{L4\ \text{semantic}}$$
where $\oplus$ denotes addition in share space followed by re-normalisation, and each layer's contribution is bounded (§7 caps L4; §6 caps L3’s trust weight).
4. Layer 1 — Baseline (electoral history)
Time-decay weighting. For each past election $e$ at distance $\Delta_e$ years from the forecast date:
$$w_e = \exp(-\lambda \Delta_e), \qquad \lambda = 0.5 \ \text{by default}$$
One election half-life of two years: GE14 (2018) would enter a GE16-era forecast at roughly 15% weight alongside GE15's 100%... and GE13 at 2%. Malaysian politics re-aligns fast; old elections inform the seat distribution's texture, not the contest.
Effective votes. With $v_{e,s,b}$ the notional votes and $n_{e,s}$ the valid votes:
$$v^{\text{eff}}{s,b} = \sum_e w_e, v{e,s,b}, \qquad n^{\text{eff}}s = \sum_e w_e, n{e,s}$$
Hierarchical shrinkage. The raw time-weighted share $\hat{p}{s,b} = v^{\text{eff}}{s,b} / n^{\text{eff}}_s$ is shrunk toward the bloc's national share $p_b^{\text{nat}}$ with pseudo-vote mass $m$:
$$\text{baseline}{s,b} = \frac{v^{\text{eff}}{s,b} + m, p_b^{\text{nat}}}{n^{\text{eff}}_s + m}, \qquad m = 800 \ \text{by default}$$
This is a two-level empirical-Bayes hierarchy (seat → nation; a state level is planned). Its job is regularisation: seats whose history is thin or stale move toward the national norm, while data-rich seats keep their own numbers. With $m=800$ against typical effective turnouts of 20,000–60,000, the pull is about 1.5–4% — enough to soften idiosyncratic seats without re-drawing the map. With GE12–GE15 now loaded, cross-election smoothing is active: at λ=0.5 the pre-2018 elections carry only ~2% weight, so their main contribution is texture in the seat distribution rather than the contest.
Calibration check: run against GE15 alone (no swings, no polls, no news), the model's 80% seat-count intervals contain every bloc's actual result — PH actual 81 vs forecast median 84 [80–88]; PN 74 vs 71 [68–75]; BN 30 vs 32 [29–36]; GPS 23 vs 20 [19–22]; GRS 6 vs 6; WARISAN 3 vs 3; OTHERS 5 vs 5.
5. Layer 2 — Swing (by-elections)
By-elections between general elections are Malaysia's only observed vote movements. Three Dewan Rakyat by-elections have occurred since GE15 — Kuala Terengganu (Aug 2023), Pulai (Sep 2023), Kemaman (Dec 2023) — and each is loaded with candidate-level votes. (Padang Serai, held 18 days after GE15 following a candidate's death, is counted as part of GE15.)
Like-for-like measurement. The unity government means blocs routinely sit out by-elections they cede to their partner, which mechanically inflates the remaining blocs' shares: PAS "won" 84.96% at Kuala Terengganu partly because BN did not contest. Measuring the naive share difference would report a phantom +20-point PN swing. Instead, for each seat we restrict to the set of blocs that contested both the by-election and the base election, renormalise both elections' shares to that contested set, and measure the swing within it:
$$\text{swing}{s,b} = \frac{v^{\text{BE}}{s,b}}{\sum_{b' \in C_s} v^{\text{BE}}{s,b'}} - \frac{\text{baseline}{s,b}}{\sum_{b' \in C_s} \text{baseline}_{s,b'}}, \qquad C_s = {\text{blocs contesting both}}$$
On this like-for-like basis the 2023 by-elections read: PN +5.3 points nationally, PH −4.2, BN −8.0 (Kemaman only) — real PN consolidation in the Malay belt, an order of magnitude smaller than the naive reading.
L2b — state-election swings. When a state votes more recently than the base general election, its PRN is itself electoral evidence for that state's parliamentary seats. Eight states now feed this layer: Johor and Negeri Sembilan (PRNs mid-2026, candidate-level), Sabah (PRN 2025, candidate-level), and the six August-2023 peninsular PRNs (Selangor, Negeri Sembilan, Penang, Kedah, Kelantan, Terengganu) loaded as aggregate state shares — the NS 2023 evidence is superseded by its 2026 PRN under a latest-per-state rule. For each such state the swing per bloc is
$$\delta^{\text{PRN}}{j,b} = \left(p^{\text{PRN}}{j,b} - \bar{p}^{\text{baseline}}{j,b}\right) \cdot \underbrace{0.5^{a_j / 365\text{d}}}{\text{age decay}} \cdot \underbrace{0.5}_{\text{structure shrink}}$$
shrunk twice: evidence fades with a 365-day half-life, and a 50% structure discount because DUN contests have different multi-corner structures and seat deals than federal ones (straight BN+PN fights in Negeri Sembilan, absent blocs in Johor). The half-life was recalibrated from an initial 120 days after the Johor 2022→2026 replay (§10) showed that four-year-old state votes still allocate 94.6% of seats correctly — a 120-day half-life would erase fresh PRN evidence years before the next federal contest. The swing is added to the by-election state residual and applied to the state's parliamentary seats through the same uniform-swing mechanism. As of October 2026 this layer reads Johor BN +11 / PN −9, Sabah GRS +4.6 / PH −5.6, and small age-decayed PN gains (+0.5–0.9) in the northern states from the 2023 evidence.
From seats to a national swing. The national swing per bloc is the mean of its by-election seat swings, then shrunk toward zero by sample size with $k_{be} = 4$ pseudo-seats:
$$\delta^{\text{nat}}_b = \frac{n}{n + 4},\overline{\text{swing}}_b$$
so three seats carry 43% of their face value. It is then blended with the poll-implied swing (§6) by weight. State swings shrink toward the national value with $k=2$ pseudo-seats, giving the uniform-plus-regional decomposition (Butler's UNS generalised). This matters in Malaysia — the 2022–23 "green wave" was regionally concentrated, and the backtest (§10) quantifies how much that regional concentration costs a purely uniform model.
When no by-elections are loaded, L2 contributes zero and the forecast is baseline + L3 + L4 only.
5a Contest structure — only the ballot can win a seat
Every layer above produces a share for every bloc in every seat, because notional history is re-bucketed per bloc. But Malaysian blocs do not contest everywhere: in PRN Melaka 2026 BN fields candidates in 23 of 28 seats and PH stands aside in others, while PN runs all 28. Applied naively, the model keeps a phantom share for an absent bloc — and can award it the seat.
The forecast therefore reads the next dated election's filed candidacies for the chamber and, per seat where a field is known:
- zeroes the blocs that are not on that ballot,
- transfers a stood-aside pact ally's share to its partner where a curated seat pact names the two as one ticket (v2, below),
- renormalises the contesting blocs to sum to 1 (their shares rise to absorb the phantom vote, which is what a real contest would have produced), and
- passes an eligibility mask to the simulation so a non-contesting bloc can never win a draw, however the noise falls.
A seat with no recorded field is left unrestricted — an unknown ballot is not an empty one, and before nomination day nothing is known. That is why GE16 (no candidates loaded) behaves exactly as before, while Melaka's five BN-free seats now reflect the actual contest.
Pact transfer (engine v2, 2026-11-15). The v1 rule renormalised absent blocs proportionally, which assumes an absent bloc's voters split like its surviving opponents. PRN Melaka 2026's BN–PN seat pact disproved this decisively: in the seats BN stood aside for PN (N.013 Paya Rumput, N.017 Bukit Katil, N.016 Ayer Keroh), BN's 2021 share transferred almost entirely to PN while the model split it — producing both of the forecast's high-confidence misses (model PH 59.4% vs actual PN 58.8% in Paya Rumput — shares nearly inverted) and the chamber-wide PH +14.9pt / BN −8.0pt bias. When a curated pact row exists for the election (data/seed/seat_pacts.csv; currently only PRN-MELAKA-2026, BN, PN), a bloc barred from a seat whose pact partner is on that ballot now transfers its share to the partner before renormalisation — full transfer, "one ticket", no fitted parameter. A pact whose members are both off a ballot, or a bloc with no pact, keeps the old proportional drop; elections with no pact row are untouched, so the chained GE12→15 backtest is byte-identical under v2. The replay gate on Melaka itself: 28/28 winners (v1: 26/28), Brier 0.011 (v1: 0.165), share MAE 9.6pts (v1: 17.2), seat tally exact (BN 21 · PH 4 · PN 3), PH bias +14.9 → +4.4. One honest caveat: the rule was designed after seeing this election's result; its structural justification (a pact is one ticket) and the no-fitted-parameter design are the safeguards, and the next pact election is the out-of-sample test.
Parties contesting alone. The contest set is bloc-keyed, so a party standing outside its coalition needs a bloc of its own for that election — supplied by the attribution override in §2.2 and seeded as a bloc row (BERSATU, 2026-11-02). It is deliberately absent from every formation, so its seats count toward no majority; formations are curated data, not an inference. The override cuts both ways: where a party's logo belongs to a coalition for this election — Wawasan carrying PN's nomination in Bemban and Kesidang (WAWASAN → PN, 2026-11-03, per the SPR's 79-candidate field) — it is attributed to that coalition rather than left in OTHERS.
Party view (added 2026-11-02). Because the engine aggregates at bloc level, several parties sharing OTHERS were indistinguishable on a seat page (Melaka 2026: BERSAMA, WAWASAN, PPBM-alone and independents in one bucket). Every run now also records a party decomposition in forecast_party_probs: each party's share is its bloc's share multiplied by that party's share within the bloc in that seat, measured from party-level history with a pseudo-vote prior so a newcomer on the ballot is visible rather than zero. Membership is per the seat's filed ballot: a party splits its bloc's share only in the seats it actually contests. The first build (2026-11-02) iterated the chamber-wide party list in every seat instead, so PUTRA — contesting Gadek alone — appeared in all 28 seats at the pseudo-prior share, and Bemban's view included a party with no candidate there (fixed 2026-11-03). Two properties are deliberate:
- Bloc totals are preserved by construction — a party's share is a slice of its bloc's share, never an addition, so no bloc-level published number changes and no reader of
forecast_seat_probscan double-count (the party rows live in their own table). - Win probability is not invented. A bloc's seat probability is the chance some party of that bloc takes the seat; it transfers to the bloc's leading party in that seat and is zero for its other members. Splitting it across members would manufacture draws in which two parties of one bloc both win.
This is a decomposition, not yet an independent party model: party-specific swings and party-level poll movement are not measured (published polls are per coalition), so the within-bloc composition is held at its historical proportions. That remaining step — party keys through L1/L2/L4 with bloc aggregation — is recorded as the open item in §11.9.
Completeness gate. Restricting a seat is only as good as the field behind it: an under-parsed candidate table would delete a bloc that is really standing, turning a correction into a confident error. The layer therefore refuses to act on any field where a seat names fewer than two blocs — five single-candidate seats in one chamber is a parsing fault, not five walkovers — and logs that it fell back to the unrestricted model. Melaka tripped this gate on 2026-10-31 (53 of ~79 candidates stored); once ingestion was fixed it opened by itself on the next run. The gate does not catch within-seat losses, though: on 2026-11-03 the stored field held 78 of the SPR's 79 candidates — Ayer Keroh's Gerakan pair was swallowed because a nested colour template in the source table split its cell, leaving the party acronym after the debris where the reducer cut it off (the parser now reads the visible tail, and the field matches the commission's 79-candidate tally). There is no configuration switch: the data decides, so the layer can never silently outrun a broken field.
Effect measured on 2026-10-31, the day this landed: Melaka had been awarding Paya Rumput and Bemban to BN — 63% and 59% win probability — for a bloc with no candidate on either ballot, and 31 seat-bloc share entries across the chamber belonged to blocs not standing in that seat. This applies to every chamber, using the same code path: it activates wherever an upcoming election has a filed field, and stays dormant everywhere else.
6. Layer 3 — Polls
Polls never touch seat-level numbers directly. They adjust the national vote shares, which propagate through the same uniform-swing mechanism as L2 — one mechanism, two evidence sources.
Decay weighting. For poll $i$ with age $a_i$ days and sample size $n_i$:
$$w_i = 0.5^{a_i / 45} \cdot \sqrt{n_i} \quad (\text{45-day half-life; } n_i \text{ defaults to 500 if unreported})$$
Polls older than six half-lives (270 days) are dropped entirely. Per-poll bloc shares are renormalised to sum to 1 before aggregation.
Trust cap. With $N$ distinct polls in the window:
$$\kappa = \min(0.7,\ 0.25,N)$$
So one poll moves the national estimate by 25%, three polls by 70% (the cap), and the baseline always retains at least 30%. The blended national share is renormalised across blocs, and the implied national swing $\delta^{\text{poll}}b = p^{\text{blended}}b - p^{\text{baseline}}b$ is merged with the by-election swing from L2 in proportion to their weights ($w{\text{polls}} = \kappa$; $w{\text{BE}} = \min(1, n{\text{BE seats}}/8)$).
This is a deliberately conservative version of dynamic poll aggregation in the spirit of Linzer (2013); house effects are not yet modelled because the number of usable Malaysian pollsters per cycle barely exceeds two, which cannot identify house-effect parameters. When a poll series accumulates, house offsets and pollster grades (already stored) will enter the weighting.
7. Layer 4 — Semantic (news, weekly)
The semantic layer converts tagged news into small, capped seat-level adjustments. It runs every week and is the layer users feel between elections.
Pipeline per weekly cycle:
-
Collect — RSS feeds →
news_articles(immutable, deduplicated by URL). Google News returns at most ~100 items per query ranked by relevance, so coverage comes from many narrow queries rather than one wide one: generic politics (EN/BM), pilihan raya, Dewan Rakyat, party names, one query per coalition in each language, the institutions that decide who may contest (Registrar of Societies, Election Commission), state-election queries, and per-seat campaign feeds inside 90 days of a polling day; plus direct publisher feeds. A baseline backfill (hk collect-news --days 180) runs every query once per weeklyafter:/before:window so the per-query cap does not truncate history. -
Tag — each article is linked to entities (seats, parties, coalitions), scored for sentiment and relevance at two levels, and given a one-sentence bilingual rationale — why the tagger judged the story to matter. Two interchangeable taggers share one schema:
- fallback (always on): deterministic whole-word matching against seat, party and coalition registries (acronyms case-sensitive, so lower-case "pas" or "gerakan" — ordinary Malay words — never tag), with a small Malay/English political lexicon for sentiment. Zero cost, fully reproducible; its rationale states that it is a keyword tag awaiting LLM assessment. It scores bloc-level rows only.
- LLM (when
LLM_API_KEYis set): an OpenAI-compatible model performs entity extraction, sentiment scoring and the rationale under a strict JSON contract. The deterministic tagger remains the floor — the LLM only refines. Its domain context encodes three standing corrections: RoS deregistration suspends a bloc's vehicle, not its component parties' ballot access (scored as coordination risk, not lost ballot access); the current government map — federal PH+BN, Johor BN, Melaka and Negeri Sembilan BN+PN, Sabah GRS, Sarawak GPS — so state-government crises are attributed to the blocs actually governing that state (post-August-2026 Negeri Sembilan coverage reflects on BN+PN, not PH); and the party-first level rule below. Each cycle also spends a bounded budget upgrading articles that only ever received keyword tags or predate a tagging-contract change (an LLM outage leaves the fallback's cruder scores behind; the upgrade pass replaces them), and the cycle's preflight (hk llm-check) makes a dead gateway a visible warning rather than days of silent fallback.
Party-first attribution (2026-10-28). Parties are the permanent unit; blocs are alignments that change. The tagger therefore scores the level the story is actually about: a story about one party's own fortunes, leaders or candidates is a party story and lands in
news_party_sentiment(a Bersatu gain is a Bersatu fact — it says nothing about PAS, its split coalition partner); only a story about the coalition as a whole — alliance formation or rupture, seat pacts between blocs, coalition leadership, registration, manifesto — produces a bloc row innews_sentiment. How much a party's signal crosses to its bloc is curated data, not an assumption from membership:party_news_flowholds a weight per party (1.0 for intact partners; 0.25 for PAS toward PN while the split persists). Bersatu has carried its ownBERSATUbloc since 2026-11-02 (§2.2), so its news counts there at full weight and toward nothing else — a leftover 0.25 weight that also routed every Bersatu story into PN's signal was removed on 2026-11-04 (the loader now mirrors the file, so a retracted weight actually retracts). -
Embed (when a key is set): article vectors stored in pgvector for semantic dedup and retrieval of seat-relevant coverage.
-
Score — for each seat $s$ and bloc $b$ within the 28-day window:
$$\text{signal}{s,b} = \sum{a \in \text{articles}(s)} \text{relevance}a \cdot \text{sentiment}{a} \cdot \text{flow}_{a \to b}$$
where $\text{flow}_{a \to b}$ is 1.0 for bloc-level stories and, for party stories, the party's party_news_flow weight — except on seats where that party is the bloc's carrier (it led the bloc's vote there in the seat's most recent election), where it counts at full strength: Bersatu news moves Bersatu's own seats, not PAS-held ones.
- Standardise and cap — per bloc across seats:
$$z_{s,b} = \frac{\text{signal}{s,b} - \overline{\text{signal}}b}{\sigma_b}, \qquad \nu{s,b} = \operatorname{clip}\left(0.01 \cdot \kappa{\text{sem}} \cdot z_{s,b},\ -0.02,\ +0.02\right)$$
with $\kappa_{\text{sem}} = 1.0$. One standard deviation of news signal therefore moves a seat by one share point, and no amount of news can move any seat-bloc share by more than two points — the formal guarantee that headlines alone cannot swing the forecast. In share space the nudges sum with L1–L3 and the row is renormalised.
Why standardise rather than use raw sentiment? Absolute sentiment scores are tagger-dependent and unbounded; z-scores measure relative news pressure across seats, which is the decision-relevant quantity ("which seats is the news cycle moving?"), and the clip bounds the units regardless of tagger calibration drift.
National coverage is read, not applied. A story that names no constituency — the Registrar of Societies deregistering Perikatan Nasional (20 October 2026) is the canonical case — is collected, tagged and shown on the site, but it cannot move a seat forecast: the signal is summed per seat, and even if such a story were attributed to every seat, the per-bloc standardisation would remove a uniform shock by construction. This is deliberate — L4 answers "which seats is the news moving?", not "is the country moving?" (that is the polls' job, L3). So that readers never mistake the omission for blindness, the chamber explanation reports the bloc-level coverage the model saw in the window (story counts, mean sentiment, the strongest headline) and states that it was not applied. Note also what such a story does and does not change: deregistering a coalition removes its vehicle — the shared symbol and the coordination it enforces — not its component parties' ability to contest, which stay registered and may run under their own symbols (in Melaka, PN's candidates under the PAS moon); and the model forecasts blocs, votes aggregated across whatever symbols they were cast for (§2.2), so the bloc does not disappear from the arithmetic. The tagger is told this so its rationales score such events as coordination risk, not lost ballot access. Treating bloc-level news as a national swing input — or as a modest widening of a bloc's uncertainty when its coordination is in question — is a possible extension of L4, not part of the current model.
8. The weekly analysis cycle
The worker runs on an adaptive cadence (HK_CYCLE_DAYS=auto): every 7 days in quiet periods, every 3 days once a dated election sits within 60 days, and every 24 hours through the campaign window (from nomination ≈ polling − 14 days until polling day). A daily decision tick re-resolves the interval from the electoral calendar, so a snap dissolution shortens the cycle within a day. Each cycle runs:
collect → tag → embed → notional-refresh → QA gates → forecast → persist
Notional results are recomputed each cycle (cheap) so that coalition-map edits take effect immediately. QA blockers abort before forecasting. The forecast run then executes L1 → L2 → L3 → L4 → simulation in that fixed order and persists:
forecast_seat_probs: per seat and bloc — win probability, expected share, σ.forecast_summaries: per bloc — median/mean seats and the p05/p10/p90/p95 interval. The most-likely-winner tally (§9a) is derived on read fromforecast_seat_probs(fetch_most_likely_seats) and published alongside it, not stored.forecast_metrics: P(hung parliament), P(government blocs ≥ 112 / ≥ 149), P(largest bloc).- run metadata: model version, all hyperparameters, and the input hash.
Runs are append-only. The site always displays the latest run; the full history is retained, so the forecast's own movement over time is auditable after the fact.
9. From shares to seats: simulation
Malaysian contests are multi-cornered by default (GE15 averaged ~4 candidates per seat, with 3+ serious blocs in Malay-majority seats). Pairwise win-probability shortcuts do not survive this; HitungKerusi simulates each seat's entire share vector jointly, with regionally correlated uncertainty:
- Draw a state shock per state and bloc: $z_{j,b} \sim \mathcal{N}(0, \sigma_{\text{state}})$, applied to every seat in state $j$ — seats in the same state move together within a simulation.
- Draw an independent seat perturbation: $\varepsilon_{s,b} \sim \mathcal{N}(0, \sigma_{\text{seat}})$.
- $\tilde{p}{s,b} = \mu{s,b} + z_{\text{state}(s),b} + \varepsilon_{s,b}$, clipped at a 0.2% floor and renormalised.
- The winner of seat $s$ in draw $d$ is $\arg\max_b \tilde{p}_{s,b}$.
Horizon-scaled volatility. Uncertainty grows with time to the election as a damped random walk:
$$\sigma_{\text{total}}(t) = \min\left(0.16,; 0.045\sqrt{1 + t/168\text{ days}}\right)$$
anchored at both ends: 4.5 share points near-term (a weekly cycle moves little), ~14–15 points at a four-year horizon (the empirical GE14→GE15 per-bloc swing σ is 16.2). The split between the two components is $\sigma_{\text{seat}} = \sqrt{1-\rho},\sigma_{\text{total}}$ and $\sigma_{\text{state}} = \sqrt{\rho},\sigma_{\text{total}}$ with $\rho = 0.4$: 40% of variance is regional. Expected polling days per chamber drive $t$ — Melaka 14 Nov 2026, Sarawak 12 Dec 2026 (SPR announced 6 Nov 2026; the entry held the outer deadline 2027-01-31 until then), Sabah ~2030, Johor and Negeri Sembilan ~2031, parliament at its auto-dissolution deadline (all env-overridable via HK_POLLING_DAY_*). A date that is only a constitutional limit is not a polling day: until the announcement lands, the horizon is provisional, and the announcement must be written into CHAMBER_CONFIG (horizon) and the elections table (which drives the site's announced/expected state) — one without the other leaves the site contradicting the model.
Across 10,000 draws this yields per-seat win probabilities, full seat-count distributions per bloc, and the headline metrics: P(no single bloc ≥ majority), P(government ≥ majority / two-thirds), and P(largest bloc) per bloc.
9a Two seat counts: the median and the most-likely-winner tally
The simulation produces a distribution of seat totals per bloc, so "how many seats does bloc X get" has two defensible answers and HitungKerusi publishes both. They usually agree and can differ by a seat or two, which is why every number on the site names which one it is.
- Median seats — the 50th percentile of bloc $b$'s simulated seat total, published with the 80% interval (p10–p90). This is the central estimate of the distribution, and the only figure that carries an uncertainty band. It is what
forecast_summariesstores and what the Seats by bloc (median, 80% interval) panel and the forecast-movement history use. - Most-likely-winner tally — the count of seats in which bloc $b$ is the single most likely winner (argmax of that seat's win probability). This is a per-seat reading, not a distributional one: it answers "if every seat went to its most likely winner, what would the chamber look like?", which is exactly what the hemicycle and the seat strip draw. It is exposed as
most_likely_seatson every bloc in/api/v1/forecast/latestand in the web read path (fetch_most_likely_seats, one aggregate over(DISTINCT ON (seat_code) … ORDER BY win_prob DESC)).
The two differ because medians of a joint distribution are not the medians of its marginals: a bloc can lead many seats narrowly (high argmax tally) while its total seat count is usually lower (median). Neither is "the" forecast; stating one without the other is what makes two figures on the same page look like an error.
Which number the site shows where — the single-number surfaces (home hero, chamber tiles, "Gov seats") use the most-likely-winner tally so they agree with the graphic beside them; the bloc panel keeps median + 80% interval, labelled as such; the spotlight's bloc list likewise shows medians under "median seats". Sarawak-2026 happens to agree under both (GPS 81 / OTHERS 1); Melaka differs (BN 21 argmax vs median 20) and is the case that forced the distinction onto the page.
Plain-language explanations. Every run also writes a short "why this forecast" paragraph — one for the chamber, one for each seat — in English and Bahasa Malaysia, rendered on the dashboards and seat pages. The text is generated, not authored: deterministic sentence templates over the run's own intermediate frames (raw baseline vs shrunk baseline, swing contribution, semantic nudge, win probabilities), the previous run for movement ("run #118 → #123 moved nothing beyond noise" names a change only past thresholds — 2pt win probability / 0.5pt share), and the window's articles for attribution (a change with fresh coverage names the strongest story; without it, the text says window turnover or the calendar). No LLM is involved at render time — the paragraphs cost under a second per run, are stored with their run in forecast_explanations, and are regenerated fresh each run so a quiet cycle reads as such.
The front-page headline is the exception, and it is the only model-written prose. Once per cycle (hk headline, run at the end of the cycle) the model is handed that cycle's figures — days to polling, the leading bloc, its most-likely-winner tally, the chamber size and majority line, P(government ≥ majority) — and asked for one sentence in English and Malay. It may use only those numbers: every digit in the answer is checked against the supplied set, and any other number, any exclamation mark, or any over-length answer rejects the whole response. On rejection, or if no key/gateway is available, nothing is stored and the site falls back to the deterministic sentence above — so the front page never carries prose that was not arithmetic-checked. Stored on the run as forecast_explanations (scope_type='headline', scope_code='home').
10. Backtesting and calibration
With GE14 and GE15 both loaded, the harness replays the model as if only GE14's notional results were known, applies the actual national swing that occurred by 2022 (the "oracle swing" — isolating seat-allocation error from national-movement error), and scores the resulting seat win probabilities against the true GE15 winners.
Empirical volatility first. The GE14→GE15 seat-level swing distribution has standard deviation 16.2 points per contested bloc (mean absolute swing 12.7; winner-share swing σ 10.3). Malaysian electoral volatility over a four-year, realigning, mid-pandemic cycle is enormous by international standards — this is the anchor for how wide long-horizon intervals must be.
Chained replay across eras (calibrated model — horizon σ + state shocks, oracle national swing; the GE14→GE15 ablation that motivated the calibrated model is retained below it):
| Replay | Era | σ | Brier | Winner accuracy | 80%-coverage |
|---|---|---|---|---|---|
| GE12→GE13 (2008→2013) | stable BN era | 0.157 | 0.236 | 85.1% | 100% |
| GE13→GE14 (2013→2018) | regime change | 0.155 | 0.479 | 68.9% | 29% |
| GE14→GE15 (2018→2022) | realignment | 0.148 | 0.396 | 69.8% | 43% |
| uniform random guess | — | — | 0.857 | ~14% | — |
GE14→GE15 ablation (why the calibrated model is the live one):
| Model variant | σ used | Brier | Winner accuracy | 80%-coverage |
|---|---|---|---|---|
| near-term σ, independent seats | 0.045 | 0.505 | 69.8% | 0% |
| flat widened σ, independent seats | 0.100 | 0.426 | 69.8% | 29% |
| calibrated: σ(t)=0.148 + state shocks (ρ=0.4) | 0.148 | 0.396 | 69.8% | 43% |
Reading: the model's skill tracks the stability of the party system. In the stable 2008→2013 era it is excellent (Brier 0.24, 85% accuracy, fully-calibrated intervals); it degrades precisely at the two systemic breaks — the 2018 regime change and the 2022 realignment — where share-level noise cannot represent bloc chemistry changing (notional re-bucketing mitigates but cannot eliminate this). GE16's replay joins this table when results are in, whatever it says.
State-chamber validation (2023–2026 ground truth). The same harness replays each loaded DUN election from the previous DUN election of that state — the first genuinely out-of-sample test against elections the model never saw:
| Replay | Horizon | Brier | Winner accuracy | 80%-coverage |
|---|---|---|---|---|
| Johor PRN 2022 → 2026 | 4.3y | 0.096 | 94.6% | 100% |
| Negeri Sembilan PRN 2023 → 2026 | 3.0y | 0.537 | 69.4% | 57% |
Johor is the model at its best: BN's consolidation was already visible in the 2022 state votes and the calibrated replay called 53 of 56 seats. Negeri Sembilan is the systemic-break finding in miniature — the 2026 BN+PN alliance fought straight contests that recombined two blocs' votes, exactly the chemistry change share-noise cannot represent. The practical reading matches the federal chain: within a stable bloc structure the state forecasts are sharp; when alliances recombine, intervals widen honestly but medians lean on stale structure.
These scores are computed with the oracle national swing, so they measure the seat-allocation machinery, not the (much harder) national-movement forecast. The in-sample calibration check in §4 (every bloc's actual GE15 count inside the model's 80% band at election-day parameters) remains the complementary evidence.
Live verification: PRN Melaka 2026 (14 November 2026). The first real election scored the full pipeline end to end — news nudges, contest restriction, party decomposition — not a replay harness. The final pre-poll forecast is frozen at run 521 (reports/PRN-MELAKA-2026/final-forecast-run521.json: predicted winner per seat by argmax win probability, per-bloc probabilities and expected shares, the party view) and is scored against actual results by scripts/compare_melaka_results.py: winner hit rate, multi-class Brier, log score of the actual winner, expected-vs-actual share error on the winner, and per-bloc bias. Two structural facts about this election shape the reading: the BN–PN alliance puts two traditionally opposed blocs on one ticket (seat pacts the 2021 baseline cannot have anticipated), and Bersatu's seven seats sit outside every coalition's majority arithmetic. This is the forecast that was actually published, so it is the only honest test of the whole system rather than of a component.
Scorecard (results in, 15 November 2026). Actuals: SPR official tally via Bernama, one row per candidate per seat, mapped to blocs via the curated contest override (data/seed/contest_blocs.csv: PPBM→BERSATU; Bersatu contests on its own logo in Melaka 2026). Compared against frozen run 521 (reports/PRN-MELAKA-2026/scorecard.json + .md, and a scorecard section on /{lang}/final-report/melaka):
| Measure | Result |
|---|---|
| Winner hit rate | 26 / 28 (93%) |
| Mean multi-class Brier | 0.1638 |
| Mean log score (ln p of actual winner) | -0.3817 |
| Mean | share error |
| Seat tally (predicted → actual) | BN 21 → 21 · PH 6 → 4 · PN 1 → 3 |
Two misses, one signature. Both misses are Malay-majority seats where the model gave PH ~100% win probability but PAS (PN) swept ~59–61%, with shares nearly inverted: N.013 Paya Rumput (model PH 59.4 / PN 38.5 vs actual PN 58.8 / PH 37.4) and N.017 Bukit Katil (model PH 61.4 / PN 37.2 vs actual PN 60.6 / PH 34.5). There is also a systematic PH +14.9pts / BN −8.0pts share bias across the chamber.
Improvement loop (Melaka generates hypotheses, the backtest decides). 28 seats is one realisation — no parameter is fitted to Melaka alone, which would be overfitting with a straight face. Baseline (chained backtest, current model): GE12→GE13 Brier 0.2360 / acc 86.0% / coverage 100%; GE13→GE14 Brier 0.4780 / acc 68.0% / coverage 37.5%; GE14→GE15 Brier 0.3952 / acc 69.8% / coverage 50%. Coverage of 50% on GE14→GE15 (target 80%) confirms the model is overconfident — consistent with Melaka's two 100%-probability misses. Three hypotheses go to the chained backtest (GE12→13→14→15 plus the PRN replays) before any code ships; each must beat these numbers without regressing hit rate or Brier, and each is pre-declared with its observable:
-
Share calibration bias term. PH is systematically over-estimated (+14.9pts) and BN under-estimated (−8.0pts). Hypothesis: a state-scoped calibration constant on L1 baseline expected shares. Observable: per-bloc bias shrinks on the backtest without raising Brier.
-
Swing magnitude by seat demographic. Both misses are Malay-majority seats that swung hard to PN–PAS despite a PH-leaning baseline. Hypothesis: swing magnitude scales with seat composition (Malay-majority seats swing further when national mood favors PN). Observable: Malay-seat swing errors shrink, no regression in mixed seats.
-
News-nudge cap for pact dynamics. The ±2pt L4 cap and party-first attribution may understate the BN–PN seat-pact effect. Hypothesis: review the cap for bloc-pact seats. Observable: backtest Brier.
v2 shipped (2026-11-15), ahead of the three hypotheses. The audit that followed the scorecard found the cause was upstream of all three: not a calibration bias or a weak nudge, but the contest layer's proportional redistribution of a stood-aside ally's share (§5a). Where BN sat out for PN under the pact, the model split BN's votes between PH and PN when the ticket delivered them ~fully to PN. The fix — pact-aware transfer, no fitted parameter — replays Melaka at 28/28 winners / Brier 0.011 / bias PH +4.4 (from +14.9), with the chained GE backtest byte-identical. Hypotheses 1–2 remain open for the next election's evidence; hypothesis 3 is largely subsumed by the pact rule. Melaka is still one realisation: the next pact election is v2's out-of-sample test.
Ship one change at a time, backtest-gated; the frozen run 521 is never edited.
11. Assumptions and limitations
- Boundaries are frozen. Constituency boundaries (unchanged since 2003... with the 2018 delimitation the last exercise) are assumed constant through the forecast horizon.
- Candidate effects are local noise. A particularly strong individual candidacy is absorbed into σ, not modelled; candidate announcements enter only via the semantic layer.
- Turnout is implicit. Shares are of valid votes; differential turnout (e.g. the 2022 drop to 73.9%, or PAS-base turnout surges) is a known systematic risk not yet modelled. A turnout layer is planned once by-election turnout data is loaded.
- Polls are scarce and possibly biased. The trust cap and heavy shrinkage reflect this; the model never requires polls.
- The semantic layer is bounded by design — it detects relative news pressure shifts, not regime changes. A genuine earthquake (a coalition collapse) enters the model through the curated coalition map and notional recomputation, not through sentiment scores. Detection is assisted, not automated: a daily alliance watch (
hk unknown-terms) flags trending proper-noun phrases that no registry knows, prompting the reviewed curation — the tagger's whitelist guarantees no unreviewed entity ever reaches the data. - Sarawak/Sabah opacity. GPS/GRS interior dynamics (seat deals, local parties) are minimally observed by national news; their baseline comes almost entirely from history, which is arguably correct. A related DUN artifact: the OTHERS bucket aggregates all minor candidates, so in fragmented seats the bucket's combined vote can exceed the GPS winner's — notional "winner" counts then understate the dominant bloc (Sarawak 2021 reads GPS 70 notional vs 76 actual). Hierarchical shrinkage toward the chamber-wide share corrects most of this (the current Sarawak forecast median is GPS 80), but it is a known aggregation bias, documented here rather than hidden.
- Party-hopping between elections changes the "current composition" view but not the forecast, which is about the next election's bloc contest. Notional recomputation handles historical realignments.
- DUN baselines are single-election. Each state chamber rests on its latest PRN alone (Melaka 2021, Sarawak 2021, Johor 2026, Negeri Sembilan 2026, Sabah 2025; older PRNs would enter with heavy time-decay anyway), so between elections their movement comes almost entirely from the semantic layer until by-elections or polls arrive. During a live campaign this makes them responsive to news and honest about it.
- The party view is a decomposition, not yet an independent party model. Attribution is a bloc decision (§2.2), so a party that leaves its coalition is given a bloc of its own for that election (
BERSATU, 2026-11-02). Every run now also records party-level shares and probabilities (§5a,forecast_party_probs), which fixes the "OTHERS hides three parties" display problem while leaving bloc arithmetic untouched. What it does not do: measure party-specific swings, party-level poll movement or party-specific news sentiment through the layers — within-bloc composition is held at historical proportions. A full party unit (party keys in L1/L2/L4, aggregated to blocs only for government arithmetic) remains the open item, and would need the chained backtests to beat this decomposition before shipping.
12. Academic anchors
- Butler, D. (1951). The British General Election of 1951 — origin of uniform swing.
- Linzer, D. (2013). "Dynamic Bayesian Forecasting of Presidential Elections in the States." Journal of the American Statistical Association 108(501).
- Jackman, S. (2005). "Incumbency Advantage and Candidate Choice." American Journal of Political Science — seat-level swing/variance modelling.
- Gelman, A., Carlin, J., Stern, H., Dunson, D., Vehtari, A., Rubin, D. (2013). Bayesian Data Analysis, 3rd ed. — hierarchical shrinkage.
- Tavits, G. & others on multiparty seat-vote models — multi-bloc share normalisation.
- Ufen, A. (2020). "Opposition Coalitions in Democratizing Southeast Asia." Government and Opposition — coalition realignment context for Malaysia.
Appendix A — Parameter reference
| Parameter | Default | Env var | Role |
|---|---|---|---|
| λ (decay) | 0.5 / year | HK_LAMBDA_DECAY | history half-life ≈ 2 years |
| m (shrinkage) | 800 votes | HK_PRIOR_STRENGTH | hierarchy pseudo-mass |
| σ (seat, near-term) | 0.045 | HK_SIGMA_SEAT | share volatility at zero horizon |
| σ horizon τ | 168 days | HK_SIGMA_TAU_DAYS | random-walk relaxation time |
| σ cap | 0.16 | HK_SIGMA_CAP | maximum total volatility |
| ρ state share | 0.4 | HK_RHO_STATE | fraction of variance that is regional |
| PRN swing half-life | 365 days | HK_PRN_SWING_HALF_LIFE | state-election evidence decay (recalibrated from 120d on Johor-replay evidence, §5/§10) |
| PRN structure shrink | 0.5 | HK_PRN_STRUCTURE_SHRINK | DUN-vs-federal contest discount |
| polling days | per chamber | HK_POLLING_DAY_* | expected election dates driving σ(t) |
| k_be (BE shrink) | 4 seats | — | by-election national-swing shrinkage toward zero |
| poll half-life | 45 days | HK_POLL_HALF_LIFE | poll decay |
| poll trust cap κ | min(0.7, 0.25·N) | — | polls' max influence |
| semantic cap | 0.02 | HK_SEMANTIC_CAP | max nudge magnitude |
| semantic κ | 1.0 | HK_SEMANTIC_KAPPA | z → points scale |
| semantic window | 28 days | HK_SEMANTIC_WINDOW_DAYS | news lookback |
| draws | 10,000 | HK_SIM_DRAWS | Monte Carlo size |
| majority | 112 / 15 / 42 / 29 / 19 / 37 | — | simple majority (Dewan Rakyat / Melaka / Sarawak / Johor / NS / Sabah) |
| two-thirds | 149 / 19 / 55 / 38 / 24 / 49 | — | two-thirds line, same chamber order |
| government blocs | per chamber (parliament PH+BN; Melaka/NS BN+PN; Sarawak GPS; Johor BN; Sabah GRS) | HK_GOV_BLOCS | incumbent arrangement driving gov metrics |
Appendix B — Reproducing a run
make weekly # collect → tag → notional → QA → forecast
psql> SELECT id, created_at, inputs_hash FROM forecast_runs ORDER BY id DESC LIMIT 1;
The inputs_hash covers every input frame plus the parameter set; two runs with equal hashes produce equal outputs up to Monte Carlo seed (fixed per run by default for exact reproducibility).