"""Replay conditional replacement pass-attempt shares from The Likely's cached CFBD boxes.""" import argparse from collections import Counter, defaultdict from datetime import date from hashlib import sha256 import json from pathlib import Path import random from statistics import mean import sys def athlete_only_boxes(games): """Keep attributable attempts. A provider Team row is an accounting entity.""" removed_rows = removed_attempts = 0 cleaned = [] for game in games: sides = [] for side in game['sides']: passers = {} for pid, row in side['qbs'].items(): if str(pid).isdecimal() and int(pid) > 0 and row[2].strip().casefold() != 'team': passers[pid] = row else: removed_rows += 1 removed_attempts += row[0] sides.append(dict(side, qbs=passers)) if all(side['qbs'] for side in sides): cleaned.append(dict(game, sides=sides)) return cleaned, {'removed_passer_rows': removed_rows, 'unattributed_attempts': removed_attempts, 'games_without_an_attributable_passer_on_both_sides': len(games) - len(cleaned)} def normalized(weights): total = sum(weights.values()) return {player: value / total for player, value in weights.items()} def predict(history): """Generate both rankings before observing the current game's passer box.""" if len(history) < 3: return None recent = Counter() for game in history[-3:]: recent.update(game) incumbent, volume = recent.most_common(1)[0] if volume < 0.60 * sum(recent.values()): return None uniform, decay = Counter(), Counter() for distance, game in enumerate(reversed(history)): for player, attempts in game.items(): if player != incumbent: uniform[player] += attempts decay[player] += attempts * 0.5 ** distance # Both methods use identical candidates and the same stable tie-breaking rule. return incumbent, normalized(uniform), normalized(decay) def total_variation(predicted, actual): return 0.5 * sum(abs(predicted.get(k, 0) - actual.get(k, 0)) for k in predicted.keys() | actual.keys()) def evaluate(games): history = defaultdict(list) cohorts, first_game_cohorts, trials = Counter(), Counter(), [] for g in sorted(games, key=lambda g: (g['season'], g['date'], g['game'])): season, week = g['season'], g['week'] day = date.fromisoformat(g['date']) both_fbs = all(t['fbs'] for t in g['sides']) for team in g['sides']: key = season, team['id'] # CFBD loader supplies dates, not game-end timestamps. Exclude the whole # target week and games that started less than two dates earlier. earlier = [attempts for past_week, past_day, attempts in history[key] if past_week < week and (day - past_day).days >= 2] prediction = predict(earlier) if both_fbs else None observed = {pid: row[0] for pid, row in team['qbs'].items()} history[key].append((week, day, observed)) if not prediction: continue cohorts[season] += 1 incumbent, equal, decay = prediction previous_share = earlier[-1].get(incumbent, 0) / sum(earlier[-1].values()) first_game = previous_share >= 0.60 first_game_cohorts[season] += int(first_game) if incumbent in observed: continue actual = normalized(observed) leaders = {pid for pid, n in observed.items() if n == max(observed.values())} row = {'season': season, 'week': week, 'game': g['game'], 'team': team['id'], 'started_previous': first_game, 'named': bool(equal), 'unseen_leader': not bool(leaders & equal.keys()), 'tied_lead': len(leaders) > 1} for name, model in (('season_weight', equal), ('recent_weight', decay)): if model: best = min(model, key=lambda pid: (-model[pid], pid)) row[name + '_hit'] = best in leaders row[name + '_tv'] = total_variation(model, actual) trials.append(row) return cohorts, first_game_cohorts, trials def summary(rows, eligible): named = [r for r in rows if r['named']] out = {'eligible_team_games': eligible, 'zero_attempt_cases': len(rows), 'named_cases': len(named), 'unseen_leader_cases': sum(r['unseen_leader'] for r in rows), 'tied_leaders': sum(r['tied_lead'] for r in rows)} if named: for model in ('season_weight', 'recent_weight'): out[model] = {'leader_hits': sum(r[model + '_hit'] for r in named), 'mean_share_error_pp': round(100 * mean(r[model + '_tv'] for r in named), 3)} by_week = defaultdict(list) for r in named: by_week[r['season'], r['week']].append(100 * (r['recent_weight_tv'] - r['season_weight_tv'])) totals = [(sum(v), len(v)) for v in by_week.values()] rng = random.Random(11282026) samples = [] for _ in range(10000): chosen = rng.choices(totals, k=len(totals)) samples.append(sum(s for s, n in chosen) / sum(n for s, n in chosen)) samples.sort() out['paired_recent_minus_season_share_error_95_pp'] = [round(samples[249], 3), round(samples[9749], 3)] out['week_blocks'] = len(totals) return out def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', type=Path, default=Path.home() / 'work') parser.add_argument('--cutoff', default='2026-11-28T16:00:00Z') args = parser.parse_args() research = args.root / 'sports-ratings-site/research' sys.path.insert(0, str(research)) from football_players import cfb_sources, clock games, _, receipts = cfb_sources(args.root / 'college-football-ensemble', args.root / 'nfl-team-ratings', 2026, clock(args.cutoff)) games, exclusions = athlete_only_boxes(games) assert len({g['game'] for g in games}) == len(games) cohorts, first_game_cohorts, rows = evaluate(games) years = sorted(cohorts) out = {'version': 'athlete-only-2', 'exclusions': exclusions, 'cutoff': args.cutoff, 'source_receipts': receipts, 'source_games': len(games), 'source_through': max(g['date'] for g in games), 'normalized_input_sha256': sha256(json.dumps(games, sort_keys=True, separators=(',', ':')).encode()).hexdigest(), 'loader_sha256': sha256((research / 'football_players.py').read_bytes()).hexdigest(), 'results': {y: summary([r for r in rows if r['season'] == y], cohorts[y]) for y in years}, 'all': summary(rows, sum(cohorts.values())), 'previous_game_60pct': {y: summary([r for r in rows if r['season'] == y and r['started_previous']], first_game_cohorts[y]) for y in years}, 'previous_game_60pct_all': summary([r for r in rows if r['started_previous']], sum(first_game_cohorts.values()))} print(json.dumps(out, indent=2)) if __name__ == '__main__': main()