Guide
Elo ratings from scratch in Python, tested on NFL
Short answer: an Elo system is a rating per team, a win probability from the rating gap, and an update scaled by surprise and margin. Tuned on 2010 to 2021 NFL games and tested on 2022 to 2026, it scored a log loss of 0.6333 against 0.6889 for a constant home rate.
Elo is a way to summarise results into one number per team. This guide builds it, tests it honestly and shows which parts matter. It is a rating exercise. Nothing in it is a recommendation to wager.
The idea in one paragraph
Every team starts at 1500. Before a game, the difference between the two ratings, plus a home-field bonus, gives a win probability. After the game, the winner's rating goes up and the loser's goes down by the same amount. The amount is the surprise, the gap between the result (1 or 0) and the forecast, times a constant K. An upset moves the ratings a lot. A win by the favourite barely moves them. The scale is set so that a 400 point gap means 10 to 1 odds.
That is the whole core. Three refinements make it good enough to be worth using, and each can be tested.
The three refinements
Home field. Add a fixed number of points to the home team's rating when computing the gap, and skip it when the venue is neutral. The API marks neutral sites with a location of Neutral, which covers the Super Bowl.
Margin of victory. A 30 point win is more informative than a 1 point win, but not 30 times more. The usual multiplier is ln(margin + 1) * 2.2 / (winner_rating_gap * 0.001 + 2.2). The log makes the effect fade with margin. The denominator shrinks the update when the winner was already far ahead, which stops a dominant team from inflating its rating by beating weak opponents, since the gap would already predict the margin. Here the gap includes the home bonus.
Season carryover. Rosters change over the winter. At each season boundary, pull every rating a fraction of the way back to 1500: new = 1500 + carry * (old - 1500). A carry of 1.0 keeps ratings unchanged and a carry of 0 resets everyone.
Step 1: get the results
EndzoneAPI's get_games returns games by season with scores, kickoff time and location. It costs 5 credits a call and takes up to 500 games, enough for a full season with the playoffs. The loop below pulls 2010 to 2026 with status set to FINAL, which is 17 calls and 85 credits. It returned 4,543 completed games. The last kickoff was December 4, 2026, so 2026 is a partial season. Games are sorted by kickoff, which matters for the next step, because Elo is a sequential algorithm: a rating is only valid as of the games before it.
import json, os, time, urllib.error, urllib.request
import pandas as pd
KEY = os.environ["ENDZONEAPI_API_KEY"]
def post(tool, body):
req = urllib.request.Request(f"https://mcp.endzoneapi.com/v1/{tool}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "x-api-key": KEY})
for wait in (2, 5, 10, 20):
try:
with urllib.request.urlopen(req, timeout=90) as r:
return json.load(r)["data"]
except urllib.error.HTTPError as e:
if e.code != 429:
raise
time.sleep(wait)
rows = []
for season in range(2010, 2027):
rows += post("get_games", {"season": season, "status": "FINAL", "limit": 500})["games"]
games = pd.DataFrame(rows)[["game_id", "season", "game_type", "week", "kickoff", "home_team", "away_team",
"home_score", "away_score", "location"]].sort_values("kickoff")
games.to_csv("nfl_games.csv", index=False)
print(len(games), games.season.nunique(), games.kickoff.max())Step 2: build, tune and test
The second script contains the whole Elo system, a grid search and the evaluation. The function run walks through the games in order and returns the pre-game home win probability for each one, which is the number we score. Ties count as 0.5. The first pass sets a rating of 1500 for any team it has not seen.
The split is by season, not at random. Parameters are chosen using only 2010 to 2021, using log loss as the target. The grid is K of 10, 15, 20 or 30, a home bonus of 30, 48 or 65, and a carryover of 0.5, 0.67, 0.75 or 0.9. Then the chosen parameters are scored on 2022 to 2026, games the tuner never saw. Because the ratings keep evolving through the test seasons, the test uses the same sequential run, so every forecast still uses only earlier games.
import math, itertools
import numpy as np, pandas as pd
games = pd.read_csv("nfl_games.csv").sort_values("kickoff").reset_index(drop=True)
games["home_win"] = (games.home_score > games.away_score).astype(float)
games.loc[games.home_score == games.away_score, "home_win"] = 0.5
games["neutral"] = games.location.eq("Neutral")
def run(games, k=20, home=48, carry=0.75, margin=True):
"""Return one pre-game home win probability per game, in kickoff order."""
elo, last_season, probs = {}, None, []
for g in games.itertuples():
if g.season != last_season: # season carryover: pull toward 1500
for t in elo:
elo[t] = 1500 + carry * (elo[t] - 1500)
last_season = g.season
h, a = elo.setdefault(g.home_team, 1500.0), elo.setdefault(g.away_team, 1500.0)
adv = 0 if g.neutral else home
diff = h + adv - a
p = 1 / (1 + 10 ** (-diff / 400))
probs.append(p)
mov = g.home_score - g.away_score
mult = 1.0
if margin and mov != 0: # margin of victory multiplier
winner_diff = diff if mov > 0 else -diff
mult = math.log(abs(mov) + 1) * 2.2 / (winner_diff * 0.001 + 2.2)
delta = k * mult * (g.home_win - p)
elo[g.home_team] = h + delta
elo[g.away_team] = a - delta
return np.array(probs), elo
def log_loss(p, y):
p = np.clip(p, 1e-6, 1 - 1e-6)
return float(-(y * np.log(p) + (1 - y) * np.log(1 - p)).mean())
train = games.season <= 2021
test = games.season >= 2022
y = games.home_win.values
# Tune on 2010-2021 only.
best = None
for k, home, carry in itertools.product([10, 15, 20, 30], [30, 48, 65], [0.5, 0.67, 0.75, 0.9]):
p, _ = run(games, k, home, carry)
ll = log_loss(p[train], y[train])
if best is None or ll < best[0]:
best = (ll, k, home, carry)
print("tuned on 2010-2021:", best)
_, K, HOME, CARRY = best
rate = y[train].mean()
rows = [("constant home rate", np.full(test.sum(), rate))]
for name, kw in [("Elo, tuned", {}), ("Elo, no margin multiplier", {"margin": False}),
("Elo, no carryover (reset)", {"carry": 0.0}), ("Elo, full carryover", {"carry": 1.0})]:
args = dict(k=K, home=HOME, carry=CARRY); args.update(kw)
p, _ = run(games, **args)
rows.append((name, p[test]))
print(f"{'model':<28}{'log loss':>9}{'Brier':>8}{'accuracy':>9}")
for name, p in rows:
yt = y[test]
print(f"{name:<28}{log_loss(p, yt):>9.4f}{((p - yt) ** 2).mean():>8.4f}{(((p > .5) == (yt > .5)).mean()):>9.3f}")
print("test games", int(test.sum()))
# Calibration of the tuned model on the test seasons.
p, elo = run(games, K, HOME, CARRY)
cal = pd.DataFrame({"p": p[test], "y": y[test]})
cal["bin"] = pd.cut(cal.p, [0, .3, .4, .5, .6, .7, .8, 1])
print(cal.groupby("bin", observed=True).agg(games=("y", "size"), mean_p=("p", "mean"), home_win=("y", "mean")).round(3))
# Bootstrap of the log loss gap vs constant.
rng = np.random.default_rng(0)
yt, pt = y[test], p[test]
gap = -(yt*np.log(pt)+(1-yt)*np.log(1-pt)) + (yt*np.log(rate)+(1-yt)*np.log(1-rate))
boot = [gap[rng.integers(0, len(gap), len(gap))].mean() for _ in range(3000)]
print("gap vs constant (negative = Elo better):", round(gap.mean(), 4), np.percentile(boot, [2.5, 97.5]).round(4))
top = sorted(elo.items(), key=lambda kv: -kv[1])
print([(t, round(r)) for t, r in top[:5]], [(t, round(r)) for t, r in top[-3:]])The tuner chose K of 20, a home bonus of 48 points and a carryover of 0.67, with a training log loss of 0.6303. The test set holds 1,319 games.
Results
| Model | Log loss | Brier | Accuracy |
|---|---|---|---|
| Constant home rate | 0.6889 | 0.2471 | 0.546 |
| Elo, tuned | 0.6333 | 0.2210 | 0.639 |
| Elo, no margin multiplier | 0.6460 | 0.2266 | 0.619 |
| Elo, reset to 1500 each season | 0.6446 | 0.2264 | 0.609 |
| Elo, full carryover | 0.6473 | 0.2257 | 0.638 |
Every refinement helps. Removing the margin multiplier costs 0.0127 in log loss. Resetting every season costs 0.0113, and keeping every rating unchanged costs 0.0140. The full-carryover model has a good Brier score and good accuracy but a poor log loss, which tells you it is overconfident: it picks about as many winners as the tuned model but assigns probabilities that are too extreme. That is the kind of difference accuracy alone hides, and the reason to score with log loss.
The gap to the constant baseline is 0.0556 in log loss, and a bootstrap over the 1,319 games puts the 95 percent interval at 0.037 to 0.073. It does not come near zero. The model is better than the baseline by a distance this sample can resolve.
Calibration
A good total can hide a bad bin, so group the forecasts and compare with outcomes.
| Forecast range | Games | Mean forecast | Home win rate |
|---|---|---|---|
| Up to 0.3 | 98 | 0.242 | 0.327 |
| 0.3 to 0.4 | 145 | 0.362 | 0.352 |
| 0.4 to 0.5 | 228 | 0.451 | 0.406 |
| 0.5 to 0.6 | 269 | 0.552 | 0.515 |
| 0.6 to 0.7 | 264 | 0.649 | 0.621 |
| 0.7 to 0.8 | 212 | 0.747 | 0.731 |
| Above 0.8 | 103 | 0.842 | 0.864 |
Calibration is good across the middle and the upper end. The weak spot is the lowest bin: home teams forecast at 0.242 won 32.7 percent of the time, so the model is a little too pessimistic about big home underdogs. With 98 games the standard error is about 0.047, so the gap of 0.085 is about 1.8 standard errors, suggestive but not conclusive.
Reading the ratings
At the end of the run, the highest ratings were Buffalo at 1712, San Francisco at 1683, Chicago at 1650, Seattle at 1632 and Jacksonville at 1627. The lowest were Arizona at 1338, Miami at 1320 and Tennessee at 1277. A rating gap of 100 points, plus nothing for home field, means about a 64 percent win chance for the stronger team. Those are our results from the code above, as of December 4, 2026, with 2026 only partly played.
Ratings are not a ranking, and they say nothing about the cause of a team's results. They do carry a quarterback injury or a coaching change slowly, because the model only learns from scores.
Adapting it to another sport
The structure ports directly. The values change. Baseball needs a smaller K and a smaller home bonus because games are closer to coin flips, and soccer needs a draw model, since a win and a draw are both common. For college football the margin multiplier matters more because schedules are lopsided, and the carryover should be tuned separately. In every case, tune on early seasons and test on later ones, and compare against the constant home rate. If the Elo cannot beat it by a clear margin, the data or the parameters are wrong.
Limits
- Scores only. The model sees no injuries, quarterbacks, rest, weather or travel. It is a baseline, and a richer model can beat it.
- Tuned parameters are tuned on a window. K 20, home 48 and carryover 0.67 were the best on 2010 to 2021 among 48 grid points. The next five grid points scored between 0.6306 and 0.6314 on the training seasons, within 0.0011 of the best, so do not read the exact numbers as truth.
- 2026 is partial. About 13 weeks of the final test season are in the sample. The full seasons are 2022 to 2025.
- Ties count as half a win. NFL ties are rare, so this has almost no effect.
- Home-field is constant. A single 48 point bonus ignores stadium and team differences, and the neutral-site flag covers only games the API marks neutral.
Live from the API
Free to embed on your own site, with no key needed. Get the embed code.
Get a free key Or download whole seasons as Parquet
Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.