-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
6182 lines (5139 loc) · 255 KB
/
Copy pathapp.py
File metadata and controls
6182 lines (5139 loc) · 255 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
"""
Ultimate Fantasy Football Trade Analyzer (IDP, Historical, & League Import)
A comprehensive tool for analyzing fantasy football trades with IDP support,
historical trends, age adjustments, team performance, and matchup analysis.
"""
import streamlit as st
import requests
import pandas as pd
from typing import Dict, List, Optional, Tuple
import json
from datetime import datetime
from fuzzywuzzy import fuzz, process
import altair as alt
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, r2_score
import warnings
warnings.filterwarnings('ignore')
from auth_utils import (
init_session_state, is_authenticated, render_auth_ui,
render_league_selector, render_add_league_modal, render_manage_leagues_modal,
get_current_user, save_trade, get_saved_trades
)
from sleeper_api import (
fetch_league_details, fetch_league_rosters, fetch_league_users,
fetch_traded_picks, fetch_league_drafts, fetch_draft_picks,
fetch_league_transactions, fetch_league_matchups,
get_roster_positions_summary, get_scoring_summary,
get_future_picks_inventory, adjust_value_for_league_scoring,
get_team_roster_composition, calculate_optimal_starter_count,
get_recent_transactions_summary, format_roster_positions, is_superflex_league,
fetch_all_nfl_players, filter_trades, parse_trade_details
)
# Configuration
API_KEY = "73280229e64f4083b54094d6745b3a7d" # SportsDataIO API key
BASE_URL = "https://api.sportsdata.io/v3/nfl"
CURRENT_YEAR = 2025 # Current NFL season available in API
# Position baselines for VORP calculation
POSITION_BASELINES = {
'QB': 12, 'RB': 24, 'WR': 30, 'TE': 12,
'K': 12, 'DEF': 12,
'DL': 24, 'LB': 30, 'DB': 24 # IDP positions
}
# Scoring weights for analysis
SCORING_WEIGHTS = {
'projections': 0.60,
'historical': 0.20,
'team_performance': 0.10,
'matchup_sos': 0.05,
'age_injury': 0.05
}
# ============================================================================
# PREDICTIVE TEXT / AUTOCOMPLETE HELPER FUNCTIONS
# ============================================================================
def format_player_display_name(player_data: Dict, player_id: str = None) -> str:
"""
Format player data into searchable display name.
Format: "Full Name (Position - Team) - Age X"
Example: "Patrick Mahomes (QB - KC) - Age 29"
"""
full_name = player_data.get('full_name') or player_data.get('display_name', 'Unknown')
first_name = player_data.get('first_name', '')
last_name = player_data.get('last_name', '')
if not full_name or full_name == 'Unknown':
full_name = f"{first_name} {last_name}".strip()
position = player_data.get('position', 'UNK')
team = player_data.get('team', 'FA')
age = player_data.get('age', '')
age_str = f" - Age {age}" if age else ""
return f"{full_name} ({position} - {team}){age_str}"
def build_searchable_player_list(all_nfl_players: Dict, active_only: bool = True) -> Dict[str, str]:
"""
Build a searchable player list with formatted names.
Returns: dict mapping display_name -> player_id
"""
player_options = {}
for player_id, player_data in all_nfl_players.items():
if active_only and player_data.get('status') not in ['Active', 'Inactive', 'Questionable', 'Doubtful', 'Out', 'PUP', 'IR']:
continue
position = player_data.get('position', '')
if position in ['QB', 'RB', 'WR', 'TE', 'K', 'DEF', 'DL', 'LB', 'DB']:
display_name = format_player_display_name(player_data, player_id)
player_options[display_name] = player_id
return player_options
def fuzzy_search_players(search_query: str, player_options: Dict[str, str], limit: int = 20) -> List[str]:
"""
Perform fuzzy search on player names.
Returns top matches sorted by similarity score.
"""
if not search_query:
return []
results = process.extract(search_query, player_options.keys(), limit=limit, scorer=fuzz.token_sort_ratio)
return [match[0] for match in results if match[1] > 40]
def build_pick_options(num_teams: int = 12, years: List[int] = None, num_rounds: int = 5) -> List[str]:
"""
Build comprehensive pick options for autocomplete.
Includes specific slots (1.01, 1.02) and general picks (Early 1st, Mid 2nd, Late 3rd).
"""
if years is None:
current_year = datetime.now().year
years = [current_year + i for i in range(1, 4)]
pick_options = []
for year in years:
for round_num in range(1, num_rounds + 1):
for slot in range(1, num_teams + 1):
pick_options.append(f"{year} {round_num}.{slot:02d}")
for timing in ['Early', 'Mid', 'Late']:
round_suffix = {1: '1st', 2: '2nd', 3: '3rd'}.get(round_num, f'{round_num}th')
pick_options.append(f"{year} {timing} {round_suffix}")
return sorted(pick_options)
def fuzzy_search_picks(search_query: str, pick_options: List[str], limit: int = 20) -> List[str]:
"""
Perform fuzzy search on draft picks.
Returns top matches sorted by relevance.
"""
if not search_query:
return []
results = process.extract(search_query, pick_options, limit=limit, scorer=fuzz.partial_ratio)
return [match[0] for match in results if match[1] > 50]
def render_searchable_player_multiselect(
label: str,
player_display_to_id: Dict[str, str],
roster_df: pd.DataFrame,
key: str,
help_text: str = None
) -> List[str]:
"""
Render a searchable multiselect for players with fuzzy matching.
Returns list of selected player display names.
"""
col_search, col_clear = st.columns([4, 1])
with col_search:
search_query = st.text_input(
f"🔍 Search {label}",
key=f"{key}_search",
placeholder="Type player name (e.g., 'Mah' for Mahomes)...",
help="Use fuzzy search to find players quickly"
)
filtered_options = []
if search_query:
matched_names = fuzzy_search_players(search_query, player_display_to_id, limit=30)
roster_player_names = set(roster_df['Name'].tolist())
filtered_options = []
for display_name in matched_names:
player_name = display_name.split(' (')[0]
if player_name in roster_player_names:
player = roster_df[roster_df['Name'] == player_name].iloc[0]
option = f"{player['Name']} ({player['Position']}, {player['Team']}, Age {player['Age']}) - {player['AdjustedValue']:.0f} pts"
filtered_options.append(option)
if filtered_options:
st.caption(f"Found {len(filtered_options)} matches")
else:
st.caption("No matches found in roster")
else:
for _, player in roster_df.iterrows():
option = f"{player['Name']} ({player['Position']}, {player['Team']}, Age {player['Age']}) - {player['AdjustedValue']:.0f} pts"
filtered_options.append(option)
selections = st.multiselect(
label,
options=filtered_options,
key=f"{key}_select",
help=help_text or "Select multiple players"
)
return selections
@st.cache_data(ttl=1800)
def calculate_league_rankings(
all_rosters_df: Dict,
traded_picks: List[Dict],
league_rosters: List[Dict],
league_users: List[Dict],
league_details: Dict,
is_superflex: bool = False
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Calculate league-wide team rankings based on player values and picks.
Returns: (players_only_df, players_plus_picks_df)
"""
if not all_rosters_df:
return pd.DataFrame(), pd.DataFrame()
current_season = int(league_details.get('season', datetime.now().year)) if league_details else datetime.now().year
num_rounds = league_details.get('settings', {}).get('draft_rounds', 5) if league_details else 5
user_map = {user['user_id']: user.get('display_name', user.get('username', 'Unknown'))
for user in league_users} if league_users else {}
roster_to_user = {roster['roster_id']: roster['owner_id'] for roster in league_rosters} if league_rosters else {}
roster_id_to_team = {}
for roster in league_rosters:
owner_id = roster.get('owner_id')
team_name = user_map.get(owner_id, f"Team {roster.get('roster_id', '?')}")
roster_id_to_team[roster['roster_id']] = team_name
rankings_data = []
for team_name, roster_df in all_rosters_df.items():
total_player_value = roster_df['AdjustedValue'].sum()
top_players = roster_df.nlargest(5, 'AdjustedValue')[['Name', 'Position', 'AdjustedValue']].to_dict('records')
top_players_str = ", ".join([f"{p['Name']} ({p['Position']}) {p['AdjustedValue']:.0f}"
for p in top_players[:3]])
team_roster_id = None
for roster_id, name in roster_id_to_team.items():
if name == team_name:
team_roster_id = roster_id
break
total_pick_value = 0
future_picks = []
if team_roster_id and traded_picks:
for future_year in range(current_season + 1, current_season + 4):
for round_num in range(1, num_rounds + 1):
owned_by_team = False
original_owner_name = None
pick_traded_away = False
for traded_pick in traded_picks:
if (str(traded_pick.get('season')) == str(future_year) and
traded_pick.get('round') == round_num and
traded_pick.get('roster_id') == team_roster_id):
pick_traded_away = True
break
if not pick_traded_away:
owned_by_team = True
original_owner_name = "Own"
for traded_pick in traded_picks:
if (str(traded_pick.get('season')) == str(future_year) and
traded_pick.get('round') == round_num and
traded_pick.get('owner_id') == team_roster_id):
owned_by_team = True
original_roster_id = traded_pick.get('roster_id')
original_owner_name = roster_id_to_team.get(original_roster_id, f"Team {original_roster_id}")
break
if owned_by_team:
pick_str = f"{future_year} {round_num}.06"
pick_value, _ = get_pick_value(pick_str, is_superflex)
total_pick_value += pick_value
round_suffix = {1: '1st', 2: '2nd', 3: '3rd'}.get(round_num, f'{round_num}th')
pick_desc = f"{future_year} {round_suffix}"
if original_owner_name and original_owner_name != "Own":
pick_desc += f" (from {original_owner_name})"
future_picks.append(pick_desc)
future_picks_str = ", ".join(future_picks) if future_picks else "None"
rankings_data.append({
'Team': team_name,
'Player Value': total_player_value,
'Pick Value': total_pick_value,
'Total Value': total_player_value + total_pick_value,
'Top Players': top_players_str,
'Future Picks': future_picks_str,
'Pick Count': len(future_picks)
})
rankings_df = pd.DataFrame(rankings_data)
players_only_df = rankings_df[['Team', 'Player Value', 'Top Players']].copy()
players_only_df['Rank'] = players_only_df['Player Value'].rank(ascending=False, method='min').astype(int)
players_only_df = players_only_df.sort_values('Player Value', ascending=False).reset_index(drop=True)
players_only_df = players_only_df[['Rank', 'Team', 'Player Value', 'Top Players']]
players_plus_picks_df = rankings_df[['Team', 'Total Value', 'Player Value', 'Pick Value', 'Future Picks', 'Pick Count']].copy()
players_plus_picks_df['Rank'] = players_plus_picks_df['Total Value'].rank(ascending=False, method='min').astype(int)
players_plus_picks_df = players_plus_picks_df.sort_values('Total Value', ascending=False).reset_index(drop=True)
players_plus_picks_df = players_plus_picks_df[['Rank', 'Team', 'Total Value', 'Player Value', 'Pick Value', 'Future Picks', 'Pick Count']]
return players_only_df, players_plus_picks_df
@st.cache_data(ttl=1800)
def fetch_all_matchups(league_id: str, current_week: int, total_weeks: int) -> Dict[int, List[Dict]]:
"""
Fetch matchups for all weeks in the season.
Returns: dict mapping week number to list of matchup dicts
"""
all_matchups = {}
for week in range(1, total_weeks + 1):
matchups = fetch_league_matchups(league_id, week)
if matchups:
all_matchups[week] = matchups
return all_matchups
def calculate_team_projected_points(
roster_df: pd.DataFrame,
league_details: Dict,
starters_only: bool = True
) -> float:
"""
Calculate projected points for a team based on their roster.
Uses AdjustedValue as weekly projection proxy.
"""
if roster_df.empty:
return 0.0
# Use AdjustedValue as season-long value, divide by ~17 weeks for weekly projection
# For starters, use top players at each position based on league settings
if starters_only and league_details:
roster_positions = league_details.get('roster_positions', [])
position_counts = {}
for pos in roster_positions:
if pos != 'BN': # Exclude bench
position_counts[pos] = position_counts.get(pos, 0) + 1
weekly_value = 0
for position, count in position_counts.items():
if position == 'FLEX':
# FLEX can be RB/WR/TE
flex_players = roster_df[roster_df['Position'].isin(['RB', 'WR', 'TE'])].nlargest(count, 'AdjustedValue')
weekly_value += flex_players['AdjustedValue'].sum() / 17
elif position == 'SUPER_FLEX':
# SUPER_FLEX can be any offensive position
sf_players = roster_df[roster_df['Position'].isin(['QB', 'RB', 'WR', 'TE'])].nlargest(count, 'AdjustedValue')
weekly_value += sf_players['AdjustedValue'].sum() / 17
else:
pos_players = roster_df[roster_df['Position'] == position].nlargest(count, 'AdjustedValue')
weekly_value += pos_players['AdjustedValue'].sum() / 17
return max(weekly_value, 0.0)
else:
# Simple average of top players
return roster_df['AdjustedValue'].sum() / 17
def simulate_matchup(
team1_projection: float,
team2_projection: float,
variance_pct: float = 0.25,
n_simulations: int = 1
) -> Tuple[float, float]:
"""
Simulate a single matchup between two teams.
Returns: (team1_win_pct, team2_win_pct)
"""
team1_wins = 0
team2_wins = 0
for _ in range(n_simulations):
# Generate scores with normal distribution
team1_score = np.random.normal(team1_projection, team1_projection * variance_pct)
team2_score = np.random.normal(team2_projection, team2_projection * variance_pct)
# Ensure non-negative scores
team1_score = max(team1_score, 0)
team2_score = max(team2_score, 0)
if team1_score > team2_score:
team1_wins += 1
elif team2_score > team1_score:
team2_wins += 1
else:
# Tie - split
team1_wins += 0.5
team2_wins += 0.5
return team1_wins / n_simulations, team2_wins / n_simulations
@st.cache_data(ttl=1800)
def run_playoff_simulation(
all_rosters_df: Dict,
league_details: Dict,
league_rosters: List[Dict],
league_users: List[Dict],
all_matchups: Dict[int, List[Dict]],
current_week: int,
n_simulations: int = 10000,
variance_pct: float = 0.25
) -> pd.DataFrame:
"""
Run Monte Carlo playoff simulation.
Returns DataFrame with columns:
- Team: Team name
- Current Wins: Actual wins so far
- Current Losses: Actual losses so far
- Projected Wins: Average wins in simulations
- Projected Losses: Average losses in simulations
- Playoff Pct: % of simulations making playoffs
- Bye Pct: % of simulations getting first-round bye
- Championship Pct: % of simulations winning championship
- Avg Seed: Average playoff seed
- Avg Points: Average points per game
"""
if not all_rosters_df or not league_details:
return pd.DataFrame()
# Map roster IDs to team names
user_map = {user['user_id']: user.get('display_name', user.get('username', 'Unknown'))
for user in league_users}
roster_id_to_team = {}
team_to_roster_id = {}
for roster in league_rosters:
owner_id = roster.get('owner_id')
roster_id = roster['roster_id']
team_name = user_map.get(owner_id, f"Team {roster_id}")
roster_id_to_team[roster_id] = team_name
team_to_roster_id[team_name] = roster_id
# Calculate projected points for each team
team_projections = {}
for team_name, roster_df in all_rosters_df.items():
team_projections[team_name] = calculate_team_projected_points(roster_df, league_details, starters_only=True)
# Get current standings
team_records = {team: {'wins': 0, 'losses': 0, 'ties': 0, 'points_for': 0.0, 'points_against': 0.0}
for team in team_projections.keys()}
# Process completed weeks
for week in range(1, min(current_week, len(all_matchups) + 1)):
if week not in all_matchups:
continue
matchups = all_matchups[week]
matchup_dict = {}
# Group matchups by matchup_id
for matchup in matchups:
roster_id = matchup.get('roster_id')
matchup_id = matchup.get('matchup_id')
points = matchup.get('points', 0)
if matchup_id and roster_id in roster_id_to_team:
if matchup_id not in matchup_dict:
matchup_dict[matchup_id] = []
matchup_dict[matchup_id].append({
'roster_id': roster_id,
'team': roster_id_to_team[roster_id],
'points': points
})
# Process each matchup
for matchup_id, teams in matchup_dict.items():
if len(teams) == 2:
team1 = teams[0]['team']
team2 = teams[1]['team']
points1 = teams[0]['points']
points2 = teams[1]['points']
if team1 in team_records and team2 in team_records:
team_records[team1]['points_for'] += points1
team_records[team1]['points_against'] += points2
team_records[team2]['points_for'] += points2
team_records[team2]['points_against'] += points1
if points1 > points2:
team_records[team1]['wins'] += 1
team_records[team2]['losses'] += 1
elif points2 > points1:
team_records[team2]['wins'] += 1
team_records[team1]['losses'] += 1
else:
team_records[team1]['ties'] += 1
team_records[team2]['ties'] += 1
# Get league settings
settings = league_details.get('settings', {})
playoff_teams = settings.get('playoff_teams', 6)
total_weeks = settings.get('playoff_week_start', 15) - 1 # Regular season ends before playoffs
playoff_bye_teams = settings.get('playoff_seed_type', 0) # 0 = no byes, 1 = top 2 get bye
# Determine remaining weeks and matchups
remaining_weeks = list(range(current_week, total_weeks + 1))
# Run simulations
simulation_results = {team: {
'playoff_count': 0,
'bye_count': 0,
'championship_count': 0,
'total_wins': 0,
'total_losses': 0,
'seeds': [],
'points': []
} for team in team_projections.keys()}
for sim in range(n_simulations):
# Copy current records
sim_records = {team: {
'wins': team_records[team]['wins'],
'losses': team_records[team]['losses'],
'points_for': team_records[team]['points_for'],
'points_against': team_records[team]['points_against']
} for team in team_projections.keys()}
# Simulate remaining regular season weeks
for week in remaining_weeks:
if week in all_matchups:
# Use actual matchup schedule
matchups = all_matchups[week]
matchup_dict = {}
for matchup in matchups:
roster_id = matchup.get('roster_id')
matchup_id = matchup.get('matchup_id')
if matchup_id and roster_id in roster_id_to_team:
if matchup_id not in matchup_dict:
matchup_dict[matchup_id] = []
matchup_dict[matchup_id].append(roster_id_to_team[roster_id])
for matchup_id, teams in matchup_dict.items():
if len(teams) == 2:
team1, team2 = teams[0], teams[1]
if team1 in team_projections and team2 in team_projections:
# Simulate game
proj1 = team_projections[team1]
proj2 = team_projections[team2]
score1 = max(0, np.random.normal(proj1, proj1 * variance_pct))
score2 = max(0, np.random.normal(proj2, proj2 * variance_pct))
sim_records[team1]['points_for'] += score1
sim_records[team1]['points_against'] += score2
sim_records[team2]['points_for'] += score2
sim_records[team2]['points_against'] += score1
if score1 > score2:
sim_records[team1]['wins'] += 1
sim_records[team2]['losses'] += 1
else:
sim_records[team2]['wins'] += 1
sim_records[team1]['losses'] += 1
# Determine playoff seeding
teams_sorted = sorted(
sim_records.items(),
key=lambda x: (x[1]['wins'], x[1]['points_for']),
reverse=True
)
# Award playoff spots
for i, (team, record) in enumerate(teams_sorted[:playoff_teams]):
seed = i + 1
simulation_results[team]['playoff_count'] += 1
simulation_results[team]['seeds'].append(seed)
simulation_results[team]['points'].append(record['points_for'])
# First-round bye (typically top 1 or 2 seeds)
if seed <= min(2, playoff_bye_teams):
simulation_results[team]['bye_count'] += 1
# Simulate playoffs (simple model: higher seed has advantage)
playoff_teams_list = [team for team, _ in teams_sorted[:playoff_teams]]
# Championship simulation (simplified: weight by seed)
if playoff_teams_list:
# Weight teams inversely by seed (seed 1 has highest weight)
weights = [1.0 / (i + 1) for i in range(len(playoff_teams_list))]
total_weight = sum(weights)
normalized_weights = [w / total_weight for w in weights]
champion = np.random.choice(playoff_teams_list, p=normalized_weights)
simulation_results[champion]['championship_count'] += 1
# Track totals
for team, record in sim_records.items():
simulation_results[team]['total_wins'] += record['wins']
simulation_results[team]['total_losses'] += record['losses']
# Build results DataFrame
results_data = []
for team in team_projections.keys():
current_wins = team_records[team]['wins']
current_losses = team_records[team]['losses']
current_pf = team_records[team]['points_for']
avg_wins = simulation_results[team]['total_wins'] / n_simulations
avg_losses = simulation_results[team]['total_losses'] / n_simulations
playoff_pct = (simulation_results[team]['playoff_count'] / n_simulations) * 100
bye_pct = (simulation_results[team]['bye_count'] / n_simulations) * 100
championship_pct = (simulation_results[team]['championship_count'] / n_simulations) * 100
avg_seed = np.mean(simulation_results[team]['seeds']) if simulation_results[team]['seeds'] else 0
avg_points = np.mean(simulation_results[team]['points']) if simulation_results[team]['points'] else current_pf
results_data.append({
'Team': team,
'Current Record': f"{current_wins}-{current_losses}",
'Current Wins': current_wins,
'Current Losses': current_losses,
'Projected Wins': avg_wins,
'Projected Losses': avg_losses,
'Playoff %': playoff_pct,
'Bye %': bye_pct,
'Championship %': championship_pct,
'Avg Seed': avg_seed,
'Avg Points': avg_points,
'Projection': team_projections[team]
})
results_df = pd.DataFrame(results_data)
results_df = results_df.sort_values('Playoff %', ascending=False).reset_index(drop=True)
return results_df
def calculate_recent_performance(
all_matchups: Dict[int, List[Dict]],
roster_id_to_team: Dict[int, str],
current_week: int,
lookback_weeks: int = 4
) -> Dict[str, Dict]:
"""
Calculate recent performance metrics for each team based on last N weeks.
Returns dict with team -> {
'recent_points': average points over last N weeks,
'recent_wins': wins in last N weeks,
'recent_games': number of games played,
'trend': 'up', 'down', or 'stable'
}
"""
team_performance = {}
start_week = max(1, current_week - lookback_weeks)
for team in roster_id_to_team.values():
team_performance[team] = {
'recent_points': 0.0,
'recent_wins': 0,
'recent_games': 0,
'weekly_points': [],
'trend': 'stable'
}
for week in range(start_week, current_week):
if week not in all_matchups:
continue
matchups = all_matchups[week]
matchup_dict = {}
for matchup in matchups:
roster_id = matchup.get('roster_id')
matchup_id = matchup.get('matchup_id')
points = matchup.get('points', 0)
if matchup_id and roster_id in roster_id_to_team:
if matchup_id not in matchup_dict:
matchup_dict[matchup_id] = []
matchup_dict[matchup_id].append({
'roster_id': roster_id,
'team': roster_id_to_team[roster_id],
'points': points
})
for matchup_id, teams in matchup_dict.items():
if len(teams) == 2:
team1 = teams[0]['team']
team2 = teams[1]['team']
points1 = teams[0]['points']
points2 = teams[1]['points']
if team1 in team_performance:
team_performance[team1]['recent_points'] += points1
team_performance[team1]['recent_games'] += 1
team_performance[team1]['weekly_points'].append(points1)
if points1 > points2:
team_performance[team1]['recent_wins'] += 1
if team2 in team_performance:
team_performance[team2]['recent_points'] += points2
team_performance[team2]['recent_games'] += 1
team_performance[team2]['weekly_points'].append(points2)
if points2 > points1:
team_performance[team2]['recent_wins'] += 1
for team in team_performance:
if team_performance[team]['recent_games'] > 0:
team_performance[team]['recent_points'] /= team_performance[team]['recent_games']
weekly_points = team_performance[team]['weekly_points']
if len(weekly_points) >= 2:
first_half = weekly_points[:len(weekly_points)//2]
second_half = weekly_points[len(weekly_points)//2:]
if len(first_half) > 0 and len(second_half) > 0:
avg_first = sum(first_half) / len(first_half)
avg_second = sum(second_half) / len(second_half)
if avg_second > avg_first * 1.05:
team_performance[team]['trend'] = 'up'
elif avg_second < avg_first * 0.95:
team_performance[team]['trend'] = 'down'
return team_performance
def calculate_strength_of_schedule(
all_matchups: Dict[int, List[Dict]],
roster_id_to_team: Dict[int, str],
team_projections: Dict[str, float],
current_week: int,
total_weeks: int
) -> Dict[str, Dict]:
"""
Calculate strength of schedule for each team.
Returns dict with team -> {
'past_sos': average opponent strength (past games),
'future_sos': average opponent strength (remaining games),
'overall_sos': combined SOS,
'sos_rank': difficulty rank (1 = hardest)
}
"""
team_schedules = {team: {'past_opponents': [], 'future_opponents': []}
for team in roster_id_to_team.values()}
for week in range(1, total_weeks + 1):
if week not in all_matchups:
continue
matchups = all_matchups[week]
matchup_dict = {}
for matchup in matchups:
roster_id = matchup.get('roster_id')
matchup_id = matchup.get('matchup_id')
if matchup_id and roster_id in roster_id_to_team:
if matchup_id not in matchup_dict:
matchup_dict[matchup_id] = []
matchup_dict[matchup_id].append(roster_id_to_team[roster_id])
for matchup_id, teams in matchup_dict.items():
if len(teams) == 2:
team1, team2 = teams[0], teams[1]
if week < current_week:
team_schedules[team1]['past_opponents'].append(team2)
team_schedules[team2]['past_opponents'].append(team1)
else:
team_schedules[team1]['future_opponents'].append(team2)
team_schedules[team2]['future_opponents'].append(team1)
sos_results = {}
for team in team_schedules:
past_opponents = team_schedules[team]['past_opponents']
future_opponents = team_schedules[team]['future_opponents']
past_sos = 0.0
if past_opponents:
past_strengths = [team_projections.get(opp, 0) for opp in past_opponents]
past_sos = sum(past_strengths) / len(past_strengths)
future_sos = 0.0
if future_opponents:
future_strengths = [team_projections.get(opp, 0) for opp in future_opponents]
future_sos = sum(future_strengths) / len(future_strengths)
total_opponents = len(past_opponents) + len(future_opponents)
if total_opponents > 0:
overall_sos = (past_sos * len(past_opponents) + future_sos * len(future_opponents)) / total_opponents
else:
overall_sos = 0.0
sos_results[team] = {
'past_sos': past_sos,
'future_sos': future_sos,
'overall_sos': overall_sos,
'sos_rank': 0
}
sorted_teams = sorted(sos_results.items(), key=lambda x: x[1]['overall_sos'], reverse=True)
for rank, (team, data) in enumerate(sorted_teams, 1):
sos_results[team]['sos_rank'] = rank
return sos_results
def calculate_power_rankings(
all_rosters_df: Dict[str, pd.DataFrame],
playoff_odds_df: pd.DataFrame,
recent_performance: Dict[str, Dict],
team_projections: Dict[str, float],
sos_data: Dict[str, Dict],
weights: Dict[str, float] = None
) -> pd.DataFrame:
"""
Calculate power rankings using weighted formula.
Weights:
- roster_value: 40% (long-term strength)
- playoff_odds: 30% (championship probability)
- recent_performance: 20% (current form)
- strength_of_schedule: 10% (difficulty adjustment)
Returns DataFrame with power rankings.
"""
if weights is None:
weights = {
'roster_value': 0.40,
'playoff_odds': 0.30,
'recent_performance': 0.20,
'strength_of_schedule': 0.10
}
power_scores = []
for team in all_rosters_df.keys():
roster_value = team_projections.get(team, 0)
playoff_row = playoff_odds_df[playoff_odds_df['Team'] == team]
playoff_pct = playoff_row['Playoff %'].iloc[0] if len(playoff_row) > 0 else 0
championship_pct = playoff_row['Championship %'].iloc[0] if len(playoff_row) > 0 else 0
playoff_score = (playoff_pct * 0.7 + championship_pct * 0.3)
recent_perf = recent_performance.get(team, {})
recent_points = recent_perf.get('recent_points', 0)
recent_wins = recent_perf.get('recent_wins', 0)
recent_games = recent_perf.get('recent_games', 1)
recent_win_pct = (recent_wins / recent_games * 100) if recent_games > 0 else 0
recent_score = (recent_points * 0.6 + recent_win_pct * 0.4)
sos = sos_data.get(team, {})
sos_rank = sos.get('sos_rank', len(all_rosters_df) / 2)
num_teams = len(all_rosters_df)
sos_score = ((num_teams - sos_rank + 1) / num_teams) * 100
max_roster_value = max(team_projections.values()) if team_projections else 1
normalized_roster = (roster_value / max_roster_value) * 100 if max_roster_value > 0 else 0
max_recent = max([rp.get('recent_points', 0) for rp in recent_performance.values()]) if recent_performance else 1
normalized_recent = (recent_score / max_recent) * 100 if max_recent > 0 else 0
power_score = (
normalized_roster * weights['roster_value'] +
playoff_score * weights['playoff_odds'] +
normalized_recent * weights['recent_performance'] +
sos_score * weights['strength_of_schedule']
)
trend = recent_perf.get('trend', 'stable')
power_scores.append({
'Team': team,
'Power Score': power_score,
'Roster Value': roster_value,
'Playoff %': playoff_pct,
'Championship %': championship_pct,
'Recent PPG': recent_points,
'Recent Record': f"{recent_wins}-{recent_games - recent_wins}" if recent_games > 0 else "0-0",
'Trend': trend,
'SOS Rank': sos_rank,
'Future SOS': sos.get('future_sos', 0),
'Overall SOS': sos.get('overall_sos', 0)
})
df = pd.DataFrame(power_scores)
df = df.sort_values('Power Score', ascending=False).reset_index(drop=True)
df['Rank'] = range(1, len(df) + 1)
cols = ['Rank', 'Team', 'Power Score', 'Trend', 'Roster Value', 'Playoff %',
'Championship %', 'Recent PPG', 'Recent Record', 'SOS Rank', 'Future SOS']
df = df[cols]
return df
def track_power_rankings_history(
current_rankings: pd.DataFrame,
current_week: int
) -> pd.DataFrame:
"""
Track power rankings history over time.
Stores in session state and returns historical DataFrame.
"""
if 'power_rankings_history' not in st.session_state:
st.session_state['power_rankings_history'] = []
history = st.session_state['power_rankings_history']
current_snapshot = []
for _, row in current_rankings.iterrows():
current_snapshot.append({
'Week': current_week,
'Team': row['Team'],
'Rank': row['Rank'],
'Power Score': row['Power Score']
})
existing_week = [i for i, item in enumerate(history) if item['Week'] == current_week]
if existing_week:
history = [item for item in history if item['Week'] != current_week]
history.extend(current_snapshot)
st.session_state['power_rankings_history'] = history
if history:
history_df = pd.DataFrame(history)
return history_df
else:
return pd.DataFrame()
def calculate_rank_change(
current_rankings: pd.DataFrame,
history_df: pd.DataFrame,
current_week: int
) -> pd.DataFrame:
"""
Calculate rank change from previous week.
"""
rankings_with_change = current_rankings.copy()
rankings_with_change['Δ Rank'] = 0
rankings_with_change['Δ Score'] = 0.0
if not history_df.empty and current_week > 1:
prev_week = current_week - 1
prev_data = history_df[history_df['Week'] == prev_week]
if not prev_data.empty:
for idx, row in rankings_with_change.iterrows():
team = row['Team']
current_rank = row['Rank']
current_score = row['Power Score']
prev_row = prev_data[prev_data['Team'] == team]
if len(prev_row) > 0:
prev_rank = prev_row['Rank'].iloc[0]
prev_score = prev_row['Power Score'].iloc[0]
rankings_with_change.at[idx, 'Δ Rank'] = prev_rank - current_rank
rankings_with_change.at[idx, 'Δ Score'] = current_score - prev_score
return rankings_with_change
def calculate_trade_value(
players: List[str],
picks: List[str],
faab: int,
all_players_data: Dict,
projections_df: pd.DataFrame,
league_details: Dict
) -> float:
"""
Calculate total value of players, picks, and FAAB in a trade.
Returns: total value
"""
total_value = 0.0
for player_name in players:
player_row = projections_df[projections_df['Player'] == player_name]
if len(player_row) > 0:
total_value += player_row['Value'].iloc[0]
pick_values = get_draft_pick_values(league_details)
for pick_str in picks:
pick_value = pick_values.get(pick_str, 0)
total_value += pick_value
total_value += faab * 2
return total_value
def analyze_historical_trade(
trade_details: Dict,
all_rosters_df: Dict[str, pd.DataFrame],
projections_df: pd.DataFrame,
league_details: Dict,
all_players_data: Dict