CourtIQ / backend /fetch.py
Ryan
cache xfg model, analytics per team, and raw fetch results to speed up team loads
8e0b00e
Raw History Blame Contribute Delete
9.76 kB
"""
Fetch play-by-play from CollegeBasketballData API and flatten
to the same PascalCase schema that analysis.py expects.
"""
import os
import requests
import pandas as pd
API_BASE = 'https://api.collegebasketballdata.com'
def _api_key():
# prefer backup key; fall back to primary
return (os.getenv('CBB_BACKUP_KEY')
or os.getenv('CBB_API_KEY')
or '')
_TEAM_DF = None
def _team_df():
global _TEAM_DF
if _TEAM_DF is None:
path = os.path.join(os.path.dirname(__file__), 'teamdata.csv')
_TEAM_DF = pd.read_csv(path, encoding='utf-8-sig')
return _TEAM_DF
def get_teams():
"""Return sorted list of D1 team names from local teamdata.csv."""
return sorted(_team_df()['School'].dropna().unique().tolist())
def get_team_logo_url(team_name: str) -> str | None:
"""Return logo URL for a team, or None if not found."""
df = _team_df()
row = df[df['School'].str.lower() == team_name.lower()]
if row.empty:
return None
team_id = row.iloc[0]['SourceId']
return f'https://cdn.collegefootballdata.com/cbb-logos/32/{int(team_id)}.png'
def get_team_colors(team_name: str) -> dict:
"""Return primary/secondary hex colors (no #) for a team, or None values if not found."""
df = _team_df()
row = df[df['School'].str.lower() == team_name.lower()]
if row.empty:
return {'primary': None, 'secondary': None}
r = row.iloc[0]
def _clean_hex(val):
s = str(val).strip() if pd.notna(val) else ''
return s if len(s) == 6 else None
return {
'primary': _clean_hex(r.get('PrimaryColor')),
'secondary': _clean_hex(r.get('SecondaryColor')),
}
_raw_cache: dict = {}
def fetch_and_flatten(team: str, season: int) -> pd.DataFrame:
"""Fetch all plays for a team/season and return a flat DataFrame."""
key = (team.lower(), season)
if key in _raw_cache:
return _raw_cache[key].copy()
r = requests.get(
f'{API_BASE}/plays/team',
headers={'Authorization': f'Bearer {_api_key()}'},
params={'team': team, 'season': season},
timeout=60,
)
if r.status_code == 429:
raise RuntimeError('API quota exceeded. Try again later.')
r.raise_for_status()
raw = r.json()
if not isinstance(raw, list) or not raw:
raise ValueError(f'No data returned for {team} {season}')
df = pd.DataFrame(raw)
df = df[df['team'].notna() & (df['team'] != '')].reset_index(drop=True)
if df.empty:
raise ValueError(f'No valid plays for {team} {season}')
# ── Flatten shotInfo ──────────────────────────────────────────────────────
shot_rows = []
for si in df['shotInfo']:
if isinstance(si, dict):
loc = si.get('location') or {}
sht = si.get('shooter') or {}
abt = si.get('assistedBy') or {}
shot_rows.append({
'ShotInfo Made': si.get('made'),
'ShotInfo Range': si.get('range'),
'ShotInfo Assisted': si.get('assisted'),
'ShotInfo Shooter Id': sht.get('id'),
'ShotInfo Shooter Name': sht.get('name'),
'ShotInfo AssistedBy Id': abt.get('id'),
'ShotInfo AssistedBy Name': abt.get('name'),
'ShotInfo Location X': loc.get('x'),
'ShotInfo Location Y': loc.get('y'),
})
else:
shot_rows.append({k: None for k in [
'ShotInfo Made', 'ShotInfo Range', 'ShotInfo Assisted',
'ShotInfo Shooter Id', 'ShotInfo Shooter Name',
'ShotInfo AssistedBy Id', 'ShotInfo AssistedBy Name',
'ShotInfo Location X', 'ShotInfo Location Y',
]})
shot_df = pd.DataFrame(shot_rows)
# ── Flatten onFloor ───────────────────────────────────────────────────────
lineup_rows = []
for _, row in df.iterrows():
players = row['onFloor'] if isinstance(row['onFloor'], list) else []
tm = row['team']
team_p = [p for p in players if isinstance(p, dict) and p.get('team') == tm]
opp_p = [p for p in players if isinstance(p, dict) and p.get('team') != tm]
r2 = {}
for j, p in enumerate(team_p[:5]):
r2[f'OnFloor[{j}] Name'] = p.get('name')
r2[f'OnFloor[{j}] Team'] = p.get('team')
r2[f'OnFloor[{j}] Id'] = p.get('id')
for j, p in enumerate(opp_p[:5]):
r2[f'OnFloor[{j+5}] Name'] = p.get('name')
r2[f'OnFloor[{j+5}] Team'] = p.get('team')
r2[f'OnFloor[{j+5}] Id'] = p.get('id')
lineup_rows.append(r2)
lu_df = pd.DataFrame(lineup_rows)
# ── Rename base columns to PascalCase ─────────────────────────────────────
rename = {
'gameId': 'GameId', 'gameSourceId': 'GameSourceId',
'gameStartDate': 'GameStartDate', 'season': 'Season',
'seasonType': 'SeasonType', 'gameType': 'GameType',
'tournament': 'Tournament', 'id': 'Id', 'sourceId': 'SourceId',
'playType': 'PlayType', 'isHomeTeam': 'IsHomeTeam',
'teamId': 'TeamId', 'team': 'Team', 'conference': 'Conference',
'teamSeed': 'TeamSeed', 'opponentId': 'OpponentId',
'opponent': 'Opponent', 'opponentConference': 'OpponentConference',
'opponentSeed': 'OpponentSeed', 'homeScore': 'HomeScore',
'awayScore': 'AwayScore', 'homeWinProbability': 'HomeWinProbability',
'period': 'Period', 'clock': 'Clock',
'secondsRemaining': 'SecondsRemaining', 'scoringPlay': 'ScoringPlay',
'shootingPlay': 'ShootingPlay', 'scoreValue': 'ScoreValue',
'wallclock': 'Wallclock', 'playText': 'PlayText',
}
base = (df
.drop(columns=['shotInfo', 'onFloor', 'participants'], errors='ignore')
.rename(columns=rename))
result = pd.concat([base.reset_index(drop=True), shot_df, lu_df], axis=1)
# 2026+ data doesn't include OnFloor columns β€” infer from substitution events
if result.get('OnFloor[0] Name', pd.Series(dtype=object)).isna().mean() > 0.9:
result = _infer_lineups_from_subs(result, team)
_raw_cache[key] = result
return result
def _infer_lineups_from_subs(df: pd.DataFrame, team: str) -> pd.DataFrame:
"""Infer on-floor lineups from substitution play events (used for 2026+ data)."""
def parse_sub(text):
text = str(text)
if f'subbing out for {team}' in text:
return text.replace(f' subbing out for {team}', '').strip(), 'out'
if f'subbing in for {team}' in text:
return text.replace(f' subbing in for {team}', '').strip(), 'in'
return None, None
# Build lineup_map: (game_id, period, secs) β†’ [p0..p4]
lineup_rows = []
for game_id, game_df in df.groupby('GameId'):
if team not in game_df['Team'].values:
continue
g = game_df.sort_values(['Period', 'SecondsRemaining'], ascending=[True, False])
# Infer starters: players whose first sub event is "out"
team_subs = g[(g['PlayType'] == 'Substitution') & (g['Team'] == team)]
seen: dict = {}
starters: set = set()
for _, row in team_subs.iterrows():
p, sub_type = parse_sub(row['PlayText'])
if p and p not in seen:
seen[p] = sub_type
if sub_type == 'out':
starters.add(p)
if not starters:
continue
on_court = set(starters)
# Group by timestamp once β€” avoids per-timestamp boolean mask scans
ts_groups = g.groupby(['Period', 'SecondsRemaining'], sort=False)
sorted_keys = sorted(ts_groups.groups.keys(), key=lambda k: (k[0], -k[1]))
for (period, secs) in sorted_keys:
ts_group = ts_groups.get_group((period, secs))
subs = ts_group[(ts_group['PlayType'] == 'Substitution') & (ts_group['Team'] == team)]
# Apply outs first, then ins (avoids momentary 6-man lineups)
for _, sub_row in subs.iterrows():
p, sub_type = parse_sub(sub_row['PlayText'])
if p and sub_type == 'out':
on_court.discard(p)
for _, sub_row in subs.iterrows():
p, sub_type = parse_sub(sub_row['PlayText'])
if p and sub_type == 'in':
on_court.add(p)
players = sorted(on_court)[:5]
row = {'GameId': game_id, 'Period': period, 'SecondsRemaining': secs}
for i, p in enumerate(players):
row[f'OnFloor[{i}] Name'] = p
row[f'OnFloor[{i}] Team'] = team
lineup_rows.append(row)
if not lineup_rows:
for i in range(5):
df[f'OnFloor[{i}] Name'] = None
df[f'OnFloor[{i}] Team'] = None
return df
# Drop the empty OnFloor columns added earlier, then merge in one shot
drop = [c for c in df.columns if c.startswith('OnFloor[')]
df = df.drop(columns=drop, errors='ignore')
lu_df = pd.DataFrame(lineup_rows)
df = df.merge(lu_df, on=['GameId', 'Period', 'SecondsRemaining'], how='left')
# Ensure all 5 slots exist even if some lineups had fewer players
for i in range(5):
if f'OnFloor[{i}] Name' not in df.columns:
df[f'OnFloor[{i}] Name'] = None
df[f'OnFloor[{i}] Team'] = None
return df