Basketball Fantasy game analysis

Jagger Hung
6 min readApr 18, 2019

A s a sports and basketball fan, I personally love fantasy sport, because it provides an opportunity for us to not only experience the part of game manager routine but also have a purpose to follow NBA every single day. Furthermore, fantasy sports creates another window for fans to know more players in NBA. Sometimes it’s so funny that you start as a Lakers fan and all suddenly you become Rockets fans just because you own James Harden, a Houston Rockets all-star guard, in your fantasy franchise.

I got a winning mentality since I was a child. I want to win in every game that relates to sports, either in sports video games, such as NBA2k or FIBA, or on the true courts, not to mention in the basketball fantasy games.

With few years lost experience, this year I was thinking is there any ways to analyze fantasy sports with the data to help me get the victory? Since it is convenience to get those data online with all open source API, I firmly believe there is a way to get close to winning. As long as I google “fantasy sports analyzing”, I suddenly realized that is the huge business in the US. There’s a bunch of websites that analyze fantasy sports with extreme detail data, provide the first-hand information, and try to help their members to get as close as to win. However, those websites need to pay. As an amateur, it makes no sense to spend money on that. Thus, I started to think to do it on my own.

My Strategy

The main strategy of my games is “Game-Plays”, especially our league is playing in the “head-to-head” rule, a rule that you’re battling your opponent for categories. “Game-plays” means everything in head-to-head. Thus, you can simply add one star to beat the superstar on the statistic, just because he plays more games. For example, Nikola Vucevic, Orlando Magic start center who averaged 20.8 pts and 12.0 rebs this season, played just 2 games on the week 23, so you just have to add some players who have average 5.0 pts and 3.0 rebs and play 4 games to against Vucevic performance. That’s the main strategy for me, so I trade all the players who play less than 3 games on playoff to those players who play more than 3 games on playoff week.

Under the “head-to-head” rule, the more “Game-plays” you have, the more possibility to win in that week.

Technology supports

Data-driven style is widespread nowadays, it takes a significant role in the business world, sports, advertisement…etc. There is lots of data for NBA. The main challenge is how to get those data as soon as possible with structure, otherwise, it has little value for me. I need not only the real-time data from NBA but also the real-time data from the fantasy league I play so that I can get more insight about other opponents’ roster, player transaction…etc. Thus, I decided to use python to get NBA data from Yahoo Fantasy Sports API.

Yahoo Fantasy Sports API

The Fantasy Sports APIs provide URIs used to access fantasy sports data. Currently the APIs support retrieval of Fantasy Football, Baseball, Basketball, and Hockey data including game, league, team, and player information. The APIs are based on a RESTful model. Therefore, resources like game, league, team, player …etc. and collections like games, leagues, teams, players form the building blocks for these APIs. Each resource is identified by a resource ID, and a collection is identified by its scope, specified in the URI.

  1. python

Step1: Authorize from yahoo fantasy

import xmltodict
import time
import os
from collections import OrderedDict
import unicodecsv
from yahoo_oauth import OAuth2
def yahoo_session():
#use yahoo_oauth library to authenticate via oauth 2.0
#note that yahoo (apparently) no longer supports oauth 1.0
oauth = OAuth2(None, None, from_file=’oauth2.json’)
if not oauth.token_is_valid():
oauth.refresh_access_token()
return oauth
def api_query(y_session, query):
r = y_session.session.get(query)
time.sleep(2)
if (r.status_code >= 500):
print(‘bad response from yahoo: status code {0}. retrying…’.format(r.status_code))
r = y_session.session.get(query)
return xmltodict.parse(r.content)
def data_to_csv(target_dir, data_to_write, desired_name):
“””Convenience function to write a dict to CSV with appropriate parameters.”””
#generate directory if doesn’t exist
global d
if len(data_to_write) == 0:
return None
if not os.path.exists(target_dir):
os.makedirs(target_dir)
if type(data_to_write) == dict:
#order dict by keys
d = OrderedDict(sorted(data_to_write.items()))
keys = d.keys()
if type(data_to_write) == list:
d = data_to_write
keys = data_to_write[0].keys()
with open(“%s/%s.csv” % (target_dir, desired_name), ‘wb’) as f:
dw = unicodecsv.DictWriter(f, keys, dialect=’ALM’, extrasaction=’ignore’)
dw.writeheader()
if type(data_to_write) == dict:
dw.writerow(d)
if type(data_to_write) == list:
dw.writerows(d)
f.close()

Step2: Acquire Property data

p = auth.api_query(y, player_data(player_key))this_player_info = p[‘fantasy_content’][‘player’]
this_player_name = p[‘fantasy_content’][‘player’][‘name’][‘full’]
this_player_stats = p[‘fantasy_content’][‘player’][‘player_stats’]
this_player = collections.OrderedDict()
this_player[‘name’] = this_player_name
this_player[‘team’] = this_player_info[‘editorial_team_abbr’]
this_player[‘owner_email’] = manager_email

for n in this_player_stats[‘stats’][‘stat’]:
if stat_cat[int(n[‘stat_id’])] == ‘1’:
pass
elif stat_cat[int(n[‘stat_id’])] == ‘GP’:
g = n[‘value’]
this_player[stat_cat[int(n[‘stat_id’])]] = g
elif n[‘value’] == ‘-’:
n[‘value’] = 0
elif type(int(n[‘value’])) == int:
this_player[stat_cat[int(n[‘stat_id’])]] = n[‘value’]
avg = round(float(n[‘value’]) / float(g), 1)
print avg
this_player[stat_cat[int(n[‘stat_id’])]] = avg
else:
this_player[stat_cat[int(n[‘stat_id’])]] = n[‘value’]
print this_player
this_player[‘status’] = k[‘status’]
this_player[‘position’] = k[‘selected_position’]
players.append(this_player)

Step3: Paste the data in particular google-sheet

2. Google sheet

Follow the step, you will get the row data from Yahoo Fantasy API. The row data includes all categories played in our league and also the status of players.

Raw data from Yahoo Fantasy API

How to analyzing

  1. Overall comparison and playoff game-plays
Overall comparison report

I utilize row data from Yahoo Fantasy API to calculate every statistic categories so that I can clearly understand what are my strengths and weaknesses. According to the image above, it shows which category you are good at and which category you are weak. That’s really helpful when we play in “head-to-head” because you only need to win more categories than your opponent. Furthermore, when I discuss trade with other teams, I would consider which stats category I need so that I won’t make a bad decision.

I also make sure I have as more as games in the playoff. Like I said above, game-plays are the main factors to win the victory in “head-to-head’ rule. Thus, when I trade or add the players, the main consideration is the playoff game-plays. This sheet can help me understand not only my game-plays but also my opponent’s game-plays.

2. “Head-to-head” analyzing

Championship week analyzing report

“Head-to-head” analyzing helps me to get more sense on what stats category you might get really close to the opponent and what stats category you might get no chance. Because the play moves per week are limit, it’s significant to decide which player you need to add. This analyzation gives me basic information that helps me to get more sense on player adding so that I wouldn’t waste the moves.

Base on the analyzing of championship week above, I got no chance on 3-points made, but points, assists, and steals are really close. Thus, I focus on adding those players that good at those categories in our free agent pool. The prediction refers that I would win in points, rebounds, assists, steals, and blocks. After the week, I only lost on assists because Russel Westbrooks, who average triple-doubles in this season, had a crazy week, getting 78 assists in only 4 games.

Result

I won the champion in our league.

After the season, I won the champion in our league. Here’s the thing, I am not saying that using analyzing can help you 100% to win, there are lots of factors, such as injuries or player’s rest, can make a big difference in the “head-to-head”, but at least it can give you further information to consider the circumstances and help you to make good decisions.

These tips helped me to win in this season, and I am sure there are more. Please feel free to share more methods with me in the comments section. Let’s win together.

--

--