Group A wins by seven factors. Group B wins by seven factors. If we’re evaluating them by scoring margin, they’re tied.
Now suppose Group A confronted a powerful opponent whereas Group B confronted a weak one. The scores have not modified, however our interpretation most likely has. Successful by seven in opposition to a superb crew usually tells us one thing totally different from successful by seven in opposition to a foul crew.
That is the thought behind opponent adjustment: use the schedule to place a efficiency in context.
Uncooked statistics do not actually lie. They describe what occurred. The error is treating these numbers as a whole measure of crew high quality when the groups confronted totally different exams.
We’ll begin with 4 fictional groups, construct a small ranking operate in Python, after which apply it to the finished 2025 faculty soccer common season. You do not want a background in statistical modeling. Some familiarity with Python and pandas will assist, however the essential half is knowing what every step is attempting to do.
Begin with three video games
Think about that each one three of those video games had been performed on impartial fields:
Group A beats Group C by 7.Group B beats Group D by 7.Group C beats Group D by 23.
Group A and Group B every have a uncooked scoring margin of +7. We even have a helpful connection between their opponents: Group C beat Group D comfortably. That provides us a purpose to worth Group A’s consequence extra extremely.
Let’s put these outcomes right into a small desk. We are going to stroll by the code assuming you might be figuring out of a brand new Jupyter pocket book. The true-data portion later will even require an API key.
Set up the packages first. This instance was run with the most recent model of the official CFBD Python shopper, which is at the moment model 5.31.2. The p.c signal makes the set up command a Jupyter command. In case you’ve already imported an older shopper, restart the kernel after putting in.
%pip set up -q “cfbd>=5.31.2” “numpy>=1.26,=2.2,=3.8,
These imports and settings assist the entire instance, together with the true video games and chart afterward. The fictional instance itself solely wants pandas.
import os
from collections import defaultdict
from datetime import datetime, timezone
from importlib.metadata import model
from pathlib import Path
import cfbd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.show import show
SEASON = 2025
HOME_FIELD_POINTS = 2.5
OUTPUT_DIR = Path(“outputs”)
plt.rcParams.replace({“determine.figsize”: (10, 6), “font.measurement”: 11})
pd.set_option(“show.max_columns”, 12)
pd.set_option(“show.float_format”, “{:,.2f}”.format)
assert model(“cfbd”) >= “5.31.2”
print({bundle: model(bundle) for bundle in [“cfbd”, “numpy”, “pandas”, “matplotlib”]})
Every sport wants two views. A seven-point win for Group A is a seven-point loss for Group C. We reverse the crew names, negate the margin, and mix the 2 units of rows:
toy_games = pd.DataFrame(
[(“Team A”, “Team C”, 7), (“Team B”, “Team D”, 7), (“Team C”, “Team D”, 23)],
columns=[“team”, “opponent”, “adjusted_margin”],
)
toy_reverse = toy_games.rename(columns={“crew”: “opponent”, “opponent”: “crew”})
toy_reverse = toy_reverse.assign(adjusted_margin=-toy_reverse[“adjusted_margin”])
toy_team_games = pd.concat([toy_games, toy_reverse], ignore_index=True)
toy_raw = toy_team_games.groupby(“crew”)[“adjusted_margin”].imply().rename(“raw_margin”)
show(toy_games, toy_raw.to_frame())
The ensuing uncooked averages are +7 for Group A, +7 for Group B, +8 for Group C, and −15 for Group D. Group C’s common features a seven-point loss and a 23-point win. Group D misplaced by seven and by 23.
The column is named adjusted_margin as a result of we’ll reuse it later for margins with a home-field adjustment. For these neutral-site fictional video games, it’s merely the rating distinction.
Let the opponents change the interpretation
Suppose we finally estimate Group C to be eight factors above the typical crew. Group A beat Group C by seven, in order that sport would counsel a ranking of +15 for Group A: seven factors of margin plus eight factors of opponent energy.
If Group D is 15 factors under common, Group B’s seven-point win suggests −8 for Group B. Beating a weak crew does not essentially make you an above-average crew.
These opponent scores are what we nonetheless want to seek out. We do not assign them by fame or convention. We estimate them from the identical sport outcomes.
We’ll use an SRS-style technique, brief for Easy Ranking System. Its central relationship is:
Group ranking = common sport margin + common opponent ranking.
There’s a round dependency right here: Group A’s ranking is dependent upon Group C’s, and Group C’s relies upon partly on Group A’s. We will work by it by repeating a easy calculation:
Begin each crew’s ranking at zero.For every sport, add the opponent’s present ranking to the crew’s margin.Common these values for every crew to get a brand new goal ranking.Transfer midway from the outdated ranking towards that focus on, then middle the scores so the typical crew is zero.Repeat till the scores barely change.
On the primary go, the goal is simply the typical margin as a result of all opponent scores are zero. Subsequent passes herald what we have discovered concerning the opponents, then their opponents, and so forth.
Transferring midway is named rest. It helps preserve the estimates from bouncing forwards and backwards. Centering offers us a reference level: including ten factors to each crew’s ranking would not change any distinction between groups. Setting the typical to zero chooses one constant scale. That is the difficulty modelers name identifiability.
def iterate_srs(
team_games,
*,
rest=0.5,
tolerance=1e-8,
max_iterations=10_000,
):
“””Match a centered iterative SRS-style ranking from team-perspective rows.”””
groups = sorted(set(team_games[“team”]) | set(team_games[“opponent”]))
scores = pd.Collection(0.0, index=groups, title=”ranking”)
for iteration in vary(1, max_iterations + 1):
game_values = team_games[“adjusted_margin”] + team_games[“opponent”].map(scores)
targets = game_values.groupby(team_games[“team”]).imply().reindex(groups)
up to date = rest * targets + (1 – rest) * scores
up to date -= up to date.imply() # zero is the typical crew
max_change = (up to date – scores).abs().max()
scores = up to date
if max_change
The principle calculation is close to the highest of the loop. map(scores) appears up the present ranking for every opponent, and groupby collects every crew’s sport values earlier than taking their imply.
The tolerance of 1e-8 is a stopping rule for the calculation, not a declare that we all know crew energy to eight decimal locations. The iteration restrict is a backstop: if the loop does not settle, it raises an error as an alternative of silently returning an unfinished consequence.
The operate returns a abstract desk, the variety of iterations, and the ultimate measurement of the change. Let’s run it on the fictional schedule:
toy_srs, toy_iterations, toy_change = iterate_srs(toy_team_games)
toy_comparison = toy_srs.merge(toy_raw, on=”crew”)
show(toy_comparison.sort_values(“adjusted_rating”, ascending=False))
TeamRaw marginAverage opponent ratingAdjusted ratingA+7+8+15C+80+8B+7−15−8D−150−15
Group A’s and Group B’s uncooked margins are nonetheless an identical. Their scores differ as a result of A’s win got here in opposition to the stronger opponent. All 4 scores common zero, and you’ll examine each sport by subtracting the opponent’s ranking from the crew’s ranking.
This instance suits completely by building. Three video games are sufficient to display the arithmetic, however far too few to determine how reliably these groups would carry out in one other sport. Actual outcomes will not match so neatly.
The schedule connects the groups
Group A by no means performed Group B. We will nonetheless evaluate them by the chain A–C–D–B. Consider groups as dots and video games because the traces connecting them.
If Group C and Group D hadn’t performed, we might have two separate teams. We might evaluate Group A with Group C and Group B with Group D, however these outcomes alone would not inform us the best way to evaluate the teams. Repeating the calculation extra instances cannot create the lacking data.
The helper under finds these teams, referred to as linked parts. It begins with one crew, follows its opponents and their opponents, and retains going till it has discovered each reachable crew. Then it checks whether or not any groups stay outdoors that group.
def connected_components(team_games):
“””Return schedule-network parts, largest first.”””
adjacency = defaultdict(set)
for crew, opponent in team_games[[“team”, “opponent”]].itertuples(index=False):
adjacency[team].add(opponent)
adjacency[opponent].add(crew)
unseen = set(adjacency)
parts = []
whereas unseen:
begin = unseen.pop()
element = {begin}
stack = [start]
whereas stack:
present = stack.pop()
neighbors = adjacency[current] & unseen
unseen -= neighbors
element |= neighbors
stack.lengthen(neighbors)
parts.append(element)
return sorted(parts, key=len, reverse=True)
print(“Toy schedule element sizes:”, [len(c) for c in connected_components(toy_team_games)])
The fictional schedule has one element containing all 4 groups. We’ll make the identical examine earlier than becoming the true knowledge. A linked schedule makes a shared relative scale attainable; a small variety of video games linking in any other case separate teams can nonetheless make estimates unstable.
For the true instance, we’ll use the 2025 FBS common season. A accomplished interval offers us extra schedule data than an early-season snapshot.
Earlier than operating the subsequent cell, set CFBD_API_KEY within the atmosphere used to launch Jupyter. Hold the important thing out of the pocket book itself. The code makes use of the official shopper’s season-specific FBS crew listing and sport endpoint.
api_key = os.getenv(“CFBD_API_KEY”)
if not api_key:
elevate RuntimeError(
“CFBD_API_KEY is just not set. Add it to your atmosphere, restart the ”
“kernel, and run the pocket book once more. Don’t paste the important thing right here.”
)
configuration = cfbd.Configuration(access_token=api_key)
with cfbd.ApiClient(configuration) as shopper:
teams_api = cfbd.TeamsApi(shopper)
games_api = cfbd.GamesApi(shopper)
fbs_teams = teams_api.get_fbs_teams(yr=SEASON)
returned_games = games_api.get_games(
yr=SEASON,
season_type=cfbd.SeasonType.REGULAR,
classification=cfbd.DivisionClassification.FBS,
)
retrieved_at = datetime.now(timezone.utc).isoformat(timespec=”seconds”)
print(f”Retrieved {SEASON} regular-season knowledge at {retrieved_at}”)
fbs_names = {crew.faculty for crew in fbs_teams}
completed_games = [
game
for game in returned_games
if game.completed and game.home_points is not None and game.away_points is not None
]
fbs_games = [
game
for game in completed_games
if game.home_team in fbs_names and game.away_team in fbs_names
]
Within the pocket book’s present run, the API returned 888 accomplished video games. Conserving solely video games between two FBS groups left 762 video games protecting 136 groups. The opposite 126 had been cross-division video games. None had been excluded for incomplete outcomes or lacking scores in that run.
The FBS filter alone does not give us an FBS-only comparability community, which is why we examine each crew names. This selection excludes FBS–FCS outcomes. Postseason video games are additionally excluded.
We’ll preserve the remaining selections easy:
Use last scoring margin with out capping blowouts.Give each included sport equal weight.Subtract an assumed 2.5-point dwelling benefit from the house crew’s margin. Use zero on impartial fields.
The two.5 factors are a instructing assumption, not an estimate fitted from these video games. For instance, a seven-point dwelling win turns into a +4.5 baseline margin for the house crew and −4.5 for the customer. A seven-point neutral-site win stays +7.
Now create the 2 crew views for each sport, as we did with the fictional outcomes:
games_df = pd.DataFrame(
[
{
“game_id”: game.id,
“week”: game.week,
“home_team”: game.home_team,
“away_team”: game.away_team,
“home_points”: game.home_points,
“away_points”: game.away_points,
“neutral_site”: game.neutral_site,
}
for game in fbs_games
]
)
home_margin = games_df[“home_points”] – games_df[“away_points”]
home_field = np.the place(games_df[“neutral_site”], 0.0, HOME_FIELD_POINTS)
home_rows = pd.DataFrame(
{
“game_id”: games_df[“game_id”],
“week”: games_df[“week”],
“crew”: games_df[“home_team”],
“opponent”: games_df[“away_team”],
“venue”: np.the place(games_df[“neutral_site”], “Impartial”, “House”),
“raw_margin”: home_margin,
“adjusted_margin”: home_margin – home_field,
}
)
away_rows = pd.DataFrame(
{
“game_id”: games_df[“game_id”],
“week”: games_df[“week”],
“crew”: games_df[“away_team”],
“opponent”: games_df[“home_team”],
“venue”: np.the place(games_df[“neutral_site”], “Impartial”, “Away”),
“raw_margin”: -home_margin,
“adjusted_margin”: -home_margin + home_field,
}
)
team_games = pd.concat([home_rows, away_rows], ignore_index=True)
show(team_games.head())
raw_margin preserves the precise rating distinction. adjusted_margin removes solely the assumed dwelling benefit at this stage. It hasn’t been adjusted for opponents but. Conserving each columns lets us distinguish the situation remedy from the schedule calculation.
We will now examine connectivity, match the scores, and put the uncooked and adjusted outcomes collectively:
parts = connected_components(team_games)
if len(parts) != 1:
elevate ValueError(f”The ultimate schedule has disconnected element sizes: {[len(c) for c in components]}”)
srs_summary, iterations, final_change = iterate_srs(team_games)
team_metadata = pd.DataFrame(
[{“team”: team.school, “conference”: team.conference} for team in fbs_teams]
)
raw_summary = (
team_games.groupby(“crew”, as_index=False)
.agg(video games=(“game_id”, “measurement”), raw_scoring_margin=(“raw_margin”, “imply”))
)
scores = (
team_metadata
.merge(raw_summary, on=”crew”, how=”internal”, validate=”one_to_one”)
.merge(
srs_summary.drop(columns=”video games”),
on=”crew”,
how=”internal”,
validate=”one_to_one”,
)
)
scores[“raw_rank”] = (
scores[“raw_scoring_margin”].rank(technique=”min”, ascending=False).astype(int)
)
scores[“baseline_rank”] = scores[“baseline_margin”].rank(technique=”min”, ascending=False).astype(int)
scores[“adjusted_rank”] = (
scores[“adjusted_rating”].rank(technique=”min”, ascending=False).astype(int)
)
scores[“rank_change”] = scores[“baseline_rank”] – scores[“adjusted_rank”]
The schedule fashioned one linked element, and the calculation converged in 206 iterations. A +10 ranking would imply ten factors above the typical of those 136 groups on this mannequin’s neutral-field scale.
What modifications once we account for the schedule?
There are three helpful numbers for every crew: its uncooked margin, its margin after the home-field remedy, and its last opponent-adjusted ranking.
For the rating comparability, we’ll begin with the home-field baseline after which add opponent adjustment. Either side use the identical video games and uncapped margins. This isolates the schedule step. Evaluating the ultimate ranking with uncooked margin alone would additionally embrace the home-field change.
The next code selects the eight largest absolute rating strikes. A optimistic rank_change means the crew moved up. Tied values share the very best occupied rank.
biggest_movers = (
scores.assign(abs_rank_change=scores[“rank_change”].abs())
.sort_values([“abs_rank_change”, “team”], ascending=[False, True])
.head(8)
)
show(biggest_movers[[
“team”, “raw_scoring_margin”, “baseline_margin”, “schedule_strength”,
“adjusted_rating”, “raw_rank”, “baseline_rank”, “adjusted_rank”, “rank_change”,
]])
The function chart reveals these eight strikes, with higher ranks towards the correct. Three groups illustrate what the mannequin is doing:
TeamRaw marginHome-adjusted baselineAverage opponent ratingFinal ratingBaseline → adjusted rankFlorida−7.64−7.64+14.56+6.92103 → 42UConn+7.91+8.14−12.82−4.6832 → 84Wisconsin−8.75−9.17+13.76+4.59109 → 53
Florida was outscored by 7.64 factors per included sport, however its opponents averaged +14.56 within the fitted scores. That provides as much as +6.92. The slate included Miami (+24.97), Georgia (+22.18), and Texas A&M (+20.80). A unfavourable scoring margin in opposition to that schedule means one thing totally different from the identical margin in opposition to common opponents.
UConn went the opposite means. Its +8.14 home-adjusted margin got here in opposition to opponents averaging −12.82, producing a −4.68 ranking. Ten of its eleven included opponents completed under zero on this mannequin. Duke was the exception at +6.01; Ball State (−22.86), Rice (−19.24), and Buffalo (−17.18) had been among the many weaker opponents.
Wisconsin had a tough slate that included Indiana (+37.14), Ohio State (+32.90), Oregon (+30.34), and Iowa (+21.13). Its baseline margin of −9.17 rose to a +4.59 ranking after accounting for a mean opponent ranking of +13.76.
These opponent values come from the identical fitted mannequin. They seem to be a technique to examine its reasoning, not impartial proof that its rankings are right. I chosen Florida and UConn as the most important rise and fall, then Wisconsin because the next-largest absolute transfer. That makes them helpful illustrations, not a prediction take a look at.
The person losses have not disappeared. The mannequin is estimating what the general efficiency means in opposition to this explicit set of opponents.
What this adjustment leaves unanswered
I’d deal with this as a baseline to grasp and examine. A number of essential selections stay:
Rubbish time and blowouts. Each level within the last rating counts, together with factors scored after the sport was successfully determined. Uncapped margins give giant wins and losses substantial affect.Accidents and roster modifications. A crew receives one ranking for the entire interval, even when its depth chart modified.Cross-division video games. Excluding FCS opponents removes data. Together with them would require a broader crew community and a transparent protection coverage.Small samples and weak connections. A full soccer season continues to be a modest pattern. Early-season scores have even much less data behind them.Recency and matchups. September and November rely equally, and one ranking cannot seize each interplay between taking part in types.
There’s additionally a timing difficulty: these full-season scores use outcomes from the complete included interval. Utilizing them to “predict” an earlier sport would herald data that wasn’t obtainable earlier than kickoff. A prediction take a look at wants scores calculated solely from data obtainable at the moment.
The identical thought carries over to basketball
Basketball offers us extra video games, however these video games nonetheless come in opposition to totally different schedules. A crew’s scoring numbers want context there, too.
Tempo provides one other consideration. A ten-point margin in a quick sport and a ten-point margin in a gradual sport do not characterize the identical distinction per possession. You would possibly begin with a possession-based measure, then account for opponents.
The precept transfers; the particular mannequin wants thought. Altering the goal to factors per possession modifications the models, so our 2.5-point dwelling adjustment would not switch straight. Separating offensive and defensive effectivity would additionally require separate results.
Comply with-up questions
Earlier than counting on a ranking, examine what sits behind the quantity:
What end result is being adjusted and what are its models?Which groups and video games are included?How are dwelling benefit and enormous margins dealt with?How effectively linked is the schedule and the way a lot data does every crew have?Are uncertainty and the timing of accessible data accounted for?Are you able to reproduce the calculation?
On your personal first experiment, examine the video games behind one crew’s ranking earlier than altering the mannequin. Examine its common margin, then its common opponent ranking. That small train makes it simpler to see what the adjustment provides and what it nonetheless leaves out.
Which crew’s schedule most modifications the way you interpret its uncooked numbers?