Skip to content

Commit

Permalink
Merge pull request #18 from justin-hsieh/update_submodule
Browse files Browse the repository at this point in the history
Update submodule
  • Loading branch information
justin-hsieh authored Nov 1, 2023
2 parents c2fdbae + 6466fcb commit 0f2efc3
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 22 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,5 @@ venv.bak/

.vscode
key.json
.ipynb
.ipynb

27 changes: 18 additions & 9 deletions fantasy_app/espn_api_submodule/espn_api/base_league.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
from .utils.logger import Logger
from .requests.espn_requests import EspnFantasyRequests


class BaseLeague(ABC):
'''Creates a League instance for Public/Private ESPN league'''

def __init__(self, league_id: int, year: int, sport: str, espn_s2=None, swid=None, debug=False):
self.logger = Logger(name=f'{sport} league', debug=debug)
self.league_id = league_id
self.year = year
self.teams = []
self.members = []
self.draft = []
self.player_map = {}

Expand All @@ -21,12 +24,13 @@ def __init__(self, league_id: int, year: int, sport: str, espn_s2=None, swid=Non
'espn_s2': espn_s2,
'SWID': swid
}
self.espn_request = EspnFantasyRequests(sport=sport, year=year, league_id=league_id, cookies=cookies, logger=self.logger)
self.espn_request = EspnFantasyRequests(
sport=sport, year=year, league_id=league_id, cookies=cookies, logger=self.logger)

def __repr__(self):
return 'League(%s, %s)' % (self.league_id, self.year, )

def _fetch_league(self, SettingsClass = BaseSettings):
def _fetch_league(self, SettingsClass=BaseSettings):
data = self.espn_request.get_league()

self.currentMatchupPeriod = data['status']['currentMatchupPeriod']
Expand All @@ -36,11 +40,13 @@ def _fetch_league(self, SettingsClass = BaseSettings):
if self.year < 2018:
self.current_week = data['scoringPeriodId']
else:
self.current_week = self.scoringPeriodId if self.scoringPeriodId <= data['status']['finalScoringPeriod'] else data['status']['finalScoringPeriod']
self.current_week = self.scoringPeriodId if self.scoringPeriodId <= data[
'status']['finalScoringPeriod'] else data['status']['finalScoringPeriod']
self.settings = SettingsClass(data['settings'])
self.members = data.get('members', [])
return data

def _fetch_teams(self, data, TeamClass, pro_schedule = None):
def _fetch_teams(self, data, TeamClass, pro_schedule=None):
'''Fetch teams in league'''
self.teams = []
teams = data['teams']
Expand All @@ -61,7 +67,8 @@ def _fetch_teams(self, data, TeamClass, pro_schedule = None):
elif member['id'] == team['owners'][0]:
break
roster = team_roster[team['id']]
self.teams.append(TeamClass(team, roster=roster, member=member, schedule=schedule, year=seasonId, pro_schedule=pro_schedule))
self.teams.append(TeamClass(team, roster=roster, member=member,
schedule=schedule, year=seasonId, pro_schedule=pro_schedule))

# sort by team ID
self.teams = sorted(self.teams, key=lambda x: x.team_id, reverse=False)
Expand All @@ -86,9 +93,10 @@ def _get_pro_schedule(self, scoringPeriodId: int = None):
pro_game = team.get('proGamesByScoringPeriod', {})
if team['id'] != 0 and (str(scoringPeriodId) in pro_game.keys() and pro_game[str(scoringPeriodId)]):
game_data = pro_game[str(scoringPeriodId)][0]
pro_team_schedule[team['id']] = (game_data['homeProTeamId'], game_data['date']) if team['id'] == game_data['awayProTeamId'] else (game_data['awayProTeamId'], game_data['date'])
pro_team_schedule[team['id']] = (game_data['homeProTeamId'], game_data['date']) if team['id'] == game_data['awayProTeamId'] else (
game_data['awayProTeamId'], game_data['date'])
return pro_team_schedule

def _get_all_pro_schedule(self):
data = self.espn_request.get_pro_schedule()

Expand All @@ -101,5 +109,6 @@ def _get_all_pro_schedule(self):
return pro_team_schedule

def standings(self) -> List:
standings = sorted(self.teams, key=lambda x: x.final_standing if x.final_standing != 0 else x.standing, reverse=False)
return standings
standings = sorted(
self.teams, key=lambda x: x.final_standing if x.final_standing != 0 else x.standing, reverse=False)
return standings
37 changes: 25 additions & 12 deletions fantasy_app/espn_api_submodule/espn_api/football/team.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
from .player import Player


class Team(object):
'''Teams are part of the league'''

def __init__(self, data, roster, member, schedule, year, **kwargs):
self.team_id = data['id']
self.team_abbrev = data['abbrev']
self.team_name = "%s %s" % (data['location'], data['nickname'])
self.team_name = data.get('name', 'Unknown')
if self.team_name == 'Unknown':
self.team_name = "%s %s" % (
data.get('location', 'Unknown'), data.get('nickname', 'Unknown'))
self.division_id = data['divisionId']
self.division_name = '' # set by caller
self.division_name = '' # set by caller
self.wins = data['record']['overall']['wins']
self.losses = data['record']['overall']['losses']
self.ties = data['record']['overall']['ties']
self.points_for = data['record']['overall']['pointsFor']
self.points_against = round(data['record']['overall']['pointsAgainst'], 2)
self.acquisitions = data.get('transactionCounter', {}).get('acquisitions', 0)
self.acquisition_budget_spent = data.get('transactionCounter', {}).get('acquisitionBudgetSpent', 0)
self.points_against = round(
data['record']['overall']['pointsAgainst'], 2)
self.acquisitions = data.get(
'transactionCounter', {}).get('acquisitions', 0)
self.acquisition_budget_spent = data.get(
'transactionCounter', {}).get('acquisitionBudgetSpent', 0)
self.drops = data.get('transactionCounter', {}).get('drops', 0)
self.trades = data.get('transactionCounter', {}).get('trades', 0)
self.playoff_pct = data.get('currentSimulationResults', {}).get('playoffPct', 0) * 100
self.playoff_pct = data.get(
'currentSimulationResults', {}).get('playoffPct', 0) * 100
self.draft_projected_rank = data.get('draftDayProjectedRank', 0)
self.owner = 'None'
if member:
Expand All @@ -27,7 +36,7 @@ def __init__(self, data, roster, member, schedule, year, **kwargs):
self.streak_type = data['record']['overall']['streakType']
self.standing = data['playoffSeed']
self.final_standing = data['rankCalculatedFinal']
if 'logo' in data:
if 'logo' in data:
self.logo_url = data['logo']
else:
self.logo_url = ''
Expand All @@ -37,11 +46,12 @@ def __init__(self, data, roster, member, schedule, year, **kwargs):
self.outcomes = []
self.mov = []
self._fetch_schedule(schedule)
self.owners = data.get('owners', [])
self._fetch_roster(roster, year)

def __repr__(self):
return 'Team(%s)' % (self.team_name, )

def _fetch_roster(self, data, year):
'''Fetch teams roster'''
self.roster.clear()
Expand All @@ -58,22 +68,25 @@ def _fetch_schedule(self, data):
if matchup['away']['teamId'] == self.team_id:
score = matchup['away']['totalPoints']
opponentId = matchup['home']['teamId']
self.outcomes.append(self._get_winner(matchup['winner'], True))
self.outcomes.append(
self._get_winner(matchup['winner'], True))
self.scores.append(score)
self.schedule.append(opponentId)
elif matchup['home']['teamId'] == self.team_id:
score = matchup['home']['totalPoints']
opponentId = matchup['away']['teamId']
self.outcomes.append(self._get_winner(matchup['winner'], False))
self.outcomes.append(
self._get_winner(matchup['winner'], False))
self.scores.append(score)
self.schedule.append(opponentId)
elif matchup['home']['teamId'] == self.team_id:
score = matchup['home']['totalPoints']
opponentId = matchup['home']['teamId']
self.outcomes.append(self._get_winner(matchup['winner'], False))
self.outcomes.append(
self._get_winner(matchup['winner'], False))
self.scores.append(score)
self.schedule.append(opponentId)

def _get_winner(self, winner: str, is_away: bool) -> str:
if winner == 'UNDECIDED':
return 'U'
Expand Down

0 comments on commit 0f2efc3

Please sign in to comment.