How to Build a Chess Game Reviewer in Python With Stockfish
Our guides are based on hands-on testing and verified sources. Each article is reviewed for accuracy and updated regularly to ensure current, reliable information.Read our editorial policy.
Key Takeaways
- Stockfish combines selective search with neural network-based position evaluation.
- The python-chess library communicates with Stockfish through the Universal Chess Interface (UCI) protocol.
- Centipawn loss estimates how much a move worsens a player’s position.
- Forced checkmate scores require different handling from ordinary numerical evaluations.
- Engine versions, search depths, and configuration settings affect analysis results.
- Chess engines should be used for completed game analysis or permitted practice.
Most chess game review tools follow a similar process. They replay the game move by move, ask an engine how good the position was before and after each move, and flag the moves that lost the most.
This guide builds a simple game reviewer with the python-chess library and a local Stockfish binary, then looks at what the numbers actually mean and where raw engine output stops being useful to a human player.
What the Engine Is Doing Under the Hood
A modern chess engine combines two parts: a search that looks ahead through possible moves, and an evaluation function that scores the positions it reaches.
Stockfish uses alpha-beta search with extensive pruning. It doesn’t look at every line equally. Less promising branches can be cut short, while promising lines are searched deeper.
Stockfish 12 introduced NNUE (Efficiently Updatable Neural Network) evaluation in 2020. This neural network runs efficiently on a CPU. Since version 16.1, Stockfish has relied on neural network-based evaluation instead of its older handcrafted evaluation function.
Leela Chess Zero takes a different route: a neural network guides a Monte Carlo tree search, typically using a GPU for faster network evaluation.
For a game reviewer, the details matter less than the output. You give the engine a position and a search limit, and it returns a score and a recommended line of play.
| Term | What It Means in the Output |
|---|---|
| Centipawn (cp) | A unit of engine evaluation traditionally equal to one-hundredth of a pawn. A score of +150 indicates a favorable position for the evaluated side, not necessarily a material advantage of one and a half pawns. |
| Mate score | Indicates that the engine has found a forced checkmate for one side. |
| Depth | The nominal search depth measured in half-moves, also known as plies. Some branches may be searched more deeply than others. |
| PV | Principal variation, the best continuation found by the engine during its search. |
| MultiPV | The number of alternative principal variations requested from the engine. |
Modern Stockfish normalizes its numerical evaluations using a statistical model derived from engine games. These scores are better understood as estimates of positional advantage than literal material counts.
Setup
You need Python 3.9 or newer, the python-chess library, and a local Stockfish executable.
Install the Python package:
pip install chessInstall Stockfish using the appropriate method for your operating system.
macOS:
brew install stockfishUbuntu or Debian:
sudo apt install stockfishWindows: Download the appropriate executable from the official Stockfish website and note its full file path.
Package managers may provide an older version of Stockfish than the official website. Record the version you use if you want to compare your results with someone else’s.
Save any completed game as game.pgn. PGN, or Portable Game Notation, is a standard text format for recording chess games. Lichess and Chess.com both allow players to export games in this format.
The example below uses Paul Morphy’s 1858 Opera Game, which is short and contains several instructive mistakes by Black.
Save the following content in your game.pgn file:
[Event "Opera Game"]
[Site "Paris, France"]
[Date "1858.??.??"]
[Round "?"]
[White "Paul Morphy"]
[Black "Duke of Brunswick and Count Isouard"]
[Result "1-0"]
1. e4 e5 2. Nf3 d6 3. d4 Bg4
4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6
7. Qb3 Qe7 8. Nc3 c6 9. Bg5 b5
10. Nxb5 cxb5 11. Bxb5+ Nbd7
12. O-O-O Rd8 13. Rxd7 Rxd7
14. Rd1 Qe6 15. Bxd7+ Nxd7
16. Qb8+ Nxb8 17. Rd8# 1-0The Reviewer
The core idea is centipawn loss. Before each move, ask the engine for the score from the mover’s point of view. After the move, ask again from the same side’s point of view. The difference estimates how much that move gave away.
Forced checkmate scores need separate handling because they are not ordinary centipawn evaluations.
Save the following Python script as review.py in the same directory as your PGN file.
import chess
import chess.engine
import chess.pgn
ENGINE_PATH = "stockfish"
LIMIT = chess.engine.Limit(depth=18)
ZERO = chess.engine.Cp(0)
def label(loss):
if loss >= 300:
return "blunder"
if loss >= 100:
return "mistake"
if loss >= 50:
return "inaccuracy"
return ""
with open("game.pgn", encoding="utf-8") as f:
game = chess.pgn.read_game(f)
if game is None or game.errors:
raise ValueError("No valid PGN game found.")
board = game.board()
if not board.is_valid():
raise ValueError("Invalid starting position.")
with chess.engine.SimpleEngine.popen_uci(ENGINE_PATH) as engine:
engine.configure({"Threads": 1, "Hash": 64})
for move in game.mainline_moves():
if board.is_game_over():
break
mover = board.turn
num = board.fullmove_number
side = "White" if mover == chess.WHITE else "Black"
before = engine.analyse(board, LIMIT)
previous = before["score"].pov(mover)
san = board.san(move)
pv = before.get("pv", [])
best_san = board.san(pv[0]) if pv else "unknown"
board.push(move)
if board.is_checkmate():
current = chess.engine.MateGiven
elif board.is_game_over():
current = ZERO
else:
after = engine.analyse(board, LIMIT)
current = after["score"].pov(mover)
if current.is_mate() and current < ZERO:
if not (previous.is_mate() and previous < ZERO):
print(f"{num}. {side} {san}: allows forced mate")
continue
if previous.is_mate() and previous > ZERO:
if not (current.is_mate() and current > ZERO):
print(f"{num}. {side} {san}: missed forced mate")
continue
if previous.is_mate() or current.is_mate():
continue
loss = max(0, previous.score() - current.score())
tag = label(loss)
if tag:
print(
f"{num}. {side} {san}: {tag} "
f"(-{loss} cp), engine preferred {best_san}"
)If Stockfish is not on your system’s PATH, replace ENGINE_PATH with the full path to its executable. On Windows, for example, you can use a raw string:
ENGINE_PATH = r"C:\stockfish\stockfish.exe"Adjust the path and filename to match your installation. Then run the reviewer:
python review.pyIf you modify the script, an online Python formatter can help clean up spacing and indentation. Check the resulting code before running it, as formatting alone does not validate Python syntax or behavior.
A few implementation notes:
| Detail | Why It Is There |
|---|---|
pov(mover) |
Converts both evaluations to the mover’s perspective so the subtraction works for both colors. |
is_mate() |
Identifies forced checkmate evaluations so they are not treated as ordinary centipawn scores. |
max(0, ...) |
Separate searches can produce slightly inconsistent evaluations. Negative centipawn loss is clamped to zero. |
board.san() before push() |
Standard Algebraic Notation (SAN) depends on the position, so it must be generated before the move is played. |
board.is_game_over() |
Prevents unnecessary engine searches when a game has ended in checkmate or an automatic draw. |
depth=18 |
A reasonable starting point for game analysis. Reduce the depth if reviewing games takes too long on your computer. |
with SimpleEngine |
Ensures the engine process is closed when analysis finishes or an exception occurs. |
This is a basic reviewer for standard chess games. It flags numerical evaluation drops and certain changes in forced mate status. It does not attempt to classify every tactical mistake or change in the distance to checkmate.
Reading the Output
When you run the script on the Opera Game at depth 18, it prints moves that cross the configured centipawn loss thresholds or introduce certain changes in forced mate status. The exact evaluations and classifications depend on the Stockfish version and search settings.
For example, suppose the engine evaluates a position at +40 cp before a move and -140 cp afterward, both from the mover’s perspective.
Centipawn loss = 40 - (-140)
Centipawn loss = 180 cp
Classification = mistakeWith the thresholds used in this script, the move would be classified as a mistake. This is an illustrative calculation rather than a measured evaluation from the Opera Game.
Looking at the Opera Game itself, Black’s position deteriorates through a series of moves in the opening and middlegame, long before the famous queen sacrifice.
After 15…Nxd7, Morphy played 16.Qb8+ Nxb8 17.Rd8#, sacrificing his queen to deliver checkmate with his remaining rook. This sequence demonstrates why forced checkmate evaluations need different handling from ordinary centipawn scores.
If the engine’s evaluation changes from a numerical score to a forced mate against the mover, the script reports allows forced mate instead of displaying an artificially large centipawn loss. If a forced mate was already detected before the move, the script does not automatically classify it as a new blunder.
Keep in mind that these classifications depend on what the engine finds within its search limit. A deeper search may discover a forced mate that a shallower search missed.
The 50, 100, and 300 centipawn thresholds are custom classification rules for this tutorial, not an official Stockfish standard.
Lichess, for example, uses an accuracy model based on estimated winning chances. Losing 200 centipawns in a position that is already +900 can matter far less than losing 200 centipawns in an approximately equal position.
If you want similar behavior, convert each score into an estimated winning chance and measure the change instead of relying entirely on centipawn loss.
Two settings change results more than people expect:
| Setting | Effect |
|---|---|
| Fixed depth vs. fixed time | Fixed depth makes comparisons more consistent. Time limits may produce different results on fast and slow hardware. Neither guarantees identical evaluations across different environments. |
| Threads and hash | Thread count and hash table size can influence the search. Using one thread and a fixed hash size helps improve consistency between reviews. |
When experimenting with different search depths or engine versions, save the output from each run and use a diff checker to compare changes in move classifications and recommended alternatives.
Where Raw Engine Output Stops Helping
The script can tell you that a move lost 180 centipawns and suggest a better alternative. It does not tell a 1200-rated player why the move was bad.
Reading the principal variation helps a little, but a 10-move engine line is hard to follow without a board, and some of its moves may be ones a human would never consider.
This is the gap that game review tools try to close. Lichess and Chess.com present engine analysis through interactive boards, evaluation indicators, and move classifications.
Other tools, such as ChessHelper, offer AI-assisted move analysis, opening study resources, and move suggestions calibrated to different skill levels. ChessHelper also advertises real-time move assistance, which should not be used in games where external engine assistance is prohibited.
These tools differ in how they present engine output and how much of the analysis they translate into information a player can understand and act on.
If you prefer studying positions through a visual interface instead of writing Python code, these chess move calculator tools provide several alternatives for independent position study and post-game analysis.
Fair-play warning: Using an engine for unauthorized assistance during an ongoing game against another player violates the fair-play rules of platforms such as Chess.com and Lichess. Use this script for completed games, independent position study, or practice environments where engine assistance is explicitly permitted.
Extensions Worth Building
Once the basic loop works, there are several useful additions you can make.
| Extension | How to Implement It |
|---|---|
| Show the top three alternatives | Use engine.analyse(board, LIMIT, multipv=3) to request up to three principal variations. This returns a list of analysis dictionaries. |
| Average centipawn loss per player | Collect numerical centipawn losses separately for White and Black, then calculate the average for each side. Report forced mate transitions separately. |
| Batch review | Call chess.pgn.read_game() repeatedly until it returns None to process multiple games from a PGN file. |
| Annotated PGN output | Iterate through the game’s mainline nodes, add analysis using node.comment, and write the annotated game back to a PGN file. |
| Opening detection | Match the opening moves or resulting positions against an Encyclopedia of Chess Openings (ECO) database. |
The full documentation for the engine module is available in the python-chess docs, and Stockfish’s UCI options are documented through the official Stockfish repository.
Summary
A basic chess game reviewer uses up to two engine calls per move and a comparison of their evaluations. The hard part is not the code. It is deciding which drops matter and explaining them in words a player understands.
Start with this Python reviewer, run it on your completed games, and look at the positions where your evaluation dropped the most. Those positions are often a useful starting point for understanding recurring mistakes and improving your play.





Comments
Comments are provided by Disqus, which sets cookies and processes data under its own privacy policy.