{"status":"reproduced","sport":"NBA","retrievedUtc":"2026-11-26T03:38:47Z","label":"Historical research on NBA regular-season games through 2014–2015. Test scores describe the 2014–2015 archive only.","claimsSource":{"url":"https://api.imd.fun/artifacts/2f09d20cc442e4fd6b82ffdab26d86383318bdbcfc6d92f0df9883da9829fe54","sha256":"2f09d20cc442e4fd6b82ffdab26d86383318bdbcfc6d92f0df9883da9829fe54"},"licence":{"name":"Creative Commons Attribution 4.0 International (CC BY 4.0)","url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quotedLines":[{"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://creativecommons.org/licenses/by/4.0/","quote":"for any purpose, even commercially."},{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quote":"b. produce, reproduce, and Share Adapted Material."},{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quote":"a. reproduce and Share the Licensed Material, in whole or"},{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quote":"indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications;"},{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quote":"indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License."},{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/LICENSE","quote":"retain the following if it is supplied by the Licensor\n               with the Licensed Material:"}],"commercialReuse":"permitted","agreeWithEarlierReading":true,"basis":"The pinned repository README extends CC BY 4.0 to its datasets unless otherwise noted. The pinned NBA Elo README specifies no different licence and credits Basketball-Reference.com for game information. The grant permits commercial sharing and adaptation subject to its terms, including attribution, licence notice, disclosure of modifications and no downstream restrictions on the licensed material."},"files":[{"url":"https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv","expectedSha256":"d46ed3540ee8d9eca31b3e94cc8c777e0be5156173d814ebf65b8195e8d616bc","computedSha256":"d46ed3540ee8d9eca31b3e94cc8c777e0be5156173d814ebf65b8195e8d616bc","match":true,"expectedBytes":18173265,"computedBytes":18173265,"change":"None detected by hash or byte count."}],"creditLine":"FiveThirtyEight, Historical NBA Elo (pinned CSV listed above), with game information credited to Basketball-Reference.com. CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Changes include filtering, deduplication, venue orientation and newly computed historical probabilities and losses.","counts":[{"name":"splits.training","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"splits.calibration","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"splits.test","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"splits.bySeason.2011","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"splits.bySeason.2012","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"splits.bySeason.2013","claimed":{"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}},"recomputed":{"periods":["2012-2013"],"firstDate":"2012-10-30","lastDate":"2013-04-17","events":1229,"outcomes":{"homeWin":752,"awayWin":477},"neutralSiteEvents":1,"teams":30,"teamGameCountHistogram":{"82":28,"81":2}},"match":true},{"name":"splits.bySeason.2014","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"splits.bySeason.2015","claimed":{"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}},"recomputed":{"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}},"match":true},{"name":"exclusions.input_rows","claimed":126314,"recomputed":126314,"match":true},{"name":"exclusions.outside_split_rows","claimed":105358,"recomputed":105358,"match":true},{"name":"exclusions.non_NBA_rows","claimed":8298,"recomputed":8298,"match":true},{"name":"exclusions.selected_rows","claimed":12658,"recomputed":12658,"match":true},{"name":"exclusions.consistent_mirror_pairs","claimed":6329,"recomputed":6329,"match":true},{"name":"exclusions.duplicate_rows_removed","claimed":6329,"recomputed":6329,"match":true},{"name":"exclusions.home_suffix_checks","claimed":5903,"recomputed":5903,"match":true},{"name":"exclusions.neutral_games_retained","claimed":6,"recomputed":6,"match":true},{"name":"exclusions.playoff_games_removed","claimed":420,"recomputed":420,"match":true},{"name":"exclusions.max_games_per_team_per_date","claimed":1,"recomputed":1,"match":true},{"name":"exclusions.playInGamesRemoved","claimed":0,"recomputed":0,"match":true},{"name":"exclusions.invalidScoreGamesRemoved","claimed":0,"recomputed":0,"match":true},{"name":"exclusions.unknownVenueGamesRemoved","claimed":0,"recomputed":0,"match":true},{"name":"exclusions.missingScoreGamesRemoved","claimed":0,"recomputed":0,"match":true},{"name":"exclusions.tiedFinalGamesRemoved","claimed":0,"recomputed":0,"match":true},{"name":"exclusionsBySeason.2011.duplicate_rows_removed","claimed":1311,"recomputed":1311,"match":true},{"name":"exclusionsBySeason.2011.playoff_games_removed","claimed":81,"recomputed":81,"match":true},{"name":"exclusionsBySeason.2012.duplicate_rows_removed","claimed":1074,"recomputed":1074,"match":true},{"name":"exclusionsBySeason.2012.playoff_games_removed","claimed":84,"recomputed":84,"match":true},{"name":"exclusionsBySeason.2013.duplicate_rows_removed","claimed":1314,"recomputed":1314,"match":true},{"name":"exclusionsBySeason.2013.playoff_games_removed","claimed":85,"recomputed":85,"match":true},{"name":"exclusionsBySeason.2014.duplicate_rows_removed","claimed":1319,"recomputed":1319,"match":true},{"name":"exclusionsBySeason.2014.playoff_games_removed","claimed":89,"recomputed":89,"match":true},{"name":"exclusionsBySeason.2015.duplicate_rows_removed","claimed":1311,"recomputed":1311,"match":true},{"name":"exclusionsBySeason.2015.playoff_games_removed","claimed":81,"recomputed":81,"match":true},{"name":"bootstrap.dateClusters","claimed":162,"recomputed":162,"match":true},{"name":"checks.latestSeasonInFile","claimed":2015,"recomputed":2015,"match":true},{"name":"checks.minimumUpdateDateGapDays","claimed":2,"recomputed":2,"match":true},{"name":"checks.updatesAppliedBeforeLastForecast","claimed":5892,"recomputed":5892,"match":true},{"name":"bootstrap.replicates","claimed":2000,"recomputed":2000,"match":true}],"figures":[{"forecaster":"baseline","metric":"n","claimed":1230,"recomputed":1230,"match":true},{"forecaster":"baseline","metric":"brier","claimed":"0.4903","recomputed":"0.4903","match":true},{"forecaster":"baseline","metric":"brierBootstrap95","endpoint":"lower","claimed":"0.4781","recomputed":"0.4781","match":true},{"forecaster":"baseline","metric":"brierBootstrap95","endpoint":"upper","claimed":"0.5020","recomputed":"0.5020","match":true},{"forecaster":"baseline","metric":"logLoss","claimed":"0.6834","recomputed":"0.6834","match":true},{"forecaster":"baseline","metric":"logLossBootstrap95","endpoint":"lower","claimed":"0.6711","recomputed":"0.6711","match":true},{"forecaster":"baseline","metric":"logLossBootstrap95","endpoint":"upper","claimed":"0.6953","recomputed":"0.6953","match":true},{"forecaster":"rawElo","metric":"n","claimed":1230,"recomputed":1230,"match":true},{"forecaster":"rawElo","metric":"brier","claimed":"0.4213","recomputed":"0.4213","match":true},{"forecaster":"rawElo","metric":"brierBootstrap95","endpoint":"lower","claimed":"0.4010","recomputed":"0.4010","match":true},{"forecaster":"rawElo","metric":"brierBootstrap95","endpoint":"upper","claimed":"0.4419","recomputed":"0.4419","match":true},{"forecaster":"rawElo","metric":"logLoss","claimed":"0.6090","recomputed":"0.6090","match":true},{"forecaster":"rawElo","metric":"logLossBootstrap95","endpoint":"lower","claimed":"0.5858","recomputed":"0.5858","match":true},{"forecaster":"rawElo","metric":"logLossBootstrap95","endpoint":"upper","claimed":"0.6332","recomputed":"0.6332","match":true},{"forecaster":"scaledElo","metric":"n","claimed":1230,"recomputed":1230,"match":true},{"forecaster":"scaledElo","metric":"brier","claimed":"0.4201","recomputed":"0.4201","match":true},{"forecaster":"scaledElo","metric":"brierBootstrap95","endpoint":"lower","claimed":"0.4022","recomputed":"0.4022","match":true},{"forecaster":"scaledElo","metric":"brierBootstrap95","endpoint":"upper","claimed":"0.4384","recomputed":"0.4384","match":true},{"forecaster":"scaledElo","metric":"logLoss","claimed":"0.6074","recomputed":"0.6074","match":true},{"forecaster":"scaledElo","metric":"logLossBootstrap95","endpoint":"lower","claimed":"0.5873","recomputed":"0.5873","match":true},{"forecaster":"scaledElo","metric":"logLossBootstrap95","endpoint":"upper","claimed":"0.6286","recomputed":"0.6286","match":true}],"reliability":{"columns":["binIndex","metricIndex","claimed","recomputed","match"],"metricNames":["n","meanPredicted","observedRate"],"binRule":"Bin i covers [i/10,(i+1)/10), with 1 included for bin 9.","byForecaster":{"baseline":[[0,0,0,0,true],[0,1,null,null,true],[0,2,null,null,true],[1,0,0,0,true],[1,1,null,null,true],[1,2,null,null,true],[2,0,0,0,true],[2,1,null,null,true],[2,2,null,null,true],[3,0,0,0,true],[3,1,null,null,true],[3,2,null,null,true],[4,0,0,0,true],[4,1,null,null,true],[4,2,null,null,true],[5,0,0,0,true],[5,1,null,null,true],[5,2,null,null,true],[6,0,1230,1230,true],[6,1,0.601624,0.601624,true],[6,2,0.574797,0.574797,true],[7,0,0,0,true],[7,1,null,null,true],[7,2,null,null,true],[8,0,0,0,true],[8,1,null,null,true],[8,2,null,null,true],[9,0,0,0,true],[9,1,null,null,true],[9,2,null,null,true]],"rawElo":[[0,0,0,0,true],[0,1,null,null,true],[0,2,null,null,true],[1,0,12,12,true],[1,1,0.177163,0.177163,true],[1,2,0.166667,0.166667,true],[2,0,63,63,true],[2,1,0.256828,0.256828,true],[2,2,0.269841,0.269841,true],[3,0,111,111,true],[3,1,0.354445,0.354445,true],[3,2,0.297297,0.297297,true],[4,0,146,146,true],[4,1,0.449663,0.449663,true],[4,2,0.376712,0.376712,true],[5,0,198,198,true],[5,1,0.554402,0.554402,true],[5,2,0.494949,0.494949,true],[6,0,218,218,true],[6,1,0.64969,0.64969,true],[6,2,0.600917,0.600917,true],[7,0,235,235,true],[7,1,0.750242,0.750242,true],[7,2,0.706383,0.706383,true],[8,0,206,206,true],[8,1,0.848081,0.848081,true],[8,2,0.81068,0.81068,true],[9,0,41,41,true],[9,1,0.920177,0.920177,true],[9,2,0.926829,0.926829,true]],"scaledElo":[[0,0,0,0,true],[0,1,null,null,true],[0,2,null,null,true],[1,0,3,3,true],[1,1,0.178832,0.178832,true],[1,2,0.333333,0.333333,true],[2,0,48,48,true],[2,1,0.261577,0.261577,true],[2,2,0.291667,0.291667,true],[3,0,110,110,true],[3,1,0.354624,0.354624,true],[3,2,0.254545,0.254545,true],[4,0,171,171,true],[4,1,0.449534,0.449534,true],[4,2,0.374269,0.374269,true],[5,0,236,236,true],[5,1,0.553999,0.553999,true],[5,2,0.508475,0.508475,true],[6,0,252,252,true],[6,1,0.651183,0.651183,true],[6,2,0.619048,0.619048,true],[7,0,244,244,true],[7,1,0.749898,0.749898,true],[7,2,0.741803,0.741803,true],[8,0,155,155,true],[8,1,0.841115,0.841115,true],[8,2,0.858065,0.858065,true],[9,0,11,11,true],[9,1,0.914573,0.914573,true],[9,2,0.909091,0.909091,true]]}},"T":{"claimed":1.1722545302799172,"recomputed":1.1722545302799172,"match":true},"fittedChecks":{"trainingHomeWinFrequency":{"claimed":0.6016236590316033,"recomputed":0.6016236590316033,"match":true},"calibrationScaledLogLoss":{"claimed":0.6131413017177624,"recomputed":0.6131413017177624,"match":true}},"leakage":{"rule":"Forecast each date as a batch, incorporating only results dated at least two calendar days earlier. Fit the constant on training labels, fix Elo constants in code and fit T on calibration labels only before test forecasts and scoring. Eligible earlier test results update ratings online with the saved raw forecast.","checksRun":["Checked chronological, disjoint split boundaries and unique event IDs. Audited the most recent update date for every forecast across all 5,909 games. Minimum applied lag was two calendar days, with 5,892 updates through the last forecast.","Truncated at a mid-test date and compared prefix forecasts. Flipped all outcomes from that date forward and confirmed forecasts through the following calendar date were unchanged. Reversed the ordering of every date batch and matched every event probability.","Verified the fit receives only training outcomes for the constant and calibration forecasts/outcomes for T. Elo constants are module constants. The first test forecast and loss evaluation execute after T is returned. No source predictions or Elo values enter the selected fields."],"checkResults":{"prefixPredictionsUnchanged":true,"flippedDateLabelsCannotChangeForecastUntilLagElapsed":true,"withinDateReorderingUnchanged":true},"violationsFound":[],"literalEndBeforeStart":"Unverifiable from this archive because it supplies event dates without start or finish timestamps. Zero violations refers to the date embargo and fit order in this implementation."},"ambiguities":["For neutral games the nominal home side is inferred from the game ID suffix. The data dictionary only documents H/A/N. Verified the suffix against all 5,903 retained H/A games and found a unique code match at each of the six neutral games. Used no venue bonus for those games and included their nominal outcomes in the constant.","The archive lacks tipoff, final and first-availability times. Used date subtraction with no timezone reconstruction and no same-day or next-day updates. Final point totals include overtime under the stated outcome rule.","Chronological order within a date has no stated tie-break for update replay. Chose game-ID order and tested reversal. Each franchise appears at most once per date. Used franchise IDs for rating continuity.","The bootstrap specifies the seed and replacement scheme but leaves the date indexing and sampling API implicit. Used ascending dates and Python Random.randrange per draw, shared across all models. Resampled loss totals divided by the resampled game count give game-weighted replicates.","The optimizer does not specify tie handling in floating-point arithmetic. Used the right interval on equal interior losses and picked the least-loss candidate from both endpoints and the final midpoint. Used full precision through scoring.","Invalid scores and venue pairs are described as assertion failures. Treated zero removals as a consequence of all selected post-deduplication regular-season records passing those validations. Missing scores and ties were explicit exclusions. Play-in zero follows the historical date window, since the file has no play-in flag.","The figure scope includes the test sample sizes, percentile interval endpoints and all reported reliability bin entries in addition to the six point losses. Empty-bin means and rates are JSON null. Reported comparisons use four decimal places and the bin values also match at the prior six-place precision."],"problems":[{"claim":"Original constants and embargo were fixed before any forecasts or scoring.","why":"The submitted method and this rerun establish the order within a run. The prior artifact contains no independently timestamped preregistration that could establish when these choices were made relative to any earlier exploratory analysis."}],"limitations":["One held-out season and one archive. Reciprocal rows establish internal consistency only. Third-party data rights, independent score accuracy and contemporaneous archival availability were not audited.","The date embargo does not certify start-to-finish chronology, and neutral nominal-home assignments rely on the archive ID pattern.","Bootstrap intervals condition on the fitted forecasts and resample dates independently. They omit fitting uncertainty and longer-range serial or team dependence. Reliability bins with few games have limited precision.","No assessment of current forecasts, profit or deployed performance. The CSV is available separately at its pinned source."],"reproduce":{"runtime":"Python 3.12.3, standard library only for computation","commands":["mkdir -p test/scratch/nba-recheck","curl -fsSL --max-time 120 https://raw.githubusercontent.com/fivethirtyeight/data/6d880e939ad3d11d94c137c911681b3cf718fd74/nba-elo/nbaallelo.csv -o test/scratch/nba-recheck/nbaallelo.csv && date -u +%FT%TZ > test/scratch/nba-recheck/retrieved.txt","sha256sum test/scratch/nba-recheck/nbaallelo.csv","wc -c test/scratch/nba-recheck/nbaallelo.csv","python3 -c 'import json, pathlib, sys; pathlib.Path(sys.argv[2]).write_text(json.load(open(sys.argv[1]))[\"reproduce\"][\"script\"], encoding=\"utf-8\")' artifacts/goal/batches/baseline-recheck-v5/items/nba/result.json test/scratch/nba-recheck/independent.py","python3 test/scratch/nba-recheck/independent.py test/scratch/nba-recheck/nbaallelo.csv > test/scratch/nba-recheck/computed.json"],"script":"import csv\nimport hashlib\nimport json\nimport math\nimport random\nimport sys\nfrom collections import Counter, defaultdict\nfrom dataclasses import dataclass, replace\nfrom datetime import datetime\nfrom itertools import groupby\nfrom pathlib import Path\n\nTRAIN, CAL, TEST = (2011, 2012, 2013), 2014, 2015\nINITIAL, K, SCALE, HOME, RETENTION, LAG = 1500, 20, 400, 100, 0.75, 2\nEPS = 1e-15\nMODELS = ('baseline', 'rawElo', 'scaledElo')\n\n@dataclass(frozen=True)\nclass Game:\n    id: str\n    date: object\n    year: int\n    home: str\n    away: str\n    neutral: bool\n    win: int\n\ndef read_games(path):\n    counts = Counter(dict.fromkeys(('missingScoreGamesRemoved', 'tiedFinalGamesRemoved',\n                                   'unknownVenueGamesRemoved', 'invalidScoreGamesRemoved'), 0))\n    groups = defaultdict(list)\n    by_year = defaultdict(Counter)\n    latest = 0\n    columns = ('game_id lg_id year_id date_game is_playoffs team_id fran_id pts '\n               'opp_id opp_fran opp_pts game_location').split()\n    with path.open(newline='', encoding='utf-8') as stream:\n        for fields in csv.DictReader(stream):\n            row = {k: fields[k] for k in columns}\n            counts['input_rows'] += 1\n            if row['lg_id'] != 'NBA':\n                counts['non_NBA_rows'] += 1\n                continue\n            year = int(row['year_id'])\n            latest = max(year, latest)\n            if year not in (*TRAIN, CAL, TEST):\n                counts['outside_split_rows'] += 1\n                continue\n            counts['selected_rows'] += 1\n            groups[row['game_id']].append(row)\n\n    games = []\n    for gid, pair in groups.items():\n        a, b = pair\n        for field in ('year_id', 'date_game', 'is_playoffs'):\n            assert a[field] == b[field], (gid, field)\n        for team, opponent in [('team_id', 'opp_id'), ('fran_id', 'opp_fran'), ('pts', 'opp_pts')]:\n            assert (a[team], b[team]) == (b[opponent], a[opponent]), (gid, team)\n        year = int(a['year_id'])\n        counts['consistent_mirror_pairs'] += 1\n        counts['duplicate_rows_removed'] += 1\n        by_year[year]['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_year[year]['playoff_games_removed'] += 1\n            continue\n        if not a['pts'].strip() or not b['pts'].strip():\n            counts['missingScoreGamesRemoved'] += 1\n            continue\n        venues = sorted(row['game_location'] for row in pair)\n        neutral = venues == ['N', 'N']\n        assert neutral or venues == ['A', 'H'], (gid, venues)\n        home, = [row for row in pair if (row['team_id'] == gid[-3:] if neutral\n                                        else row['game_location'] == 'H')]\n        assert home['team_id'] == gid[-3:]\n        date = datetime.strptime(home['date_game'], '%m/%d/%Y').date()\n        assert date.strftime('%Y%m%d') == gid[:8]\n        points, opposing = int(home['pts']), int(home['opp_pts'])\n        assert min(points, opposing) >= 0\n        if points == opposing:\n            counts['tiedFinalGamesRemoved'] += 1\n            continue\n        counts['neutral_games_retained' if neutral else 'home_suffix_checks'] += 1\n        games.append(Game(gid, date, year, home['fran_id'], home['opp_fran'], neutral,\n                          int(points > opposing)))\n\n    games.sort(key=lambda g: (g.date, g.id))\n    assert len({g.id for g in games}) == len(games)\n    counts['max_games_per_team_per_date'] = max(Counter(\n        (g.date, team) for g in games for team in (g.home, g.away)).values())\n    # No archive play-in flag. The NBA's history dates the format to 2020.\n    assert max(g.year for g in games) < 2020\n    counts['playInGamesRemoved'] = 0\n    return games, counts, by_year, latest\n\ndef summarize(games):\n    teams = Counter(team for g in games for team in (g.home, g.away))\n    wins = sum(g.win for g in games)\n    return dict(periods=[f'{year-1}-{year}' for year in sorted({g.year for g in games})],\n                firstDate=str(games[0].date), lastDate=str(games[-1].date),\n                events=len(games), outcomes=dict(homeWin=wins, awayWin=len(games)-wins),\n                neutralSiteEvents=sum(g.neutral for g in games), teams=len(teams),\n                teamGameCountHistogram=Counter(teams.values()))\n\ndef forecast(games, history, ratings, audit):\n    \"\"\"Use a sweep index over past forecasts. Carry state across the calibration boundary.\"\"\"\n    cursor, gaps, violations = audit\n    for day, batch in groupby(games, key=lambda g: g.date):\n        today = list(batch)\n        year = today[0].year\n        assert all(g.year == year for g in today)\n        if history:\n            assert day > history[-1][0].date\n        while cursor < len(history):\n            earlier, probability = history[cursor]\n            gap = (day - earlier.date).days\n            if gap < LAG:\n                break\n            gaps.append(gap)\n            change = K * (earlier.win - probability)\n            ratings[earlier.home] += change\n            ratings[earlier.away] -= change\n            cursor += 1\n        if history and history[-1][0].year != year:\n            assert cursor == len(history)\n            for team, rating in ratings.items():\n                ratings[team] = INITIAL + RETENTION * (rating - INITIAL)\n        for game in today:\n            # All applied updates form a chronological prefix. Its latest date bounds\n            # every directly or indirectly consumed outcome, including after regression.\n            if cursor and (game.date - history[cursor-1][0].date).days < LAG:\n                violations.append(game.id)\n            edge = ratings[game.home] - ratings[game.away] + (0 if game.neutral else HOME)\n            history.append((game, 1 / (1 + 10 ** (-edge / SCALE))))\n    audit[0] = cursor\n\ndef fresh():\n    return [], defaultdict(lambda: INITIAL), [0, [], []]\n\ndef scale(p, t):\n    return 1 / (1 + math.exp(-math.log(p / (1-p)) / t))\n\ndef log_loss(p, y):\n    p = min(1-EPS, max(EPS, p))\n    return -math.log(p) if y else -math.log1p(-p)\n\ndef temperature(calibration):\n    def objective(log_t):\n        t = math.exp(log_t)\n        return math.fsum(log_loss(scale(p, t), g.win) for g, p in calibration) / len(calibration)\n\n    bounds = math.log(0.25), math.log(4)\n    left, right = bounds\n    fraction = (3 - math.sqrt(5)) / 2\n    for _ in range(100):\n        width = right - left\n        lower, upper = left + fraction * width, right - fraction * width\n        if objective(lower) < objective(upper):\n            right = upper\n        else:\n            left = lower\n    best = min((*bounds, (left + right) / 2), key=objective)\n    return math.exp(best), objective(best)\n\ndef evaluate(test, baseline, t):\n    daily = defaultdict(list)\n    bins = defaultdict(list)\n    for game, raw in test:\n        losses = []\n        for model, p in zip(MODELS, (baseline, raw, scale(raw, t))):\n            clipped = min(1-EPS, max(EPS, p))\n            losses.extend((2*(clipped-game.win)**2, log_loss(p, game.win)))\n            bins[model, min(9, int(10*p))].append((p, game.win))\n        daily[game.date].append(losses)\n\n    blocks = [(len(rows), tuple(map(math.fsum, zip(*rows)))) for _, rows in sorted(daily.items())]\n    rng = random.Random(20261126)\n    boot = [[] for _ in range(6)]\n    for _ in range(2000):\n        sample = [blocks[rng.randrange(len(blocks))] for _ in blocks]\n        total = sum(n for n, _ in sample)\n        for series, losses in zip(boot, zip(*(values for _, values in sample))):\n            series.append(math.fsum(losses) / total)\n\n    def percentile(series, q):\n        left, frac = divmod((len(series)-1)*q, 1)\n        i = int(left)\n        return series[i] + frac*(series[i+1]-series[i])\n\n    results, reliability = {}, {}\n    totals = tuple(map(math.fsum, zip(*(values for _, values in blocks))))\n    for j, model in enumerate(MODELS):\n        results[model] = {'n': len(test)}\n        for i, metric in enumerate(('brier', 'logLoss'), start=2*j):\n            results[model][metric] = f'{totals[i]/len(test):.4f}'\n            dist = sorted(boot[i])\n            results[model][metric+'Bootstrap95'] = [f'{percentile(dist,q):.4f}' for q in (.025,.975)]\n        reliability[model] = []\n        for i in range(10):\n            rows = bins[model, i]\n            n = len(rows)\n            reliability[model].append(dict(n=n,\n                meanPredicted=round(math.fsum(p for p, _ in rows)/n, 6) if n else None,\n                observedRate=round(sum(y for _, y in rows)/n, 6) if n else None))\n    return results, reliability, len(blocks)\n\ndef compute(path):\n    games, exclusions, by_year, latest = read_games(path)\n    years = {y: [g for g in games if g.year == y] for y in (*TRAIN, CAL, TEST)}\n    train = [g for y in TRAIN for g in years[y]]\n    cal, test = years[CAL], years[TEST]\n    assert train[-1].date < cal[0].date <= cal[-1].date < test[0].date\n    counts = dict(training=summarize(train), calibration=summarize(cal), test=summarize(test),\n                  bySeason={y:summarize(rows) for y,rows in years.items()})\n    baseline = sum(g.win for g in train)/len(train)\n    history, ratings, audit = fresh()\n    forecast(train + cal, history, ratings, audit)\n    assert all(g.year in (*TRAIN, CAL) for g, _ in history)\n    t, calibration_loss = temperature(tuple(history[len(train):]))\n    # No test forecast or loss has been calculated when the scalar parameters freeze.\n    forecast(test, history, ratings, audit)\n    results, reliability, clusters = evaluate(history[-len(test):], baseline, t)\n\n    pivot = test[len(test)//2].date\n    prefix, flipped, reversed_days = fresh(), fresh(), fresh()\n    forecast([g for g in games if g.date <= pivot], *prefix)\n    forecast([replace(g, win=1-g.win) if g.date >= pivot else g for g in games], *flipped)\n    reordered = [g for _, day in groupby(games, key=lambda g:g.date) for g in reversed(list(day))]\n    forecast(reordered, *reversed_days)\n    probabilities = lambda rows: {g.id: p for g,p in rows}\n    checks = dict(\n        prefixPredictionsUnchanged=probabilities(prefix[0]) ==\n            probabilities((g,p) for g,p in history if g.date <= pivot),\n        flippedDateLabelsCannotChangeForecastUntilLagElapsed=\n            probabilities((g,p) for g,p in flipped[0] if (g.date-pivot).days < LAG) ==\n            probabilities((g,p) for g,p in history if (g.date-pivot).days < LAG),\n        withinDateReorderingUnchanged=probabilities(history) == probabilities(reversed_days[0]))\n    assert all(checks.values()) and not audit[2]\n    return dict(sha256=hashlib.sha256(path.read_bytes()).hexdigest(), bytes=path.stat().st_size,\n                splits=counts, exclusions=exclusions, exclusionsBySeason=by_year,\n                latestSeason=latest, baseline=baseline, temperature=t, calibrationLoss=calibration_loss,\n                testResults=results, reliabilityBins=reliability, dateClusters=clusters,\n                minGap=min(audit[1]), updates=audit[0], violations=audit[2], checks=checks)\n\nif __name__ == '__main__':\n    print(json.dumps(compute(Path(sys.argv[1])), allow_nan=False))\n"}}
