class MySportsFeedsFactory: def __init__(self, v='1.2'): self.msf = MySportsFeeds(version=v) self.msf.authenticate(environ['apikey_token'], environ['password']) def getMySportsFeed(self): return self.msf
def request_all_team_gamelogs(team_list): initial_inputs() data_category = 'team' for key in team_list: if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed="team_gamelogs", format=file_format, team=key) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed="team_gamelogs", format=file_format, team=key)
class MSFConnector: def __init__(self, version, api_key, password, call_file): self.__conn = MySportsFeeds(version=version) self.__conn.authenticate(api_key, password) self.__call_signature = {} self.call_signatures = {} with open(call_file) as f: self.call_signatures = json.load(f) @property def file_name(self): return (f'results/{self.__call_signature["feed"]}-{self.__call_signature["league"]}-' f'{self.__call_signature["season"]}.{self.__call_signature["format"]}') def get_current_season(self, league, response_format='json'): try: season_data = self.__conn.msf_get_data(league=league, force=True, feed='current_season', format=response_format, fordate=date.today().strftime('%Y%m%d')) season_details = season_data['currentseason']['season'][0]['details'] season = season_details['slug'].split('-') season[0] = int(season[0]) except Exception as e: season = [1776, 'pre'] return season def make_api_call(self, data_source): if data_source == DataSources.FILE: with open(self.file_name, 'r') as f: output = json.load(f) else: output = self.__conn.msf_get_data(league=self.__call_signature['league'], force=True, season=self.__call_signature['season'], feed=self.__call_signature['feed'], format=self.__call_signature['format']) return output def set_call_signature(self, league, season_type, call_type, season=0): call_signature = self.call_signatures[league][season_type][call_type] self.__call_signature['league'] = call_signature['league'] self.__call_signature['feed'] = call_signature['feed'] self.__call_signature['format'] = call_signature['format'] self.__call_signature['season_year'] = call_signature['season_year'] self.__call_signature['season_type'] = call_signature['season_type'] self.__call_signature['season'] = (f'{self.__call_signature["season_year"]}-' f'{self.__call_signature["season_type"]}') if season > 0: self.update_season_in_call_signature(season) def update_season_in_call_signature(self, new_season): self.__call_signature['season_year'] = new_season self.__call_signature['season'] = (f'{self.__call_signature["season_year"]}-' f'{self.__call_signature["season_type"]}')
def import_game(import_date): """imports game for the selected date (YYYYMMDD)""" msf = MySportsFeeds(version='1.0') msf.authenticate(username, password) try: output = msf.msf_get_data(league='nhl', season='current', feed='scoreboard', fordate=import_date, team=fav_team, format='json') return True except Warning: print("Import failed") return False
def setup_import(): msf = MySportsFeeds(version='1.0') msf.authenticate(username, password) try: output = msf.msf_get_data(league='nhl', season='current', feed='full_game_schedule', team=fav_team, format='json') output = msf.msf_get_data(league='nhl', season='current', feed='team_gamelogs', team=fav_team, format='json') print("Import succesful") return True except Warning or FileNotFoundError: print("Import failed") return False
def msf(season, feed, team): # f = open(('E:/school/2018-19/caps/A Foot in the Door/json/%(feed)s-nfl-%(season)s.json' % # {'feed': feed, 'season': season}), 'w+') msf = MySportsFeeds(version ='1.2') msf.authenticate('API_KEY', 'PASSWORD') output = msf.msf_get_data(force = 'true', league='nfl', feed = feed, season=season, format='json', team = team) #, position = 'te' # f.write(output) # json.dump(output, f) return output
def main(): # Create instance of MySportsFeeds API and authenticate msf = MySportsFeeds('2.1', verbose=False) msf.authenticate(config.MySportsFeeds_key, config.msfPassword) # Create MongoDB client instance client = pymongo.MongoClient( 'mongodb+srv://' + config.mongoBlock + ':' + config.mongoBlockPW + '@nba-data.nftax.azure.mongodb.net/NBA-ML?retryWrites=true&w=majority') season = '2020-2021-regular' # updateYesterdayData(msf, client, season) # predictTodayGames(msf, client, season) updateTodaySpreads(msf, client, season)
def getDailyPlayerStatsData(df): Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate('poly91', 'abel1234') for gameDate in df['Game Date'].tolist(): print(gameDate) try: Output = Data_query.msf_get_data(league='nba', season='2016-2017-regular', feed='daily_player_stats', fordate=str(gameDate), format='csv', sort='player.team') except: print("errorinfo: ", sys.exc_info()[0]) print('Issue with %d', gameDate)
def request_daily(): initial_inputs() data_type = [ "daily_game_schedule", "daily_player_stats", "scoreboard", "roster_player" ] data_category = input( "Enter 'all' for daily_game_schedule, daily_player_stats three, and scoreboard or any given data: " ) date = input( "Enter the date of the data that you want in the format of YYYYMMDD: ") if data_category == "all": for x in range(0, len(data_type)): if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed=data_type[x], format=file_format, fordate=date) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_end + season_name_type, feed=data_type[x], format=file_format, fordate=date) #can add more optional params manually else: if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed=data_category, format=file_format, fordate=date) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed=data_category, format=file_format, fordate=date)
def request_game(): initial_inputs() data_type = ["game_playbyplay", "game_boxscore", "game_startinglineup"] data_category = input( "Enter 'all' for game_playbyplay,game_boxscore,and game_startinglineup or any given data: " ) gameid = input( "Enter game id in the form of:game date YYYYMMDD + '-'+ away team abbr +'-'+ home team abbr. Example 20161212-BOS-CLE: " ) if data_category == "all": for x in range(0, len(data_type)): if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed=data_type[x], format=file_format, gameid=gameid) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_end + season_name_type, feed=data_type[x], format=file_format, gameid=gameid) #can add more optional params manually else: if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed=data_category, format=file_format, gameid=gameid) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed=data_category, format=file_format, gameid=gameid)
def pull_game_logs(player_names, stats_of_interest): msf_user = "" msf_pass = "" with open("inputs/msf.txt", "r") as my_file: msf_user = my_file.readline() #Pull game logs for various player names and returns dfs. msf = MySportsFeeds(version="1.2") msf.authenticate("e09cc51e-beb1-43ac-b888-20a591", "0010RugbyFight") output = msf.msf_get_data(league='nba', season='2018-2019-regular', feed='player_gamelogs', format='json', player=player_names, sort="player.lastname") gamelogs = output['playergamelogs']['gamelogs'] return gamelogs
def request_gamelogs(): initial_inputs() data_category = input( "enter either 'player' or 'team' to request for data: ") if data_category == "player": player = input( "Enter the player's name in the form of: last name, first-last,first-last-playerID: " ) if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed="player_gamelogs", format=file_format, player=player) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed="player_gamelogs", format=file_format, player=player) #can add more optional params manually else: team = input( "Enter the team's abbr in the form of: abbreviation or city-teamname" ) if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed="team_gamelogs", format=file_format, team=team) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed="team_gamelogs", format=file_format, team=team)
def get_output_from_api(username, password): # where api json file is stored path = 'results/roster_players-nfl-2017-2018-regular.json' # load json from results cache if Path(path).exists(): with open(path, 'r') as f: output = json.load(f) # make request to API if no cache else: msf = MySportsFeeds(version="1.2", verbose=True) msf.authenticate(username, password) output = msf.msf_get_data(league='nfl', season='2017-2018-regular', feed='roster_players', format='json') return output
def main(): # Create instance of MySportsFeeds API and authenticate msf = MySportsFeeds('2.1', verbose=False) msf.authenticate(config.MySportsFeeds_key, config.msfPassword) teamDict = {} output = msf.msf_get_data(feed='seasonal_team_stats', league='nba', season='2019-2020-regular', format='json', force='true') for team in output['teamStatsTotals']: teamInfo = team['team'] teamDict[teamInfo[ 'abbreviation']] = teamInfo['city'] + ' ' + teamInfo['name'] unitsFilename = '../features/dictionaries/teamAbbrevToName.json' with open(unitsFilename, 'w') as outFile: json.dump(teamDict, outFile, indent=4, separators=(',', ': ')) return 0
def request_all_player_gamelogs(player_list): initial_inputs() data_category = 'player' for key in player_list: if season_name_type == 'playoff': Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed="player_gamelogs", format=file_format, player=key) else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed="player_gamelogs", format=file_format, player=key)
class GetData: def __init__(self, stats=None): self.temp_file = tempfile.TemporaryFile() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) self.user_name = os.environ['sport_user'] self.password = os.environ['sport_password'] self.feed = MySportsFeeds(version="1.1", store_type=None) self.feed.authenticate(self.user_name, self.password) self.stats = stats self.stat_data = None self.score_data = None def get_data(self, league, season, wanted_feed, for_date='', return_format='json', player_stats=''): if for_date is '': for_date = self.format_current_date() results = self.feed.msf_get_data(league=league, season=season, feed=wanted_feed, fordate=for_date, format=return_format, force=True, playerstats=player_stats) self.logger.info(player_stats) self.logger.debug(results) return json.dumps(results) def format_current_date(self): date = datetime.now() year = date.year month = '{:02d}'.format(date.month) day = '{:02d}'.format(date.day) return f'{year}{month}{day}'
def get_player_info(player_name): player_name = player_name.lower() player_name = player_name.replace(' ', '-') msf = MySportsFeeds(version="1.2") msf.authenticate("cameronchandra", "29Malysana") output = msf.msf_get_data(league='mlb', season='latest', format='json', feed='cumulative_player_stats', player=player_name) mlb_team = output['cumulativeplayerstats']['playerstatsentry'][0]['team'][ 'Abbreviation'] position = output['cumulativeplayerstats']['playerstatsentry'][0][ 'player']['Position'] avg = output['cumulativeplayerstats']['playerstatsentry'][0]['stats'][ 'BattingAvg']['#text'] hr = output['cumulativeplayerstats']['playerstatsentry'][0]['stats'][ 'Homeruns']['#text'] steals = output['cumulativeplayerstats']['playerstatsentry'][0]['stats'][ 'StolenBases']['#text'] runs = output['cumulativeplayerstats']['playerstatsentry'][0]['stats'][ 'Runs']['#text'] return mlb_team, position, avg, hr, steals, runs
def main(): client = pymongo.MongoClient( 'mongodb+srv://' + config.mongoBlock + ':' + config.mongoBlockPW + '@nba-data.nftax.azure.mongodb.net/NBA-ML?retryWrites=true&w=majority') # Create instance of MySportsFeeds API and authenticate msf = MySportsFeeds('2.1', verbose=False) msf.authenticate(config.MySportsFeeds_key, "MYSPORTSFEEDS") season = '2020-2021-regular' # df = pd.read_csv('../features/gameData/' + season + 'games.csv').set_index('gameID', drop=False) # updateTodayGames(msf, client, season) deleteUnplayedGames(client, season) insertUnplayedGames(msf, client, season) # insertGamesFromCSV(client, season) # df = pd.read_csv('../features/gameData/' + season + '-games.csv').set_index('gameID', drop=False) # updateGames(msf, client, season, df) client.close()
def main(): # Create instance of MySportsFeeds API and authenticate msf = MySportsFeeds('2.1', verbose=False) msf.authenticate(config.MySportsFeeds_key, "MYSPORTSFEEDS") # seasons = [] season = '2020-2021-regular' # addDateStintsToCSV(season, '20200728', 100) # outputStintCSV(msf, season) dateStart = '' dateEnd = '' printRatings = True # for season in seasons: ratingBasePath = getBasePath(season, dateStart, dateEnd, 'RAPM-ratings') inputBasePath = getBasePath(season, dateStart, dateEnd, 'RAPM-inputs') # if config.debug: print("Analyzing play-by-play data for " + season + "... ") units, points, weights = extractPbpData(msf, season, dateStart, dateEnd) # unitsImported, pointsImported, weightsImported = importPbpDataFromJSON(inputBasePath) # if config.debug: print("Getting player names...") playerDict = getPlayerNames(msf, season) # if config.debug: print("exporting play-by-play to JSON... ") exportPbpDataToJSON(units, points, weights, inputBasePath) # if config.debug: print("Calculating RAPM...") ratings = calculateRAPM(units, points, weights) # ratingsImported = calculateRAPM(unitsImported[:224], pointsImported[:224], weightsImported[:224]) if printRatings: for rating in ratings: print(rating[0], "{}".format(playerDict[int(rating[0])]), "{0:.3f}".format(rating[1])) # if config.debug: print("Export RAPM ratings...") exportPlayerRatings(ratings, playerDict, ratingBasePath)
def request_general(): file_format = "json" league_name = input("League name: ") season_name_begin = input("Enter the beginning of the season ") + "-" season_name_end = input("Enter the end of the season ") + "-" season_name_type = input("Enter either 'regular' or 'playoff '") data_type = [ "cumulative_player_stats", "full_game_schedule", "active_players", "overall_team_standings", "conference_team_standings", "division_team_standings", "playoff_team_standings", "player_injuries", "latest_updates" ] #for loop to download all the data at a given season for x in range(0, len(data_type)): if season_name_type == "playoff": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + season_name_type, feed=data_type[x], format=file_format) #can add more optional params manually elif data_type[x] == "playoff_team_standings": Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data(league=league_name, season=season_name_begin + "playoff", feed=data_type[x], format=file_format) #can add more optional params manually else: Data_query = MySportsFeeds('1.0', verbose=True) Data_query.authenticate(authorize.username, authorize.password) Output = Data_query.msf_get_data( league=league_name, season=season_name_begin + season_name_end + season_name_type, feed=data_type[x], format=file_format)
import pdb import os import time from ohmysportsfeedspy import MySportsFeeds import json import sys msf = MySportsFeeds(version="1.0") msf.authenticate("kendallweihe", os.environ["PWD_MSF"]) def get_dates(): game_dates = [] year = "2015" for i in range(10, 13): for j in range(1, 32): date = "{}{}{}".format(year, i, str(j).zfill(2)) game_dates.append(date) year = "2016" for i in range(1, 8): for j in range(1, 32): date = "{}{}{}".format(year, str(i).zfill(2), str(j).zfill(2)) game_dates.append(date) return game_dates def get_daily_player(date): time.sleep(5) stats = msf.msf_get_data(league="nba",
# Install MySportsFeed and simplejson # pip install ohmysportsfeedspy # pip install simplejson from ohmysportsfeedspy import MySportsFeeds import pymongo import requests import json # Authenticating the MySportsFeeds API Data_query = MySportsFeeds('1.2',verbose=True) Data_query.authenticate('Aiyana410', '04101993mad') # The default port used by MongoDB is 27017 # https://docs.mongodb.com/manual/reference/default-mongodb-port/ conn = 'mongodb://localhost:27017' client = pymongo.MongoClient(conn) # Declare the database db = client.nba # Declare the collection collection = db.nba_bio # Google API Servcies key gkey ="Use your Google API Service Key" # List of seasons needed season=['2015-2016','2016-2017'] # Intializing the index for each document being stored index=1
from ohmysportsfeedspy import MySportsFeeds import json import pprint Data_query = MySportsFeeds('1.2', verbose=True) Data_query.authenticate('7af68037-2f3f-4bf5-bbd5-173ad2', 'Dk30RQHT') Output = Data_query.msf_get_data(league='nfl', season='upcoming', feed='player_injuries', format='json') total_weight = 0 total_height = 0 for item in Output['playerinjuries']['playerentry']: name = item["player"]["FirstName"] + ' ' + item["player"]["LastName"] weight = item["player"]["Weight"] height = item["player"]["Height"] ft, inch = height.split("'") injury = item["injury"] total_weight = total_weight + int(weight) ft_inch = int(ft) * 12 + int(inch[:-1]) total_height = total_height + ft_inch print(name, height, weight, injury) avg_height = total_height / 15 avg_height = avg_height / 12 inch_height = avg_height - int(avg_height) inch_height = inch_height * 10 print("The average weight for an injured nfl player is:", int(total_weight / 15), "lbs")
from ohmysportsfeedspy import MySportsFeeds Data_query = MySportsFeeds('1.2', verbose=True) Data_query.authenticate('7f38bf2c-0bb5-4308-85b0-6057b8', 'Dk30RQHT') Output = Data_query.msf_get_data(league='nba', season='2016-2017-regular', feed='player_gamelogs', format='json', player='stephen-curry') print(Output)
from ohmysportsfeedspy import MySportsFeeds msf = MySportsFeeds(version="2.0") msf.authenticate("a13e361c-0c35-4934-b4e4-527214", "MYSPORTSFEEDS") output = msf.msf_get_data(league='nba', season='2016-2017-regular', feed='seasonal_player_gamelogs', format='json', player='stephen-curry') print(output)
from ohmysportsfeedspy import MySportsFeeds import json import pprint Data_query = MySportsFeeds('1.2', verbose=True) Data_query.authenticate('afc252ab406ec30e66d849ab957c6cc6275bbda94b2032a1f6f0c8b5ca75fd2a', 'ee88662fbead382e5f4352709331284f100e24e512f45d3f73d1e151c986aaa8') Output = Data_query.msf_get_data(league='nfl', season='upcoming', feed='active_players', team=['SF'], format='json') r = requests.get('https://api.github.com/user', auth=('user', 'pass')) # states = {} # for i in range(108): # for key, value in Output["activeplayers"]["playerentry"][i]["player"].items(): # if key == "BirthCity": # cities = value.split(",") # if len(cities) == 2: # city = cities[0] # state = cities[1] # else: # city = cities[0] # state = "" # if state not in states.keys(): # states[state] = {} # states[state][city] = {} # print(json.dumps(states, indent=4))
from ohmysportsfeedspy import MySportsFeeds from decouple import config key = config('API_key') password = config('password') msf = MySportsFeeds(version="1.2") msf.authenticate(key, password) # output = msf.msf_get_data(league='nba',season='current',feed='cumulative_player_stats',format='json',player='stephen-curry') # print(output['cumulativeplayerstats']['playerstatsentry'][0]['stats']['Fg3PtAttPerGame']['#text']) # stat = output['cumulativeplayerstats']['playerstatsentry'][0]['stats'] # print(stat['Fg3PtAttPerGame']['#text']) output = msf.msf_get_data(league='nfl', season='2018-regular', feed='cumulative_player_stats', format='json', player='cam-newton') print(output)
from ohmysportsfeedspy import MySportsFeeds Data_query = MySportsFeeds('2.0', verbose=True) Data_query.authenticate('7a623d32-510c-4ccf-8a7b-8a3af9', 'MYSPORTSFEEDS') Output = Data_query.msf_get_data(league='nba', season='2018-2019-regular', feed='seasonal_player_gamelogs', player='anthony-davis', format='json', force='true') print(Output)
# Script to get all regular season games from My Sports Feed API and post to database import os from ohmysportsfeedspy import MySportsFeeds from not_yours import MSF_API_KEY, MSF_PASSWORD import requests msf = MySportsFeeds(version="1.2") msf.authenticate(MSF_API_KEY, MSF_PASSWORD) result = msf.msf_get_data(league='mlb', season='2019-regular', feed='full_game_schedule', format='json') for gameentry in result['fullgameschedule']['gameentry']: r = requests.post('http://localhost:5000/api/games', json=gameentry)
from ohmysportsfeedspy import MySportsFeeds import json msf = MySportsFeeds(version="1.2") msf.authenticate("05e421a4-2932-44c1-99e4-0fb8e2", "mysportsfeeds100") output = msf.msf_get_data(league='nfl', season='2018-2019-regular', feed='cumulative_player_stats', format='json', team='dallas-cowboys') with open( "E:/school/2018-19/caps/A Foot in the Door/pythonFiles/results/boys.json", "w+") as f: json.dump(output, f)