{"fileIntegrity":{"sha256":"d46ed3540ee8d9eca31b3e94cc8c777e0be5156173d814ebf65b8195e8d616bc","bytes":18173265},"columnsUsed":["game_id","lg_id","year_id","date_game","is_playoffs","team_id","fran_id","pts","opp_id","opp_fran","opp_pts","game_location"],"splits":{"training":{"periods":["2010-2011","2011-2012","2012-2013"],"firstDate":"2010-10-26","lastDate":"2013-04-17","events":3449,"outcomes":{"homeWin":2075,"awayWin":1374},"neutralSiteEvents":3,"teams":30,"teamGameCountHistogram":{"229":2,"230":28}},"calibration":{"periods":["2013-2014"],"firstDate":"2013-10-29","lastDate":"2014-04-16","events":1230,"outcomes":{"homeWin":714,"awayWin":516},"neutralSiteEvents":1,"teams":30,"teamGameCountHistogram":{"82":30}},"test":{"periods":["2014-2015"],"firstDate":"2014-10-28","lastDate":"2015-04-15","events":1230,"outcomes":{"homeWin":707,"awayWin":523},"neutralSiteEvents":2,"teams":30,"teamGameCountHistogram":{"82":30}},"bySeason":{"2011":{"periods":["2010-2011"],"firstDate":"2010-10-26","lastDate":"2011-04-13","events":1230,"outcomes":{"homeWin":743,"awayWin":487},"neutralSiteEvents":2,"teams":30,"teamGameCountHistogram":{"82":30}},"2012":{"periods":["2011-2012"],"firstDate":"2011-12-25","lastDate":"2012-04-26","events":990,"outcomes":{"homeWin":580,"awayWin":410},"neutralSiteEvents":0,"teams":30,"teamGameCountHistogram":{"66":30}},"2013":{"periods":["2012-2013"],"firstDate":"2012-10-30","lastDate":"2013-04-17","events":1229,"outcomes":{"homeWin":752,"awayWin":477},"neutralSiteEvents":1,"teams":30,"teamGameCountHistogram":{"81":2,"82":28}},"2014":{"periods":["2013-2014"],"firstDate":"2013-10-29","lastDate":"2014-04-16","events":1230,"outcomes":{"homeWin":714,"awayWin":516},"neutralSiteEvents":1,"teams":30,"teamGameCountHistogram":{"82":30}},"2015":{"periods":["2014-2015"],"firstDate":"2014-10-28","lastDate":"2015-04-15","events":1230,"outcomes":{"homeWin":707,"awayWin":523},"neutralSiteEvents":2,"teams":30,"teamGameCountHistogram":{"82":30}}}},"exclusions":{"input_rows":126314,"outside_split_rows":105358,"non_NBA_rows":8298,"selected_rows":12658,"consistent_mirror_pairs":6329,"duplicate_rows_removed":6329,"home_suffix_checks":5903,"neutral_games_retained":6,"playoff_games_removed":420,"max_games_per_team_per_date":1,"playInGamesRemoved":0,"invalidScoreGamesRemoved":0,"unknownVenueGamesRemoved":0,"missingScoreGamesRemoved":0,"tiedFinalGamesRemoved":0},"exclusionsBySeason":{"2011":{"duplicate_rows_removed":1311,"playoff_games_removed":81},"2012":{"duplicate_rows_removed":1074,"playoff_games_removed":84},"2013":{"duplicate_rows_removed":1314,"playoff_games_removed":85},"2014":{"duplicate_rows_removed":1319,"playoff_games_removed":89},"2015":{"duplicate_rows_removed":1311,"playoff_games_removed":81}},"fitted":{"trainingHomeWinFrequency":0.6016236590316033,"temperature":1.1722545302799172,"calibrationScaledLogLoss":0.6131413017177624},"testResults":{"baseline":{"n":1230,"brier":"0.4903","brierBootstrap95":["0.4781","0.5020"],"logLoss":"0.6834","logLossBootstrap95":["0.6711","0.6953"]},"rawElo":{"n":1230,"brier":"0.4213","brierBootstrap95":["0.4010","0.4419"],"logLoss":"0.6090","logLossBootstrap95":["0.5858","0.6332"]},"scaledElo":{"n":1230,"brier":"0.4201","brierBootstrap95":["0.4022","0.4384"],"logLoss":"0.6074","logLossBootstrap95":["0.5873","0.6286"]}},"reliabilityBins":{"baseline":[{"bin":"[0.0,0.1)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.1,0.2)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.2,0.3)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.3,0.4)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.4,0.5)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.5,0.6)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.6,0.7)","n":1230,"meanPredicted":0.601624,"observedRate":0.574797},{"bin":"[0.7,0.8)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.8,0.9)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.9,1.0]","n":0,"meanPredicted":null,"observedRate":null}],"rawElo":[{"bin":"[0.0,0.1)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.1,0.2)","n":12,"meanPredicted":0.177163,"observedRate":0.166667},{"bin":"[0.2,0.3)","n":63,"meanPredicted":0.256828,"observedRate":0.269841},{"bin":"[0.3,0.4)","n":111,"meanPredicted":0.354445,"observedRate":0.297297},{"bin":"[0.4,0.5)","n":146,"meanPredicted":0.449663,"observedRate":0.376712},{"bin":"[0.5,0.6)","n":198,"meanPredicted":0.554402,"observedRate":0.494949},{"bin":"[0.6,0.7)","n":218,"meanPredicted":0.64969,"observedRate":0.600917},{"bin":"[0.7,0.8)","n":235,"meanPredicted":0.750242,"observedRate":0.706383},{"bin":"[0.8,0.9)","n":206,"meanPredicted":0.848081,"observedRate":0.81068},{"bin":"[0.9,1.0]","n":41,"meanPredicted":0.920177,"observedRate":0.926829}],"scaledElo":[{"bin":"[0.0,0.1)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.1,0.2)","n":3,"meanPredicted":0.178832,"observedRate":0.333333},{"bin":"[0.2,0.3)","n":48,"meanPredicted":0.261577,"observedRate":0.291667},{"bin":"[0.3,0.4)","n":110,"meanPredicted":0.354624,"observedRate":0.254545},{"bin":"[0.4,0.5)","n":171,"meanPredicted":0.449534,"observedRate":0.374269},{"bin":"[0.5,0.6)","n":236,"meanPredicted":0.553999,"observedRate":0.508475},{"bin":"[0.6,0.7)","n":252,"meanPredicted":0.651183,"observedRate":0.619048},{"bin":"[0.7,0.8)","n":244,"meanPredicted":0.749898,"observedRate":0.741803},{"bin":"[0.8,0.9)","n":155,"meanPredicted":0.841115,"observedRate":0.858065},{"bin":"[0.9,1.0]","n":11,"meanPredicted":0.914573,"observedRate":0.909091}]},"bootstrap":{"method":"Percentile game-date cluster bootstrap; dates sampled with replacement; all games on each sampled date retained; common draws for all models; no refitting","replicates":2000,"seed":20261126,"dateClusters":162,"quantile":"Linear interpolation at (replicates-1)*q, q=0.025 and 0.975"},"checks":{"sourceHashAndBytesVerified":true,"uniqueEventIds":true,"pairedRowsConsistent":true,"splitsDisjointAndChronological":true,"latestSeasonInFile":2015,"calibrationAndTestEach30Teams82Games":true,"noTeamTwiceOnSameDate":true,"minimumUpdateDateGapDays":2,"updatesAppliedBeforeLastForecast":5892,"noWithinDateUpdates":true,"prefixPredictionsUnchanged":true,"flippedDateLabelsCannotChangeForecastUntilLagElapsed":true,"withinDateReorderingUnchanged":true},"status":"computed","sport":"NBA","label":"Historical regular-season home/away final-score baseline, overtime included. Research only; not live or deployed accuracy; no wagers.","candidates":[{"name":"FiveThirtyEight/data: Historical NBA Elo results archive","url":"https://github.com/fivethirtyeight/data/tree/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo","licenceName":"Creative Commons Attribution 4.0 International (CC BY 4.0)","licenceUrl":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","licenceDeedUrl":"https://creativecommons.org/licenses/by/4.0/","quotedTerms":[{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/README.md","quote":"Unless otherwise noted, our data sets are available under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/)"},{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quote":"       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material."},{"url":"https://creativecommons.org/licenses/by/4.0/","quote":"for any purpose, even commercially."}],"commercialReuse":"permitted","fetched":true,"decision":"Repository licence scope covers datasets unless otherwise noted; the fetched folder README contains no different licence. Commercial reuse is permitted subject to attribution and the licence conditions. One archive candidate used; no need to try another."}],"dataset":{"publisher":"FiveThirtyEight","title":"Historical NBA Elo / nbaallelo.csv","commit":"6d880e939ad3d11d94c137c911681b3cf718fd74","fileUrls":["https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv"],"files":[{"path":"nba-elo/nbaallelo.csv","url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv","sha256":"d46ed3540ee8d9eca31b3e94cc8c777e0be5156173d814ebf65b8195e8d616bc","bytes":18173265,"retrievedUtc":"2026-11-26T03:29:50.053736+00:00"}],"retrievedUtc":"2026-11-26T03:29:50.053736+00:00","documentationUrl":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/README.md","licenceScopeUrl":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/README.md","archiveLatestSeasonEndYear":2015,"completenessEvidence":"Latest season: 2015. Test and calibration each have 1230 games, 30 franchises, 82 games/franchise, computed from pinned bytes."},"creditLine":"FiveThirtyEight, Historical NBA Elo (https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv), credits Basketball-Reference.com for game information. CC BY 4.0: https://creativecommons.org/licenses/by/4.0/. Changes: filtering, deduplication, home/away normalization, new forecasts and evaluation. No endorsement implied.","splitDeclaration":"Before forecast computation: latest complete regular season in this file (2014-2015) held out for test; 2013-2014 calibration; preceding three seasons 2010-2011, 2011-2012, 2012-2013 training. No earlier games initialize ratings; no test-based model or parameter selection.","outcomeRule":{"outcomes":["homeWin","awayWin"],"definition":"Orient a row to home: homeWin iff pts > opp_pts, else awayWin. Use archived final totals including overtime, with no overtime exclusion. Exclude/count tied finals.","homeDesignation":"H/A: home is H. N/N: nominal home team_id matches game_id final three characters. Convention inferred, not documented; verified on all 5903 retained non-neutral games. All six neutrals resolve uniquely; H=0.","source":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv","documentationUrl":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/README.md"},"exclusionRules":{"order":"Sequential: non-NBA rows; outside-period rows; reciprocal duplicate rows; playoffs (is_playoffs=1); missing scores; tied finals. Invalid scores/venues fail assertions.","units":"Rows before deduplication, games after. Mirror pairs, suffix checks, retained neutrals and games/team/date are audit counts.","reconciliation":"126314-8298-105358=12658 rows; 12658-6329 duplicates-420 playoffs=5909 games=3449+1230+1230.","playIn":{"count":0,"reason":"Pre-2020 window.","source":"https://www.nba.com/news/play-in-tournament-history"},"missingScores":{"count":0,"scope":"Selected unique games after playoff removal"},"duplicateRows":{"count":6329,"note":"One reciprocal row/game, including 420 playoff pairs; grouping by game_id only."},"otherExclusions":"None. Neutrals retained. No separate play-in flag: script pinned to this pre-2020 window."},"method":{"baseline":{"probabilityHome":0.6016236590316033,"probabilityAway":0.3983763409683967,"numeratorHomeWins":2075,"denominatorTrainingGames":3449,"choice":"Unsmoothed training home-win frequency, fixed through calibration and test"},"elo":{"initialRating":1500,"K":20,"ratingScale":400,"homeAdvantagePoints":100,"neutralHomeAdvantagePoints":0,"seasonRetention":0.75,"regressionTarget":1500,"probability":"p(home)=1/(1+10**(-(Rhome-Raway+H)/400)); p(away)=1-p(home)","update":"At eligibility, delta=20*(y_home-p_home_saved_at_forecast); add delta to home rating, subtract from away. No margin multiplier. Results are queued; scaled probabilities never feed rating updates.","offseason":"Apply all eligible prior-season regular results before the next season; regress each existing rating to 1500 + 0.75*(rating-1500). Unseen franchise IDs start at 1500. Franchise identifiers link renamed team codes.","updateLagCalendarDays":2,"withinDateUpdates":false,"selection":"All Elo constants, the lag and regression were fixed before any forecasts or scoring; no hyperparameter search."},"temperature":{"T":1.1722545302799172,"formula":"sigmoid(log(p_raw/(1-p_raw))/T)","fitting":"Minimize mean natural-log loss on 1230 calibration events only, over log(T) in [log(0.25),log(4)]. Golden-section search, 100 iterations, then compare midpoint and both endpoints. Freeze T before generating/scoring test forecasts.","calibrationLoss":0.6131413017177624,"bounds":[0.25,4.0],"iterations":100},"evaluation":{"brier":"Mean over events of (p_home-y_home)^2 + (p_away-y_away)^2 = 2*(p_home-y_home)^2; range 0 to 2.","logLoss":"Mean -log(probability of realized outcome), natural logarithm.","epsilon":1e-15,"clipping":"For loss evaluation only, probabilities clipped to [1e-15,1-1e-15].","rounding":"Metrics and bootstrap endpoints are decimal strings with four places, from unrounded computations. Reliability means/rates have six decimal places.","reliability":"Test only; ten fixed home-win probability bins of width 0.1, left inclusive and right exclusive except final bin includes 1; empty-bin means/rates null."}},"leakageRule":"Only the whitelisted identifiers, league/season/postseason metadata, date, venue flag and final scores are read. Each forecast uses ratings updated solely from games dated at least two calendar days earlier. Every date is forecast as a batch. Final labels are used for updates only after that embargo. Calibration and test results update subsequent Elo ratings online under the same frozen rule. Training frequency uses training labels only; T uses calibration labels only. No source Elo, forecasts, odds, lineups or notes enter the model. No exact start/end timestamps exist: the embargo is a conservative date proxy, not a verified timestamp ordering.","additionalChecks":{"ignoredSourceColumnsPerturbationInvariant":true,"analyticLossChecksPassed":true,"constantBaselineIndependentFormulaPassed":true,"reliabilityBinTotalsPassed":true},"limitations":["Historical 2015-file evidence only; no current accuracy, profitability or guaranteed-outcome claim.","Dates cannot certify literal end-before-start timing. Two-day embargo reduces ambiguity but discards recent information.","Licence relies on the repository CC BY 4.0 grant. Third-party rights were not audited; retain attribution, notices and change disclosure.","Neutral nominal-home inference is not independently documented; no physical home advantage is assumed.","No second-provider score audit. Reciprocal rows are not independent evidence; retrospective corrections may differ from contemporaneous data.","Training retains archived 990 games in 2011-2012 and 1229 in 2012-2013 (two teams: 81 games); nothing imputed.","One test season; cold initial ratings; no injuries, roster, rest or other contextual inputs.","Bootstrap conditions on fixed fitted forecasts; longer serial/team dependence and fitting uncertainty are omitted. Sparse bins are noisy; future calibration is unproved.","Raw CSV is not embedded. Supply pinned bytes locally for offline reproduction; no Python packages needed."],"reproduce":{"runtime":"Python 3.12 standard library only; no packages, API keys or paid services","commands":["python3 - <<'PY'\nimport json,pathlib,urllib.request,hashlib\nr=json.loads(pathlib.Path('artifacts/goal/batches/sport-baselines-v5/items/nba/result.json').read_text())\nw=pathlib.Path('test/scratch/nba-reproduce'); w.mkdir(parents=True,exist_ok=True)\n(w/'baseline.py').write_text(r['reproduce']['script'],encoding='utf-8')\np=w/'nbaallelo.csv'\nif not p.exists():\n    p.write_bytes(urllib.request.urlopen(r['dataset']['fileUrls'][0],timeout=120).read())\nf=r['dataset']['files'][0]\nassert p.stat().st_size==f['bytes'] and hashlib.sha256(p.read_bytes()).hexdigest()==f['sha256']\nPY","python3 test/scratch/nba-reproduce/baseline.py test/scratch/nba-reproduce/nbaallelo.csv > test/scratch/nba-reproduce/computed.json","python3 - <<'PY'\nimport json,pathlib\nr=json.loads(pathlib.Path('artifacts/goal/batches/sport-baselines-v5/items/nba/result.json').read_text())\na=json.loads(pathlib.Path('test/scratch/nba-reproduce/computed.json').read_text())\nfor k in r['reproduce']['comparisonKeys']:\n    assert a[k]==r[k], k\nprint('All reproduced computation fields match.')\nPY"],"script":"#!/usr/bin/env python3\n\"\"\"Historical NBA baseline. Python 3 standard library; never reads source forecasts.\"\"\"\nimport collections\nimport csv\nimport datetime as dt\nimport hashlib\nimport json\nimport math\nimport pathlib\nimport random\nimport sys\n\nURL = 'https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv'\nSHA = 'd46ed3540ee8d9eca31b3e94cc8c777e0be5156173d814ebf65b8195e8d616bc'\nSIZE = 18173265\nTRAIN = (2011, 2012, 2013)\nCAL, TEST = 2014, 2015\nK, HOME, SCALE, RETAIN, LAG = 20.0, 100.0, 400.0, 0.75, 2\nSEED, REPS = 20261126, 2000\nCOLS = ('game_id', 'lg_id', 'year_id', 'date_game', 'is_playoffs',\n        'team_id', 'fran_id', 'pts', 'opp_id', 'opp_fran', 'opp_pts', 'game_location')\n\n\ndef load(path, verify=True):\n    blob = pathlib.Path(path).read_bytes()\n    digest = hashlib.sha256(blob).hexdigest()\n    if verify:\n        assert digest == SHA and len(blob) == SIZE, 'Source bytes changed'\n    counts = collections.Counter()\n    groups = collections.defaultdict(list)\n    with pathlib.Path(path).open(newline='', encoding='utf-8') as f:\n        for full in csv.DictReader(f):\n            r = {k: full[k] for k in COLS}\n            counts['input_rows'] += 1\n            if r['lg_id'] != 'NBA':\n                counts['non_NBA_rows'] += 1\n                continue\n            if int(r['year_id']) not in (*TRAIN, CAL, TEST):\n                counts['outside_split_rows'] += 1\n                continue\n            counts['selected_rows'] += 1\n            groups[r['game_id']].append(r)\n    games = []\n    by_season = collections.defaultdict(collections.Counter)\n    for gid, rows in sorted(groups.items()):\n        assert len(rows) == 2, ('Unexpected multiplicity', gid)\n        a, b = rows\n        assert all(a[k] == b[k] for k in ('game_id', 'date_game', 'year_id', 'is_playoffs'))\n        assert a['team_id'] == b['opp_id'] and b['team_id'] == a['opp_id']\n        assert a['fran_id'] == b['opp_fran'] and b['fran_id'] == a['opp_fran']\n        assert a['pts'] == b['opp_pts'] and b['pts'] == a['opp_pts']\n        counts['consistent_mirror_pairs'] += 1\n        counts['duplicate_rows_removed'] += 1\n        season = int(a['year_id'])\n        by_season[season]['duplicate_rows_removed'] += 1\n        assert a['is_playoffs'] in ('0', '1')\n        if a['is_playoffs'] == '1':\n            counts['playoff_games_removed'] += 1\n            by_season[season]['playoff_games_removed'] += 1\n            continue\n        if not a['pts'].strip() or not a['opp_pts'].strip():\n            counts['missing_score_games_removed'] += 1\n            by_season[season]['missing_score_games_removed'] += 1\n            continue\n        neutral = a['game_location'] == b['game_location'] == 'N'\n        if neutral:\n            # Inference from identifier structure, checked on every H/A game below.\n            home = [r for r in rows if gid[-3:] == r['team_id']]\n            assert len(home) == 1, ('Unresolved neutral designation', gid)\n            home = home[0]\n            counts['neutral_games_retained'] += 1\n        else:\n            assert sorted(r['game_location'] for r in rows) == ['A', 'H']\n            home = next(r for r in rows if r['game_location'] == 'H')\n            assert gid[-3:] == home['team_id']\n            counts['home_suffix_checks'] += 1\n        date = dt.datetime.strptime(home['date_game'], '%m/%d/%Y').date()\n        assert gid[:8] == date.strftime('%Y%m%d')\n        hs, aws = int(home['pts']), int(home['opp_pts'])\n        assert hs >= 0 and aws >= 0\n        if hs == aws:\n            counts['tied_final_games_removed'] += 1\n            by_season[season]['tied_final_games_removed'] += 1\n            continue\n        games.append(dict(id=gid, date=date.isoformat(), season=season,\n                          home=home['fran_id'], away=home['opp_fran'],\n                          neutral=neutral, y=int(hs > aws)))\n    games.sort(key=lambda g: (g['date'], g['id']))\n    assert len({g['id'] for g in games}) == len(games)\n    teams_per_day = collections.Counter((g['date'], t) for g in games for t in (g['home'], g['away']))\n    assert max(teams_per_day.values()) == 1\n    counts['max_games_per_team_per_date'] = max(teams_per_day.values())\n    for year in (CAL, TEST):\n        c = collections.Counter(t for g in games if g['season'] == year for t in (g['home'], g['away']))\n        assert len(c) == 30 and set(c.values()) == {82}\n    # No NBA rows with a later season exist in these pinned bytes (checked separately).\n    with pathlib.Path(path).open(newline='', encoding='utf-8') as f:\n        latest = max(int(r['year_id']) for r in csv.DictReader(f) if r['lg_id'] == 'NBA')\n    assert latest == TEST\n    return games, dict(counts), {str(k): dict(v) for k, v in sorted(by_season.items())}, digest\n\n\nclass Elo:\n    def __init__(self):\n        self.rating = collections.defaultdict(lambda: 1500.0)\n        self.pending = collections.deque()\n        self.season = None\n        self.last_date = None\n        self.min_gap = 1000000\n        self.applied = 0\n\n    def run(self, games):\n        out = []\n        for date, it in __import__('itertools').groupby(games, key=lambda g: g['date']):\n            day = list(it)\n            now = dt.date.fromisoformat(date)\n            assert self.last_date is None or date > self.last_date\n            while self.pending and (now - dt.date.fromisoformat(self.pending[0][0]['date'])).days >= LAG:\n                g, p = self.pending.popleft()\n                gap = (now - dt.date.fromisoformat(g['date'])).days\n                self.min_gap = min(self.min_gap, gap)\n                self.applied += 1\n                change = K * (g['y'] - p)\n                self.rating[g['home']] += change\n                self.rating[g['away']] -= change\n            season = day[0]['season']\n            assert all(g['season'] == season for g in day)\n            if self.season is not None and season != self.season:\n                assert not self.pending, 'Prior season results must precede regression'\n                for t in self.rating:\n                    self.rating[t] = 1500.0 + RETAIN * (self.rating[t] - 1500.0)\n            self.season = season\n            for g in day:\n                advantage = 0.0 if g['neutral'] else HOME\n                z = (self.rating[g['home']] - self.rating[g['away']] + advantage) / SCALE\n                p = 1.0 / (1.0 + 10.0 ** (-z))\n                assert 0.0 < p < 1.0\n                out.append(dict(g, p=p))\n                self.pending.append((g, p))\n            self.last_date = date\n        return out\n\n\ndef scaled(p, temperature):\n    return 1.0 / (1.0 + math.exp(-math.log(p / (1.0 - p)) / temperature))\n\n\ndef loss(p, y):\n    p = min(1.0 - 1e-15, max(1e-15, p))\n    return 2.0 * (p - y) ** 2, -(y * math.log(p) + (1 - y) * math.log1p(-p))\n\n\ndef fit_temperature(cal):\n    def objective(logt):\n        return math.fsum(loss(scaled(g['p'], math.exp(logt)), g['y'])[1] for g in cal) / len(cal)\n    lo, hi = math.log(0.25), math.log(4.0)\n    ratio = (math.sqrt(5.0) - 1.0) / 2.0\n    c, d = hi - ratio * (hi - lo), lo + ratio * (hi - lo)\n    fc, fd = objective(c), objective(d)\n    for _ in range(100):\n        if fc < fd:\n            hi, d, fd = d, c, fc\n            c = hi - ratio * (hi - lo)\n            fc = objective(c)\n        else:\n            lo, c, fc = c, d, fd\n            d = lo + ratio * (hi - lo)\n            fd = objective(d)\n    best = min((math.log(0.25), math.log(4.0), (lo + hi) / 2.0), key=objective)\n    return math.exp(best), objective(best)\n\n\ndef summary(games):\n    def one(gs):\n        teams = collections.Counter(t for g in gs for t in (g['home'], g['away']))\n        return dict(periods=[str(y-1) + '-' + str(y) for y in sorted({g['season'] for g in gs})],\n                    firstDate=gs[0]['date'], lastDate=gs[-1]['date'], events=len(gs),\n                    outcomes=dict(homeWin=sum(g['y'] for g in gs), awayWin=sum(1-g['y'] for g in gs)),\n                    neutralSiteEvents=sum(g['neutral'] for g in gs), teams=len(teams),\n                    teamGameCountHistogram=dict(sorted(collections.Counter(teams.values()).items())))\n    result = {name: one([g for g in games if g['season'] in years])\n              for name, years in [('training', TRAIN), ('calibration', (CAL,)), ('test', (TEST,))]}\n    result['bySeason'] = {str(y): one([g for g in games if g['season'] == y]) for y in (*TRAIN, CAL, TEST)}\n    return result\n\n\ndef evaluate(test, constant, temperature):\n    names = ('baseline', 'rawElo', 'scaledElo')\n    bins = {name: [[] for _ in range(10)] for name in names}\n    daily = collections.defaultdict(list)\n    losses = {name: [] for name in names}\n    for g in test:\n        probs = (constant, g['p'], scaled(g['p'], temperature))\n        values = []\n        for name, p in zip(names, probs):\n            v = loss(p, g['y'])\n            losses[name].append(v)\n            values.extend(v)\n            bins[name][min(9, int(p * 10))].append((p, g['y']))\n        daily[g['date']].append(values)\n    blocks = [(len(rows), [math.fsum(r[i] for r in rows) for i in range(6)])\n              for _, rows in sorted(daily.items())]\n    rng = random.Random(SEED)\n    boot = [[] for _ in range(6)]\n    for _ in range(REPS):\n        selected = [blocks[rng.randrange(len(blocks))] for _ in blocks]\n        n = sum(b[0] for b in selected)\n        for i in range(6):\n            boot[i].append(math.fsum(b[1][i] for b in selected) / n)\n    def quantile(v, q):\n        a = sorted(v)\n        pos = (len(a) - 1) * q\n        i = int(pos)\n        return a[i] + (a[min(i + 1, len(a) - 1)] - a[i]) * (pos - i)\n    results, reliability = {}, {}\n    for j, name in enumerate(names):\n        metric = dict(n=len(test))\n        for i, label in enumerate(('brier', 'logLoss')):\n            metric[label] = format(math.fsum(v[i] for v in losses[name]) / len(test), '.4f')\n            metric[label + 'Bootstrap95'] = [format(quantile(boot[2*j+i], q), '.4f') for q in (0.025, 0.975)]\n        results[name] = metric\n        reliability[name] = [dict(bin=f'[{i/10:.1f},{(i+1)/10:.1f}' + (']' if i == 9 else ')'),\n                                 n=len(b), meanPredicted=round(math.fsum(p for p, _ in b)/len(b), 6) if b else None,\n                                 observedRate=round(sum(y for _, y in b)/len(b), 6) if b else None)\n                             for i, b in enumerate(bins[name])]\n    return results, reliability, len(blocks)\n\n\ndef compute(path, verify=True):\n    games, counts, exclusions_by_season, digest = load(path, verify)\n    train = [g for g in games if g['season'] in TRAIN]\n    cal_games = [g for g in games if g['season'] == CAL]\n    test_games = [g for g in games if g['season'] == TEST]\n    assert max(g['date'] for g in train) < min(g['date'] for g in cal_games)\n    assert max(g['date'] for g in cal_games) < min(g['date'] for g in test_games)\n    constant = sum(g['y'] for g in train) / len(train)\n    model = Elo()\n    prior = model.run(train + cal_games)\n    calibration = [g for g in prior if g['season'] == CAL]\n    temperature, cal_loss = fit_temperature(calibration)\n    # Temperature is now frozen. Only earlier eligible results update Elo in test.\n    test = model.run(test_games)\n    results, reliability, ndates = evaluate(test, constant, temperature)\n    # Later-label and same-day-label leakage regression tests.\n    cutoff = test_games[len(test_games) // 2]['date']\n    prefix = [g for g in games if g['date'] <= cutoff]\n    predicted_prefix = Elo().run(prefix)\n    full = prior + test\n    assert [g['p'] for g in predicted_prefix] == [g['p'] for g in full if g['date'] <= cutoff]\n    changed = [dict(g, y=1-g['y']) if g['date'] == cutoff else dict(g) for g in games]\n    changed_predictions = Elo().run(changed)\n    horizon = (dt.date.fromisoformat(cutoff) + dt.timedelta(days=LAG-1)).isoformat()\n    assert [g['p'] for g in changed_predictions if g['date'] <= horizon] == [g['p'] for g in full if g['date'] <= horizon]\n    # Arbitrarily reorder games within dates: every event must get the same forecast.\n    reordered = sorted(games, key=lambda g: (g['date'], -int(g['id'][:8]), g['id'][::-1]))\n    reordered_predictions = Elo().run(reordered)\n    assert {g['id']: g['p'] for g in reordered_predictions} == {g['id']: g['p'] for g in full}\n    assert model.min_gap >= LAG\n    return dict(fileIntegrity=dict(sha256=digest, bytes=pathlib.Path(path).stat().st_size),\n                columnsUsed=list(COLS), splits=summary(games),\n                exclusions=dict(counts, playInGamesRemoved=0, invalidScoreGamesRemoved=0,\n                                unknownVenueGamesRemoved=0, missingScoreGamesRemoved=counts.get('missing_score_games_removed',0),\n                                tiedFinalGamesRemoved=counts.get('tied_final_games_removed',0)),\n                exclusionsBySeason=exclusions_by_season,\n                fitted=dict(trainingHomeWinFrequency=constant, temperature=temperature,\n                            calibrationScaledLogLoss=cal_loss),\n                testResults=results, reliabilityBins=reliability,\n                bootstrap=dict(method='Percentile game-date cluster bootstrap; dates sampled with replacement; all games on each sampled date retained; common draws for all models; no refitting',\n                               replicates=REPS, seed=SEED, dateClusters=ndates,\n                               quantile='Linear interpolation at (replicates-1)*q, q=0.025 and 0.975'),\n                checks=dict(sourceHashAndBytesVerified=verify, uniqueEventIds=True,\n                            pairedRowsConsistent=True, splitsDisjointAndChronological=True,\n                            latestSeasonInFile=TEST, calibrationAndTestEach30Teams82Games=True,\n                            noTeamTwiceOnSameDate=True, minimumUpdateDateGapDays=model.min_gap,\n                            updatesAppliedBeforeLastForecast=model.applied,\n                            noWithinDateUpdates=True, prefixPredictionsUnchanged=True,\n                            flippedDateLabelsCannotChangeForecastUntilLagElapsed=True,\n                            withinDateReorderingUnchanged=True))\n\n\nif __name__ == '__main__':\n    assert len(sys.argv) == 2, 'Usage: python3 baseline.py nbaallelo.csv'\n    print(json.dumps(compute(sys.argv[1]), indent=2, allow_nan=False))\n","comparisonKeys":["fileIntegrity","columnsUsed","splits","exclusions","exclusionsBySeason","fitted","testResults","reliabilityBins","bootstrap","checks"],"offline":"Place the pinned CSV at test/scratch/nba-reproduce/nbaallelo.csv before running the commands; an existing matching file avoids all network access. SHA-256 mismatch is a hard error."}}
