-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredictions.py
More file actions
2590 lines (2236 loc) · 124 KB
/
predictions.py
File metadata and controls
2590 lines (2236 loc) · 124 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import numpy as np
import joblib
from pathlib import Path
import requests
from typing import Dict, List, Optional
import sys
import os
from datetime import datetime, timezone
from dateutil import parser as date_parser
import pytz
# Must be called once at module level — sub-pages must NOT call set_page_config
st.set_page_config(
page_title="Bracket Oracle - March Madness Predictions",
page_icon="🏀",
layout="wide",
)
# Add the current directory to the path so we can import data_collection
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
from data_collection import fetch_games, fetch_betting_lines, fetch_adjusted_efficiency, fetch_team_stats
from underdog_value import (
identify_underdog_value,
format_value_bet_display,
get_betting_recommendation,
moneyline_to_implied_probability
)
from data_tools.efficiency_loader import EfficiencyDataLoader
from fetch_live_odds import fetch_live_odds
from features import find_upset_candidates, predict_win_probability
# line movement helpers (reads from opening_lines.json or uses API)
try:
# This module may not be available in all environments (e.g., CI/test), so we
# fall back gracefully.
from scripts.odds_api_integration import track_line_movement # type: ignore[import]
except ImportError:
track_line_movement = None
from upset_prediction import UpsetPredictor, generate_upset_watch_list, display_upset_watch, identify_cinderella_candidates, display_cinderella_candidates
from bracket_simulation import load_real_tournament_bracket, create_bracket_from_data, create_predictor_from_models
except ImportError as e:
st.error(f"Could not import required functions: {e}")
st.stop()
# Configuration
DATA_DIR = Path("data_files")
MODEL_DIR = DATA_DIR / "models"
def get_dataframe_height(df, row_height=35, header_height=38, padding=2, max_height=600):
"""
Calculate the optimal height for a Streamlit dataframe based on number of rows.
Args:
df (pd.DataFrame): The dataframe to display
row_height (int): Height per row in pixels. Default: 35
header_height (int): Height of header row in pixels. Default: 38
padding (int): Extra padding in pixels. Default: 2
max_height (int): Maximum height cap in pixels. Default: 600 (None for no limit)
Returns:
int: Calculated height in pixels
Example:
height = get_dataframe_height(my_df)
st.dataframe(my_df, height=height)
"""
num_rows = len(df)
calculated_height = (num_rows * row_height) + header_height + padding
if max_height is not None:
return min(calculated_height, max_height)
return calculated_height
# Load models
@st.cache_resource
def load_models():
"""Load trained prediction models."""
models = {}
# Spread models
try:
models['spread'] = {
'xgboost': joblib.load(MODEL_DIR / 'spread_xgboost.joblib'),
'random_forest': joblib.load(MODEL_DIR / 'spread_random_forest.joblib'),
'linear': joblib.load(MODEL_DIR / 'spread_linear_regression.joblib')
}
# Load scaler for linear regression
try:
models['spread_scalers'] = {
'linear': joblib.load(MODEL_DIR / 'spread_linear_regression_scaler.joblib')
}
except:
models['spread_scalers'] = {}
except:
st.error("Spread models not found. Please run model training first.")
models['spread'] = None
# Total models
try:
models['total'] = {
'xgboost': joblib.load(MODEL_DIR / 'total_xgboost.joblib'),
'random_forest': joblib.load(MODEL_DIR / 'total_random_forest.joblib'),
'linear': joblib.load(MODEL_DIR / 'total_linear_regression.joblib')
}
# Load scaler for linear regression
try:
models['total_scalers'] = {
'linear': joblib.load(MODEL_DIR / 'total_linear_regression_scaler.joblib')
}
except:
models['total_scalers'] = {}
except:
st.error("Total models not found. Please run model training first.")
models['total'] = None
# Moneyline models
try:
models['moneyline'] = {
'xgboost': joblib.load(MODEL_DIR / 'moneyline_xgboost.joblib'),
'random_forest': joblib.load(MODEL_DIR / 'moneyline_random_forest.joblib'),
'logistic': joblib.load(MODEL_DIR / 'moneyline_logistic_regression.joblib')
}
# Load scaler for logistic regression
try:
models['moneyline_scalers'] = {
'logistic': joblib.load(MODEL_DIR / 'moneyline_logistic_regression_scaler.joblib')
}
except:
models['moneyline_scalers'] = {}
except:
st.error("Moneyline models not found. Please run model training first.")
models['moneyline'] = None
return models
@st.cache_data(ttl=3600) # Cache for 1 hour
def load_live_odds():
"""Load live betting odds, cached for 1 hour."""
try:
return fetch_live_odds()
except Exception as e:
st.warning(f"Could not load live odds: {e}")
return {}
@st.cache_data(ttl=60) # Cache for 1 minute (development mode)
def load_precomputed_predictions(target_date: Optional[str] = None) -> Optional[Dict]:
"""Load pre-computed predictions from JSON file."""
from datetime import datetime
# Load from precomputed predictions directory (written by precompute_predictions.py)
precomputed_dir = DATA_DIR / "precomputed_predictions"
if not precomputed_dir.exists():
return None
# Use target date or today's date
if target_date:
date_str = target_date
else:
date_str = datetime.now().strftime('%Y-%m-%d')
# Try exact date first
filepath = precomputed_dir / f"predictions_{date_str}.json"
if not filepath.exists():
# Fall back to most recent file
json_files = list(precomputed_dir.glob("predictions_*.json"))
if not json_files:
return None
filepath = max(json_files, key=lambda p: p.stat().st_mtime)
try:
import json
with open(filepath, 'r') as f:
data = json.load(f)
# info about using pre-computed predictions suppressed
return data
except Exception as e:
st.warning(f"Could not load pre-computed predictions: {e}")
return None
def format_game_datetime(game) -> str:
"""Format game date/time in Eastern Time."""
try:
# Get the start date from the game
if isinstance(game, dict):
start_date_str = game.get('startDate') or game.get('start_date')
else:
start_date_str = getattr(game, 'startDate', None) or getattr(game, 'start_date', None)
if not start_date_str:
return "Date TBD"
# Parse the date (it's in ISO format with timezone)
if isinstance(start_date_str, str):
game_datetime = date_parser.parse(start_date_str)
else:
game_datetime = start_date_str
# Convert to Eastern Time
eastern = pytz.timezone('US/Eastern')
game_datetime_et = game_datetime.astimezone(eastern)
# Format nicely
now = datetime.now(eastern)
if game_datetime_et.date() == now.date():
# Today
return f"Today {game_datetime_et.strftime('%I:%M %p ET')}"
elif (game_datetime_et - now).days == 1:
# Tomorrow
return f"Tomorrow {game_datetime_et.strftime('%I:%M %p ET')}"
elif game_datetime_et.year == now.year:
# This year
return game_datetime_et.strftime('%b %d, %I:%M %p ET')
else:
# Different year
return game_datetime_et.strftime('%b %d, %Y %I:%M %p ET')
except Exception as e:
return "Date TBD"
def sort_games_by_date(games: List) -> List:
"""Sort games by start date (most recent first)."""
def get_game_datetime(game):
try:
if isinstance(game, dict):
start_date_str = game.get('startDate') or game.get('start_date')
else:
start_date_str = getattr(game, 'startDate', None) or getattr(game, 'start_date', None)
if start_date_str:
return date_parser.parse(start_date_str)
else:
# If no date, put at the end
return datetime.min.replace(tzinfo=timezone.utc)
except:
return datetime.min.replace(tzinfo=timezone.utc)
return sorted(games, key=get_game_datetime, reverse=True)
@st.cache_data(ttl=3600)
def load_espn_games() -> pd.DataFrame:
"""Load ESPN game data from CSV."""
espn_file = DATA_DIR / "espn_cbb_current_season.csv"
if espn_file.exists():
return pd.read_csv(espn_file)
return pd.DataFrame()
def normalize_team_name(espn_name: str) -> str:
"""Convert ESPN team name to CBBD format.
ESPN uses 'Michigan Wolverines', CBBD uses 'Michigan'.
"""
# Common patterns: remove mascots/nicknames
# Split on space and take first part(s) that aren't mascots
mascots = [
'Wolverines', 'Hoosiers', 'Cyclones', 'Knights', 'Gators', 'Tigers',
'Wolfpack', 'Dukes', 'Billikens', 'Bonnies', 'Buckeyes', 'Demon Deacons', 'Flashes', 'RedHawks', 'Ducks',
'Spartans', 'Bears', 'Raiders', 'Razorbacks', 'Commodores', 'Bulldogs',
'Bruins', 'Boilermakers', 'Buffaloes', 'Jayhawks', 'Wildcats', 'Aggies',
'Huskies', 'Tar Heels', 'Blue Devils', 'Cardinals', 'Sooners', 'Longhorns',
'Crimson Tide', 'Volunteers', 'Gamecocks', 'Rebels', 'Broncos', 'Cougars',
'Panthers', 'Eagles', 'Owls', 'Rams', 'Bulls', 'Golden Knights', 'Mean Green',
'Thundering Herd', 'Miners', 'Roadrunners', 'Hilltoppers', 'Golden Flashes',
'Bearcats', 'Fighting Illini', 'Terrapins', 'Cornhuskers', 'Waves', 'Golden Gophers',
'Cavaliers', 'Mountaineers', 'Hokies', 'Cowboys', 'Utes', 'Dons', 'Dolphins', 'Red Flash',
'Chargers', 'Skyhawks', 'Lakers', 'Mastodons', 'Jaguars', 'Seahawks', 'Sharks', 'Salukis',
'Purple Aces', 'Trojans', 'Badgers', 'Scarlet Knights', 'Friars', 'Revolutionaries', 'Minutemen', 'Horned Frogs', 'Flyers',
'Braves', 'Cardinal', 'Flames', 'Gaels', 'Grizzlies', 'Jaspers', 'Kangaroos', 'Leopards', 'Mavericks', 'Pilots', 'Redhawks', 'Stags'
]
# Multi-word mascots that need special handling
multi_word_mascots = [
'Tar Heels', 'Blue Devils', 'Fighting Irish', 'Golden Flashes', 'Red Raiders',
'Golden Knights', 'Thundering Herd', 'Crimson Tide', 'Mean Green', 'Fighting Illini',
'Demon Deacons', 'Golden Gophers', 'Yellow Jackets', 'Red Flash', 'Purple Aces', 'Scarlet Knights',
'A&M Rattlers', 'Arizona Lumberjacks', 'Baptist Lancers', 'Beach St 49ers', 'Golden Lions',
'Canyon Antelopes', 'Diego Toreros', 'Fullerton Titans', 'Golden Griffins', 'Mary\'s Gaels',
'Michigan Chippewas', 'Mountain Hawks', 'Northridge Matadors', 'Rainbow Warriors',
'San Diego Tritons', 'Santa Barbara Gauchos', 'St Bobcats', 'St Braves', 'St Sun Devils',
'State Bengals', 'Tech Trailblazers', 'Utah Thunderbirds', 'Wolf Pack', 'Irvine Anteaters',
'Mexico Lobos', 'Poly Mustangs'
]
# Handle special cases
special_cases = {
# Existing mappings
'Miami (FL)': 'Miami',
'Miami (OH)': 'Miami (OH)',
'NC State': 'North Carolina State',
'Kent State Golden Flashes': 'Kent State',
'Texas Tech Red Raiders': 'Texas Tech',
'UCF': 'UCF',
'UCLA': 'UCLA',
'USC': 'USC',
'LSU': 'LSU',
'TCU': 'TCU',
'SMU': 'SMU',
'BYU': 'BYU',
'VCU': 'VCU',
'UNLV': 'UNLV',
'IU Indianapolis Jaguars': 'IU Indianapolis',
'IU Indianapolis': 'IU Indianapolis',
'IUPUI': 'IU Indianapolis',
'Long Island University Sharks': 'Long Island University',
'LIU': 'Long Island University',
'LIU Sharks': 'Long Island University',
'Purdue Fort Wayne Mastodons': 'Purdue Fort Wayne',
'Central Connecticut Blue Devils': 'Central Connecticut',
'Chicago State Cougars': 'Chicago State',
'Southern Illinois Salukis': 'Southern Illinois',
'Saint Francis Red Flash': 'Saint Francis (PA)',
'New Haven Chargers': 'New Haven',
'New Haven': 'New Haven',
'Stonehill Skyhawks': 'Stonehill',
'Mercyhurst Lakers': 'Mercyhurst',
'Wagner Seahawks': 'Wagner',
'Le Moyne Dolphins': 'Le Moyne',
'San Francisco Dons': 'San Francisco',
'USC Trojans': 'USC',
'Wisconsin Badgers': 'Wisconsin',
'Michigan State Spartans': 'Michigan State',
'Rutgers Scarlet Knights': 'Rutgers',
'Providence Friars': 'Providence',
'George Washington Revolutionaries': 'George Washington',
'Massachusetts Minutemen': 'Massachusetts',
'TCU Horned Frogs': 'TCU',
'Dayton Flyers': 'Dayton',
'Kansas St': 'Kansas State',
# New mappings for Odds API abbreviations
'Pacific': 'Pacific',
'Seattle': 'Seattle',
'Long': 'Long Beach State',
'UC': 'UC Irvine', # This might need refinement based on context
'Cal': 'California',
'CSU': 'Colorado State',
'Fresno St': 'Fresno State',
'Grand': 'Grand Canyon',
'Utah Valley': 'Utah Valley',
'UIC': 'Illinois Chicago',
'Northern': 'Northern Arizona',
'N Colorado': 'North Colorado',
'Weber State': 'Weber State',
'Saint': 'Saint Mary\'s',
'New': 'New Mexico',
'UMKC': 'UMKC',
'Omaha': 'Omaha',
'California Golden': 'California',
'Southern': 'Southern Utah',
'San': 'San Diego',
'Santa Clara': 'Santa Clara',
'Hawai\'i': 'Hawaii',
'Stonehill': 'Stonehill',
'Central Connecticut St': 'Central Connecticut',
'Mercyhurst': 'Mercyhurst',
'Chicago St': 'Chicago State',
'Fort Wayne': 'Purdue Fort Wayne',
# Additional common abbreviations
'St': 'State', # General St -> State mapping
'N': 'North', # N Colorado -> North Colorado
}
if espn_name in special_cases:
return special_cases[espn_name]
# Check for multi-word mascots first
for mascot in multi_word_mascots:
if espn_name.endswith(' ' + mascot):
return espn_name[:-len(' ' + mascot)].strip()
# Remove single-word mascot from end
parts = espn_name.split()
if len(parts) > 1 and parts[-1] in mascots:
return ' '.join(parts[:-1])
return espn_name
# @st.cache_data(ttl=3600)
def get_team_data(season: int = 2025):
"""Fetch team stats and efficiency ratings for specified season with fallback to previous seasons."""
# Try current season first, then fall back to previous seasons
for s in [season, season-1, season-2]:
try:
efficiency_list = fetch_adjusted_efficiency(s)
stats_list = fetch_team_stats(s)
if efficiency_list and stats_list:
return efficiency_list, stats_list, s
except:
continue
return [], [], None
def get_kenpom_barttorvik_data():
"""Load KenPom and BartTorvik efficiency data for all teams."""
try:
loader = EfficiencyDataLoader()
kenpom_df = loader.load_kenpom()
bart_df = loader.load_barttorvik()
return kenpom_df, bart_df
except Exception as e:
print(f"Error loading KenPom/BartTorvik data: {e}")
return None, None
def get_haslametrics_data():
"""Load Haslametrics efficiency data for all teams."""
try:
loader = EfficiencyDataLoader()
return loader.load_haslametrics()
except Exception as e:
print(f"Error loading Haslametrics data: {e}")
return None
def enrich_with_advanced_metrics(home_team_name, away_team_name, kenpom_df=None, bart_df=None, hasla_df=None):
"""Enrich team efficiency with KenPom, BartTorvik, and Haslametrics metrics."""
metrics = {
'home': {'kenpom': None, 'barttorvik': None, 'haslametrics': None},
'away': {'kenpom': None, 'barttorvik': None, 'haslametrics': None}
}
if kenpom_df is not None:
home_kp = kenpom_df[kenpom_df['canonical_team'] == home_team_name]
away_kp = kenpom_df[kenpom_df['canonical_team'] == away_team_name]
if not home_kp.empty:
metrics['home']['kenpom'] = {
'NetRtg': home_kp.iloc[0]['NetRtg'],
'ORtg': home_kp.iloc[0]['ORtg'],
'DRtg': home_kp.iloc[0]['DRtg'],
'AdjT': home_kp.iloc[0]['AdjT'],
'Luck': home_kp.iloc[0]['Luck'],
'SOS_NetRtg': home_kp.iloc[0]['SOS_NetRtg']
}
if not away_kp.empty:
metrics['away']['kenpom'] = {
'NetRtg': away_kp.iloc[0]['NetRtg'],
'ORtg': away_kp.iloc[0]['ORtg'],
'DRtg': away_kp.iloc[0]['DRtg'],
'AdjT': away_kp.iloc[0]['AdjT'],
'Luck': away_kp.iloc[0]['Luck'],
'SOS_NetRtg': away_kp.iloc[0]['SOS_NetRtg']
}
if bart_df is not None:
home_bt = bart_df[bart_df['canonical_team'] == home_team_name]
away_bt = bart_df[bart_df['canonical_team'] == away_team_name]
if not home_bt.empty:
row = home_bt.iloc[0]
# BartTorvik canonical CSV may use different column names; try common names with fallbacks
adj_oe = row.get('Adj OE') if 'Adj OE' in home_bt.columns else (row.get('Adj_OE') if 'Adj_OE' in home_bt.columns else (row.get('H2') if 'H2' in home_bt.columns else None))
adj_de = row.get('Adj DE') if 'Adj DE' in home_bt.columns else (row.get('Adj_DE') if 'Adj_DE' in home_bt.columns else (row.get('H3') if 'H3' in home_bt.columns else None))
metrics['home']['barttorvik'] = {
'Adj OE': adj_oe,
'Adj DE': adj_de
}
if not away_bt.empty:
row = away_bt.iloc[0]
adj_oe = row.get('Adj OE') if 'Adj OE' in away_bt.columns else (row.get('Adj_OE') if 'Adj_OE' in away_bt.columns else (row.get('H2') if 'H2' in away_bt.columns else None))
adj_de = row.get('Adj DE') if 'Adj DE' in away_bt.columns else (row.get('Adj_DE') if 'Adj_DE' in away_bt.columns else (row.get('H3') if 'H3' in away_bt.columns else None))
metrics['away']['barttorvik'] = {
'Adj OE': adj_oe,
'Adj DE': adj_de
}
if hasla_df is not None:
home_hl = hasla_df[hasla_df['canonical_team'] == home_team_name]
away_hl = hasla_df[hasla_df['canonical_team'] == away_team_name]
def _hasla_row(row_df):
if row_df.empty:
return None
r = row_df.iloc[0]
return {
'O_Eff': r.get('O_Eff'),
'D_Eff': r.get('D_Eff'),
'hasla_net': r.get('hasla_net_eff'),
'O_AP%': r.get('O_AP%'),
'D_AP%': r.get('D_AP%'),
'O_FG%': r.get('O_FG%'),
'D_FG%': r.get('D_FG%'),
'O_3P%': r.get('O_3P%'),
'D_3P%': r.get('D_3P%'),
}
metrics['home']['haslametrics'] = _hasla_row(home_hl)
metrics['away']['haslametrics'] = _hasla_row(away_hl)
return metrics
def enrich_espn_game_with_cbbd_data(game_row, efficiency_list, stats_list, season_used) -> Optional[Dict]:
"""Combine ESPN game data with CBBD stats and efficiency ratings."""
try:
home_team_espn = game_row['home_team']
away_team_espn = game_row['away_team']
# Normalize team names to match CBBD format
home_team = normalize_team_name(home_team_espn)
away_team = normalize_team_name(away_team_espn)
# Load live odds
live_odds = load_live_odds()
# Find matching efficiency and stats (CBBD returns dicts, not objects)
home_eff = next((e for e in efficiency_list if e.get('team') == home_team), None)
away_eff = next((e for e in efficiency_list if e.get('team') == away_team), None)
home_stats_obj = next((s for s in stats_list if s.get('team') == home_team), None)
away_stats_obj = next((s for s in stats_list if s.get('team') == away_team), None)
# If any data is missing, substitute reasonable defaults so the game can be
# enriched and passed to the prediction step instead of being skipped.
def default_eff_from_rank(rank):
# Create a conservative default offensive/defensive rating based on rank
try:
r = int(rank) if rank is not None else None
except Exception:
r = None
if r and r != 99:
val = 110 - (r / 10)
else:
val = 100.1
return {'offensiveRating': val, 'defensiveRating': val, 'netRating': 0}
def default_stats():
# Minimal stats structure matching what extract_stats() expects
return {
'games': 32,
'pace': 70,
'teamStats': {
'points': {'total': 2240},
'fourFactors': {
'effectiveFieldGoalPct': 48.0,
'turnoverRatio': 0.15,
'offensiveReboundPct': 30.0,
'freeThrowRate': 30.0
},
'fieldGoals': {'pct': 44.0},
'threePointFieldGoals': {'pct': 33.0}
},
'opponentStats': {'points': {'total': 2240}}
}
# Fill missing efficiency entries with defaults derived from ranks
if not home_eff:
home_eff = default_eff_from_rank(game_row.get('home_rank'))
if not away_eff:
away_eff = default_eff_from_rank(game_row.get('away_rank'))
# Fill missing stats objects with minimal defaults
if not home_stats_obj:
home_stats_obj = default_stats()
if not away_stats_obj:
away_stats_obj = default_stats()
# Create efficiency dicts (we already verified these exist above)
home_eff_dict = {
'offensiveRating': home_eff.get('offensiveRating', 100),
'defensiveRating': home_eff.get('defensiveRating', 100),
'netRating': home_eff.get('netRating', 0)
}
away_eff_dict = {
'offensiveRating': away_eff.get('offensiveRating', 100),
'defensiveRating': away_eff.get('defensiveRating', 100),
'netRating': away_eff.get('netRating', 0)
}
# Create stats dicts (we already verified these exist above)
def extract_stats(stats_dict):
team_stats = stats_dict.get('teamStats', {})
opp_stats = stats_dict.get('opponentStats', {})
four_factors = team_stats.get('fourFactors', {})
field_goals = team_stats.get('fieldGoals', {})
three_pt_fg = team_stats.get('threePointFieldGoals', {})
games = stats_dict.get('games', 32)
return {
'ppg': team_stats.get('points', {}).get('total', 2240) / games,
'pace': stats_dict.get('pace', 70),
'efg_pct': four_factors.get('effectiveFieldGoalPct', 48.0) / 100.0,
'to_rate': four_factors.get('turnoverRatio', 0.15),
'orb_pct': four_factors.get('offensiveReboundPct', 30.0) / 100.0,
'ft_rate': four_factors.get('freeThrowRate', 30.0) / 100.0,
'opp_ppg': opp_stats.get('points', {}).get('total', 2240) / games,
'fg_pct': field_goals.get('pct', 44.0) / 100.0,
'three_pct': three_pt_fg.get('pct', 33.0) / 100.0
}
home_stats_dict = extract_stats(home_stats_obj)
away_stats_dict = extract_stats(away_stats_obj)
# Attempt to fetch betting lines for this game and populate moneylines
betting_spread = None
betting_over_under = None
home_ml = None
away_ml = None
try:
lines_data = fetch_betting_lines(season_used or 2026, 'postseason')
for line in lines_data:
if isinstance(line, dict):
line_home = line.get('homeTeam') or line.get('home_team') or line.get('home')
line_away = line.get('awayTeam') or line.get('away_team') or line.get('away')
providers = line.get('lines') or []
else:
line_home = (getattr(line, 'home_team', None) or getattr(line, 'homeTeam', None) or getattr(line, 'home', None))
line_away = (getattr(line, 'away_team', None) or getattr(line, 'awayTeam', None) or getattr(line, 'away', None))
providers = getattr(line, 'lines', []) or []
try:
lh = str(line_home) if line_home is not None else None
la = str(line_away) if line_away is not None else None
except Exception:
lh = line_home
la = line_away
if ((lh == home_team_espn and la == away_team_espn) or
(lh == home_team and la == away_team) or
(lh == normalize_team_name(home_team_espn) and la == normalize_team_name(away_team_espn))):
provider = providers[0] if providers and len(providers) > 0 else None
if provider:
if isinstance(provider, dict):
betting_spread = provider.get('spread') or betting_spread
betting_over_under = provider.get('overUnder') or provider.get('over_under') or betting_over_under
home_ml = provider.get('homeMoneyline') or provider.get('home_moneyline') or home_ml
away_ml = provider.get('awayMoneyline') or provider.get('away_moneyline') or away_ml
else:
betting_spread = getattr(provider, 'spread', None) or betting_spread
betting_over_under = getattr(provider, 'overUnder', None) or betting_over_under
home_ml = getattr(provider, 'homeMoneyline', None) or getattr(provider, 'home_moneyline', None) or home_ml
away_ml = getattr(provider, 'awayMoneyline', None) or getattr(provider, 'away_moneyline', None) or away_ml
else:
if isinstance(line, dict):
betting_spread = line.get('spread') or betting_spread
betting_over_under = line.get('overUnder') or betting_over_under
home_ml = line.get('homeMoneyline') or line.get('home_moneyline') or home_ml
away_ml = line.get('awayMoneyline') or line.get('away_moneyline') or away_ml
else:
betting_spread = getattr(line, 'spread', None) or betting_spread
betting_over_under = getattr(line, 'overUnder', None) or betting_over_under
home_ml = getattr(line, 'homeMoneyline', None) or getattr(line, 'home_moneyline', None) or home_ml
away_ml = getattr(line, 'awayMoneyline', None) or getattr(line, 'away_moneyline', None) or away_ml
break
except Exception:
pass
# If no moneylines from CFBD, try live odds
if not home_ml and live_odds:
game_key = f"{normalize_team_name(home_team_espn)} vs {normalize_team_name(away_team_espn)}"
# Also try the reverse order in case Odds API has home/away swapped
reverse_key = f"{normalize_team_name(away_team_espn)} vs {normalize_team_name(home_team_espn)}"
odds = None
if game_key in live_odds:
odds = live_odds[game_key]
elif reverse_key in live_odds:
# If found with reversed order, we need to swap the odds too
odds = live_odds[reverse_key]
# Swap home/away odds since the teams are swapped
if odds:
odds = odds.copy()
# Swap moneyline
orig_home_ml = odds.get('home_moneyline')
orig_away_ml = odds.get('away_moneyline')
odds['home_moneyline'] = orig_away_ml
odds['away_moneyline'] = orig_home_ml
# Swap spread (flip the sign)
orig_home_spread = odds.get('home_spread')
orig_away_spread = odds.get('away_spread')
if orig_home_spread is not None and orig_away_spread is not None:
odds['home_spread'] = -orig_away_spread # Flip sign
odds['away_spread'] = -orig_home_spread # Flip sign
# Keep the odds the same since spread direction changed
orig_home_spread_odds = odds.get('home_spread_odds')
orig_away_spread_odds = odds.get('away_spread_odds')
odds['home_spread_odds'] = orig_away_spread_odds
odds['away_spread_odds'] = orig_home_spread_odds
if odds:
home_ml = odds.get('home_moneyline')
away_ml = odds.get('away_moneyline')
# Optionally update spread/over_under if not set
if not betting_spread:
betting_spread = odds.get('home_spread')
if not betting_over_under:
betting_over_under = odds.get('total_line')
return {
'home_team': home_team_espn, # Use ESPN name for display
'away_team': away_team_espn, # Use ESPN name for display
'home_eff': home_eff_dict,
'away_eff': away_eff_dict,
'home_stats': home_stats_dict,
'away_stats': away_stats_dict,
'betting_spread': betting_spread,
'betting_over_under': betting_over_under,
'home_moneyline': home_ml,
'away_moneyline': away_ml,
'home_ml': home_ml,
'away_ml': away_ml,
'game_date': game_row.get('game_date') or game_row.get('date') or game_row.get('start_date') or '',
'status': game_row.get('status', ''),
'venue': game_row.get('venue', ''),
'neutral_site': game_row.get('neutral_site', False),
'home_rank': game_row.get('home_rank') if game_row.get('home_rank') != 99 else None,
'away_rank': game_row.get('away_rank') if game_row.get('away_rank') != 99 else None,
'season_used': season_used # Track which season data we used
}
except Exception as e:
return None
def get_upcoming_games() -> List[Dict]:
"""Get games from ESPN data and enrich with CBBD stats for predictions."""
try:
# Try loading pre-computed predictions first
precomputed = load_precomputed_predictions()
if precomputed and precomputed.get('games'):
# precomputed predictions loaded (message suppressed)
return precomputed['games']
# Fall back to live computation
# (suppressed info message about generating live predictions)
# Load ESPN games
espn_df = load_espn_games()
if espn_df.empty:
st.warning("No ESPN game data found. Run fetch_espn_cbb_scores.py first.")
return get_sample_games()
# Get team data from CBBD (uses most recent available season)
with st.spinner("Fetching team stats from recent seasons..."):
efficiency_list, stats_list, season_used = get_team_data(2025)
if not efficiency_list or not stats_list:
st.error("Could not fetch team data from CBBD API.")
return get_sample_games()
st.success(f"Using {season_used} season data for predictions")
# Filter for upcoming or recent games
eastern = pytz.timezone('US/Eastern')
now = datetime.now(eastern)
# Convert date column to datetime
espn_df['date_dt'] = pd.to_datetime(espn_df['date'])
# Separate upcoming and recent games
upcoming = espn_df[espn_df['date_dt'] > pd.Timestamp.now(tz='UTC')].copy()
recent = espn_df[espn_df['date_dt'] <= pd.Timestamp.now(tz='UTC')].copy()
# Prioritize upcoming games, but show recent if none upcoming
if len(upcoming) > 0:
st.success(f"Found {len(upcoming)} upcoming games!")
# Process all upcoming games (no artificial limit)
games_to_process = upcoming.sort_values('date_dt')
st.info(f"Processing all {len(upcoming)} upcoming games chronologically")
else:
st.info("No upcoming games scheduled. Showing recent games for analysis.")
games_to_process = recent.sort_values('date_dt', ascending=False).head(20)
# Enrich games with CBBD data
enriched_games = []
skipped_count = 0
for idx, game_row in games_to_process.iterrows():
enriched = enrich_espn_game_with_cbbd_data(game_row, efficiency_list, stats_list, season_used)
if enriched:
enriched_games.append(enriched)
else:
skipped_count += 1
if skipped_count > 0:
st.info(f"Skipped {skipped_count} games due to missing team data in {season_used} season")
if not enriched_games:
st.warning("Could not enrich games with team stats. Using sample data.")
return get_sample_games()
st.info(f"Prepared {len(enriched_games)} games with team stats for predictions")
return enriched_games
except Exception as e:
st.error(f"Error loading games: {e}")
return get_sample_games()
def get_sample_games() -> List[Dict]:
"""Return sample games for demo purposes."""
return [
{
"home_team": "Duke",
"away_team": "North Carolina",
"home_eff": {"offensiveRating": 118.5, "defensiveRating": 89.2, "netRating": 29.3},
"away_eff": {"offensiveRating": 115.8, "defensiveRating": 91.5, "netRating": 24.3},
"home_stats": {"ppg": 78.5, "pace": 68.2, "efg_pct": 0.52, "to_rate": 0.15, "orb_pct": 0.32, "ft_rate": 0.35, "opp_ppg": 65.2},
"away_stats": {"ppg": 75.8, "pace": 67.8, "efg_pct": 0.51, "to_rate": 0.16, "orb_pct": 0.31, "ft_rate": 0.33, "opp_ppg": 68.1},
"betting_spread": -3.5,
"betting_over_under": 145.5
},
{
"home_team": "Kansas",
"away_team": "Texas",
"home_eff": {"offensiveRating": 122.1, "defensiveRating": 87.8, "netRating": 34.3},
"away_eff": {"offensiveRating": 119.4, "defensiveRating": 90.1, "netRating": 29.3},
"home_stats": {"ppg": 82.1, "pace": 69.5, "efg_pct": 0.54, "to_rate": 0.14, "orb_pct": 0.34, "ft_rate": 0.37, "opp_ppg": 63.8},
"away_stats": {"ppg": 79.4, "pace": 68.9, "efg_pct": 0.53, "to_rate": 0.15, "orb_pct": 0.33, "ft_rate": 0.36, "opp_ppg": 66.2},
"betting_spread": -4.0,
"betting_over_under": 148.0
}
]
def format_game_data(game) -> Optional[Dict]:
"""Convert API game object to our expected format."""
try:
# Extract team names - handle both dict and object formats
if isinstance(game, dict):
# Dict format from API
home_team = game.get('homeTeam') or game.get('home_team')
away_team = game.get('awayTeam') or game.get('away_team')
else:
# Object format
home_team = (getattr(game, 'home_team', None) or
getattr(game, 'home', None) or
getattr(game, 'homeTeam', None))
away_team = (getattr(game, 'away_team', None) or
getattr(game, 'away', None) or
getattr(game, 'awayTeam', None))
if not home_team or not away_team:
return None
# Get team names as strings
if isinstance(home_team, str):
home_team_name = home_team
elif hasattr(home_team, 'name'):
home_team_name = home_team.name
else:
home_team_name = str(home_team)
if isinstance(away_team, str):
away_team_name = away_team
elif hasattr(away_team, 'name'):
away_team_name = away_team.name
else:
away_team_name = str(away_team)
# Try to get efficiency data for both teams
try:
efficiency_data = fetch_adjusted_efficiency(2026) # Current season
home_eff = next((e for e in efficiency_data if getattr(e, 'team', None) == home_team_name), {})
away_eff = next((e for e in efficiency_data if getattr(e, 'team', None) == away_team_name), {})
except:
home_eff = {}
away_eff = {}
# Try to get team stats
try:
team_stats_data = fetch_team_stats(2026)
home_stats = next((s for s in team_stats_data if getattr(s, 'team', None) == home_team_name), {})
away_stats = next((s for s in team_stats_data if getattr(s, 'team', None) == away_team_name), {})
except:
home_stats = {}
away_stats = {}
# Try to get betting lines (spread, o/u, moneylines) and parse moneylines
betting_spread = None
betting_over_under = None
home_ml = None
away_ml = None
try:
# Use the season we selected earlier where possible
lines_data = fetch_betting_lines(2026, "postseason")
# Find lines for this specific game - try multiple matching criteria
for line in lines_data:
# The CFBD response may be a dict (cached JSON) or an object
if isinstance(line, dict):
line_home = line.get('homeTeam') or line.get('home_team') or line.get('home')
line_away = line.get('awayTeam') or line.get('away_team') or line.get('away')
providers = line.get('lines') or []
else:
line_home = (getattr(line, 'home_team', None) or
getattr(line, 'homeTeam', None) or
getattr(line, 'home', None))
line_away = (getattr(line, 'away_team', None) or
getattr(line, 'awayTeam', None) or
getattr(line, 'away', None))
providers = getattr(line, 'lines', []) or []
# Normalize some values to strings for comparison
try:
lh = str(line_home) if line_home is not None else None
la = str(line_away) if line_away is not None else None
except Exception:
lh = line_home
la = line_away
# Match either by ESPN display name or normalized canonical name
if ((lh == home_team_name and la == away_team_name) or
(lh == normalize_team_name(home_team_name) and la == normalize_team_name(away_team_name))):
# Prefer the first provider entry if present
provider = providers[0] if providers and len(providers) > 0 else None
if provider:
# provider may be dict-like or object-like
if isinstance(provider, dict):
betting_spread = provider.get('spread') or provider.get('formattedSpread') or betting_spread
betting_over_under = provider.get('overUnder') or provider.get('over_under') or betting_over_under
home_ml = provider.get('homeMoneyline') or provider.get('home_moneyline') or provider.get('homeML') or home_ml
away_ml = provider.get('awayMoneyline') or provider.get('away_moneyline') or provider.get('awayML') or away_ml
else:
betting_spread = getattr(provider, 'spread', None) or getattr(provider, 'formattedSpread', None) or betting_spread
betting_over_under = getattr(provider, 'overUnder', None) or getattr(provider, 'over_under', None) or betting_over_under
home_ml = getattr(provider, 'homeMoneyline', None) or getattr(provider, 'home_moneyline', None) or getattr(provider, 'homeML', None) or home_ml
away_ml = getattr(provider, 'awayMoneyline', None) or getattr(provider, 'away_moneyline', None) or getattr(provider, 'awayML', None) or away_ml
else:
# Some cached responses may put moneylines at top level
if isinstance(line, dict):
home_ml = line.get('homeMoneyline') or line.get('home_moneyline') or home_ml
away_ml = line.get('awayMoneyline') or line.get('away_moneyline') or away_ml
betting_spread = line.get('spread') or betting_spread
betting_over_under = line.get('overUnder') or betting_over_under
else:
home_ml = getattr(line, 'homeMoneyline', None) or getattr(line, 'home_moneyline', None) or home_ml
away_ml = getattr(line, 'awayMoneyline', None) or getattr(line, 'away_moneyline', None) or away_ml
betting_spread = getattr(line, 'spread', None) or betting_spread
betting_over_under = getattr(line, 'overUnder', None) or betting_over_under
# Stop after first match
break
except Exception:
# Do not fail enrichment if betting lines are unavailable
pass
# Get actual scores if available
if isinstance(game, dict):
actual_home_score = game.get('homePoints') or game.get('home_points')
actual_away_score = game.get('awayPoints') or game.get('away_points')
else:
actual_home_score = getattr(game, 'home_points', None) or getattr(game, 'homePoints', None)
actual_away_score = getattr(game, 'away_points', None) or getattr(game, 'awayPoints', None)
# Create the game data structure with default values if data is missing
return {
"home_team": home_team_name,
"away_team": away_team_name,
"actual_home_score": actual_home_score,
"actual_away_score": actual_away_score,
"home_eff": {
"offensiveRating": float(getattr(home_eff, 'offensive_rating', 100) or getattr(home_eff, 'adj_offense', 100) or 100),
"defensiveRating": float(getattr(home_eff, 'defensive_rating', 100) or getattr(home_eff, 'adj_defense', 100) or 100),
"netRating": float(getattr(home_eff, 'net_rating', 0) or getattr(home_eff, 'adj_net', 0) or 0)
},
"away_eff": {
"offensiveRating": float(getattr(away_eff, 'offensive_rating', 100) or getattr(away_eff, 'adj_offense', 100) or 100),
"defensiveRating": float(getattr(away_eff, 'defensive_rating', 100) or getattr(away_eff, 'adj_defense', 100) or 100),
"netRating": float(getattr(away_eff, 'net_rating', 0) or getattr(away_eff, 'adj_net', 0) or 0)
},
"home_stats": {
"ppg": float(getattr(home_stats, 'points_per_game', 70) or getattr(home_stats, 'ppg', 70) or 70),
"pace": float(getattr(home_stats, 'pace', 68) or 68),
"efg_pct": float(getattr(home_stats, 'effective_fg_pct', 0.50) or getattr(home_stats, 'efg_pct', 0.50) or 0.50),
"to_rate": float(getattr(home_stats, 'turnover_pct', 0.15) or getattr(home_stats, 'to_rate', 0.15) or 0.15),
"orb_pct": float(getattr(home_stats, 'orb_pct', 0.30) or 0.30),
"ft_rate": float(getattr(home_stats, 'ft_rate', 0.35) or 0.35),
"opp_ppg": float(getattr(home_stats, 'opp_points_per_game', 70) or getattr(home_stats, 'opp_ppg', 70) or 70)
},
"away_stats": {
"ppg": float(getattr(away_stats, 'points_per_game', 70) or getattr(away_stats, 'ppg', 70) or 70),
"pace": float(getattr(away_stats, 'pace', 68) or 68),
"efg_pct": float(getattr(away_stats, 'effective_fg_pct', 0.50) or getattr(away_stats, 'efg_pct', 0.50) or 0.50),
"to_rate": float(getattr(away_stats, 'turnover_pct', 0.15) or getattr(away_stats, 'to_rate', 0.15) or 0.15),
"orb_pct": float(getattr(away_stats, 'orb_pct', 0.30) or 0.30),
"ft_rate": float(getattr(away_stats, 'ft_rate', 0.35) or 0.35),
"opp_ppg": float(getattr(away_stats, 'opp_points_per_game', 70) or getattr(away_stats, 'opp_ppg', 70) or 70)
},
"betting_spread": betting_spread,
"betting_over_under": betting_over_under,
# Moneyline fields for market comparisons (aliases for compatibility)
"home_moneyline": home_ml,
"away_moneyline": away_ml,
"home_ml": home_ml,
"away_ml": away_ml
}
except Exception as e:
print(f"Error formatting game {game}: {e}")
return None
def calculate_features(home_team: Dict, away_team: Dict, home_eff: Dict, away_eff: Dict, advanced_metrics: Dict = None) -> Dict:
"""Calculate prediction features for a game."""
# Prefer centralized feature helpers from features.py when available
try:
from features import (
calculate_efficiency_differential as _calc_eff_diff,
calculate_spread_features as _calc_spread_feats,
calculate_total_features as _calc_total_feats,
calculate_win_probability_features as _calc_win_feats,
)