52 min read

Nusrat typed one line into the terminal on her old laptop in Dhaka and waited.

Chapter 39 — Capstone: Your Cricket Analytics Platform — Dashboard, Models, and the System You Built Yourself

Nusrat typed one line into the terminal on her old laptop in Dhaka and waited.

streamlit run project/app.py

For twelve seconds nothing seemed to happen. The fan whirred. Then a browser tab opened on a page called Crease, and the IPL 2026 final filled the screen: Gujarat Titans 155 for 8, Royal Challengers Bengaluru 161 for 5 in 18 overs, a Manhattan with its tall orange bars late in the chase, and below it a single black line that started at 41% for Gujarat, wobbled up to 46% in the second over, and then fell, wicket by wicket, until it lay flat on the floor of the chart long before Virat Kohli finished on 75 not out off 42 balls.

She had not typed a single number into that page. Every figure on it came from the 233 deliveries Cricsheet recorded for the match, run through code she had written herself, one chapter at a time, over the whole of this book. The Manhattan came from the charting module she built in Chapter 7. The line came from the win-probability model she fitted in Chapter 20, and the model had never seen a ball of 2026: it was trained on men's T20 chases from 2023 to 2025 and asked, cold, to price a final it knew nothing about. It said that at the innings break Bengaluru were 86.5% to win. They won.

The largest single swing it found was not a six or a dropped catch. It was the fourth ball of the fourth over of the match, when B Sai Sudharsan was caught off Bhuvneshwar Kumar and Gujarat's chance fell nine points, from 36.8% to 27.7%. Nobody in a commentary box would have called that the moment the final was decided. The model did, and its reasons were on the screen: a top-order wicket early in a first innings, on a ground and in an era where 155 was nowhere near enough.

Wendell Baptiste, watching over a video call from Port of Spain, was not impressed by the line. He was impressed by something else. "You built this?" he said. "All of it?"

"Thirty-six modules," Nusrat said. "Six hundred and seventeen functions. Fifteen thousand lines, roughly. And a test that checks every one of them still works."

"And if it's wrong?"

"Then it tells you how wrong," she said, and clicked to the page that showed it.

This chapter is about that page, and the six others like it. You have built every piece already. Here you assemble them: you measure what you built, wire it into a dashboard, run one real 2026 match through the whole pipeline from raw deliveries to a pre-match forecast and a live projection, write a model card for each model that says what it is for and where it fails, and test the lot so it stays working. The cricket question that runs through it is the oldest one in analytics: can you trust the number on the screen? The answer this chapter gives is "yes, to a stated degree, and here is the degree".

🏏 Fan Track: Read 39.3 to 39.7 for the IPL 2026 final told through the platform, ball by ball and model by model, and 39.8 for the honest limits of each model. You can skip the code blocks.

📊 Analyst Track: Everything, in order. The architecture (39.1–39.2), the testing (39.9) and the model cards (39.8) are what separate a project from a portfolio piece.

🧑‍💼 Franchise Track: 39.6 (pre-match), 39.8 (model cards) and 39.10's Auction Board and Matchups pages, then the roadmap in 39.11. Model cards are the document a head coach should ask for before trusting any number.


39.1 What you built: Crease, measured

Before you wire anything together, take stock. The cricket question is simple and a little humbling: what exactly is in this package, and does it hang together? A capstone that cannot answer that about itself is a pile of chapters, not a platform.

You could answer by memory, chapter by chapter. Don't. Measure it, the way you would measure a batter. The script code/01_architecture.py reads every file in project/crease/ with Python's ast module (which parses code without running it), counts the public functions and classes, checks which have docstrings, counts the non-blank code lines, and records which other Crease modules each one imports.

for f in sorted(CREASE.glob("*.py")):
    tree = ast.parse(f.read_text(encoding="utf-8"))
    doc = ast.get_docstring(tree) or ""
    ch = re.search(r"Chapter (\d+)", doc)                       # which chapter built it
    pub = [n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef))
           and not n.name.startswith("_")]
    documented = sum(1 for n in pub if ast.get_docstring(n))
    for n in ast.walk(tree):                                     # internal imports -> graph edges
        if isinstance(n, ast.ImportFrom) and (n.module or "").startswith("crease."):
            deps.add(n.module.split(".")[1])

Full script: code/01_architecture.py. The real output, top lines:

Crease: 36 modules, 617 public functions/classes (612 with docstrings, 99.2%), 14,969 non-blank code lines
app.py: 600 code lines, imports 15 Crease modules directly: auction, batting, bowling, charts, data, explore, live, match_model, matchups, projection, storytelling, tournament, translation, valuation_batting, winprob
tests/test_smoke.py: 37 test functions

Internal imports: 28 edges; modules that import no other Crease module and are imported by none: 9 of 36
Most-imported modules: states (4), formats (3), charts (3), projection (3), venue_toss (2), betting (2)
Longest import chain: batting_order -> live -> winprob -> impact (is a DAG: True )

Modules per layer:
1 data & description       6
2 player metrics          11
3 match models            11
4 decisions & products     8

Thirty-six modules, one per chapter from Chapter 2 to Chapter 37. Six hundred and seventeen public functions and classes (588 top-level functions plus 29 classes; Chapter 38's checkpoint counted functions only, hence its 588), of which only five lack a docstring. Just under fifteen thousand lines of code that is not blank and not a comment. That is a real software project by any standard, and it was written in small, testable pieces, each one answering a cricket question.

📐 Definition: A dependency graph has one node per module and an arrow from A to B when module A imports module B. It is a DAG (directed acyclic graph) when no chain of arrows leads back to where it started. A DAG can always be built, tested and explained from the bottom up.

Crease's 36 modules placed by the chapter that built them, coloured by layer, with arrows for internal imports

📊 Figure (described): Each dot is one Crease module, placed left to right by the chapter that built it and stacked in four coloured bands: data and description (Chapters 2–7), player metrics (8–18), match models (19–29) and decisions and products (30–37). Dot size grows with the number of public functions. Grey arrows show imports. Most arrows point left and down, from later chapters to earlier ones; none points forward in time, and nine modules stand entirely alone.

Three things in that picture matter for everything that follows.

The graph only points backwards. No module imports a later chapter's module. That was a rule from the start (a module may import an earlier chapter's module only if it already exists), and the graph proves it held. It means you can understand Crease the way you read the book: from the bottom up. states.py (Chapter 19's expected-runs tables and Markov innings model) is the most-imported module in the package, because win probability, resource tables, live projection and batting-order simulation all stand on it.

The longest chain is four modules. batting_order imports live, which imports winprob, which imports impact. If Chapter 9's empirical win-probability table broke, Chapter 30's batting-order simulator could break with it, three steps away. The graph tells you where a change can ripple, which is exactly what a test suite needs to know (39.9).

A quarter of the package stands alone. Nine modules, including data, uncertainty, batting and bowling, import no other Crease module and are imported by none. That is not a flaw. Those modules hold definitions (what a strike rate is, what shrinkage does) that later chapters re-implemented in a line or two rather than take a dependency. Small duplication bought a lot of independence: you can lift uncertainty.py into a football project tomorrow.

🔄 Check your understanding 1. The longest import chain is batting_order -> live -> winprob -> impact. If you change how impact.innings_states counts wickets, which dashboard pages could change? 2. Why is it reassuring that the dependency graph is a DAG?

Answer

  1. Anything downstream of impact: WP v1 (winprob imports it), therefore the Match Centre's curve, turning points and WPA, and the Live Projection page (via live, which imports winprob). That is why the smoke tests call one function in every module, not just the ones you changed.
  2. No circular imports means every module can be built, tested and explained using only modules "below" it. A cycle would mean two modules each need the other to work, so neither can be tested alone.

39.2 The dashboard: one file, three layers

The cricket question for this section is about people, not code: who will use this, and what do they need to see first? A coach needs a match in one screen. An auction room needs value against price. A broadcaster needs a range, not a point. The dashboard has seven pages because Crease answers seven kinds of question, and each page leads with the answer, not the method.

Page The question it answers Crease modules it calls
Match Centre What happened, and which moments decided it? charts, winprob, storytelling, explore, data
Player Explorer How good is this player, by phase, and what next season? batting, bowling, projection, translation
Matchups Who should bowl to this batter? matchups, charts
Auction Board Who is worth what they are paid? valuation_batting, auction
Match Predictor Who wins before the first ball? match_model
Tournament Sim Who lifts the trophy? tournament, match_model
Live Projection Where is this innings heading, honestly? live

All seven live in one file, project/app.py, written with Streamlit, a free Python library that turns a script into a web page: each st.selectbox becomes a drop-down, each st.pyplot becomes a chart, and the page reruns from the top whenever a widget changes. It is the quickest route from a pandas analysis to something a coach can click.

The temptation in a dashboard is to do the analysis inside the page. Resist it. app.py is built in three layers, and the discipline of keeping them apart is the most transferable lesson in this chapter.

📐 Definition: The three-layer dashboard: (1) data and model functions that compute and are cached, and know nothing about the screen; (2) figure builders (fig_*) that take computed results and return a chart; (3) page functions (page_*) that only arrange widgets, call layers 1 and 2, and display what comes back.

Here is layer 1 for the Match Centre, lightly trimmed from project/app.py:

@_cache("resource")
def wp_states(gender: str = "male"):
    """Chapter 20's ball states for every 20-over, decided, non-DLS match of one gender."""
    return winprob.build_states(MEN_T20 if gender == "male" else WOMEN_T20)


@_cache("resource")
def wp_model(gender: str, year: int):
    """WP v1 and its first-innings par, fitted ONLY on seasons before ``year``."""
    d = wp_states(gender)
    s2, s1 = d.s2[d.s2["year"] < year], d.s1[d.s1["year"] < year]
    label = f"WP v1 fitted on {'men' if gender == 'male' else 'women'}'s T20 chases before {year}"
    if gender == "male" and year >= 2024:                 # Chapter 20's policy for the
        s2 = s2[s2["year"] >= 2023]                       # Impact-Player era
        label = f"WP v1 (era-only) fitted on men's T20 chases 2023-{year - 1}"
    return winprob.fit_wp(s2), winprob.ParWP().fit(s1), label

Look at what those few lines enforce. The win-probability model for a match in season Y is fitted only on seasons before Y, so the Match Centre can never show a curve that peeked at the result. Women's matches get a model fitted on women's chases: Chapter 20 found that the men's model overrates women's chasers by 9.4 points even with a women's scoring environment, so the dashboard never lets one stand in for the other. And for men's matches from 2024 on, the fit uses only the Impact-Player era, because Chapter 20 showed the pooled model under-rates modern IPL chasers.

📐 Definition: Caching stores a function's result the first time it is called with given arguments and returns the stored result on later calls. Streamlit offers two kinds: st.cache_data (returns a fresh copy each time, safe for tables you might modify) and st.cache_resource (returns the same object each time, right for fitted models and large shared tables you will only read).

Caching is what makes the dashboard usable on an old laptop. Building ball states for every men's T20 match takes about nine seconds; fitting WP v1 about two. A page that did that on every click would be unusable. With @_cache("resource") the first visit pays, and every later click, in every browser tab on that machine, is instant until the server restarts.

🔍 Why this works: Streamlit reruns your whole script top to bottom on every widget change. That sounds wasteful, and without caching it is. But it also means the page can never get into a stale, half-updated state: what you see is always the script's output for the current widget values. Caching turns "rerun everything" into "rerun everything that changed", which is how a spreadsheet recalculates. The design is only safe because the cached functions are pure: same arguments, same answer, no hidden state. That is why wp_model takes year as an argument instead of reading it from a widget.

The small helper _cache does one more job. If Streamlit is not installed, it falls back to Python's own functools.lru_cache, so the data and figure layers still import and run:

try:
    import streamlit as st
except ImportError:
    st = None

def _cache(kind: str = "data"):
    if st is not None:
        return (st.cache_resource if kind == "resource" else st.cache_data)(show_spinner=False)
    return functools.lru_cache(maxsize=None)

That is why this chapter's own scripts can import app and call app.fig_matchup(...) to draw the very figure the Matchups page shows, without a browser and without a server. Layer 3, the page functions, is then almost boring, which is the point:

def page_live():
    st.header("Live Projection")
    code = c1.selectbox("Competition", [...], format_func=LABEL.get, key="lp_code")
    ...
    lp = live_path(code, mid)                              # layer 1: cached computation
    over = st.slider("After over", 1, int(lp["path"]["over"].max()), 10, key="lp_over")
    row = lp["path"].set_index("over").loc[over]
    k2.metric("Median projection", f"{row['median']:.0f}", f"80%: {row['lo']:.0f}-{row['hi']:.0f}")
    st.info(row["line"])                                   # live.broadcast_line, Chapter 27
    show(fig_live_path(lp))                                # layer 2: figure builder

⚠️ Common pitfall: Putting st.cache_data on a function that fits a model. Every call then pickles and unpickles the fitted model (slow) and hands back a copy that cannot be updated in place. Models, large shared tables and anything with internal state belong in st.cache_resource; small results you might sort or filter belong in st.cache_data. And never mutate what cache_resource returns: Chapter 24's Predictor.update changes ratings in place, so the dashboard builds a fresh predictor rather than updating the cached one.

How do you know it works? You cannot click through seven pages by hand every time you change a module. Streamlit ships a test harness, streamlit.testing.v1.AppTest, that runs the script in the same Python process, lets you change widgets from code, and reports any exception a page raises. The chapter's code/project_checkpoint.py drives every page that way, then changes a few widgets so the non-default paths run too (a WPL match, the World Cup, the 15-over mark):

Streamlit 1.67.0; app = C:\books\cricket-analytics\project\app.py
  PASS  Match Centre (IPL 2026 final)                   9.7 s   charts  2  tables  3  metrics  0
  PASS  Player Explorer                                 7.8 s   charts  1  tables  4  metrics  0
  PASS  Matchups                                        8.1 s   charts  2  tables  1  metrics  0
  PASS  Auction Board                                   3.6 s   charts  1  tables  3  metrics  0
  PASS  Match Predictor                                13.5 s   charts  0  tables  0  metrics  3
  PASS  Tournament Sim                                  0.2 s   charts  1  tables  1  metrics  0
  PASS  Live Projection                                11.2 s   charts  1  tables  0  metrics  3
  PASS  Tournament Sim -> 2026 men's T20 World Cup      0.6 s   charts  1  tables  1  metrics  0
  PASS  Match Centre -> WPL (women's WP v1)             4.0 s   charts  2  tables  3  metrics  0
  PASS  Live Projection -> after over 15                0.3 s   charts  1  tables  0  metrics  3

10 of 10 page runs passed; smoke tests passed.

The times are first visits on the build machine, with nothing cached; the slowest page, the Match Predictor, spends most of its 13.5 seconds freezing team-sheet ratings for twelve men's competitions. We also started the real server (streamlit run project/app.py --server.headless true), confirmed it answered on its port, and stopped it. A headless browser capture of the running page caught only Streamlit's grey loading skeleton, because the page builds itself after the browser's "loaded" signal. So every dashboard picture in this chapter is drawn by the app's own fig_* functions from the same cached results, not captured from a screen. They are the same pixels the page would show; they are not presented as screenshots.

🔄 Check your understanding 1. A colleague moves the WP model fit inside page_match_centre so "it's all in one place". What two things break? 2. Which cache should hold the matchups table (a 260,000-row shrunk table you only read)?

Answer

  1. Speed (the model is refitted on every widget change unless that code is cached), and testability (scripts and tests can no longer get the model or its figures without running a Streamlit page). Often a third: the leakage rule becomes easy to break, because the page has the selected match in scope when it fits.
  2. st.cache_resource: it is large, shared and read-only, so copying it on every call (what cache_data does) wastes time and memory.

39.3 The pipeline on one real match: data and metrics

Now run a real match through the whole platform, the way an analyst would on the morning after. The match is the IPL 2026 final: Gujarat Titans v Royal Challengers Bengaluru at the Narendra Modi Stadium, Ahmedabad, on 31 May 2026 (Cricsheet id 1535465). We follow it through six stages, each one a call into a module you built:

Stage Question Module (chapter) Key call
1 Data What happened? data (2), explore (3), charts (7) data.load, explore.batting_card, charts.match_balls
2 Metrics Who are these players, in context? batting (8), bowling (14) batting.sr_plus, bowling.bowling_profile
3 Win probability How did the chance of winning move? winprob (20) build_states, fit_wp, ParWP, wp_curve
4 Attribution Who moved it? winprob (20), building on impact (9) turning_points, wpa
5 Pre-match What should we have expected? match_model (24) fit_pooled_t20, build_predictor
6 Live What could a broadcaster have said during the innings? live (27) LiveChain, project_total

Stage 1 is three calls. data.load("ipl") returns every IPL delivery (memoised, so the second call is free); explore.innings_total, batting_card and bowling_card build the scorecard the way Chapter 3 taught you. From code/02_end_to_end.py:

balls = data.load("ipl")
games = data.load_games("ipl")
mb = charts.match_balls(balls, MID)              # one match, in bowling order, super overs removed
for inn in (1, 2):
    tot = explore.innings_total(balls, MID, inn)
    card = explore.batting_card(balls, MID, inn)
    bc = explore.bowling_card(balls, MID, inn)
STAGE 1 - DATA
IPL deliveries in the snapshot: 295,732 from 1,243 matches; this match: 233 deliveries
Gujarat Titans v Royal Challengers Bengaluru, Narendra Modi Stadium, Ahmedabad, 31 May 2026; toss: Royal Challengers Bengaluru chose to field; winner Royal Challengers Bengaluru (by 5 wickets); player of the match V Kohli
  innings 1: Gujarat Titans 155/8 (20 overs)
    B Sai Sudharsan 12 (12); N Sindhu 20 (18); JC Buttler 19 (23); Washington Sundar 50 (37)
    bowling: JA Duffy 4-38-0; B Kumar 4-29-2; JR Hazlewood 4-37-2; Rasikh Salam 4-27-3; KH Pandya 4-23-1
  innings 2: Royal Challengers Bengaluru 161/5 (18 overs)
    VR Iyer 32 (16); V Kohli 75 (42); RM Patidar 15 (13); TH David 24 (17); JM Sharma 11 (14)
    bowling: Mohammed Siraj 4-36-1; K Rabada 3-44-1; JO Holder 2-16-0; Rashid Khan 4-25-2; Arshad Khan 4-32-1; M Prasidh Krishna 1-7-0

(The batting lines list only innings of ten balls or more; Shubman Gill's 10 off 8 is in the full card.) Then the two charts every match report starts with, drawn by Chapter 7's charts.manhattan and charts.worm:

Manhattan and worm for the IPL 2026 final

📊 Figure (described): Left, a Manhattan: runs in each over as paired bars, Gujarat Titans in blue and Royal Challengers Bengaluru in orange, with a red X over the bar for each wicket. Right, a worm: cumulative runs against overs for both innings. Bengaluru's orange line runs above Gujarat's from the second over of the chase and reaches 161 two overs early; Gujarat's blue line is dotted with wickets through the middle overs.

Stage 2 asks who these players are, using the metric the book built to replace the raw strike rate. SR+ (Chapter 8) is a batter's runs divided by what a league-average batter would have scored on the same balls, given the season and the phase in which each ball was faced, times 100. A figure of 100 is exactly par.

s26 = balls[balls["start_date"].dt.year == 2026]
srp = batting.sr_plus(s26).reset_index()                       # par = IPL 2026, by phase
srp = srp[srp["batter"].isin(in_match_bat) & (srp["balls"] >= 100)]
bp = bowling.bowling_profile(s26).reset_index()
STAGE 2 - METRICS (IPL 2026 season, before AND including the final: context, not prediction)
               batter  balls  runs  strike_rate  par_sr  sr_plus
0          RM Patidar    260   501        192.7   154.7    124.5
1            TH David    162   305        188.3   158.5    118.8
2             VR Iyer    112   209        186.6   160.8    116.0
3          D Padikkal    275   464        168.7   153.8    109.7
4             V Kohli    407   675        165.8   155.2    106.9
5        Shubman Gill    449   732        163.0   154.5    105.5
6     B Sai Sudharsan    457   722        158.0   155.7    101.5
7          JC Buttler    345   526        152.5   154.2     98.9
8   Washington Sundar    251   377        150.2   158.6     94.7
9           KH Pandya    155   226        145.8   156.7     93.1
10          R Tewatia    132   190        143.9   160.0     90.0
              bowler  balls  wickets  economy  dot_pct
0          JO Holder    230       17     7.57    40.87
1            B Kumar    378       28     7.95    40.21
2          KH Pandya    303       14     8.42    29.04
3     Mohammed Siraj    372       19     9.06    46.24
4        Rashid Khan    341       21     9.08    34.31
5       Rasikh Salam    257       19     9.46    32.68
6       JR Hazlewood    309       15     9.59    40.78
7           K Rabada    388       29     9.68    44.33
8  M Prasidh Krishna    234       16    10.44    33.76
9           JA Duffy    144        9    10.96    39.58

Two lessons from earlier chapters jump out. First, Bengaluru's middle order went into the final as the fastest-scoring group on the field relative to par: Rajat Patidar at SR+ 124.5, Tim David 118.8. Gujarat's top three, Gill, Sai Sudharsan and Buttler, were all within six points of par: excellent run accumulators in a season when par strike rates were above 150. Second, Kohli's raw strike rate of 165.8 looks only a little above Gill's 163.0, but on his own mix of phases his par was 155.2, so his SR+ is 106.9: better, by about the margin the raw numbers suggest, but now you know it is not a phase-mix illusion.

⚠️ Common pitfall: Quoting these season numbers as if they predicted the final. They include the final itself and every match before it, so they are context, not forecast. Stage 5 is where prediction happens, with everything frozen the morning before.

🏏 Eye test: Wendell looked at Washington Sundar's line, 50 off 37 after walking in at 73 for 4 in the 13th over, and at his season SR+ of 94.7. "Your number says he's below par. I watched a man rebuild an innings with the top order gone. He batted to the situation." He is right, and the data half-agrees: SR+ adjusts for phase and season, not for wickets down. A batter who walks in at 73 for 4 is supposed to bat a little below par for a while. Win probability, stage 3, is the tool that values batting to the situation. It gives Sundar −0.002: his innings neither won nor lost Gujarat the final, because he scored at almost exactly the rate the situation needed and Gujarat stayed where they were, losing.


39.4 Stage 3: the win-probability curve

The question every broadcast graphic tries to answer: after each ball, how likely was each side to win? Chapter 9 answered it with an empirical lookup table (WP v0). Chapter 20 replaced it with WP v1, a logistic regression on the match state (runs needed, balls left, wickets in hand, with log and interaction terms) plus three pieces of context: the target, the scoring environment (env_par, the recent average first-innings total in that competition, computed only from earlier matches) and the pre-match Elo gap between the teams. A first-innings win probability comes from projecting the batting side's total (Chapter 19's expected-runs table, rescaled to the environment) and pricing that total with WP v1's chase curve.

The pipeline is four calls:

wpd = winprob.build_states(winprob.MEN_T20)                       # 12 men's T20 competitions
fit2 = wpd.s2[(wpd.s2["year"] >= 2023) & (wpd.s2["year"] <= 2025)] # era-only, never sees 2026
model = winprob.fit_wp(fit2)
par = winprob.ParWP().fit(wpd.s1[wpd.s1["year"] <= 2025])
curve = winprob.wp_curve(MID, model, par, data=wpd)
STAGE 3 - WIN PROBABILITY (WP v1)
states built for 9,117 men's T20 matches; WP v1 fitted on 2,780 chases 2023-25 (306,209 ball states); par on 8,215 first innings to 2025 [8.3 s]
context: env_par 191.7; Elo before the match Gujarat Titans 1579, Royal Challengers Bengaluru 1612
                      moment  score  P(GT wins)  P(RCB wins)
0      innings 1, first ball    0/0       0.406        0.594
1   innings 1, after 6 overs   45/2       0.311        0.689
2  innings 1, after 10 overs   63/3       0.220        0.780
3  innings 1, after 15 overs  105/5       0.169        0.831
4      innings 2, first ball    0/0       0.135        0.865
5   innings 2, after 6 overs   70/2       0.014        0.986
6  innings 2, after 10 overs  100/4       0.015        0.985
7  innings 2, after 15 overs  139/5       0.001        0.999

These are exactly the numbers Chapter 20's first case study reported for this final (Bengaluru 0.865 at the innings break), which is no coincidence: the dashboard calls the same functions with the same fitting window. When an assembled system reproduces its parts' published results, you have a regression test for free. If a later change to states.py moved this number, you would want to know.

WP v1 curve for the IPL 2026 final with the four biggest swings labelled

📊 Figure (described): Gujarat Titans' win probability after every delivery, from 41% at the first ball to zero when Bengaluru won in the 18th over of the chase. The area below 50% is shaded orange (Bengaluru more likely) for almost the whole match. Labels mark the four biggest swings: Gill caught off Hazlewood (2.2, −8 points), Sai Sudharsan caught off Bhuvneshwar Kumar (3.4, −9), Sindhu caught off Rasikh Salam (7.6, −6), and Venkatesh Iyer's six off Rabada early in the chase (+4 for Bengaluru).

The curve tells a story the scorecard hides. Gujarat were underdogs from the first ball, at 40.6%, because Bengaluru's Elo was higher (1,612 v 1,579 in the within-competition ratings WP v1 uses) and because in a 191.7-run scoring environment, a chasing side is favoured at the start. Three wickets in the first eight overs took Gujarat from 46% to 24%. By the end of their innings, 155 in an environment where the recent average first-innings total was over 190 left them at 13.5%, and Bengaluru's 70 for 2 after six overs effectively ended it (98.6%).

🔄 Check your understanding 1. Why does the model favour Bengaluru (59.4%) before a ball is bowled, when the teams' Elo ratings are only 33 points apart? 2. The final ended at 161 for 5 in 18 overs. Why is the WP after 15 overs (0.999) not exactly 1?

Answer

  1. Two effects add up: the Elo gap (33 points to Bengaluru) and the way WP v1 prices a par first innings in this environment. Its chase model was fitted on 2023–25, when chasers did well (in Chapter 20's 2023–26 test set, IPL sides batting first won 47.4%), so a projected par total is priced as slightly less than an even chance for the side batting first.
  2. Needing 17 off 30 with five wickets in hand is close to certain but not certain; five quick wickets is a real (tiny) possibility. A model that says 1.000 before the last run is overconfident.

🧩 Productive struggle: Before you read stage 4, look at the curve and decide: which single player did most to win this final for Bengaluru? Write down a name and a reason. Kohli made 75 not out off 42 and was player of the match. Rasikh Salam took 3 for 27. Venkatesh Iyer made 32 off 16. Pick one before you scroll.


39.5 Stage 4: turning points and Win Probability Added

📐 Definition: Win Probability Added (WPA) for a delivery is the change in the batting side's win probability from before the ball to after it. A batter is credited with the change on every ball he faces; the bowler is credited with the same change with the sign flipped. Summed over a match, a player's WPA is the share of a win he added (Chapter 9).

tp = winprob.turning_points(curve, n=6)                 # the biggest |dWP| deliveries
wb = winprob.wpa(curve, by="batter")
wl = winprob.wpa(curve, by="bowler")
STAGE 4 - TURNING POINTS AND WIN PROBABILITY ADDED
   innings                 batting_team over_ball           batter        bowler                             what  wp_before  wp_after    dwp
0        1               Gujarat Titans       3.4  B Sai Sudharsan       B Kumar  WICKET B Sai Sudharsan (caught)      0.368     0.277 -0.090
1        1               Gujarat Titans       2.2     Shubman Gill  JR Hazlewood     WICKET Shubman Gill (caught)      0.464     0.387 -0.077
2        1               Gujarat Titans       7.6         N Sindhu  Rasikh Salam         WICKET N Sindhu (caught)      0.308     0.244 -0.064
3        2  Royal Challengers Bengaluru       1.3          VR Iyer      K Rabada                         6 run(s)      0.861     0.904  0.043
4        1               Gujarat Titans      12.1       JC Buttler     KH Pandya      WICKET JC Buttler (stumped)      0.196     0.153 -0.043
5        1               Gujarat Titans      14.1      Arshad Khan  JR Hazlewood      WICKET Arshad Khan (caught)      0.211     0.170 -0.041
batting WPA:
               batter                         team   runs  balls    wpa  gained   lost
0             VR Iyer  Royal Challengers Bengaluru 32.000 16.000  0.078   0.134 -0.056
1             V Kohli  Royal Challengers Bengaluru 75.000 42.000  0.073   0.085 -0.012
2            TH David  Royal Challengers Bengaluru 24.000 17.000  0.008   0.021 -0.012
...
14       Shubman Gill               Gujarat Titans 10.000  8.000 -0.053   0.042 -0.095
15         JC Buttler               Gujarat Titans 19.000 23.000 -0.059   0.023 -0.082
16    B Sai Sudharsan               Gujarat Titans 12.000 12.000 -0.087   0.042 -0.129
bowling WPA:
               bowler                         team  balls    wpa
0        Rasikh Salam  Royal Challengers Bengaluru     24  0.112
1             B Kumar  Royal Challengers Bengaluru     24  0.105
2        JR Hazlewood  Royal Challengers Bengaluru     24  0.064
3           KH Pandya  Royal Challengers Bengaluru     24  0.054
...
9            JA Duffy  Royal Challengers Bengaluru     24 -0.063
10           K Rabada               Gujarat Titans     18 -0.115

(The full tables are in code/02_end_to_end_output.txt.) If you picked Kohli in the productive struggle, you picked the player of the match, and you are in good company. WPA disagrees, and the reason is the whole idea of the metric. Kohli's 75 not out came in a chase that began at 86.5% and was at 98.6% after six overs. His runs were excellent, but the win probability they could add was small, because there was little left to add: he gained 0.085 and lost only 0.012, a near-flawless innings worth 0.073 of a win. Rasikh Salam's 3 for 27, bowled while the match was still alive, added 0.112, the most of anyone. Bhuvneshwar Kumar's 2 for 29 added 0.105. The final was won in Gujarat's first eight overs, and Bengaluru's bowlers won it.

WPA for batters and bowlers in the IPL 2026 final

📊 Figure (described): Two horizontal bar charts. Left, batting WPA: Venkatesh Iyer (+0.078) and Kohli (+0.073) lead for Bengaluru (orange); Sai Sudharsan (−0.087), Buttler, Gill and Sindhu trail for Gujarat (blue). Right, bowling WPA: Rasikh Salam (+0.112), Bhuvneshwar Kumar (+0.105), Hazlewood and Krunal Pandya all positive for Bengaluru; Rabada is the most negative (−0.115) for Gujarat, with Jacob Duffy the one Bengaluru bowler below zero.

Two cautions keep WPA honest. It is one match: a single game's WPA is a story about that game, not a rating of a player (Chapter 20's IPL 2026 leaderboard needed a full season to rank batters, and even then it correlated 0.71 with strike rate). And it inherits every weakness of the model that produced it: if WP v1 is miscalibrated in some state, WPA in that state is wrong by the same amount. Rabada's −0.115 includes the six Venkatesh Iyer hit off him in the second over of the chase, at a moment when one boundary still moved a probability that was not yet settled.

📋 Try it — Analyze this match: Use the Match Centre (or winprob.wp_curve directly) on Chapter 20's second example, Mumbai Indians v Delhi Capitals, 11 April 2023 (1359490), with the dashboard's policy for 2023 (WP v1 pooled, fitted before 2023). Which delivery is the top turning point, and who has the highest batting WPA?

Worked answer

Chapter 20's checkpoint ran exactly this setup: the top swing is Tim David's two off the last ball (Mumbai's WP 0.671 → 1.000), and the top match WPA belongs to Axar Patel (+0.224 for 54 off 25 in a losing cause). The lesson is the same as the final's: WPA rewards the runs that moved an uncertain match, so a losing batter can top the list. Your dashboard should reproduce those numbers exactly; if it does not, check which seasons the model was fitted on.


39.6 Stage 5: before the first ball

Rewind to the morning of 31 May 2026. The question a broadcaster, a bettor or a team analyst asks before the toss: who should we expect to win, and how sure should we be? Chapter 24 built the answer: Elo ratings for every team, plus a team-sheet strength (each player's projected batting and bowling value in runs per match above par, from Chapter 25's Marcel projections), plus a home flag, combined in one logistic regression. Chapter 24 also found the trap: fitted on the IPL alone (a few hundred matches) the model puts a negative weight on Elo, so the recommended model is pooled across twelve men's T20 competitions and applied to the IPL with the IPL's own tuned Elo settings.

day = pd.Timestamp("2026-05-31")                       # nothing on or after this date is used
pooled = match_model.fit_pooled_t20(day)
pr = match_model.build_predictor("ipl", day, elo=dict(k=10, home_adv=50, season_regress=0.25),
                                 model=pooled)
pr.predict_match("Gujarat Titans", "Royal Challengers Bengaluru", home="Gujarat Titans",
                 xi_a=xi_gt, xi_b=xi_rcb)              # the announced team sheets

The script code/03_prematch_and_live.py compares five reasonable settings:

STAGE 5 - PRE-MATCH (frozen at the start of 31 May 2026)
pooled men's T20 logit: 6,255 decided matches; coefficients per unit elo_diff +0.0050, bat_diff +0.0189, bowl_diff +0.0143, home +0.0026
Elo on the morning of the final: Gujarat Titans 1535, Royal Challengers Bengaluru 1541
announced team sheets in the data: Gujarat Titans 12 names, Royal Challengers Bengaluru 12 names (Impact Player era: 12 listed)
                                    setting  P(GT)  P(RCB)
0                      Elo only, GT at home  0.562   0.438
1  Elo + last team sheets, venue -> GT home  0.577   0.423
2           Elo + last team sheets, neutral  0.514   0.486
3      Elo + announced team sheets, GT home  0.571   0.429
4      Elo + announced team sheets, neutral  0.509   0.491

Row 3 is exactly the 0.571 Chapter 24 reported for this final, and row 1 is what the Match Predictor page shows by default (57.7%), because the page does not know the announced team sheets and uses each side's most recent XI instead. The pre-match model made Gujarat slight favourites. The win-probability model of stage 3 made Bengaluru favourites at the first ball (59.4%). Both are Crease. Who is right?

Neither number is wrong; they answer slightly different questions with different evidence, and a good analyst can say exactly why they differ:

  • Two Elo systems. WP v1 uses a plain walk-forward Elo inside each competition (K = 20, no home bonus, no pull towards the mean between seasons), which had Bengaluru 33 points ahead. The pre-match model uses the IPL's tuned Elo (K = 10, a 50-point home bonus, a 25% pull towards the mean between seasons), which had the teams 6 points apart. Chapter 24 tuned those settings because they forecast better out of sample.
  • Home. The final was played at Gujarat's home ground. The pre-match model's home term is worth about six points of probability here (0.577 v 0.514). WP v1 has no home term at all. Whether a final at one finalist's ground carries home advantage is a modelling choice, and Chapter 35 showed the price of the final moves with it.
  • Team sheets. The pre-match model sees who is playing; WP v1 sees only the score.

🔍 Why this works: The disagreement is a feature. Two models built on different evidence that agree give you confidence; two that disagree point you to the assumption that matters (here, home advantage at a final). When you present to a coach, show the range ("between 51% and 58% for Gujarat, depending mainly on whether you believe in home advantage at a final") rather than picking the number you like.

Gujarat lost. That is not a failure of the model either. A 57% favourite loses 43% of the time, and Chapter 24's out-of-time test is blunt about how little any pre-match model knows in the IPL: across 2023–26 the Elo favourite won only 47.6% of 286 IPL matches, worse than a coin flip on log loss, and a model that knew every team's true strength would still have called only 54.3%. Parity and luck dominate the IPL. A franchise analyst who promises more than that is selling something.

Tom Ashworth, who spent years pricing matches before he taught risk, put it more simply when Nusrat showed him the page. "Your model said 57–43 and the 43 came in. Ask me again after a thousand matches whether your 57s won about 57% of the time. One final tells you nothing."

🔄 Check your understanding 1. Why does the Match Predictor page show 57.7% for Gujarat when Chapter 24 reported 57.1%? 2. Gujarat lost as 57% favourites. What evidence would show the model is badly calibrated?

Answer

  1. The page uses each side's most recent team sheet before the freeze date; Chapter 24 used the announced sheets for the final. With the announced sheets and the same home setting, the platform gives 0.571 too (row 3).
  2. Many forecasts, not one: group hundreds of matches by forecast (say 55–60%) and check how often the favourite won. Chapter 24 did exactly that for 2023–26, and in the IPL the favourites won less often than the forecasts implied.

⚠️ Common pitfall: Calling build_predictor("ipl", as_of) without model=. The default fits a logit on the IPL alone, and with only about 520 matches it learns a negative weight on Elo (the better-rated side is predicted to do worse). The dashboard always passes the pooled model for men's competitions and uses pure Elo for women's T20Is, for which Crease has no team-sheet model.


39.7 Stage 6: during the first innings

A live broadcast graphic asks the question every viewer asks at the drinks break: where is this innings heading? The scoreboard's answer is the current run rate times twenty overs. Chapter 27 showed that is the worst method available, and built a better one: a Markov innings simulator (from Chapter 19's state model) that plays out the rest of the innings ten thousand times from the current score, balls left and wickets in hand, in the match's scoring environment, and reports the median and an 80% range.

📐 Definition: An 80% projection range is the interval between the 10th and 90th percentiles of the simulated final totals. If the model is calibrated, the real total should fall inside it in about 80% of innings, no more and no less.

The simulator for the final is frozen before the 2026 season began, so it knows nothing about IPL 2026:

s, g = live.load_first_innings()
fit = s[(s["start_date"] < season_start) & s["complete"]]
chain = live.LiveChain(tau=0.0, tau_future=0.07).fit(fit)
for ov in range(1, 20):
    st_ = inn[inn["legal_before"] == 6 * ov].iloc[0]
    p = live.project_total(st_["score_before"], 6 * ov, st_["wkts_before"], gm["env_par"], chain,
                           thresholds=(160, 180, 200))
STAGE 6 - LIVE PROJECTION (Gujarat Titans' innings)
first-innings states for 9,117 men's T20 matches; chain fitted on 8,225 complete first innings before 28 Mar 2026; chain par 159.1; this match's scoring environment 191.7
    over  score  median   lo80   hi80  rr_x20  P(160+)  P(180+)
5      6   45/2  178.00 140.00 219.00  150.00     0.73     0.48
9     10   63/3  164.00 135.00 195.00  126.00     0.58     0.25
14    15  105/5  157.00 139.00 177.00  140.00     0.44     0.07
after  6: Heading for about 180 — 80% of similar innings finish between 140 and 220; 160+ about 75% (about 3 in 4).
after 10: Heading for about 165 — 80% of similar innings finish between 135 and 195; 160+ about 60% (about 3 in 5).
after 15: Heading for about 155 — 80% of similar innings finish between 140 and 175; 160+ about 45% (about 2 in 5).
real total 155: inside the 80% range after 19 of 19 overs; median miss 10.0 runs; run-rate projection median miss 13.6
simulate_innings from 63/3 after 10 overs: mean 164.5, sd 23.8, share of simulated innings at or below 155: 0.355

(Three rows of nineteen are shown; the full table is in code/03_prematch_and_live_output.txt.)

Live projection of Gujarat Titans' innings after every over, with the 80% range, the run-rate projection and the real total

📊 Figure (described): After each over of Gujarat's innings, a blue line shows the simulator's median projected total inside a shaded 80% band, an orange dashed line shows the scoreboard's run rate times 20, and a black horizontal line marks the real total, 155. The band narrows from 151–258 after one over to 150–164 after nineteen and contains 155 throughout. The run-rate line swings from 260 after the first over to 126 after ten.

Two things stand out. The run-rate projection is badly behaved at both ends: 260 after a 13-run first over, 126 at the halfway mark when Gujarat had slowed to 63 for 3. The simulator was steadier; its median missed the real total by ten runs or fewer in half the overs. And the range did its job: 155 was inside the 80% band after every one of the nineteen overs. That is pleasant but proves little on its own. One innings cannot show calibration, any more than one final can. Section 39.8 tests it on a whole season.

Notice also what the broadcast line says after ten overs: "Heading for about 165 — 80% of similar innings finish between 135 and 195; 160+ about 60% (about 3 in 5)." That is Chapter 27's rule for graphics: a range, not a point; a probability phrased as odds a viewer can picture; numbers rounded so nobody mistakes them for precision. Kavya Subramanian's verdict, when Nusrat sent her the line, was a producer's: "I can put that on air. I couldn't put '163.7' on air with a straight face."

🔄 Check your understanding 1. After 10 overs the simulator said "160+ about 60%". Gujarat made 155. Was the simulator wrong? 2. Why freeze the simulator at the start of the season rather than on the morning of the final?

Answer

  1. No. It gave about a 40% chance of finishing below 160, and from 63 for 3 about 35.5% of its simulated innings finished at or below 155. An outcome it rated at roughly one in three happened. Only many such forecasts can show whether its 60%s come true about 60% of the time.
  2. It is the stricter test, and the one the season-wide check in 39.8 uses: a model frozen before the season can be scored on every 2026 innings without any of them having helped fit it. Freezing on the morning of each match is legitimate too, but needs a refit per match.

🪞 Learning check-in: Pause and look back over the six stages. Which one could you rebuild from memory, with only the modules' docstrings to help? Which one would you have to reread a chapter for? For many readers the answer to the second is stage 3: the first-innings half of win probability (projecting a total and pricing it with the chase model) is the least intuitive idea in the pipeline. If that is you, reread the first-innings section of Chapter 20 before 39.8, because its weaknesses are on the model cards. Then ask a harder question: which stage do you trust least, and is it the same one you understand least? It often is. Distrust usually comes from not knowing where a number came from, and the model cards exist to fix exactly that.


39.8 Model cards: what each model is for, and where it fails

A model card is a short document that travels with a model. The idea comes from machine learning practice, where it was proposed so that the people using a model can see what it was trained on, how it was tested and where it should not be used. Chapter 38's portfolio template has a slot for one per model. Here are Crease's, filled in.

📐 Definition: A model card records, for one predictive model: its purpose; its training data and the period it saw; its target; its out-of-time evaluation (scored on data later than anything it was fitted on) against a naive baseline; its known failure modes; and what it must not be used for.

Every card below quotes two kinds of evidence: the out-of-time test from the chapter that built the model, and a fresh re-test on the newest season in the snapshot, run by code/04_model_cards.py with each model frozen before 2026 and asked to forecast all of it.

Scorecard on the newest season (lower is better for every metric):
                              model      metric  model_score  baseline        baseline_name  improvement_pct
0              WP v1 (ball by ball)       Brier       0.1062    0.2500     season base rate          57.5047
1                   Pre-match (IPL)       Brier       0.2516    0.2500            coin flip          -0.6569
2  Live projection (after 10 overs)    MAE runs      16.7324   24.0000        run rate x 20          30.2817
3           Player projection (SR+)        RMSE      13.9301   20.1926  same as last season          31.0139
4            Tournament (IPL title)  -log score       1.8734    2.3026              1 in 10          18.6391

Each model's improvement over a naive baseline on the 2026 season

📊 Figure (described): Horizontal bars show how much better each Crease model did than a naive baseline on the 2026 season, with every model frozen before the season. WP v1 beats the season base rate by 57.5% on Brier score; the player projection beats "same as last season" by 31.0% on RMSE; the live projection beats run rate × 20 by 30.3% on mean error after ten overs; the tournament model beats a one-in-ten guess by 18.6% on log score. The pre-match IPL model is the one bar below zero: 0.7% worse than a coin flip.

Card 1 — WP v1 (winprob.py, Chapter 20)

Field Entry
Purpose Chase win probability after every ball; first-innings WP via a projected total; WPA
Training data Men's T20 chases from 12 competitions (8,939 chases, 999,986 ball states in the full pool); the dashboard fits only seasons before the match's season, era-only (2023 on) for men's matches from 2024
Target Did the chasing side win (ties dropped when fitting)
Book's test Fitted before 2023, tested 2023–26: Brier 0.1143 v WP v0's 0.1252 (Chapter 20)
Re-test, 2026 Fitted 2023–25: Brier 0.1062 on 94,698 ball states from 879 men's T20 chases (base rate 0.2500); calibration slope 0.99
Known weaknesses The last ball: needing 4 off the final ball, WP v1 said 7.8% when 34% of such chasers won (47 cases, Chapter 20); in 2026 the 258 last-ball states averaged a 5.8% forecast against 9.7% won. IPL chasers under-rated again in 2026 (mean forecast 0.568 v 0.631 won; slope 1.33). The men's model overrates women's chasers by 9.4 points
Do not use it for Women's matches (use the women's fit); betting stakes without an edge test; Tests or ODIs
  all men's T20, 2026  chases  879, states  94,698: Brier 0.1062 (base rate 0.2500); log loss 0.3282; mean forecast 0.500 v observed 0.494; calibration slope 0.99
  IPL 2026             chases   70, states   8,081: Brier 0.0949 (base rate 0.2329); log loss 0.3018; mean forecast 0.568 v observed 0.631; calibration slope 1.33
  last-ball states in 2026: 258; mean forecast 0.058 v observed 0.097 (the known weak spot)

Reliability of WP v1 on 2026 men's T20 chases

📊 Figure (described): A reliability diagram. Each dot is one tenth of the probability scale: the average WP v1 forecast in that bin (x) against the share of those ball states that the chasing side went on to win (y), with dot area showing how many states fell in the bin. The dots sit on or just below the diagonal; the largest gap is in the 0.7–0.8 bin, where forecasts averaging 75.0% won 71.1% of the time.

Read the card's halves together. Across all men's T20 the model is close to perfectly calibrated on a season it never saw (slope 0.99). In the IPL alone it is under-confident in chasers again (slope 1.33): the Impact-Player era kept moving after 2025, and 2026's IPL chasers won 63.1% of the states where the model averaged 56.8%. Chapter 40's roadmap item R2, a drift monitor, exists for exactly this.

Card 2 — Pre-match model (match_model.py, Chapter 24)

Field Entry
Purpose P(team A wins) before the toss, frozen at a date
Training data Pooled logit on decided men's T20 matches from 12 competitions (6,255 before 31 May 2026); Elo settings tuned per competition on seasons before 2023
Book's test 2023–26 out of time, Elo favourite won: men's full-member T20Is 64.1%, men's ODIs 61.2%, women's T20Is 71.9%, decided Tests 67.7%, IPL 47.6% (Chapter 24)
Re-test, 2026 Frozen on the eve of IPL 2026, all 72 decided matches: favourite won 54.2%; Brier 0.2516 v coin 0.2500; log loss 0.6965 v 0.6931
Known weaknesses The IPL ceiling: a model knowing every team's true strength would call only 54.3% of IPL matches (luck share 91.6%). Team sheets add almost nothing to Elo. The IPL-only default logit has a negative Elo weight. Home advantage at a final is an assumption
Do not use it for IPL betting (it does not beat a coin); any claim of "60–65% accurate" outside men's internationals

Card 3 — Live projection (live.py, Chapter 27)

Field Entry
Purpose First-innings total from any point: median, 80% range, threshold odds, broadcast line
Training data Complete first innings in 12 men's T20 competitions before the season (8,225 before 28 March 2026); the women's version uses women's innings
Book's test Fitted before 2023, tested 2023–26: the best projection was within ±15 runs only about 41% of the time after 6 overs, so "±15 after the powerplay" is false; Monte Carlo 80% ranges covered 84% of IPL totals but 65% of associate T20Is (Chapter 27)
Re-test, 2026 71 complete IPL 2026 first innings: mean miss 20.0 / 16.7 / 12.0 runs after 6 / 10 / 15 overs v 35.1 / 24.0 / 13.3 for run rate × 20; 80% ranges held 84.5% / 81.7% / 69.0%
Known weaknesses Ranges too narrow late in the innings (69% coverage after 15 overs in 2026) and in associate cricket; knowing which batters are in barely helps (0.3–0.7 runs)
Do not use it for Exact numbers on air; women's or associate matches with the men's chain
      innings    mae  mae_rr  within_15  coverage_80
over                                                
6          71 20.049  35.070      0.507        0.845
10         71 16.732  24.000      0.563        0.817
15         71 11.958  13.296      0.662        0.690

Card 4 — Player projection and translation (projection.py, translation.py, Chapters 25–26)

Field Entry
Purpose Next-season SR+ (and dismissal and bowling indices) with an 80% range; other leagues' records in IPL units
Training data IPL batting lines by season; translation factors from players who appeared in two leagues in the same year (2021–26)
Book's test IPL SR+ 2019–26: Marcel RMSE 13.4 v 19.6 for "same as last season"; 80% intervals covered 80% (Chapter 25). Translation cut the untranslated bias from +2.07 to −0.04 SR+ points (Chapter 26)
Re-test, 2026 Fitted on targets 2011–25, 81 IPL 2026 regulars: RMSE 13.93 v 20.19 (last season), 18.04 (unregressed three-year), 15.25 (league average); 80% range held 86%
Known weaknesses Wickets are essentially unprojectable (Chapter 25: Marcel was no better than par for wicket rate). No birth dates in the data, so no true aging curve. IPL newcomers: translated history barely beats par
Do not use it for A bowler's wicket count; a player's "peak age"

Card 5 — Matchup shrinkage (matchups.py, Chapter 11)

Field Entry
Purpose A batter's strike rate against each bowling type, shrunk towards what a batter of his skill would score against that type
Training data Men's T20 balls since 2015 (IPL, T20Is and ten leagues) with bowler type from the styles table
Book's test Out-of-sample error: raw matchups 414 v ignoring matchups 222 v shrunk 209 (Chapter 11)
Today's run Shrinkage constant k = 303 balls for strike rate, 1,956 balls for dismissal rate, on the final styles table
Known weaknesses Dismissal matchups are mostly noise (k near 2,000 balls); no venue adjustment; bowler type is known for only 24.2% of men's associate T20I balls (Chapter 40)
Do not use it for A raw head-to-head of 30 balls; "bunny" claims about dismissals

Card 6 — Batting value (valuation_batting.py, Chapter 13)

Field Entry
Purpose IPL batting runs above replacement (RAR), wins, rupee value, value v salary
Training data IPL deliveries; replacement level by era and phase; runs per win 140.2 (2022–26); salaries from data/reference/ipl_auction.csv
Book's test Salary v wins above replacement Spearman 0.32; six-hitting premium real, no nationality premium found (Chapter 13)
Known weaknesses Batting only (never mix with Chapter 34's all-skills scale); replacement level sensitive to the minimum-balls filter; early-over wicket values noisy
Do not use it for Bowlers or all-rounders; one season as proof of a bargain (Anchor B did not persist)

Card 7 — Tournament simulator (tournament.py, Chapter 28)

Field Entry
Purpose Title, final and knockout probabilities for IPL seasons and ICC events, by Monte Carlo
Book's test Over 26 tournaments, Brier skill v base rate for top-four/semi-final forecasts: IPL +0.037, men's World Cups +0.424, women's +0.389 (Chapter 28)
Re-test, 2026 IPL 2026 from its eve: the real champion, Bengaluru, was given 15.4%, the highest of the ten teams; log score −1.873 v −2.303 for a know-nothing forecast
Known weaknesses Net run rate not simulated (ties on points broken at random); the truly best IPL side wins only about one title in five at IPL-sized gaps; Afghanistan's strength must be assumed in ICC events
Do not use it for "Team X will win the IPL"; treating a 95% top-four forecast as a certainty (Case Study 2)

⚠️ Common pitfall: Writing a model card with only the good half. A card that lists accuracy but no failure modes is an advertisement. The useful parts are the last two rows of each table: they stop a coach, an editor or a trader from using the number where it breaks.

📋 Try it — Build this metric: The scorecard compares each model with a naive baseline. Turn it into one number per model: a skill score = 1 − (model score ÷ baseline score), which is 0 for "no better than the baseline" and 1 for perfect. Compute it for the five rows and rank them. Then ask: is it fair to rank models that are scored on different metrics?

Worked answer

Skill = improvement_pct ÷ 100: WP v1 0.575, player projection 0.310, live projection 0.303, tournament 0.186, pre-match −0.007. The ranking is not a ranking of quality. WP v1's high skill comes from an easy baseline (the base rate ignores the score entirely); the pre-match model's negative skill comes from the hardest problem in the book (IPL parity). A skill score compares a model with its own baseline, not with other models. That is why every card names its baseline.


39.9 Keeping it working: smoke tests

The cricket question here is the one a coach asks the morning after you change something: is the number I trusted yesterday still the number you would give me today? Code rots quietly. A library upgrade changes a default; a styles-table extension shifts a join; a "small" fix in one module breaks a function three imports away. The cure is a test suite you run every time.

📐 Definition: A smoke test checks that a piece of software runs at all: each part loads and produces output of the right shape on a small, real input. It does not check that the output is correct in every detail. The name comes from hardware testing: switch it on, and see whether smoke comes out.

project/tests/test_smoke.py has one test per Crease module plus one that imports them all. Each test calls one fast public function on real data (the IPL 2026 final's 233 deliveries, the last Test in the snapshot, or one IPL season) or on a tiny hand-made input, and asserts something a cricket person would recognise as right:

def test_states():
    st = mod("states").innings_states(final_balls(), innings=1)
    assert st["final_total"].iloc[0] == 155                       # Gujarat made 155

def test_impact():
    s2 = mod("impact").innings_states(final_balls(), games, innings=2)
    assert s2["runs_needed"].iloc[0] == 156                       # Bengaluru needed 156

def test_resources():
    r = mod("resources")
    assert r.overs_to_balls(34.3) == 207 and r.balls_to_overs(207) == "34.3"

The file finds the modules on disk (pkgutil.iter_modules), so a module added later is reported as MISS until someone writes its test. It runs under plain Python or under pytest, because some readers will have pytest and some will not:

Crease smoke tests: 36 modules found in project/crease/, 37 tests

  PASS  all_modules_import       0.97 s
  PASS  auction                  0.00 s
  PASS  batting                  0.18 s
  ...
  PASS  winprob                  0.06 s

37 passed, 0 failed, 0 without a test - 2.1 s

(The full list is in code/project_checkpoint_output.txt.) Every module in the package passed. The whole suite takes two to three seconds, which matters: a test you can run in three seconds gets run; one that takes ten minutes gets skipped.

Writing the suite also caught two mistakes, both in the tests rather than the modules. The first draft assumed fielding.dismissal_mix returned a single row as a Series (it returns a one-row table), and that runs_saved_to_economy returned a key called team_economy (it is team_economy_drop). That is a small, real lesson: a test written from memory of an interface is itself a test of your memory. Read the docstring.

⚠️ Common pitfall: Smoke tests that check only "it didn't crash". assert len(table) > 0 passes when a join silently drops 90% of the rows. Assert something you know is true about cricket: the final's first-innings total is 155; a resource-table conversion of 34.3 overs is 207 balls; a partnership table's runs add up to the innings total. Those catch the quiet failures.

The second layer of testing is the dashboard itself, driven headlessly (39.2): ten page runs, all passing. The third, and the most valuable, is checking that the assembled system reproduces the book. The dashboard's numbers for the IPL 2026 final match what each module's own chapter reported: 0.865 for Bengaluru at the innings break (Chapter 20), 0.571 for Gujarat with the announced team sheets (Chapter 24), 15.4% for Bengaluru's title chance on the eve of the season (Chapter 28's 0.154), India at 46.5% on the eve of the 2026 men's T20 World Cup (Chapter 28's 0.465). When a number a chapter published and the number the assembled platform produces agree to three decimal places, the pipeline between them has not drifted.

🔄 Check your understanding 1. The smoke test for winprob fits a state-only model on one IPL season and checks that needing 10 off 60 with 8 wickets in hand gives a win probability above 0.9. Why not fit the full WP v1? 2. What would a reproduction test against Chapter 20's 0.865 catch that the smoke test would miss?

Answer

  1. Speed. The full fit needs nine seconds of state-building; a smoke test should take a fraction of a second so the whole suite stays fast. The small fit still exercises fit_wp and predict end to end.
  2. Silent numerical drift: a change in how states, the scoring environment or the Elo are computed that leaves everything running but moves the answer. The smoke test only checks it runs and is sensible; the reproduction test checks it is the same.

39.10 The other pages: players, matchups, the auction and the trophy

The Match Centre carried the worked example. The other pages each answer a question from an earlier part of the book, and each one leads with the honest version of the answer. The figures below are drawn by the app's own fig_* functions (code/05_dashboard_figures.py).

Player Explorer — "how good is he, and what next season?"

Player Explorer: Virat Kohli's SR+ by phase, IPL 2024–26

📊 Figure (described): Three bars show Virat Kohli's SR+ in the IPL 2024–26 by phase, with the balls faced in each: powerplay 107.6 (639 balls), middle overs 94.8 (600), death 115.6 (101). A dashed line at 100 marks league par for the same seasons and phases.

Player Explorer - V Kohli, IPL 2024-26, batting by phase:
       phase  balls  runs  strike_rate  par_sr  sr_plus  dot_pct  boundary_ball_pct
0  powerplay    639  1051        164.5   152.9    107.6     32.5               26.0
1     middle    600   821        136.8   144.3     94.8     24.2               14.3
2      death    101   201        199.0   172.1    115.6     21.8               30.7
2027 projection card (Marcel, 80% range for 300 balls):
          2024  2025  2026  weighted  n_eff  reliability  age_adj  projection   lo    hi
sr_plus  104.5  97.1 106.9     103.0 1058.0          0.7      0.0       102.1 89.2 115.0

The page puts three chapters on one screen. Chapter 8's SR+ shows Kohli above par in the powerplay and at the death but below it in the middle overs, where he takes the anchoring role. Chapter 25's Marcel projection weights his last three seasons 5:4:3 and shrinks towards the league: 102.1 for 2027, with an 80% range of 89.2 to 115.0 for a 300-ball season. Note how wide that range is for one of the most-measured batters in the game; that is not the model being timid, it is Theme 3 (small samples) stated honestly. The page's translation table (Chapter 26) shows his 109 balls in full-member T20Is in 2024 at SR+ 88.9, worth 84.6 in IPL units once the 1.051 exchange rate is applied.

Matchups — "who should bowl to him?" (Anchor D)

Matchups: Quinton de Kock against six bowling types, shrunk with 90% intervals

📊 Figure (described): For each of six bowling types, a blue dot shows Quinton de Kock's shrunk strike rate with a 90% interval, an orange diamond shows what a batter of his skill would be expected to score against that type, and a grey cross shows his raw strike rate. Against off-spin the whole interval (108.5–122.4) sits left of the expected 125.8; against right-arm pace he is well above expectation.

Matchups - Q de Kock, men's T20 since 2015 (k_sr = 303 balls, k_dr = 1956 balls):
                     balls  sr_obs  sr_exp  sr_shr  sr_lo  sr_hi  d_sr
group                                                                 
Right-arm pace        2647   153.5   135.8   151.6  146.6  156.7  15.8
Left-arm pace          917   135.4   132.8   134.8  127.0  142.6   2.0
Off-spin              1226   112.9   125.8   115.5  108.5  122.4 -10.4
Left-arm orthodox      606   147.5   151.2   148.8  139.7  157.8  -2.5
Leg-spin               455   126.8   146.7   134.7  124.8  144.7 -11.9
Left-arm wrist-spin    104   118.3   140.2   134.6  121.1  148.1  -5.6

This is Anchor D, live. Chapter 11 settled it as de Kock against off-spin: 1,226 balls, shrunk SR 115.5 (90% interval 108.5–122.4) against an expected 125.8. The dashboard runs on the same final styles table and reproduces those figures exactly, which is what a reproduction test should confirm. The page also shows the trap Chapter 11 warned about: against left-arm wrist-spin his raw strike rate is 118.3, which looks like a weakness, but on 104 balls it shrinks to 134.6, with an interval wide enough to include his expectation.

Auction Board — "who is worth what he is paid?" (Anchor B)

Auction Board: IPL 2025 salary against batting wins above replacement, Pant and Verma highlighted

📊 Figure (described): Each grey dot is a specialist batter in IPL 2025, placed by salary in force (log scale, ₹0.3 crore to ₹27 crore) and batting wins above replacement. Aniket Verma, at ₹0.3 crore, sits at +0.25 wins; Rishabh Pant, at ₹27 crore, the most expensive batter on the chart, sits at −0.13. Most dots cluster near zero at every price, with no tight line rising from left to right.

Anchor B pair card, IPL 2025:
                        balls  runs  outs  wicket_cost   rar  repl  strike_rate  balls_per_out  rar_per_100
name         phase                                                                                         
Aniket Verma middle        82   139     4         27.9  26.5   1.0        169.5           20.5         32.3
RR Pant      death         41    77     2          0.0  16.1   1.5        187.8           20.5         39.2
             middle       108   141     8         58.0 -28.5   1.0        130.6           13.5        -26.4
Anchor B pair card, IPL 2026:
Aniket Verma middle        21    16     3         20.7 -27.1   1.1         76.2            7.0       -129.0
RR Pant      death         45    95     2          2.4  26.4   1.5        211.1           22.5         58.8

(Rows selected from code/05_dashboard_figures_output.txt.) The page reproduces Anchor B exactly as Chapter 13 settled it: in the 2025 middle overs Pant scored 141 off 108 with 8 outs, runs above replacement −28.5; Verma 139 off 82 with 4 outs, +26.5. And because the page lets you change the season, it also shows the two caveats the book always attaches. In 2026 Verma's middle overs were 16 off 21 (−27.1), so the edge did not persist; and Pant was the better death-overs batter in both seasons (2026: 95 off 45, +26.4). The page prints both caveats in a warning box under the card, because a dashboard that shows only the striking half of a finding teaches the wrong lesson.

🏏 Eye test: "That chart," Wendell said, "tells me nobody in that auction room knew what they were doing." Nusrat disagreed. The chart shows batting value only; Pant is also a wicketkeeper, and the market pays for things a batting table cannot see. The Spearman correlation between salary and batting value was only 0.32 in Chapter 13, so the market prices batting loosely, but "loosely" is not "randomly", and no single season's dot proves a bargain. Both of them were half right, which is usually where analytics and the eye test meet.

Tournament Sim — "who lifts the trophy?"

Tournament Sim: title probabilities for the 2026 men's T20 World Cup from its eve

📊 Figure (described): Horizontal bars show each team's simulated chance of winning the 2026 men's T20 World Cup from the eve of the tournament, 7 February 2026. India, highlighted as the real champion, leads at 46.5%, then Australia 15.7%, England 15.4%, New Zealand 7.1% and Pakistan 6.2%.

Tournament Sim - men's T20 World Cup 2026 from 07 Feb 2026:
          team  p_title  p_final  p_knockout
0        India    0.465    0.634       0.857
1    Australia    0.157    0.349       0.595
2      England    0.154    0.324       0.621
3  New Zealand    0.071    0.177       0.390
4     Pakistan    0.062    0.170       0.392
5  Afghanistan    0.030    0.102       0.276

India won, so the forecast looks good, but a 46.5% favourite wins less than half the time, and New Zealand, the beaten finalist, were given 17.7% to reach the final. Afghanistan's line carries a warning on the page: Cricsheet withholds Afghanistan's men's internationals, so their rating is assumed (1,500), and their 3.0% is a statement about that assumption, not about Afghanistan. The same page re-runs IPL 2026 with real results locked in as the season unfolds (the conditioning trick from Chapter 28), which is how Case Study 2 caught the platform being confidently wrong about Punjab Kings.

🔄 Check your understanding 1. De Kock's raw strike rate against left-arm wrist-spin is 118.3, well below what a batter of his skill would expect (140.2). Why does the page not call it a weakness? 2. On the Auction Board, which two facts must always travel with the Pant–Verma comparison?

Answer

  1. It rests on 104 balls. Shrunk towards his expectation it becomes 134.6, and its 90% interval (121.1–148.1) includes the expected 140.2, so there is no evidence of a weakness.
  2. The gap did not persist in 2026 (Verma 16 off 21 in the middle overs), and Pant was the better death-overs batter in both seasons.

📋 Try it — Evaluate this player: Open the Player Explorer for Smriti Mandhana in the WPL (2024–26) and the Matchups page's women's equivalent through app.matchup_table("female"). Using the chapter's rules, write three sentences a selector could act on: her SR+ by phase with the balls behind each, one matchup with its shrunk interval, and one thing the data cannot tell you.

Worked answer

Your numbers come from your run, but the shape of a good answer is fixed. (1) Phase SR+ with ball counts, flagging any phase under about 100 balls as too thin to read. (2) One matchup quoted as the shrunk strike rate with its 90% interval and the expected value beside it; if the interval includes the expectation, say "no evidence of a weakness", not "a slight weakness". Remember that women's dismissal matchups are almost pure noise (Chapter 11's women's k for dismissal rate was 2,905 balls). (3) A limit: no line and length, no fitness or form in the nets, and for the WPL a short history, so the projection's interval will be wide. For context, Case Study 1 shows her 87 off 41 in the 2026 WPL final, the largest WPA in that match (+0.659).


39.11 What to build next

Crease is finished in the sense that every chapter's module is in it, the dashboard draws them and the tests pass. It is unfinished in every sense that matters, and the model cards say where. Chapter 40's project/ROADMAP.md lists thirteen extensions in three tiers. Three of them follow directly from this chapter's evidence:

  • R2, a drift monitor. Section 39.8 was a drift monitor run by hand: freeze every model before the newest season and score it on that season. It found WP v1 under-rating IPL chasers again in 2026 (slope 1.33) and the live ranges too narrow after 15 overs (69% coverage). Automate it, and make it raise a flag when a model's newest-season calibration leaves its own interval.
  • R3, women's cricket first. The Match Centre already refuses to use a men's model for a women's match. The Match Predictor still has no women's team-sheet model (pure Elo), and the Matchups page defaults to men. Case Study 1 shows what the wrong table does to a women's final.
  • R10, a live bowling planner. The Live Projection page projects the batting side; Chapter 31's rotation optimiser plans the bowling before the innings. A page that re-plans the remaining overs at each over break, using the live state and the shrunk matchups, would turn two descriptive pages into a decision tool.

Two engineering steps make any of these easier. Put the smoke tests in a scheduled job (a free continuous-integration service will run python project/tests/test_smoke.py on every change). And add reproduction tests: one assertion per settled book number (0.865, 0.571, 0.154) so that any drift in the assembled system is caught the day it happens.

Wendell's question from the hook, "and if it's wrong?", is the right one to carry into Chapter 40. A platform that can answer it, with a model card, a test and a number for how wrong, is worth more than a platform that is merely clever.


Spaced Review

Three earlier ideas carry this chapter. Try each question before you read the reminder.

  1. Chapter 6 — regression to the mean. The Matchups page shrinks de Kock's raw 112.9 against off-spin to 115.5, and his raw 118.3 against left-arm wrist-spin all the way to 134.6. Why does one move about three points and the other sixteen? Reminder: shrinkage pulls a raw rate towards its expectation with a weight of n ÷ (n + k). With k = 303 balls, 1,226 balls keep about 80% of their distance from expectation; 104 balls keep about 26%. Small samples regress hardest, which is Chapter 6's threshold concept.
  2. Chapters 9 and 20 — value is change in win probability. Kohli made the most runs in the final but not the most WPA. In one sentence, why? Reminder: WPA credits each ball with the change in win probability it caused, so runs scored when the result is nearly settled add little (Chapter 9's threshold concept), and the model producing the probabilities must be calibrated for WPA to mean anything (Chapter 20's).
  3. Chapter 24 — the ceiling. The 2026 re-test found the pre-match IPL model slightly worse than a coin. Is that a bug? Reminder: no. Chapter 24 showed a model knowing every team's true strength would call only 54.3% of IPL matches, because the luck share of IPL results is about 92%. A model cannot be more accurate than the sport is predictable; the right response is to say so on the model card, not to tune until 2026 looks good.

Project Checkpoint: app.py and tests/

This chapter's contribution to Crease is not a module in project/crease/. It is the two files that make the package a product: project/app.py, the dashboard, and project/tests/test_smoke.py, the smoke tests, plus project/README.md, which tells a stranger how to install, run and understand it.

Nusrat's checklist for the night she finished:

Piece What it does Lines / tests
app.py layer 1 Cached data and model functions: wp_states, wp_model, match_centre_data, player_card, projection_models, translation_tables, matchup_table, value_board, pooled_model, predictor, ipl_season_sim, world_cup_2026_sim, live_states, live_chain, live_path pure functions, cached by Streamlit or lru_cache
app.py layer 2 Figure builders: fig_scoreboard, fig_wp, fig_phase_profile, fig_matchup, fig_value_price, fig_title_odds, fig_live_path each returns a matplotlib Figure
app.py layer 3 Seven page_* functions and main() (sidebar, page choice) widgets only
tests/test_smoke.py One test per module + an import-everything test; plain Python or pytest 37 tests, about 3 s
README.md Install, run, ASCII architecture, page table, module table, short model cards —

The chapter's code/project_checkpoint.py runs both checks without a browser:

code = test_smoke.main()                                    # 1. every module, one real call each
at = AppTest.from_file(str(PROJECT / "app.py"), default_timeout=900)
at.run()                                                    # 2. Match Centre (default page)
for p in pages:
    at.sidebar.radio[0].set_value(p).run()                  #    every other page
    assert not at.exception
10 of 10 page runs passed; smoke tests passed.

What the pages showed for the IPL 2026 final (default selections):
  Match Centre      : Gujarat Titans v Royal Challengers Bengaluru, Narendra Modi Stadium, Ahmedabad, 2026-05-31 — Royal Challengers Bengaluru won by 5 wickets
                      top turning point: ['1', '3.4', 'B Sai Sudharsan', 'WICKET B Sai Sudharsan (caught)'] dWP -0.090
                      top WPA batters: VR Iyer +0.078, V Kohli +0.073, TH David +0.008
  Match Predictor   : [('P(Gujarat Titans wins)', '57.7%'), ('P(Royal Challengers Bengaluru wins)', '42.3%'), ('Elo gap (A - B)', '-6')]
  Live Projection   : after 10 overs [('Score', '63/3'), ('Median projection', '164'), ('Run rate x 20', '126')]
  Tournament Sim    : IPL 2026 from its eve, top three: Royal Challengers Bengaluru 0.154, Gujarat Titans 0.138, Kolkata Knight Riders 0.108
  Match Centre (WPL): Delhi Capitals v Royal Challengers Bengaluru, Kotambi Stadium, Vadodara, 2026-02-05 — Royal Challengers Bengaluru won by 6 wickets

Every number the pages show matches the pipeline scripts of 39.3–39.7, because both call the same cached functions with the same windows. To run the dashboard yourself, from the book's root folder: streamlit run project/app.py; the first visit to each page takes 5–20 seconds while it fits, then it is instant. Next, Chapter 40 adds no module. It closes the book with project/ROADMAP.md, and with Nusrat choosing her first extension.


Chapter Summary

The pipeline, one match, six calls:

Stage Module (chapter) Key function(s) IPL 2026 final output
1 Data data (2), explore (3), charts (7) load, batting_card, manhattan, worm GT 155/8; RCB 161/5 in 18 overs; 233 deliveries
2 Metrics batting (8), bowling (14) sr_plus, bowling_profile Patidar SR+ 124.5; Kohli 106.9; B Kumar economy 7.95
3 Win probability winprob (20) build_states, fit_wp, ParWP, wp_curve RCB 0.594 at first ball, 0.865 at innings break
4 Attribution winprob (20), impact (9) turning_points, wpa Top swing Sai Sudharsan out 3.4 (−0.090); top WPA Rasikh Salam +0.112
5 Pre-match match_model (24) fit_pooled_t20, build_predictor GT 0.571 (announced sheets, home) to 0.509 (neutral)
6 Live live (27) LiveChain, project_total, broadcast_line After 10 overs: median 164, 80% 135–195; real 155 inside all 19 ranges

Before you trust a number on a dashboard, check:

  1. Was the model fitted only on matches before the one shown? (Every Crease page: yes, by design.)
  2. Is it the right population's model (men's or women's, IPL era or pooled)?
  3. Is the number shown with a range or a sample size, and is the shrunk value shown rather than the raw?
  4. Does its model card name a baseline it beats out of time, and a failure mode that applies here?
  5. Do the smoke tests pass, and does the system still reproduce the settled numbers?

Key definitions: dependency graph and DAG; three-layer dashboard; caching (st.cache_data v st.cache_resource); WPA; 80% projection range; model card; smoke test; reproduction test.


What's Next

You have built the platform. Chapter 40, The Future of Cricket Analytics, looks up from it: at the data the public record still lacks (ball tracking, player tracking, workload), at what AI can and cannot add, at the ethics of all of it, and at the roadmap of extensions you could start next week.