Data Lab Guide

This guide is for whoever runs the labs: the instructor, a teaching assistant, or the person who builds the lab machine image. It complements the reader-facing Setting Up Your Environment page and Appendix B, which documents every toolkit function and column.


Setup checklist

Work through this before week 1. Allow an afternoon the first time.

On your own machine (two weeks before term)

  • [ ] Python 3.10 or newer installed (the book was run with Python 3.13).
  • [ ] Book folder unpacked to a short path with no special characters (for example C:\cricket\cricket-analytics).
  • [ ] Virtual environment created and activated; pip install -r requirements.txt completed. Check with python -c "import pandas, pyarrow, sklearn, xgboost; print(pandas.__version__)" (2.2 or later).
  • [ ] All twenty archives built: python toolkit/cricdata.py tests_male odis_male t20s_male t20s_female it20s_male odis_female ipl bbl psl cpl sat hnd ilt mlc bpl lpl ntb sma wpl wbb. The IPL alone should report ipl: 1,243 matches, 295,732 deliveries.
  • [ ] Chapter 1's checkpoint passes: from part-01-foundations/chapter-01-cricket-moneyball-moment, run python code/project_checkpoint.py and see READY FOR CHAPTER 2.
  • [ ] Every script you plan to demonstrate has been run once, and its output matches the chapter.
  • [ ] Your Windows console prints ₹ without error (see "Windows" below).

For the lab room

  • [ ] Decide where the data lives. Either each machine builds its own cache in week 1 (about 93 MB download, about 143 MB on disk), or you build it once on the machine image or a network share.
  • [ ] If a network share: check that students can read the Parquet files and that the book folder structure is intact (scripts find toolkit/ and data/ from their own location).
  • [ ] Check RAM. 8 GB is comfortable. On 4 GB machines, avoid loading the full men's Test deliveries (about 2 GB in memory) in a lab; Chapter 2, §2.6 shows how to read only the columns needed.
  • [ ] Install streamlit if you will reach Chapter 39 (it is in requirements.txt).
  • [ ] Put the UTF-8 tip and the troubleshooting table below on the first lab handout.

For students working at home

  • [ ] Set the data build as week-1 homework, with the Chapter 1 checkpoint output as the deliverable.
  • [ ] For students on slow or metered connections, download one archive at a time, starting with ipl, which most chapters use. The toolkit skips archives it already has, so an interrupted run can simply be repeated.
  • [ ] If home bandwidth is a real barrier, offer the built data/ folder on a campus share or a USB drive. Cricsheet's data is released under the Open Data Commons Attribution Licence (ODC-By), which permits sharing with attribution. Keep the licence text that comes in each archive, and read the licence itself rather than relying on this summary.

The toolkit

Three files in toolkit/ form the shared data layer. Every chapter script imports from them.

File What it does Functions students meet first
cricdata.py Downloads Cricsheet archives, parses them into Parquet, and computes the book's standard batting and bowling tables load_deliveries(code), load_matches(code), batting_summary(balls, by=...), bowling_summary(balls, by=...), only_player(balls, name), primary_id(balls, name), load_many(codes), load_people(), download, build
venues.py Maps venues to host countries and condition buckets add_host(matches), add_home_away(balls, matches), condition_bucket(country) → SENA, Subcontinent, West Indies, UAE, Other
tracking_sim.py Attaches simulated tracking columns to real deliveries add_tracking(balls, styles=None, seed=2026)

The definitions in batting_summary and bowling_summary are the book's definitions. Students should use them rather than rebuild their own, because a number then means the same thing in Chapter 4 as in Chapter 34:

  • Balls faced exclude wides (no-balls count). Runs are off the bat.
  • Outs include non-striker run-outs and exclude retired hurt and retired not out.
  • Bowling balls are legal deliveries. Runs conceded exclude byes, leg-byes and penalties (wides and no-balls are charged to the bowler). Wickets are bowled, caught, caught and bowled, lbw, stumped and hit wicket.
  • Phases follow the 1-based over convention (T20 1–6 / 7–15 / 16–20; ODI 1–10 / 11–40 / 41–50; The Hundred by balls 1–25 / 26–75 / 76–100; Tests "none").
  • Both functions drop super-over deliveries.

Use batting_summary(balls, "batter_id") (or by=[..., "batter_id"]) for any work that combines competitions: it groups by registry id and matches outs and innings by id too.

The Crease modules students build live in project/crease/. Each chapter's scripts add toolkit/ and project/ to Python's path through the standard header, so a script can import crease modules written in earlier chapters.


The reference tables

data/reference/ holds the sourced tables that Cricsheet does not provide. Each has a *_SOURCES.md file explaining how it was built.

File Contents Use it for
ipl_auction.csv 879 rows, 2022–2026: auction purchases, retentions, trades and right-to-match signings, with price and base price in lakh, nationality, overseas and capped flags, role, and the Cricsheet name Anchor B and every price-versus-value analysis (Chapters 13, 34). About 91% of rows match Cricsheet names
player_styles.csv 2,011 players (final version): batting hand, bowling style, bowling type (pace/spin), arm, confidence (high/medium/low), notes on shared names Pace/spin and handedness splits (Chapters 10, 11, 15, 16, 18, 31)
player_styles_sim_v1.csv A frozen 1,551-row copy of an earlier styles table Read only by tracking_sim.py (see "Reproducibility")
data/raw/people.csv Cricsheet's people register: about 18,700 people with identifiers linked to other databases Linking ids to names and to other sources

Teach students to report coverage alongside any split that depends on the styles table. Coverage is high (for example, 96.6% of IPL 2026 legal balls have a typed bowler) but not complete, and players who debut after the snapshot are missing. When joining by name, match on gender too: "SR Taylor" is two different players.

Auction money is in ₹ lakh and crore (₹1 crore = 100 lakh). Purses by season: ₹90 crore (2022), ₹95 crore (2023), ₹100 crore (2024), ₹120 crore (2025) and a reported ₹125 crore (2026).


What is real and what is simulated

Real (from Cricsheet, downloadable by anyone) Simulated (the toolkit's sim_* columns, plus Chapter 17's labelled fielding layer) Not available at all
Every delivery: batter, non-striker, bowler, runs off the bat, extras by type, legality, fours and sixes, wickets and their kind, fielders named in dismissals, phase, innings, target (limited-overs), season, date, venue, gender, registry ids Length and line, pitching distance, speed, swing, spin rate, position at the stumps, shot angle, distance and zone Dropped catches, misfields, fielding positions, real Hawk-Eye or DRS values, batting-position labels (inferred from entry), player roles, official session times, weather
Match results, toss, method (rain rule), player of the match Dropped chances and catch difficulty in Chapter 17's simulated fielding layer (attached to real catches; figures anonymised) Afghanistan men's internationals (withheld by Cricsheet: 14 Tests, 162 ODIs, 166 T20Is and 10 non-official T20s in this snapshot)

How the simulation works. Each simulated location is drawn conditioned on the real outcome (a real six is more likely to have been in the slot or short; a real bowled or LBW more likely full and straight) and on format, phase and the bowler's real type. Each player has a stable simulated signature, which is not that player's real signature.

The rules students must follow (enforced in every rubric):

  1. Label every use: a 🧪 Simulated data note in prose, and "simulated tracking layer — real outcomes, simulated locations" in every figure title or caption.
  2. Never state a sim_ number as a fact about a real player.
  3. Teach the method on the simulated layer, then say what a team with the real tracking feed would see differently.

Run Chapter 15's audits (code/03_artefact_audit.py) in a lab before students build anything on the simulated layer. They show how a simulation can manufacture a convincing finding on its own.


Reproducibility

The book's promise is that the same script on the same snapshot gives the same output. Four things make that true, and students should know all four.

  1. The snapshot is fixed. The data was downloaded from Cricsheet on 18 November 2026. The toolkit never refreshes its cache by itself. If a student downloads later, Cricsheet will have added (and occasionally corrected) matches, and the decimal places will move. Keep a copy of the built data/ folder for the whole term and tell students not to refresh mid-course. If they must refresh, they should use download(code, force=True) and build(code, force=True) and expect different numbers.
  2. Seeds everywhere. Every model and simulation in the book sets random_state= or a seed. Require the same in student code. A bootstrap interval that changes on every run is not reproducible, however correct its method.
  3. The simulated layer is deterministic, with one catch. add_tracking(balls, seed=2026) gives the same output for the same input. Its output depends on the exact set of rows passed in, though. House rule: call add_tracking on a whole competition's deliveries (for example all of load_deliveries("ipl")) and then filter. Students who filter first get different simulated values from the book's.
  4. The frozen styles copy. tracking_sim.py reads player_styles_sim_v1.csv, a frozen 1,551-row copy of the styles table, not the live player_styles.csv. That is why the styles table could be extended (to 2,011 rows) without shifting any simulated value. Bowlers absent from the frozen copy get a hash-guessed type in the simulation only. Real pace/spin analysis always uses the live table. Don't let students "fix" the simulator by pointing it at the live table: every simulated number in the book would change.

Library versions can shift the last decimal place of a model's output. Differences larger than that usually mean different data.


Troubleshooting

Symptom Cause Fix
python is not recognized (Windows) Python not on PATH Use py, or rerun the installer with "Add python.exe to PATH" ticked; open a new terminal
ModuleNotFoundError: No module named 'pandas' Virtual environment not active, or install incomplete Activate .venv; rerun pip install -r requirements.txt
ModuleNotFoundError: No module named 'cricdata' Script run from the wrong folder, or moved Run from the chapter folder: python code/01_….py
"Unable to find a usable engine" pyarrow missing pip install pyarrow
UnicodeEncodeError: 'charmap' codec can't encode character '\u20b9' Windows console encoding $env:PYTHONIOENCODING = "utf-8" (PowerShell), set PYTHONIOENCODING=utf-8 (Command Prompt), or python -X utf8 code/…py
PowerShell refuses to activate the environment Execution policy Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, or use Command Prompt and .venv\Scripts\activate.bat
BadZipFile Interrupted download Delete that zip from data/raw/ and its Parquet files from data/processed/; rebuild
Machine slows to a crawl loading Tests Memory Load only needed columns; close other programs
Output differs from the book in the last decimal Library versions Accept it; the method is what matters
Output differs substantially Different data (refreshed snapshot) or filtering before add_tracking Check the match counts against Step 5 of the setup page; follow the add_tracking house rule
A player's numbers look too big Two people with the same name merged Group by id, or use only_player
A notebook gives a different answer from the script Stale variables in the kernel Restart kernel and run all

When in doubt, rerun Chapter 1's code/project_checkpoint.py. It checks the Python version, the libraries, the toolkit and all twenty data files, and compares Kohli's IPL line with the book. It tells you which piece is missing.


Running a lab session

A pattern that works for a 2-hour lab:

  1. Reproduce (15 minutes). Students run the chapter script and confirm one printed number. Nobody moves on until it matches.
  2. Read (15 minutes). In pairs, students annotate the key 20–40 lines of the script: what each block does, and which of the book's definitions it relies on.
  3. Change (45 minutes). The extension: a different competition, women's data, another format, a different k, a different split. Students predict the result before running it.
  4. Interpret (30 minutes). A short written answer: what changed, why, how much to trust it.
  5. Exit (15 minutes). One sentence each: the most surprising number today, with its sample size.

The live-coding demos in each chapter's notes are designed to fit step 3.