Appendix A — Python and python-chess Primer
This appendix is for the chess player who has never written a line of code and would like to — or who has written some, long ago, and wants a single place to look things up. It covers exactly the Python this book uses and no more: enough of the language to read the chapters' code, the python-chess library that turns moves and positions into objects a program can reason about, the pandas library that turns millions of games into tables you can question, and the book's own toolkit, which wraps the Stockfish 19 engine, the diagrams and the datasets.
Every snippet below was run on the book's data snapshot, and every block of output is the real output,
pasted unchanged. The complete scripts live in appendices/code/:
| Script | What it runs |
|---|---|
a01_primer.py |
Sections A.3–A.10: boards, FEN, PGN, iterating games, legal moves, engines, diagrams, pandas |
a02_python_basics.py |
Section A.2: the language itself, with chess-flavoured examples |
Run them from the book's root folder with python appendices/code/a01_primer.py. The first script takes
about half a minute; most of that is loading four million Lichess games into memory.
♟️ Improver Track: Read A.2–A.5 and A.9. That is enough to follow the code in Part I and to draw your own diagrams. Come back for the rest when a chapter sends you here.
📊 Analyst Track: A.6, A.8 and A.10 are the working core: iterating games, asking the engine, and grouping a table by rating band. Pair this appendix with Appendix B, which documents every column you will touch.
💻 Developer Track: Skim A.2, then read A.7 (move generation and perft) and A.8 (the engine wrapper, caching and parallel analysis) carefully — they are what the Outpost project builds on.
A.1 Setting up
What you need
| Component | Version used in this book | Where it comes from |
|---|---|---|
| Python | 3.13 (any 3.11+ should work) | python.org; on Windows tick "Add python.exe to PATH" |
| python-chess | 1.11.2 | pip install python-chess (imported as chess) |
| pandas | 2.3 | pip install pandas |
| pyarrow | 24.0 | reads the book's .parquet files |
| numpy, matplotlib, seaborn, scipy, scikit-learn | recent releases | pip install ... |
| requests, zstandard | recent releases | network calls (cached) and compressed downloads |
| Stockfish | 19 | stockfishchess.org — the binary goes in engine/stockfish.exe |
The book's root folder contains a requirements.txt listing the minimum versions, so the whole Python side
is one command:
python -m venv .venv
.venv\Scripts\activate (Windows) | source .venv/bin/activate (macOS / Linux)
pip install -r requirements.txt
A virtual environment (.venv) is a private copy of Python for this project, so the libraries you
install here cannot break anything else on your computer. Activate it in every new terminal before you run
the book's code.
Stockfish is a separate program, not a Python library. Download the build for your operating system and put
the executable at engine/stockfish.exe inside the book folder — or anywhere you like, with the environment
variable STOCKFISH_PATH pointing to it. The toolkit finds it either way.
The book's folder layout
chess-analytics/
├── toolkit/ chessdata.py, engine.py, boards.py, structures.py (the shared code)
├── data/
│ ├── processed/ the parquet tables (Appendix B)
│ ├── cache/ engine.sqlite, tablebase.sqlite, explorer/, chesscom/
│ └── reference/ small CSV/parquet tables quoted in the chapters
├── engine/ stockfish.exe
├── project/outpost/ the Outpost package you build chapter by chapter
├── part-01-.../chapter-01-.../code/ each chapter's scripts
└── appendices/code/ the scripts behind Appendices A-E
The standard script header
Every script in the book starts the same way. Here is the version for a chapter script (three folders below the root):
import sys
from pathlib import Path
sys.stdout.reconfigure(encoding="utf-8") # chess symbols print on Windows too
BOOK = Path(__file__).resolve().parents[3] # ...\chess-analytics
sys.path.insert(0, str(BOOK / "toolkit")) # so "import chessdata" works
sys.path.insert(0, str(BOOK / "project")) # so "from outpost import ..." works
import matplotlib
matplotlib.use("Agg") # draw to files, never open a window
import chess
import chessdata, boards, engine # the book's toolkit
Line by line: sys.stdout.reconfigure makes the terminal accept characters such as ♟ and –; Path(__file__)
is the script's own location, and .parents[3] walks three folders up to the book's root (an appendix
script is two folders deep, so it uses .parents[2]); sys.path.insert tells Python where to look for the
toolkit; matplotlib.use("Agg") lets charts be saved without a screen.
⚠️ Common pitfall: running a script from the wrong folder. The header above makes every path relative to the script's own location, so it works from anywhere. If you write your own scripts with paths like
"data/processed/..."they will only work when the terminal sits in the book's root. Build paths fromBOOKinstead.⚠️ Common pitfall (Windows): any script that analyses games in parallel (
engine.analyse_games_parallel) must put its main code underif __name__ == "__main__":. Windows starts each worker by re-importing your script; without the guard every worker tries to start its own workers.
A.2 Python in one sitting
You do not need to become a programmer to use this book; you need to read a dozen kinds of statement. Here they all are, with chess on the board.
# variables and types
rating = 1650 # an int
opponent = 1720
expected = 1 / (1 + 10 ** ((opponent - rating) / 400)) # a float
name = "Dev" # a str
won = False # a bool
print(name, rating, round(expected, 3), won)
# lists: ordered, indexable from 0
moves = ["e4", "c5", "Nf3", "d6", "d4"]
print(moves[0], moves[-1], len(moves), moves[1:3])
moves.append("cxd4")
print(moves)
# dictionaries: key -> value
values = {"P": 1, "N": 3, "B": 3, "R": 5, "Q": 9}
print(values["R"], "Q" in values, values.get("K", 0))
Dev 1650 0.401 False
e4 d4 5 ['c5', 'Nf3']
['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4']
5 True 0
A few things to notice. # starts a comment — Python ignores the rest of the line. ** is "to the power
of". List positions start at 0, so moves[0] is the first move and moves[-1] the last; moves[1:3]
is a slice, positions 1 and 2 (the end is excluded). A dictionary looks values up by key; .get("K", 0)
returns 0 instead of crashing when the key is missing.
# loops and conditions
material = 0
for piece in ["Q", "R", "R", "B", "N", "P", "P"]:
material += values[piece]
print("material:", material)
for score in (1, 0.5, 0):
if score == 1:
word = "win"
elif score == 0.5:
word = "draw"
else:
word = "loss"
print(score, word)
# functions
def expected_score(ra, rb):
"""Elo expected score of a player rated ra against rb."""
return 1 / (1 + 10 ** ((rb - ra) / 400))
print(f"1500 vs 1700: {expected_score(1500, 1700):.3f}")
# list comprehension: build a list in one line
gaps = [0, 100, 200, 400]
print([round(expected_score(1500 + g, 1500), 3) for g in gaps])
# errors are information
try:
values["K"]
except KeyError as e:
print("KeyError for", e)
material: 27
1 win
0.5 draw
0 loss
1500 vs 1700: 0.240
[0.5, 0.64, 0.76, 0.909]
KeyError for 'K'
Indentation is grammar in Python: the four spaces under for, if and def mark which lines belong
to the loop, the branch or the function. def defines a function; the text in triple quotes right under it
is its docstring, the documentation you see with help(expected_score). An f-string (f"...") puts
values inside text; {x:.3f} means "x with three decimals". A list comprehension — [... for g in gaps]
— is a compact loop that builds a list. And try/except catches an error instead of stopping the
program. In this book an error is almost always information: an IllegalMoveError means a move you typed is
not legal in that position, which is exactly the check we want (see A.3).
The expected-score function above is the Elo formula you will meet in
Chapter 30; the toolkit has the canonical
version, chessdata.expected_score, which you should use in real code so every chapter agrees.
Two libraries do the heavy lifting with numbers and tables:
import numpy as np
import pandas as pd
scores = np.array([1, 0.5, 0, 1, 1])
print("mean score:", scores.mean())
df = pd.DataFrame({"opening": ["Italian", "Italian", "Najdorf", "Najdorf", "Najdorf"],
"score": [1, 0.5, 0, 0, 1]})
print(df.groupby("opening").score.agg(["mean", "size"]))
mean score: 0.7
mean size
opening
Italian 0.750000 2
Najdorf 0.333333 3
import numpy as np loads a library under a short nickname. A numpy array does arithmetic on a whole
list of numbers at once. A pandas DataFrame is a table with named columns, and groupby(...).agg(...)
is the single most-used line in Part VI: split the table by a column, summarise each group. Section A.10
does the same thing on four million real games.
🔄 Check your understanding 1. What does
moves[2]return formoves = ["e4", "c5", "Nf3", "d6"]? 2. Why doesvalues.get("K", 0)not crash whenvalues["K"]does? 3. In thegroupbyoutput, why is the Najdorf's mean 0.333?
Answer
"Nf3"— positions count from 0. 2..getreturns the default (0) when the key is missing; square brackets raiseKeyError. 3. Three Najdorf games scored 0, 0 and 1: one point in three games.
A.3 Boards, moves and SAN
python-chess represents a position as a chess.Board. You create one, play moves on it, ask it questions,
and take moves back. Everything else in the book is built on these few operations.
import chess
board = chess.Board() # the starting position
print(board) # ASCII diagram, White at the bottom
print("legal moves:", board.legal_moves.count())
board.push_san("e4") # play a move written in SAN
board.push_san("e5")
board.push_san("Nf3")
print("after 1.e4 e5 2.Nf3 - side to move:", "White" if board.turn == chess.WHITE else "Black")
move = board.parse_san("Nc6") # SAN -> Move object (raises ValueError if illegal)
print("Nc6 as a Move:", move, "| from", chess.square_name(move.from_square), "to", chess.square_name(move.to_square))
print("same move in UCI:", move.uci(), "| back to SAN:", board.san(move))
board.push(move)
print("last move popped:", board.pop(), "| moves played so far:", len(board.move_stack))
try:
board.push_san("Ke2") # illegal for Black here: the king cannot reach e2
except ValueError as e:
print("illegal move rejected:", type(e).__name__)
print("piece on f3:", board.piece_at(chess.F3), "| is e5 attacked by White?",
board.is_attacked_by(chess.WHITE, chess.E5))
print("White attackers of e5:", [chess.square_name(s) for s in board.attackers(chess.WHITE, chess.E5)])
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q K B N R
legal moves: 20
after 1.e4 e5 2.Nf3 - side to move: Black
Nc6 as a Move: b8c6 | from b8 to c6
same move in UCI: b8c6 | back to SAN: Nc6
last move popped: b8c6 | moves played so far: 3
illegal move rejected: IllegalMoveError
piece on f3: N | is e5 attacked by White? True
White attackers of e5: ['f3']
The vocabulary:
| Concept | python-chess | Meaning |
|---|---|---|
| Position | chess.Board() / chess.Board(fen) |
pieces, side to move, castling rights, en-passant square, move counters, and the move history |
| Square | chess.E4, chess.square_name(sq), chess.parse_square("e4") |
an integer 0–63 (a1 = 0, h8 = 63) with a name |
| Move | chess.Move.from_uci("g1f3") |
from-square, to-square, optional promotion piece |
| SAN | board.san(move), board.parse_san("Nf3"), board.push_san("Nf3") |
Standard Algebraic Notation — needs the board, because "Nf3" only means something in a position |
| UCI notation | move.uci() → "g1f3" |
from-square + to-square (+ promotion letter): what engines speak |
| Play / undo | board.push(move), board.pop() |
move_stack remembers every move, so you can step back |
| Questions | is_check(), is_checkmate(), is_stalemate(), is_capture(m), gives_check(m), is_attacked_by(color, sq), attackers(color, sq), piece_at(sq) |
the building blocks of every feature in Parts I–II |
| Colours | chess.WHITE (True), chess.BLACK (False); board.turn |
side to move |
SAN versus UCI. SAN (Nc6) is what humans write and what PGN files store; it depends on the position
(which knight? the one that can reach c6). UCI notation (b8c6) names the squares outright, so an engine can
read it without knowing the position's history. Converting between them always needs a board:
board.san(move) and board.parse_san(text). Appendix C covers
both notations in full, including disambiguation, promotion and castling.
🔍 Why this works:
push_sanis a legality check. python-chess generates the legal moves of the position and looks for one that matches your text; if none does, it raisesIllegalMoveError(a kind ofValueError). That is why the book insists every opening line be replayed through python-chess: a typo in a move list becomes an error you see, not a wrong diagram a reader sees.⚠️ Common pitfall:
board.push(move)does not check legality — it plays whateverMoveobject you hand it. Usepush_san, or testmove in board.legal_movesfirst, whenever the move comes from outside your own code.
A.4 FEN: a position in one line
A FEN (Forsyth–Edwards Notation) string describes a position completely — except the move history — in six space-separated fields. It is how the book stores positions, how the engine cache keys them, and how you can paste a position from any chess website into Python.
print("FEN:", board.fen())
b2 = chess.Board("r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3")
print("loaded, White to move:", b2.turn == chess.WHITE, "| castling rights FEN field:", b2.fen().split()[2])
print("move number:", b2.fullmove_number, "| half-move clock:", b2.halfmove_clock)
FEN: rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2
loaded, White to move: True | castling rights FEN field: KQkq
move number: 3 | half-move clock: 2
The six fields of rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2:
| Field | Value here | Meaning |
|---|---|---|
| 1. Placement | rnbqkbnr/.../RNBQKB1R |
ranks 8 → 1, files a → h; upper case White, lower case Black; digits = empty squares |
| 2. Side to move | b |
Black to move |
| 3. Castling | KQkq |
which castlings are still allowed (not whether they are legal right now) |
| 4. En passant | - |
target square if an en-passant capture is possible (conventions differ — Appendix C) |
| 5. Half-move clock | 1 |
plies since the last capture or pawn move (for the 50- and 75-move rules) |
| 6. Full-move number | 2 |
starts at 1, increases after Black's move |
board.fen() writes it, chess.Board(fen) reads it, and board.board_fen() returns only the first field —
handy for asking "is this the same arrangement of pieces?" regardless of move counters. The toolkit's engine
cache uses the first four fields (placement, side, castling, en passant), so the same position reached at move
12 or move 30 shares one cached evaluation — even though a full-game analysis, which passes the move history
to Stockfish, may have scored that position as a repetition draw (Appendix B,
B.11, explains the consequence).
⚠️ Common pitfall: a position copied from a diagram without the side-to-move field is ambiguous, and the evaluation can swing by a full tempo — about 0.64 pawns in the starting position by the pass test of Chapter 19. Always set the second field deliberately.
A.5 Reading PGN: a real game from the book's data
PGN (Portable Game Notation) is the text format every chess database uses: a block of [Tag "value"]
headers followed by the moves in SAN, with optional comments in braces. The toolkit stores games as PGN text
inside its tables, and chessdata.find_game retrieves them. Here is the Opera Game — Morphy against the
Duke of Brunswick and Count Isouard in consultation, Paris 1858 — loaded from the PGN Mentor collection, never
typed from memory:
row = chessdata.find_game(white="Morphy", black="Isouard").iloc[0]
game = chessdata.game_from_row(row)
for k in ("Event", "Site", "Date", "White", "Black", "Result"):
print(f" {k}: {game.headers.get(k)}")
sans = []
b = game.board()
for mv in game.mainline_moves():
sans.append(b.san(mv))
b.push(mv)
print("plies:", len(sans), "| first six:", " ".join(sans[:6]), "| last:", sans[-1])
print("final position is checkmate:", b.is_checkmate())
counts = []
b = game.board()
for mv in game.mainline_moves():
counts.append(b.legal_moves.count())
b.push(mv)
print(f"legal moves per position: mean {sum(counts) / len(counts):.1f}, min {min(counts)}, max {max(counts)}")
Event: Paris it
Site: Paris
Date: 1858.??.??
White: Morphy, Paul
Black: Duke Karl Count Isouard
Result: 1-0
plies: 33 | first six: e4 e5 Nf3 d6 d4 Bg4 | last: Rd8#
final position is checkmate: True
legal moves per position: mean 31.7, min 1, max 51
Three objects are in play. row is one row of a pandas table (the pgn column holds the full text).
game is a chess.pgn.Game: headers in game.headers (a dictionary-like object), the move tree hanging
below it. And game.board() returns the starting position of that game (usually the standard one; a
SetUp/FEN header would change it). The loop pattern — make a fresh board, walk
game.mainline_moves(), push each move — is the most common loop in the book. Inside it you can measure
anything about each position before or after the move: here, the number of legal moves, which averaged 31.7
in this short game.
Useful chess.pgn tools:
| Call | Returns |
|---|---|
chess.pgn.read_game(stream) |
the next game from a text stream, or None at the end |
game.headers["White"] |
a header value |
game.mainline_moves() |
the moves of the main line (variations skipped) |
game.mainline() |
the nodes of the main line — each has .move, .comment, .eval(), .clock() |
node.eval() |
the [%eval ...] annotation as a score object (Appendix C) |
node.clock() |
the [%clk ...] annotation in seconds |
game.end().board() |
the final position |
str(game) |
the game written back out as PGN |
⚠️ Common pitfall:
find_gamereturns every row that matches the name substrings, in table order. When two players met many times,.iloc[0]silently picks the first one — which may be a blitz game. Addyear=,event=orresult=filters until exactly one row is left, and print the headers to confirm.
A.6 Iterating over many games
One game is an anecdote; the book's arguments rest on thousands. Two patterns cover almost everything.
Pattern 1 — work on a table first, parse only what you need. The tables already contain results, ratings, ECO codes and move counts, so many questions never need python-chess at all:
morphy = chessdata.master_games(player="Morphy")
print("games in the Morphy collection:", len(morphy))
as_white = morphy[morphy.white.str.contains("Morphy")]
print("as White:", len(as_white), "| score as White:", round(as_white.score_white.mean() * 100, 1), "%")
games in the Morphy collection: 211
as White: 136 | score as White: 91.2 %
Pattern 2 — stream PGN text game by game. When you do need the moves, read games one at a time from a text stream; memory use stays small however many games you have:
import io
pgn_text = "\n\n".join(morphy.pgn.head(3))
stream = io.StringIO(pgn_text)
n = 0
while True:
g = chess.pgn.read_game(stream)
if g is None:
break
n += 1
print(f" game {n}: {g.headers['White']} - {g.headers['Black']}, {g.headers['Result']}, "
f"{len(list(g.mainline_moves()))} plies")
game 1: Morphy, Paul - Anderssen, Adolf, 1-0, 37 plies
game 2: Anderssen, Adolf - Morphy, Paul, 1-0, 63 plies
game 3: Anderssen, Adolf - Morphy, Paul, 0-1, 70 plies
The same loop reads a .pgn file you downloaded from Lichess or Chess.com: replace io.StringIO(...) with
open("my_games.pgn", encoding="utf-8"). The Outpost module games.py from
Chapter 1 wraps exactly this
in read_pgn_file(path) and returns tidy GameRecord objects.
A speed rule for big jobs. Notice what is expensive. Reading a table: seconds. Parsing PGN into python-chess
objects: roughly a millisecond or more per game. Asking Stockfish about every position: about 130 ms per position at depth 16 on the book's machine. Filter the table first, parse second, call the engine last — and only on the positions that matter.
A.7 Legal moves and move generation
board.legal_moves generates every legal move in a position. Counting the leaves of the move tree to a
fixed depth is called perft (performance test) and is how engine authors check that their move generator
is correct — the counts from the starting position are known exactly.
def perft(bd, depth):
if depth == 0:
return 1
total = 0
for mv in bd.legal_moves:
bd.push(mv)
total += perft(bd, depth - 1)
bd.pop()
return total
start = chess.Board()
print("perft 1..3 from the start:", [perft(start, d) for d in (1, 2, 3)])
b = chess.Board("r1bqkbnr/pppp1ppp/2n5/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3")
caps = [b.san(m) for m in b.legal_moves if b.is_capture(m)]
checks = [b.san(m) for m in b.legal_moves if b.gives_check(m)]
print("Black to move after 3.Bc4: legal", b.legal_moves.count(), "| captures", caps, "| checks", checks)
perft 1..3 from the start: [20, 400, 8902]
Black to move after 3.Bc4: legal 31 | captures [] | checks []
perft is a recursive function: it calls itself one level deeper for every legal move, pushing the move
before the call and popping it after, so the board is back where it started when the loop ends. 20, 400 and
8,902 are the published values, so python-chess passes. The second half shows the filters the calculation
chapters lean on: captures and checks are the first two items of the "checks, captures, threats" scan in
Chapter 10, whose Outpost module calc.py
adds the third. In this quiet Italian position Black has 31 legal moves and not a single capture or check.
| Generator | Yields |
|---|---|
board.legal_moves |
legal moves (.count() is fast) |
board.pseudo_legal_moves |
moves that ignore whether your own king is left in check |
board.generate_legal_captures() |
legal captures only |
board.attacks(sq) |
squares the piece on sq attacks (a SquareSet) |
board.pieces(chess.KNIGHT, chess.WHITE) |
squares of White's knights (a SquareSet) |
🔄 Check your understanding Why does the
perftfunction needbd.pop()after the recursive call?
Answer
pushchanges the board in place. Withoutpop, the next move in the loop would be played on top of the previous one, in a position that no longer exists in the game tree; the counts would be wrong (and usually the loop would hit illegal positions).
A.8 Asking the engine
An engine is a separate program; Python talks to it through the UCI protocol (Universal Chess
Interface), a short text conversation described in Appendix C.
python-chess speaks UCI for you, and the book's toolkit/engine.py adds a permanent cache and the book's
metrics on top.
Raw python-chess
import chess.engine
with chess.engine.SimpleEngine.popen_uci(str(BOOK / "engine" / "stockfish.exe")) as sf:
print("engine:", sf.id["name"])
info = sf.analyse(chess.Board(), chess.engine.Limit(depth=12))
print("start position, depth 12 (fresh search, not cached):", info["score"].white(),
"| best move:", chess.Board().san(info["pv"][0]))
engine: Stockfish 19
start position, depth 12 (fresh search, not cached): +32 | best move: e4
popen_uci starts Stockfish as a child process; the with block makes sure it is shut down afterwards.
sf.analyse(board, limit) searches the position and returns a dictionary: info["score"] is a score from the
side to move's view, so the book always calls .white() to turn it into White's view; info["pv"] is the
principal variation, the line the engine expects. A Limit can be a depth, a time (time=0.5 seconds) or a
node count. Scores print as +32 (centipawns, hundredths of a pawn) or #5 (mate in five).
The toolkit wrapper
For book work, use the toolkit. It stores every evaluation in data/cache/engine.sqlite, keyed by position,
depth, number of lines and engine version, so the same question always gets the same answer — the property
that lets a chapter quote "+0.30 at depth 20" and a reader reproduce it exactly.
r = engine.evaluate(chess.STARTING_FEN, depth=20) # cached in data/cache/engine.sqlite
print(f"toolkit evaluate(start, depth=20): cp {r['cp']}, best {r['pv'][0]}, "
f"win% for White {r['win_pct_white']:.1f}")
df = engine.analyse_game(row.pgn, depth=16)
print(engine.game_summary(df).to_string())
cm = engine.critical_moments(df, n=3)
print(cm[["ply", "move_no", "side", "san", "eval_before", "eval_after", "wp_drop"]].to_string(index=False))
toolkit evaluate(start, depth=20): cp 30, best e4, win% for White 52.8
moves acpl accuracy inaccuracies mistakes blunders
side
black 16 59.9 88.9 2 2 0
white 17 7.5 98.2 0 0 0
ply move_no side san eval_before eval_after wp_drop
12 6 black Nf6 129.0 275.0 11.695945
18 9 black b5 269.0 503.0 13.518924
20 10 black cxb5 480.0 704.0 7.622304
So the starting position is +0.30 (Stockfish 19, depth 20) and 1.e4 is the engine's choice; the Lichess
win% model (see Appendix D) turns +0.30 into a 52.8% expectation for White.
analyse_game evaluates every position of the Opera Game at depth 16 and returns one row per ply with the
evaluation before and after, the engine's best move, centipawn loss, win-% drop, move accuracy and the
Lichess-style classification. game_summary condenses it: Morphy's 17 moves average 7.5 centipawns of loss
(book accuracy 98.2), the allies' 16 moves 59.9 (88.9), with two mistakes. The three largest drops in Black's
winning chances were 6...Nf6, 9...b5 and 10...cxb5 — none of them a 15-point blunder by the book's
definition, which is a fair summary of the Opera Game: Black never made one catastrophic move; Morphy
punished a sequence of slow ones.
The conventions that make engine numbers comparable across the book:
| Convention | Rule |
|---|---|
| Point of view | cp, eval_before, eval_after are always White's point of view, in centipawns |
| Mover's view | cpl, wp_before, wp_after, wp_drop, accuracy are from the side that moved |
| Clipping | evaluations are clipped to ±1000 cp; a mate becomes ±1000 |
| Depth | always stated: write evals as "+0.83 (Stockfish 19, depth 20)" |
| Cache | the same (position, depth, lines) returns the same stored number; a cold re-search can differ by a few centipawns |
| Lines | evaluate(fen, depth, multipv=3) returns a list of three lines; single-line and multi-line searches of the same position can disagree slightly — say which you quote |
⚠️ Common pitfall: quoting an evaluation without its depth, or comparing a depth-12 number with a depth-24 one. Kasparov–Topalov 1999 is the book's standing example: Stockfish 19 chooses 24.Rxd4 at every depth from 12 to 32 but rates it between −0.46 (depth 12) and −0.17 (depth 32) — never winning (Chapter 1).
Many games at once
engine.analyse_games_parallel(pgns, depth=16, workers=2) runs one Stockfish per worker process and
returns the concatenated per-ply table with a game_index column. On the book's machine depth 16 costs
about 130 ms per position on one thread, so a 70-ply game takes roughly nine seconds cold and is instant
from the cache. Keep the worker count modest — each worker is a full engine — and remember the
if __name__ == "__main__": guard on Windows.
A.9 Drawing diagrams
The toolkit's boards.py draws every diagram in the book with matplotlib — no image files of pieces are
needed, because the pieces are Unicode chess glyphs.
b = game.board()
moves = list(game.mainline_moves())
for mv in moves[:30]: # 30 plies played: White to play 16.Qb8+ (ply 31)
b.push(mv)
boards.save_board(IMG / "app-a-pos-01-opera-before-16qb8.png", b, arrows=[("b3", "b8", "green")],
title="Morphy - Duke Karl / Count Isouard, before 16.Qb8+")
print("saved diagram; FEN:", b.fen())
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 3.2))
boards.eval_graph(df, ax=ax, title="Opera Game, Stockfish 19 depth 16")
fig.savefig(IMG / "app-a-fig-01-opera-eval-graph.png", dpi=120, bbox_inches="tight", facecolor="white")
plt.close(fig)
saved diagram; FEN: 4kb1r/p2n1ppp/4q3/4p1B1/4P3/1Q6/PPP2PPP/2KR4 w k - 0 16
saved eval graph

♟️ Position: White Kc1, Qb3, Rd1, Bg5, a2, b2, c2, f2, g2, h2, e4; Black Ke8, Qe6, Rh8, Bf8, Nd7, e5, a7, f7, g7, h7 — White to move. FEN:
4kb1r/p2n1ppp/4q3/4p1B1/4P3/1Q6/PPP2PPP/2KR4 w k - 0 16

📊 Figure (described): White's win % after every ply of the Opera Game, Stockfish 19 at depth 16. The curve climbs in three steps — after 6...Nf6, 9...b5 and 10...cxb5, the three moves marked — and is above 90% from move 10 on. Morphy's advantage was built by the allies' slow moves, then cashed in by a combination.
The two calls you will use most:
| Call | Key arguments |
|---|---|
boards.save_board(path, board_or_fen, ...) |
arrows=[("b3","b8","green")], highlights={"e5": "yellow"}, heat={sq: value}, pawns_only=True (the skeleton), flipped=True (Black at the bottom), title=, caption= |
boards.eval_graph(df, ax=None, critical=None, n_critical=3, title=) |
draws White's win % from an analyse_game table and labels the critical moves |
boards.draw_control_map(board) shades each square by White-minus-Black attackers, and boards.board_grid
lays several positions side by side. Appendix B lists every argument.
Arrow colours are named ("green" for plans, "red" for threats, "blue", "orange", "yellow") and were
chosen to stay distinguishable for colour-blind readers.
📋 Try it — Engine analysis. Load Kasparov–Topalov 1999 with
chessdata.find_game(white="Kasparov", black="Topalov", year=1999, event="Hoogovens"), draw the position before White's 24th move with an arrow d1–d4, and evaluate it at depths 12 and 20.
Answer
The position before 24.Rxd4 is reached after 46 plies (
moves[:46]), andsans[46]isRxd4(ply 47). At depth 12 Stockfish 19 already picks 24.Rxd4 but scores the position −0.46; deeper searches keep the move and keep the evaluation slightly negative (−0.33 at depth 20 in the book's cache). The lesson of Chapter 1 — the engine agrees with the move but not with the legend that it was winning — is now something you have checked yourself.
A.10 pandas on the book's tables
The book's datasets are stored as parquet files: compressed, column-oriented tables that pandas reads in
seconds. You can read them directly with pd.read_parquet, but the toolkit's loaders add the book's
definitions (average rating, rating difference, White's score, bot exclusion), so start there.
g = chessdata.lichess_games(speed="blitz", balanced=True)
print("balanced human blitz games:", len(g))
g["band"] = chessdata.rating_bands(g.avg_elo)
t = g.groupby("band", observed=True).agg(games=("score_white", "size"),
white_score=("score_white", "mean"),
draws=("result", lambda s: (s == "1/2-1/2").mean()))
t["white_score"] = (t.white_score * 100).round(1)
t["draws"] = (t.draws * 100).round(1)
print(t.to_string())
balanced human blitz games: 1583582
games white_score draws
band
<1000 80493 52.2 3.9
1000-1199 145182 51.9 3.4
1200-1399 230619 51.8 3.4
1400-1599 310101 51.5 3.7
1600-1799 338336 51.7 4.1
1800-1999 276887 51.7 4.6
2000-2199 143757 51.8 5.5
2200-2399 45274 52.4 7.1
2400+ 12933 52.4 9.0
That is a complete database study in eight lines: White scores between 51.5% and 52.4% in every band of balanced Lichess blitz games (opponents within 100 points), while the draw rate climbs from 3.4% to 9.0% as the average rating rises. The idioms:
| Idiom | What it does |
|---|---|
df[df.speed == "blitz"] |
keep rows where a condition is true (combine with &, |, ~ and parentheses) |
df["band"] = ... |
add a column |
df.groupby("band", observed=True) |
split by a column; observed=True skips empty categories of a categorical column |
.agg(name=(column, function)) |
named summaries per group: "size", "mean", "median", or your own function |
lambda s: (s == "1/2-1/2").mean() |
a one-line function; the mean of a True/False column is a share |
.query("size >= 20000") |
filter with a small expression language |
.sort_values("mean", ascending=False).head(5) |
rank and keep the top rows |
top = (g.groupby("eco", observed=True).score_white.agg(["size", "mean"])
.query("size >= 20000").sort_values("mean", ascending=False).head(5))
print((top.assign(mean=lambda d: (d["mean"] * 100).round(1))).to_string())
size mean
eco
C44 37408 54.1
C23 20649 53.4
D02 40510 53.0
D00 74604 52.9
C41 39246 52.5
Among ECO codes with at least 20,000 balanced blitz games, C44 (king's-pawn openings with 2...Nc6, including the Scotch) scores best for White at 54.1%. Before you rush to play it, read Appendix E on selection: who chooses an opening is part of why it scores what it scores.
Reading a parquet file directly, and weights
Sometimes you want only a few columns of a big table — reading four columns of game_features takes a
fraction of the time of loading all 78. Then you are responsible for the book's filters yourself:
import pandas as pd
gf = pd.read_parquet(BOOK / "data" / "processed" / "game_features.parquet",
columns=["source", "endgame_ply", "pure_endgame_ply", "sample_weight", "white_title",
"black_title"])
li = gf[(gf.source == "lichess") & ~chessdata.is_bot_game(gf)]
raw = li.endgame_ply.notna().mean() * 100
w = (li.endgame_ply.notna() * li.sample_weight).sum() / li.sample_weight.sum() * 100
print(f"Lichess games reaching a book endgame: unweighted {raw:.1f}% vs weighted {w:.1f}%")
Lichess games reaching a book endgame: unweighted 51.6% vs weighted 51.8%
game_features keeps every Lichess game that the server analysed but only one in eight of the others, so
each un-analysed game carries sample_weight = 8. A weighted share is sum(indicator × weight) / sum(weight).
Here the two numbers happen to be close (51.6% vs 51.8%); for other questions — anything that correlates with
whether someone asked for computer analysis — they are not, and the weighted number is the one that describes
the Lichess population. Appendix B explains why, and
Appendix E shows how different the analysed games are.
⚠️ Common pitfall: filtering bot games with
df.white_title != "BOT". The title columns use pandas' nullable string type, where an untitled player is<NA>, and<NA> != "BOT"is not True but<NA>— so the mask silently drops every untitled player. On the full Lichess table that naive mask keeps 2,384 of 4,000,000 games instead of the correct 3,979,052 (run in Appendix B). Usechessdata.is_bot_game(df), or.fillna("")before comparing.⚠️ Common pitfall: pandas "SettingWithCopyWarning". If you filter a table and then add a column, call
.copy()after the filter (sub = df[df.speed == "rapid"].copy()), so pandas knows you mean a new table.
A.11 When things go wrong
| Message or symptom | Likely cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'chessdata' |
the toolkit folder is not on the path | use the standard header (A.1); check BOOK points at the root |
ModuleNotFoundError: No module named 'chess' |
python-chess not installed in this environment | activate .venv, then pip install python-chess |
IllegalMoveError: illegal san: 'Nf6' in ... |
the move is not legal in that position — often a wrong move number or a missing move | print board, board.fen() and the moves played so far |
FileNotFoundError ... run scripts/build_... first |
a data file is missing | rebuild it with the named script in scripts/ |
Engine FileNotFoundError / EngineTerminatedError |
Stockfish not at engine/stockfish.exe, or the machine is overloaded |
set STOCKFISH_PATH; run fewer workers |
| Script hangs or spawns endless processes on Windows | parallel analysis without the __main__ guard |
put the main code under if __name__ == "__main__": |
UnicodeEncodeError: 'charmap' codec |
the Windows console cannot print ♟ or ≥ |
sys.stdout.reconfigure(encoding="utf-8") at the top |
| A filter returns far fewer rows than expected | <NA> in a string column, or a category typo |
.fillna(""), check df[col].value_counts(dropna=False) |
TypeError: boolean value of NA is ambiguous |
converting a column with missing values to bool |
compare explicitly: .eq("True"), or use chessdata.game_features() |
| A number differs slightly from the book's | different depth, a multi-line search, or a cold (uncached) search | match depth and multipv; the cache makes repeat runs identical |
A.12 A first complete project: one player's first moves
Everything above fits together in about thirty lines. The question: which first move does a strong online
player choose as White, and does any of them score better than his ratings predict? The data: Hikaru
Nakamura's public Chess.com archive, which the toolkit has cached (public account of a public figure; the
ratings are Chess.com's own blitz ratings, not FIDE). The script is appendices/code/a04_mini_project.py.
a = chessdata.chesscom_archive("Hikaru") # cached parquet, no network
a = a[(a.rules == "chess") & (a.time_class == "blitz") & (a.end_time.dt.year == 2026)]
w = a[a.color == "white"].copy()
print("blitz games in 2026:", len(a), "| as White:", len(w))
first = re.compile(r"\n1\. ([^\s{]+)")
w["first"] = w.pgn.str.extract(first, expand=False)
w["expected"] = chessdata.expected_score(w.my_rating, w.opp_rating)
t = w.groupby("first").agg(games=("score", "size"), points=("score", "sum"), expected=("expected", "mean"))
t = t[t.games >= 30].sort_values("games", ascending=False)
t["score %"] = (t.points / t.games * 100).round(1)
t["expected %"] = (t.expected * 100).round(1)
t["95% CI"] = [wilson(p, n) for p, n in zip(t.points, t.games)]
print(t[["games", "score %", "expected %", "95% CI"]].to_string())
blitz games in 2026: 3444 | as White: 1730
games score % expected % 95% CI
first
b3 591 94.6 93.8 (92.5, 96.1)
e4 576 87.2 87.2 (84.3, 89.7)
d4 362 86.7 86.9 (82.9, 89.9)
c4 127 81.9 84.8 (74.3, 87.6)
Nf3 52 81.7 86.3 (69.2, 89.9)
Walk through the steps. Filter the archive to standard chess (rules == "chess" — the archive also holds
Chess960, Crazyhouse and odds games), blitz, games ending in 2026. Pull the first move out of each PGN with a
regular expression (a text pattern: "a newline, 1., a space, then everything up to the next space or
brace"). Compute the Elo-expected score of every game from the two ratings. Group by first move; keep moves
played at least 30 times. Add a Wilson interval (wilson is the eight-line function in the script; the
statistics are in Appendix E).
The answer is a lesson in its own right. The most frequent first move in 2026 blitz was 1.b3 (591 games), not 1.e4 — but every first move scores within a few points of what the ratings predict, and every expected score sits inside the first move's 95% interval. The raw scores (94.6% with 1.b3, 81.7% with 1.Nf3) differ because the opponents differ, not because one move is better. That pattern — a raw difference that vanishes against expectation — recurs throughout the book, most famously in the opening-preparation chapters (Chapter 20 and Chapter 24).
📋 Try it — Database research. Change the script to Black's replies to 1.e4 (filter
color == "black"and extract the move after1. e4), or to GothamChess's archive. Which replies are played at least 30 times, and does any interval exclude its expected score?
Answer
The pattern to extract becomes
r"\n1\. e4 (?:\{[^}]*\} )?1\.\.\. ([^\s{]+)"because Chess.com PGNs put a clock comment after each move. What you find depends on the year you filter; the method is the point: group, count, compare with the expected score, and believe a difference only when the interval excludes the expectation.
A.13 Where to go next
- The data. Appendix B documents every table, column and quirk, and the full toolkit API.
- The formats. Appendix C: SAN, FEN, PGN comments, UCI, EPD and the rules that decide how games end.
- The numbers. Appendix D defines every metric with code; Appendix E covers the statistics behind every interval.
- The chapters that teach the code in context. Chapter 1 builds
outpost/games.py(Chapter 1); Chapter 26 reviews one game end to end with the engine (Chapter 26); Chapter 31 turns the tables into a query engine (Chapter 31); Chapter 32 runs engine analysis at scale (Chapter 32); Chapter 34 writes a small engine from scratch (Chapter 34).
Quick reference card
| Task | Code |
|---|---|
| New board / from FEN | chess.Board() · chess.Board(fen) |
| Play a move (checked) | board.push_san("Nf3") |
| Undo | board.pop() |
| Legal moves | list(board.legal_moves) · board.legal_moves.count() |
| SAN ↔ Move | board.san(move) · board.parse_san("Nf3") |
| Position as text | board.fen() · print(board) |
| Load a famous game | row = chessdata.find_game(white=..., black=..., year=...).iloc[0] · chessdata.game_from_row(row) |
| Walk a game | b = game.board() then for mv in game.mainline_moves(): b.push(mv) |
| Evaluate | engine.evaluate(fen, depth=18) → cp (White POV), pv, win_pct_white |
| Analyse a game | engine.analyse_game(pgn, depth=16) → game_summary, critical_moments |
| Diagram | boards.save_board(path, board, arrows=[...], highlights={...}) |
| Lichess games | chessdata.lichess_games(speed="blitz", min_elo=..., max_elo=..., balanced=True) |
| OTB games | chessdata.broadcast_games(speed="classical"), then drop engine_game and online |
| Rating bands | chessdata.rating_bands(df.avg_elo) |
| Group and summarise | df.groupby("band", observed=True).score_white.agg(["mean", "size"]) |