-
Notifications
You must be signed in to change notification settings - Fork 0
/
ff_trader_gui.py
713 lines (585 loc) · 26.4 KB
/
ff_trader_gui.py
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
import sys
sys.path.append(r'C:\Anaconda2\pkgs\gurobi-6.5.2-py27_0\Lib\site-packages\gurobipy')
from gurobipy import *
import csv
from Tkinter import *
import Tkinter as ttk
from ttk import *
Positions = ["QB","RB","WR","TE","D/ST","K"]
NumStarters = {}
NumStarters["QB"] = 1
NumStarters["RB"] = 2
NumStarters["WR"] = 3
NumStarters["TE"] = 1
NumStarters["D/ST"] = 1
NumStarters["K"] = 1
StarterCoeff = 1
NumTier2 = {}
NumTier2["QB"] = 1
NumTier2["RB"] = 2
NumTier2["WR"] = 2
NumTier2["TE"] = 1
NumTier2["D/ST"] = 1
NumTier2["K"] = 0
Tier2Coeff = 0.6
BenchCoeff = 0.2
TotalRosterSize = 0
RELATIVE_VALUES = False; #Make all values relative to best available free agent
VERBOSE = False;
UTILITARIAN = True;
def readInCSV(path):
with open(path, "rU") as f:
csvFile = csv.reader(f)
Header = csvFile.next();
#Index for each column. SENSITIVE TO COLUMN NAMES!!
indFantasyTeam = Header.index("team")
indID = Header.index("id")
indName = Header.index("name")
indPos = Header.index("position")
indPercOwned = Header.index("percentOwning")
indRank = Header.index("positionRank")
#Below is NF data - may be missing for some players
indHasNF = Header.index("hasNumberfire")
indNfRank= Header.index("numberfire_overall_rank")
indNfProjPts = Header.index("numbefire_fantasy_points") #whoops, typo in script for CSV
#Stack all values for each time
FantasyTeams = []
Rosters = {}
FreeAgents = {}
for pos in Positions:
FreeAgents[pos] = [];
for row in csvFile:
jFantasyTeam = row[indFantasyTeam]
jID = row[indID]
jName = row[indName]
jPos = row[indPos]
jRank = row[indRank]
#TODO: spit warning
try:
jRank = float(jProjPts)
except:
jRank = 41;
jPercOwned = row[indPercOwned]
try:
jPercOwned = float(jPercOwned)
except:
jPercOwned = 0;
jHasNF = row[indHasNF]
jValue = 0;
try:
jNfProjPts = float(row[indNfProjPts])
except:
jNfProjPts = 0; #No NF data
jValue = getValue( 0, 0, jNfProjPts); #Debug: ranks not currently used
"""
if jHasNF == "TRUE":
jNfRank = int(row[indNfRank])
jNfProjPts = float(row[indNfProjPts])
jValue = getValue( jRank, jNfRank, jNfProjPts );
else:
jValue = getBasicValue( jRank, jPercOwned );
"""
jplayer = {}
jplayer["ID"] = jID;
jplayer["Name"] = jName;
jplayer["Value"] = jValue
jplayer["Val Adj"] = 1; #Default value - may get changed later.
if jFantasyTeam == "FA":
#Add player to list of FAs
FreeAgents[jPos].append(jplayer)
#Player belongs to a team
else:
if jFantasyTeam not in FantasyTeams:
#Initialize new fantasy team roster
FantasyTeams.append(jFantasyTeam);
Rosters[jFantasyTeam] = {};
for pos in Positions:
Rosters[jFantasyTeam][pos] = [];
#Add player to appropriate team, position
Rosters[jFantasyTeam][jPos].append(jplayer)
#Get total roster size
max_team_size=0
for team in FantasyTeams:
j_team_size=0
for pos in Positions:
j_team_size+=len(Rosters[team][pos])
max_team_size = max(max_team_size,j_team_size)
global TotalRosterSize
TotalRosterSize = max_team_size
if RELATIVE_VALUES:
#find highest value of free agents at each position
BestFreeAgentValue = {}
for pos in Positions:
BestFreeAgentValue[pos] = 0;
for player in FreeAgents[pos]:
BestFreeAgentValue[pos] = max(player["Value"],BestFreeAgentValue[pos]);
#Reduce roster values by this amount, at each position.
for team in FantasyTeams:
for pos in Positions:
for player in Rosters[team][pos]:
player["Value"] = player["Value"]-BestFreeAgentValue[pos]
return (Rosters, FreeAgents, FantasyTeams)
def findTopFreeAgent(Positions):
topFA = {}
for pos in FreeAgents:
topFA[pos] = None
for player in FreeAgents[pos]:
if(topFA[pos] == None):
topFA[pos] = player
elif(player["Value"] > topFA[pos]["Value"]):
topFA[pos] = player
return topFA
def submitRatings():
##This will be the command called when the user submits rankings
print("This will be the command called when the user submits rankings")
#TODO: Pull personal rankings - may just go into Rosters dict
# - Other team players will already be there. Just pull your team's adjustments (LHS)
for player in myPlayerNames:
playerName = player[0]
playerPos = player[1]
for jPlayer in Rosters[myTeam][playerPos]:
if jPlayer["Name"] == playerName:
entryValAdj = ratingEntries[playerName].get()
try:
jPlayer["Val Adj"] = float( entryValAdj )
except:
pass #TODO: could throw error if it isn't just empty
iterateTeams(myTeam, Rosters, FreeAgents, FantasyTeams)
def getValue( Rank, NfRank, NfProjPts ):
"""
#Wow, this works shitty
adjRank1 = (max(41-Rank,0)/4)**2;
adjRank2 = (max(41-NfRank,0)/4)**2;
value = (adjRank1 + 3*adjRank2)/4 + NfProjPts
"""
value = NfProjPts
return value
def getBasicValue(Rank,PercentOwned):
#Use if there are no numberfire projections
"""
#Wow, this works shitty
adjRank = (max(41-Rank,0)/4)**2;
adjPerc = (PercentOwned/20)**2
value = (adjRank + adjPerc)/2
"""
value=PercentOwned/10
return value
def iterateTeams(myTeam, Rosters, FreeAgents, FantasyTeams):
TradeProposals = []
for otherTeam in FantasyTeams:
if otherTeam == myTeam:
continue;
print "\n\n\nTRADES WITH %s"%otherTeam
findTrade(Rosters[myTeam], Rosters[otherTeam], FreeAgents)
"""
#TODO: how are these trades stored? what is being returned?
#TODO: be able to get multiple trades per team
jTrades = findTrade(Rosters[myTeam], Rosters[otherTeam])
for jTrade in jTrades:
TradeProposals.append(jTrade.extend(otherTeam))
"""
print "\nDONE!!"
return TradeProposals
def findTrade(myRoster, otherRoster, FreeAgents):
(AllNames, AllValues, UserVals, Roster, NumPlayersByPos) = stackTeams(myRoster, otherRoster)
PrevTeamValue = getTeamValue(myRoster, otherRoster)
topFA = findTopFreeAgent(FreeAgents)
##Create model
TradeModel = Model("Trade Test Model")
Select = {}
Starter = {}
Tier2 = {}
Bench = {}
AddFA = {}
StarterFA = {}
Tier2FA = {}
BenchFA = {}
for team in ["Team1","Team2"]:
Select[team] = {}
Starter[team] = {}
Tier2[team] = {}
Bench[team] = {}
AddFA[team] = {}
StarterFA[team] = {}
Tier2FA[team] = {}
BenchFA[team] = {}
for pos in Positions:
Select[team][pos] = []
Starter[team][pos] = []
Tier2[team][pos] = []
Bench[team][pos] = []
#AddFA[team][pos] = TradeModel.addVar(vtype = GRB.BINARY, name = "FreeAgentPickup_" + team+"_"+pos)
StarterFA[team][pos] = TradeModel.addVar(vtype = GRB.BINARY, name = "FreeAgentStarter_" + team+"_"+pos)
Tier2FA[team][pos] = TradeModel.addVar(vtype = GRB.BINARY, name = "FreeAgentTier2_" + team+"_"+pos)
BenchFA[team][pos] = TradeModel.addVar(vtype = GRB.BINARY, name = "FreeAgentBench_" + team+"_"+pos)
AddFA[team][pos] = StarterFA[team][pos] + Tier2FA[team][pos] + BenchFA[team][pos]
for i in range(NumPlayersByPos[pos]):
#Select[team][pos].append( TradeModel.addVar(vtype = GRB.BINARY, name = "Select_" + team + "_" + pos + "_" + str(i)) )
Starter[team][pos].append( TradeModel.addVar(vtype = GRB.BINARY, name = "Starter_" + team + "_" + pos + "_" + str(i)) )
Tier2[team][pos].append( TradeModel.addVar(vtype = GRB.BINARY, name = "Tier2_" + team + "_" + pos + "_" + str(i)) )
Bench[team][pos].append( TradeModel.addVar(vtype = GRB.BINARY, name = "Bench_" + team + "_" + pos + "_" + str(i)) )
Select[team][pos].append( Starter[team][pos][i] + Tier2[team][pos][i] + Bench[team][pos][i] )
TradeModel.update()
TradeModel.setParam('OutputFlag',False) #stfu
FADiscount = 0.6
#Calculate adjusted team value
TeamValue = {}
for team in ["Team1","Team2"]:
TeamValue[team] = 0;
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
if team == "Team1":
UserVal = UserVals[pos][i]
else:
UserVal = 1 #Assume other people value consensus
#TeamValue[team] += UserVal * Select[team][pos][i] * AllValues[pos][i] * \
# (BenchCoeff + (StarterCoeff-BenchCoeff)*Starter[team][pos][i] + (Tier2Coeff-BenchCoeff)*Tier2[team][pos][i])
TeamValue[team] += UserVal * AllValues[pos][i] * \
(BenchCoeff*Bench[team][pos][i] + StarterCoeff*Starter[team][pos][i] + Tier2Coeff*Tier2[team][pos][i])
#TeamValue[team] += FADiscount * AddFA[team][pos] * topFA[pos]["Value"] * \
# (BenchCoeff + (StarterCoeff-BenchCoeff)*StarterFA[team][pos] + (Tier2Coeff-BenchCoeff)*Tier2FA[team][pos])
TeamValue[team] += FADiscount * topFA[pos]["Value"] * \
(BenchCoeff*BenchFA[team][pos] + StarterCoeff*StarterFA[team][pos] + Tier2Coeff*Tier2FA[team][pos])
#TeamValue[team] += AddFA[team]*topFA["Value"]
Improvement = (TeamValue["Team1"] - PrevTeamValue["Team1"]) + (TeamValue["Team2"] - PrevTeamValue["Team2"])
"""
#Assign each player to exactly 1 team
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Select["Team1"][pos][i] + Select["Team2"][pos][i] == 1)
"""
#TO ADD DROPS:
#Assign each player to at most 1 team
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Select["Team1"][pos][i] + Select["Team2"][pos][i] <= 1)
"""
#Starter only if selected
for team in ["Team1","Team2"]:
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Starter[team][pos][i] <= Select[team][pos][i])
#Tier2 only if selected
for team in ["Team1","Team2"]:
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Tier2[team][pos][i] <= Select[team][pos][i])
"""
#Number of starters at each position
for team in ["Team1","Team2"]:
for pos in Positions:
TradeModel.addConstr( quicksum(Starter[team][pos]) == NumStarters[pos] )
#Number of tier2 at each position
for team in ["Team1","Team2"]:
for pos in Positions:
TradeModel.addConstr( quicksum(Tier2[team][pos]) <= NumTier2[pos] )
#Cannot simultaneous start and be tier2 and bench
for team in ["Team1","Team2"]:
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Tier2[team][pos][i] + Starter[team][pos][i] + Bench[team][pos][i] <= 1 )
#Total roster size
for team in ["Team1","Team2"]:
TradeModel.addConstr( quicksum(sum(Select[team][pos]) for pos in Positions) <= TotalRosterSize )
#Max number of players to trade away
TotalNumPlayersTradedAway = 0
for team in ["Team1","Team2"]:
numPlayersTradedAway = 0
for pos in Positions:
numPlayersTradedAway += quicksum( Roster[team][pos][i]*(1 - Select[team][pos][i]) for i in range(NumPlayersByPos[pos]))
TradeModel.addConstr( numPlayersTradedAway <= 3 )
TradeModel.addConstr( numPlayersTradedAway >= 1)
TotalNumPlayersTradedAway += numPlayersTradedAway
#TODO: Make above an option on GUI (at most 2 players maybe)
#Trade beneficial to both teams
TradeModel.addConstr(TeamValue["Team1"] >= PrevTeamValue["Team1"])
TradeModel.addConstr(TeamValue["Team2"] >= PrevTeamValue["Team2"])
#Only add FreeAgent if the team has less than the required number of players
for team in ["Team1","Team2"]:
#Total number of FAs picked up is less than number of open slots
TradeModel.addConstr(quicksum(AddFA[team][pos] for pos in Positions) <= \
TotalRosterSize - quicksum(sum(Select[team][pos]) for pos in Positions))
for pos in Positions:
#Added FA is starter only if there are starter slots available
TradeModel.addConstr( StarterFA[team][pos] == NumStarters[pos] - quicksum(Starter[team][pos]) )
#Added FA is Tier 2 only if there are starter slots available
TradeModel.addConstr( Tier2FA[team][pos] <= NumTier2[pos] - quicksum(Tier2[team][pos]) )
#Added FA is not starter and tier 2 simultaneously; and only if we are adding a FA
TradeModel.addConstr( AddFA[team][pos] <= 1)
#Don't let both players pick up same person
for pos in Positions:
TradeModel.addConstr( AddFA["Team1"][pos] + AddFA["Team2"][pos] <= 1 )
for team in ["Team1","Team2"]:
pos = "K"
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Roster[team][pos][i] == Select[team][pos][i] )
pos = "D/ST"
for i in range(NumPlayersByPos[pos]):
TradeModel.addConstr( Roster[team][pos][i] == Select[team][pos][i] )
FAadds=0
for team in ["Team1","Team2"]:
FAadds += sum(AddFA[team][pos] for pos in Positions);
w=0.01 #Mess with this
w2=0.05
if UTILITARIAN:
objective = Improvement - w*TotalNumPlayersTradedAway - w2*FAadds;
else:
objective = (TeamValue["Team1"] - PrevTeamValue["Team1"]) - (w/2)*TotalNumPlayersTradedAway - (w2/2)*FAadds;
TradeModel.setObjective(objective, GRB.MAXIMIZE)
#### OPTIMIZE AND PRINT RESULTS
TradeModel.optimize()
#TODO: Put this in a pop-up window
print '\n\nOPTIMAL SOLUTION\n'
print 'TEAM 1 Trading Away:'
PostTeamValue = {}
PostTeamValue["Team1"] = 0;
PostTeamValue["Team2"] = 0;
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
#if Roster["Team1"][pos][i] == 1 and Select["Team1"][pos][i].X == 0:
if Roster["Team1"][pos][i] == 1 and Select["Team1"][pos][i].getValue() == 0:
#Look for a drop - other team doesn't own now either
if Select["Team2"][pos][i].getValue() == 0:
print "\t%s: %0.02f DROP \t[%s]"%(pos,AllValues[pos][i],AllNames[pos][i])
else:
print "\t%s: %0.02f\t[%s]"%(pos,AllValues[pos][i],AllNames[pos][i])
#if Select["Team1"][pos][i].X == 1:
#if Select["Team1"][pos][i].getValue() == 1:
if Starter["Team1"][pos][i].X:
PostTeamValue["Team1"] += AllValues[pos][i]*StarterCoeff
elif Tier2["Team1"][pos][i].X:
PostTeamValue["Team1"] += AllValues[pos][i]*Tier2Coeff
elif Bench["Team1"][pos][i].X:
PostTeamValue["Team1"] += AllValues[pos][i]*BenchCoeff
for pos in Positions:
if AddFA["Team1"][pos].getValue():
print "\t%s: %0.02f\t[FA: %s]"%(pos,topFA[pos]["Value"],topFA[pos]["Name"])
if StarterFA["Team1"][pos].X:
PostTeamValue["Team1"] += FADiscount * topFA[pos]["Value"] * StarterCoeff
elif Tier2FA["Team1"][pos].X:
PostTeamValue["Team1"] += FADiscount * topFA[pos]["Value"] * Tier2Coeff
elif BenchFA["Team1"][pos].X:
PostTeamValue["Team1"] += FADiscount * topFA[pos]["Value"] * AllValues[pos]*BenchCoeff
print 'TEAM 2 Trading Away:'
for pos in Positions:
for i in range(NumPlayersByPos[pos]):
#if Roster["Team2"][pos][i] == 1 and Select["Team2"][pos][i].X == 0:
if Roster["Team2"][pos][i] == 1 and Select["Team2"][pos][i].getValue() == 0:
#Look for a drop - other team doesn't own now either
#if Select["Team1"][pos][i].X == 0:
if Select["Team1"][pos][i].getValue() == 0:
print "\t%s: %f DROP \t[%s]"%(pos,AllValues[pos][i],AllNames[pos][i])
else:
print "\t%s: %f\t[%s]"%(pos,AllValues[pos][i],AllNames[pos][i])
#if Select["Team2"][pos][i].X == 1:
if Select["Team2"][pos][i].getValue() == 1:
if Starter["Team2"][pos][i].X:
PostTeamValue["Team2"] += AllValues[pos][i]*StarterCoeff
elif Tier2["Team2"][pos][i].X:
PostTeamValue["Team2"] += AllValues[pos][i]*Tier2Coeff
else:
PostTeamValue["Team2"] += AllValues[pos][i]*BenchCoeff
for pos in Positions:
if AddFA["Team2"][pos].getValue():
print "\t%s: %0.02f\t[FA: %s]"%(pos,topFA[pos]["Value"],topFA[pos]["Name"])
print "\nStarting team values:\n\t\t%f\t%f"%(PrevTeamValue["Team1"],PrevTeamValue["Team2"])
print "\nEnding team values:\n\t\t%f\t%f"%(TeamValue["Team1"].getValue(),TeamValue["Team2"].getValue())
print "\nTOTAL IMPROVEMENT = %0.02f"%(TeamValue["Team1"].getValue() + TeamValue["Team2"].getValue() - \
(PrevTeamValue["Team1"]+PrevTeamValue["Team2"]) )
if VERBOSE:
for pos in Positions:
print pos+":"
for i in range(NumPlayersByPos[pos]):
#print("\t%f: \t%i (%i)"%(AllValues[pos][i],Select["Team1"][pos][i].X, Starter["Team1"][pos][i].X) ),
print("\t%f: \t%i (%i)"%(AllValues[pos][i],Select["Team1"][pos][i].getValue(), Starter["Team1"][pos][i].X) ),
#print("\t %i (%i)\t[%s]"%(Select["Team2"][pos][i].X, Starter["Team2"][pos][i].X, AllNames[pos][i]) ),
print("\t %i (%i)\t[%s]"%(Select["Team2"][pos][i].getValue(), Starter["Team2"][pos][i].X, AllNames[pos][i]) ),
print "" #newline
def stackTeams(myRoster, otherRoster):
##Stack all values per position
AllValues = {}
UserValues = {}
AllNames = {}
NumPlayersByPos = {}
Roster = {}
Roster["Team1"] = {}
Roster["Team2"] = {}
for pos in Positions:
numPlayers = len(myRoster[pos]) + len(otherRoster[pos])
Roster["Team1"][pos] = []
Roster["Team2"][pos] = []
AllValues[pos] = []
UserValues[pos] = []
AllNames[pos] = []
NumPlayersByPos[pos] = numPlayers
for i in range(len(myRoster[pos])):
Roster["Team1"][pos].append(1)
Roster["Team2"][pos].append(0)
AllValues[pos].append( myRoster[pos][i]["Value"] )
UserValues[pos].append( myRoster[pos][i]["Val Adj"] )
AllNames[pos].append( myRoster[pos][i]["Name"] )
for i in range(len(otherRoster[pos])):
Roster["Team1"][pos].append(0)
Roster["Team2"][pos].append(1)
AllValues[pos].append( otherRoster[pos][i]["Value"] )
UserValues[pos].append( otherRoster[pos][i]["Val Adj"] )
AllNames[pos].append( otherRoster[pos][i]["Name"] )
return (AllNames, AllValues, UserValues, Roster, NumPlayersByPos)
def getTeamValue(myRoster, otherRoster):
#Make sure this matches what is done above
TeamValue = {}
Values = {}
UserValues = {}
for team in ["Team1","Team2"]:
Values[team] = {};
UserValues[team] = {};
TeamValue[team] = 0;
for pos in Positions:
Values[team][pos] = [];
UserValues[team][pos] = [];
for pos in Positions:
for player in myRoster[pos]:
Values["Team1"][pos].append(player["Value"])
UserValues["Team1"][pos].append(player["Val Adj"])
for player in otherRoster[pos]:
Values["Team2"][pos].append(player["Value"])
UserValues["Team2"][pos].append( 1 ) #Other team: no value adjustment
for team in ["Team1","Team2"]:
for pos in Positions:
Values[team][pos].sort(reverse=True) #Sort descending
for (i, val) in enumerate(Values[team][pos]):
if i<NumStarters[pos]:
#Starter
TeamValue[team] += StarterCoeff*val*UserValues[team][pos][i]
elif i<NumStarters[pos] + NumTier2[pos]:
#Tier2
TeamValue[team] += Tier2Coeff*val*UserValues[team][pos][i]
else:
#Bench: discounted value
TeamValue[team] += BenchCoeff*val*UserValues[team][pos][i]
return TeamValue
#if __name__ == "__main__":
args = sys.argv[1:] #strip script name from args
#TODO: handle custom arguments
if len(args)<1:
csvPath = "data_11_16.csv"
else:
csvPath = args[0]
if len(args)<2:
myTeam = "ENTH"
else:
myTeam = args[1]
(Rosters, FreeAgents, FantasyTeams) = readInCSV(csvPath);
#Build player universe
myPlayerNames = []
otherPlayerNamesDict = {}
otherPlayerNames = []
for pos in Positions:
for player in Rosters[myTeam][pos]:
myPlayerNames.append([player["Name"], pos])
otherPlayerNamesDict[pos] = []
for team in FantasyTeams:
if team==myTeam:
continue;
for player in Rosters[team][pos]:
otherPlayerNames.append([player["Name"], pos])
otherPlayerNamesDict[pos].append(player["Name"])
#run_gui()
FFgui = Tk()
FFgui.title("Fantasy Football Trade Optimizer")
totalAdjustments = 0
#Initialize Grid Size
FFgui.geometry("750x550")
#Enable Resizing of the Grid
FFgui.columnconfigure(0, weight = 1)
#Build Title Labels
myRoster = Label(FFgui, text = "My Roster")
myRoster.grid(row = 0, column = 0, columnspan = 3, padx = 50, pady=20)
LeagueAdj = Label(FFgui, text = "League Adjustments")
LeagueAdj.grid(row = 0, column = 3, columnspan = 3, padx = 50, pady=20)
Position = Label(FFgui, text = "Position")
Position.grid(row = 1, column = 0)
PlayerLeft = Label(FFgui, text = "Player")
PlayerLeft.grid(row = 1, column = 1)
Rating = Label(FFgui, text = "Enter Player Value")
Rating.grid(row = 1, column = 2)
PlayerRight = Label(FFgui, text = "Player")
PlayerRight.grid(row = 1, column = 3)
TradeValue = Label(FFgui, text = "Trade Value")
TradeValue.grid(row = 1, column = 4)
#Build DropDown Box
playerNameVar = StringVar(FFgui)
playerNameVar.set(otherPlayerNames[0][0])
playerMenuButton = Menubutton(FFgui, textvariable=playerNameVar)
playerTopMenu = Menu(playerMenuButton, tearoff=False)
playerMenuButton.configure(menu=playerTopMenu)
for key in sorted(otherPlayerNamesDict.keys()):
jMenu = Menu(playerTopMenu)
playerTopMenu.add_cascade(label=key, menu=jMenu)
for value in otherPlayerNamesDict[key]:
jMenu.add_radiobutton(label=value, variable = playerNameVar, value=value)
playerMenuButton.pack()
#changeValue = OptionMenu(FFgui, var, *(player[0] for player in otherPlayerNames))
#changeValue = OptionMenu(FFgui, var, *otherPlayerNamesDict)
#changeValue.grid(row = 2, column =3)
playerMenuButton.grid(row = 2, column =3)
TradeValue = StringVar()
# Bind TradeValue instead of var
Value_ent = Entry(FFgui, width = 30)
Value_ent.grid(column = 4, row = 2)
numAdjustments = 0
adjustmentLabels = {}
def addAdjustment(event):
##This command is called when the user submits rankings
global numAdjustments
numAdjustments +=1
#TODO: Save value to roster adjustment dict
player_name = playerNameVar.get()
player_val = Value_ent.get()
if player_name not in adjustmentLabels.keys():
#Add new item
adjustmentLabels[player_name]={}
adjustmentLabels[player_name]["NameText"] = Label(FFgui, text = player_name)
adjustmentLabels[player_name]["ValueText"]= Label(FFgui, text = player_val)
adjustmentLabels[player_name]["NameText"].grid(column = 3, row = 2 + numAdjustments, sticky = E)
adjustmentLabels[player_name]["ValueText"].grid(column = 4, row = 2 + numAdjustments, sticky = W)
else:
#Update existing item
adjustmentLabels[player_name]["ValueText"].config(text=player_val)
#Label_1 = Label(FFgui, text = player_name)
#Label_2 = Label(FFgui, text = player_val)
#Label_1.grid(column = 3, row = 2 + numAdjustments, sticky = E)
#Label_2.grid(column = 4, row = 2 + numAdjustments,sticky = W)
for team in FantasyTeams:
for pos in Positions:
for (i,player) in enumerate(Rosters[team][pos]):
if player["Name"] == player_name:
Rosters[team][pos][i]["Val Adj"] = float(player_val)
#Add Button
addButton = Button(FFgui, text = "Add")
addButton.bind("<Button-1>", addAdjustment)
addButton.grid(row = 2, column = 5, padx = 20)
#Add Main Menu with Submit Button
menu = Menu(FFgui)
FFgui.config(menu = menu)
submitMenu = Menu(menu)
menu.add_cascade(label = "File",menu = submitMenu)
submitMenu.add_command(label = "SUBMIT RANKINGS", command = submitRatings)
#Automatically Populate My Roster
count = 0
ratingEntries = {}
for player in myPlayerNames: #Pull my roster
#Player Labels
#player = "Player" + i
playerLabel = Label(FFgui, text = player[0])
playerLabel.grid(row = 2+count, column = 0)
#Player Positions
#position = "Position" +i
positionLabel = Label(FFgui, text = player[1])
positionLabel.grid(row = 2+count, column = 1)
#Entry
ratingEntries[player[0]] = Entry(FFgui) #Key = player name
ratingEntries[player[0]].grid(row=2+count, column = 2)
count += 1
FFgui.mainloop()
#iterateTeams(myTeam, Rosters, FreeAgents, FantasyTeams)