-
Notifications
You must be signed in to change notification settings - Fork 54
/
fantasy_stats.py
314 lines (251 loc) · 13.6 KB
/
fantasy_stats.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
import pandas as pd
from yahoo_oauth import OAuth2
import json
from json import dumps
import datetime
class Yahoo_Api():
def __init__(self, consumer_key, consumer_secret,
access_key):
self._consumer_key = consumer_key
self._consumer_secret = consumer_secret
self._access_key = access_key
self._authorization = None
def _login(self):
global oauth
oauth = OAuth2(None, None, from_file='./auth/oauth2yahoo.json')
if not oauth.token_is_valid():
oauth.refresh_access_token()
class UpdateData():
#def __init__(self):
def UpdateTransactions(self):
# TRANSACTIONS
# Convert existing 'Transactions_new.json' into 'Transactions_old.json' before
#### downloading up-to-date new transactions
load_file = open('./transactions/Transaction_old.json') # load old_transactions
old_transactions = json.load(load_file)
load_file.close()
load_file = open('./transactions/Transaction_new.json') # load new_transactions (this will get written over once we download the newest data from Yahoo)
new_transactions = json.load(load_file)
load_file.close()
with open('./transactions/Transaction_old.json', 'w') as outfile: # save the new*_transactions as old so we can compare the actual new transactions
json.dump(new_transactions, outfile)
load_file = open('./transactions/Transaction_old.json') # now load the *new* old_transactions as the base for comparison
old_transactions = json.load(load_file)
load_file.close()
yahoo_api._login() # get the newest transactions and write over the existing new_transactions
url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/'+game_key+'.l.'+league_id+'/transactions'
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
with open('./transactions/Transaction_new.json', 'w') as outfile:
json.dump(r, outfile)
#### load in newest transaction data
load_file = open('./transactions/Transaction_new.json')
new_transactions = json.load(load_file)
load_file.close()
#### get number of new transactions since last transaction download
old_trans = old_transactions['fantasy_content']['league'][1]['transactions']['count']
new_trans = new_transactions['fantasy_content']['league'][1]['transactions']['count']
newest_trans = new_trans-old_trans
transactions = new_transactions['fantasy_content']['league'][1]['transactions']
#load team number and names references as a dictionary
team_numbers = {}
with open('./teams/team_numbers.txt', 'r') as f:
#for line in f:
team_numbers= eval(f.read())
if new_trans > 0: # only run if there are new transactions
transaction = 0
#for transaction in range(len(transactions)-1):
for transaction in range(newest_trans-1, -1, -1):
# transaction(tr) info
tr_num = str(transaction).zfill(2) #adds zeros to the front of the number to keep it all the same length
tr_id = transactions[str(transaction)]['transaction'][0]['transaction_id']
tr_type = transactions[str(transaction)]['transaction'][0]['type']
tr_date = datetime.datetime.fromtimestamp(int(transactions[str(transaction)]['transaction'][0]['timestamp'])).strftime('%m-%d-%Y %H:%M:%S')
# DROPS ### need to update to handle multiple drops, can only handle 1 at a time right now and "AND also dropped..."
if tr_type == 'drop':
players = transactions[str(transaction)]['transaction'][1]['players']
for player in range(len(players)-1):
tm_name = players[str(player)]['player'][1]['transaction_data']['source_team_name']
tm_key = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][1]['transaction_data'][0]['destination_team_key']
tm_real_nm = team_numbers[str(tm_key)]
player_name = players[str(player)]['player'][0][2]['name']['full']
status = tm_name, " (", tm_real_nm ,") dropped", player_name
# print(status)
# add code to append transaction to list, this was originalyl used to Tweet every transaction
# TRADES
elif tr_type == "trade":
pX_name = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][0][2]['name']['full']
pX_pos = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][0][4]['display_position']
pY_name = transactions[str(transaction)]['transaction'][1]['players']['1']['player'][0][2]['name']['full']
pY_pos = transactions[str(transaction)]['transaction'][1]['players']['1']['player'][0][4]['display_position']
trader = transactions[str(transaction)]['transaction'][0]['trader_team_name']
trader_key = transactions[str(transaction)]['transaction'][0]['trader_team_key']
trader_real_nm = team_numbers[str(trader_key)]
tradee = transactions[str(transaction)]['transaction'][0]['tradee_team_name']
tradee_key = transactions[str(transaction)]['transaction'][0]['tradee_team_key']
tradee_real_nm = team_numbers[str(tradee_key)]
trade = trader + " (" +trader_real_nm+ ") traded "+ pX_name+ \
"-"+ pX_pos+ " to "+ tradee+ " (" + tradee_real_nm +") for "+ pY_name+ "-"+ pY_pos
status = trade
# print(status)
# add code to append transaction to list, this was originalyl used to Tweet every transaction
# ADD/DROP
elif tr_type == "add/drop":
tm_name = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][1]['transaction_data'][0]['destination_team_name']
tm_key = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][1]['transaction_data'][0]['destination_team_key']
tm_real_nm = team_numbers[str(tm_key)]
pl_add = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][0][2]['name']['full']
pl_add_pos = transactions[str(transaction)]['transaction'][1]['players']['0']['player'][0][4]['display_position']
pl_drop = transactions[str(transaction)]['transaction'][1]['players']['1']['player'][0][2]['name']['full']
pl_drop_pos = transactions[str(transaction)]['transaction'][1]['players']['1']['player'][0][4]['display_position']
try:
faab = transactions[str(transaction)]['transaction'][0]['faab_bid']
except:
faab = '0'
if int(faab) > 0:
faab = transactions[str(transaction)]['transaction'][0]['faab_bid']
faab = " || FAAB Spent: $"+ faab
else:
faab = ''
add_drop = tm_name + " (" + tm_real_nm + ") added " + \
pl_add + "-" + pl_add_pos + " and dropped " + pl_drop + "-" + pl_drop_pos + faab
status = add_drop
# print(status)
# add code to append transaction to list, this was originalyl used to Tweet every transaction
# ADD
elif tr_type == 'add':
players = transactions[str(transaction)]['transaction'][1]['players']
for player in range(0, len(players)-1):
tm_name = players[str(player)]['player'][1]['transaction_data'][0]['destination_team_name']
tm_key = players[str(player)]['player'][1]['transaction_data'][0]['destination_team_key']
tm_real_nm = team_numbers[str(tm_key)]
player_name = players[str(player)]['player'][0][2]['name']['full']
status = tm_name, " (", tm_real_nm, ") added", player_name
# print(status)
# add code to append transaction to list, this was originalyl used to Tweet every transaction
# COMMISH
elif tr_type == "commish":
status = "Commish made some changes to [Enter League Name Here]"
# print(status)
# add code to append transaction to list, this was originalyl used to Tweet every transaction
transaction += transaction
return;
def UpdateLeague(self):
# LEAGUE OVERVIEW
yahoo_api._login()
url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/'+game_key+'.l.'+league_id+'/'
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
with open('league.json', 'w') as outfile:
json.dump(r, outfile)
return;
def UpdateLeagueStandings(self):
# STANDINGS
yahoo_api._login()
url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/'+game_key+'.l.'+league_id+'/standings'
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
with open('standings.json', 'w') as outfile:
json.dump(r, outfile)
return;
def UpdateScoreboards(self):
# WEEKLY SCORE BOARD
yahoo_api._login()
week = 1
while week < num_weeks+1: #assumes 16 week-schedule
url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/'+game_key+'.l.'+league_id+'/scoreboard;week='+str(week)
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
file_name = 'week_' + str(week) + 'scoreboard.json'
with open('./weekly_scoreboard/'+file_name, 'w') as outfile:
json.dump(r, outfile)
week += 1
return;
def UpdateYahooLeagueInfo(self):
# UPDATE LEAGUE GAME ID
yahoo_api._login()
url = 'https://fantasysports.yahooapis.com/fantasy/v2/game/nfl'
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
with open('YahooGameInfo.json', 'w') as outfile:
json.dump(r, outfile)
global game_key
game_key = r['fantasy_content']['game'][0]['game_key'] # game key as type-string
return;
def UpdateRosters(self):
# WEEKLY ROSTERS - TAKES A WHILE
yahoo_api._login()
week = 1
for week in range(1, num_weeks+1): #assumes 16-week schedule
team = 1
for team in range(1, num_teams+1): #assumes 12-team league
url = 'https://fantasysports.yahooapis.com/fantasy/v2/team/'+game_key+'.l.'+league_id+'.t.'+str(team)+'/roster;week='+str(week)
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
file_name = 'team_'+str(team)+'_wk_' + str(week) + '_roster.json'
with open('./rosters/week_'+str(week)+'/'+ file_name, 'w') as outfile:
json.dump(r, outfile)
team =+ 1
print("Week",week, "roster update - done")
week += 1
return;
def CurrentWeek():
current_week = 1
#with open('./league.json', 'r') as fobj:
# info = json.load(fobj)
#current_week = info['fantasy_content']['league'][0]['current_week']
return current_week;
### WHERE ALL THE MAGIC HAPPENS #########
def main():
##### Get Yahoo Auth ####
# Yahoo Keys
with open('./auth/oauth2yahoo.json') as json_yahoo_file:
auths = json.load(json_yahoo_file)
yahoo_consumer_key = auths['consumer_key']
yahoo_consumer_secret = auths['consumer_secret']
yahoo_access_key = auths['access_token']
#yahoo_access_secret = auths['access_token_secret']
json_yahoo_file.close()
#### Declare Yahoo, and Current Week Variable ####
global yahoo_api
yahoo_api = Yahoo_Api(yahoo_consumer_key, yahoo_consumer_secret, yahoo_access_key)#, yahoo_access_secret)
global current_week
current_week = CurrentWeek()
with open('./Initial_Setup/league_info_form.txt', 'r') as f:
rosters = eval(f.read())
global num_teams
num_teams = rosters['num_teams']
global num_weeks
num_weeks = rosters['num_weeks']
global league_id
league_id = str(rosters['league_id'])
#### Where the tweets happen ####
bot = Bot(yahoo_api)
bot.run()
class Bot():
def __init__(self, yahoo_api):
self._yahoo_api = yahoo_api
def run(self):
# Data Updates
UD = UpdateData()
UD.UpdateYahooLeagueInfo()
print('Yahoo League Info Updated')
UD.UpdateLeague()
print('League update - Done')
UD.UpdateLeagueStandings()
print('Standings update - Done')
UD.UpdateScoreboards()
print('Scoreboards update - Done')
UD.UpdateTransactions()
print('Transactions update - Done')
UD.UpdateRosters()
print('Rosters update - Done')
print('Update Complete')
if __name__ == "__main__":
main()
try:
pass
except Exception as e:
raise
else:
pass