-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
143 lines (115 loc) · 6.89 KB
/
Copy pathmain.py
File metadata and controls
143 lines (115 loc) · 6.89 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
import os, sys, traceback, pandas as pd
from main_phase4 import load_and_clean_slate, score_player_ace_mode, optimize_single_lineup
from advanced_optimizer import AdvancedOptimizer
from portfolio_manager import PortfolioManager
from output_formatter import OutputFormatter
# FanDuel NBA Classic display order
SLOT_NAMES = ["PG", "PG", "SG", "SG", "SF", "SF", "PF", "PF", "C"]
def validate_lineup(lp: pd.DataFrame):
errors = []
if len(lp) != 9:
errors.append(f"Wrong size: {len(lp)} players (need 9)")
if lp["Id"].duplicated().any():
errors.append(f"Duplicate IDs: {lp[lp['Id'].duplicated()]['Name'].tolist()}")
if lp["Salary"].sum() > 60000:
errors.append(f"Over cap: ${lp['Salary'].sum():,.0f}")
return len(errors) == 0, errors
def print_lineup(index: int, lp: pd.DataFrame):
"""Print one lineup in FanDuel display order with matchup intel."""
ordered = lp.sort_values("_assigned_slot_idx").reset_index(drop=True)
total_sal = ordered["Salary"].sum()
total_fppg = ordered["FPPG"].sum()
total_ace = ordered["AceScore"].sum()
print(f"\n{'─'*72}")
print(f" Lineup {index:>2} | Salary: ${total_sal:>6,.0f} | "
f"FPPG: {total_fppg:>6.1f} | AceScore: {total_ace:>7.2f}")
print(f"{'─'*72}")
print(f" {'Slot':<5} {'Name':<24} {'Pos':<8} {'Salary':>7} "
f"{'FPPG':>6} {'Ace':>7} {'Matchup'}")
print(f" {'─'*5} {'─'*24} {'─'*8} {'─'*7} {'─'*6} {'─'*7} {'─'*12}")
for i, row in ordered.iterrows():
slot = SLOT_NAMES[int(row.get("_assigned_slot_idx", i))] if i < len(SLOT_NAMES) else "?"
name = str(row.get("Name", ""))[:24]
pos = str(row.get("Position", ""))[:8]
salary = int(row.get("Salary", 0))
fppg = float(row.get("FPPG", 0))
ace = float(row.get("AceScore", 0))
grade = row.get("MatchupGrade", 5.0)
label = str(row.get("MatchupLabel", "") or "")
opp = str(row.get("Opponent", "") or "")
matchup_str = f"vs {opp:<4} {grade:.1f}/10 {label}"
print(f" {slot:<5} {name:<24} {pos:<8} ${salary:>6,} "
f"{fppg:>6.1f} {ace:>7.2f} {matchup_str}")
print(f" {'─'*5} {'─'*24} {'─'*8} {'─'*7} {'─'*6} {'─'*7}")
print(f" {'TOTAL':<5} {'':<24} {'':<8} ${total_sal:>6,} "
f"{total_fppg:>6.1f} {total_ace:>7.2f}")
def main():
try:
print("=" * 72)
print(" SPORTY THIEVES — Ace Mode")
print("=" * 72)
# ── 1. Load + Clean Slate ─────────────────────────────────────────────
slate_df = load_and_clean_slate()
# ── 2. Leverage / Ownership Model ────────────────────────────────────
adv = AdvancedOptimizer(slate_df)
slate_df = adv.calculate_ownership_and_leverage()
# ── 3. AceScore (now includes matchup bonus) ──────────────────────────
if "AceScore" not in slate_df.columns:
slate_df["AceScore"] = slate_df.apply(
lambda r: score_player_ace_mode(r, slate_df), axis=1
)
# Print top-10 AceScore players for reference
top10 = slate_df.nlargest(10, "AceScore")[
["Name", "Position", "Opponent", "Salary", "FPPG", "AceScore",
"MatchupGrade", "MatchupLabel"]
]
print("\n── Top 10 AceScore Players ──────────────────────────────────────────")
print(f" {'Name':<24} {'Pos':<8} {'Opp':<5} {'Salary':>7} "
f"{'FPPG':>6} {'Ace':>7} {'Matchup'}")
print(f" {'─'*24} {'─'*8} {'─'*5} {'─'*7} {'─'*6} {'─'*7} {'─'*12}")
for _, r in top10.iterrows():
print(f" {str(r['Name']):<24} {str(r['Position']):<8} "
f"{str(r['Opponent']):<5} ${int(r['Salary']):>6,} "
f"{r['FPPG']:>6.1f} {r['AceScore']:>7.2f} "
f"vs {r['Opponent']} {r['MatchupGrade']:.1f}/10 {r.get('MatchupLabel','')}")
# ── 4. Build Portfolio ────────────────────────────────────────────────
print("\n── Building 20-Lineup Portfolio ─────────────────────────────────────")
pm = PortfolioManager(slate_df, num_lineups=20)
raw_portfolio = pm.build_portfolio(None, slate_df)
valid_portfolio = []
for lp in raw_portfolio:
is_valid, errs = validate_lineup(lp)
if is_valid:
valid_portfolio.append(lp)
else:
print(f" [SKIP] Lineup rejected: {errs}")
# Emergency bridge
if not valid_portfolio:
print("\n ⚠️ All lineups rejected — attempting emergency build...")
emergency = optimize_single_lineup(slate_df, floor=50000)
if not emergency.empty:
valid_portfolio = [emergency]
if not valid_portfolio:
print("CRITICAL: Even emergency build failed. Check player pool size.")
return
# ── 5. Print Lineups ──────────────────────────────────────────────────
print(f"\n── {len(valid_portfolio)} Valid Lineups ───────────────────────────────────────────")
for i, lp in enumerate(valid_portfolio, 1):
print_lineup(i, lp)
# ── 6. Export ─────────────────────────────────────────────────────────
formatter = OutputFormatter()
lineups_df = formatter.format_for_fanduel_upload(valid_portfolio)
lineups_df.to_csv("fd_lineups_upload.csv", index=False)
print(f"\n✅ Exported {len(valid_portfolio)} lineups to fd_lineups_upload.csv")
# Exposure report
exposure_df = formatter.calculate_exposures(valid_portfolio)
exposure_df.to_csv("lineup_exposures.csv", index=False)
print(f"✅ Exposure report saved to lineup_exposures.csv")
print("\n── Top Exposure ──────────────────────────────────────────────────────")
print(exposure_df.head(15).to_string(index=False))
except SystemExit as e:
print(f"\n[FATAL] {e}")
except Exception:
traceback.print_exc()
if __name__ == "__main__":
main()