Comments (6)
Hi @sstratt1 what data are you trying to get? You shouldn't need to directly create a player class. The League class should populate all of that data and be the main entry point into the package.
from espn-api.
from espn-api.
Nice, you should be able to accomplish that all through the league box_score
functionality. The box score class has list of home and away lineup of the box player class. In that class you can see if they were on the bench or in the lineup by slot_position
field. The box player class also inherits the Player Class so you can also access eligibleSlots
field as well. To get the box_score class It would look something like this.
from espn_api.football import League
# init league example
league = League(league_id=1245, year=2022, espn_s2='ASCWD', swid='{03JFJHW-FWFWF-044G}')
# gets current week box score class
box_score = league.box_scores()
From here you can loop through the box_scores and calculate what if
from espn-api.
Hi @sstratt1, I've done a similar analysis and have two functions that might help you.
def get_top_players(lineup: List[Player], slot: str, n: int) -> List[Player]:
"""Takes a list of players and returns a list of the top n players based on points scored."""
# Gather players of the desired position
eligible_players = []
for player in lineup:
if slot in player.eligibleSlots:
eligible_players.append(player)
return sorted(eligible_players, key=lambda x: x.points, reverse=True)[:n]
def get_best_lineup(league: League, lineup: List[Player]) -> float:
"""Returns the score of the best possible lineup for team during the loaded week."""
# Save full roster
saved_roster = copy(lineup)
# Find Best Lineup
best_lineup = []
# Get best RB before best RB/WR/TE
for slot in sorted(league.roster_settings["starting_roster_slots"].keys(), key=len):
num_players = league.roster_settings["starting_roster_slots"][slot]
best_players = get_top_players(saved_roster, slot, num_players)
best_lineup.extend(best_players)
# Remove selected players from consideration for other slots
for player in best_players:
saved_roster.remove(player)
return np.sum([player.points for player in best_lineup])
This function will look at a league's settings to determine what a starting lineup looks like (how many QBs, how many RBs, etc.), and then look at a given lineup (pass in box_score[0].home_lineup
for example, from @cwendt94 's example above) to determine which players would have comprised the best score possible. I only return the final score, but you could surface the best_lineup
variable to do more analysis and see the actual makeup of the optimal starting lineup.
Note: in my repo, I have a wrapper for the League
class that gets roster settings. To use the functions above, you would have to pass your League
object into two more functions:
def set_league_endpoint(league: League) -> None:
"""Set the league's endpoint."""
# Current season
if league.year >= (datetime.datetime.today() - datetime.timedelta(weeks=12)).year:
league.endpoint = (
"https://fantasy.espn.com/apis/v3/games/ffl/seasons/"
+ str(league.year)
+ "/segments/0/leagues/"
+ str(league.league_id)
+ "?"
)
# Old season
else:
league.endpoint = (
"https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory/"
+ str(league.league_id)
+ "?seasonId="
+ str(league.year)
+ "&"
)
def get_roster_settings(league: League) -> None:
"""This grabs the roster and starting lineup settings for the league
- Grabs the dictionary containing the number of players of each position a roster contains
- Creates a dictionary roster_slots{} that only inlcludes slotIds that have a non-zero number of players on the roster
- Creates a dictionary starting_roster_slots{} that is a subset of roster_slots{} and only includes slotIds that are on the starting roster
- Add roster_slots{} and starting_roster_slots{} to the League attribute League.rosterSettings
"""
print("[BUILDING LEAGUE] Gathering roster settings information...")
# This dictionary maps each slotId to the position it represents
rosterMap = {
0: "QB",
1: "TQB",
2: "RB",
3: "RB/WR",
4: "WR",
5: "WR/TE",
6: "TE",
7: "OP",
8: "DT",
9: "DE",
10: "LB",
11: "DL",
12: "CB",
13: "S",
14: "DB",
15: "DP",
16: "D/ST",
17: "K",
18: "P",
19: "HC",
20: "BE",
21: "IR",
22: "",
23: "RB/WR/TE",
24: " ",
}
endpoint = "{}view=mMatchupScore&view=mTeam&view=mSettings".format(league.endpoint)
r = requests.get(endpoint, cookies=league.cookies).json()
if type(r) == list:
r = r[0]
settings = r["settings"]
league.name = settings["name"]
# Grab the dictionary containing the number of players of each position a roster contains
roster = settings["rosterSettings"]["lineupSlotCounts"]
# Create an empty dictionary that will replace roster{}
roster_slots = {}
# Create an empty dictionary that will be a subset of roster_slots{} containing only starting players
starting_roster_slots = {}
for positionId in roster:
position = rosterMap[int(positionId)]
# Only inlclude slotIds that have a non-zero number of players on the roster
if roster[positionId] != 0:
roster_slots[position] = roster[positionId]
# Include all slotIds in the starting_roster_slots{} unless they are bench, injured reserve, or ' '
if positionId not in ["20", "21", "24"]:
starting_roster_slots[position] = roster[positionId]
# Add roster_slots{} and starting_roster_slots{} as a league attribute
league.roster_settings = {
"roster_slots": roster_slots,
"starting_roster_slots": starting_roster_slots,
}
return
I hope this helps!
from espn-api.
Nice, you should be able to accomplish that all through the league
box_score
functionality. The box score class has list of home and away lineup of the box player class. In that class you can see if they were on the bench or in the lineup byslot_position
field. The box player class also inherits the Player Class so you can also accesseligibleSlots
field as well. To get the box_score class It would look something like this.from espn_api.football import League # init league example league = League(league_id=1245, year=2022, espn_s2='ASCWD', swid='{03JFJHW-FWFWF-044G}') # gets current week box score class box_score = league.box_scores()From here you can loop through the box_scores and calculate what if
@cwendt94 I am trying to accomplish something similar - I am trying to iterate through all the weekly box scores
and grab the individual player stats for each team, for each week. The end analysis I want is essentially a mapping of
{
player1 : {week_1 : players_point_total, week_2: players_point_total,...},
player2: {week_1: ....}
},
I have grabbed the league & box scores using the following code:
league_id = ...
espn_s2 = ....
swid = ....
league = League(league_id=league_id, year=2023, espn_s2=espn_s2, swid=swid)
boxscores_week5 = league.box_scores(week=5)
It looks like I can iterate over the each box_score
in my new boxscores_week5 list, and potentiall call box_score._get_team_data()
to get the point totals for each player involved in that particular box_score
. However the _get_team_data
requires the following parameters to be set
_get_team_data() missing 6 required positional arguments: 'team', 'data', 'pro_schedule', 'positional_rankings', 'week', and 'year'
What are the team
, data
, pro_schedule
, positional_rankings
parameters and how can I find the correct values to populate? Or, is there a different way to achieve my ultimate goal rather than iterating over the individual box_scores
for each week of the year?
from espn-api.
I think you can achieve this using the league.player_info
call. This will get all the stats for that player and break it down per week. So it should look something like this
# go through each team
for team in league.teams:
playerIds = []
# get all the playerIds on their roster
for player in team.roster:
playerIds.append(player.playerId)
# call player_info with the array of ids
players = league.player_info(playerId=playerIds)
# then can get stats for each player
players[0].stats
The stats will look like this
# week 1
players[0].stats[1]
{'points': 24.0, 'breakdown': {'receivingReceptions': 9.0, 'receivingYards': 150.0, '47': 30.0, '48': 15.0, '49': 7.0, '50': 6.0, '51': 3.0, '52': 1.0, '54': 1.0, 'receiving100To199YardGame': 1.0, 'receivingTargets': 12.0, 'receivingYardsAfterCatch': 67.0, 'receivingYardsPerReception': 16.667, 'defensiveSoloTackles': 1.0, 'defensiveTotalTackles': 1.0, 'teamLoss': 1.0, '210': 1.0, '213': 5.0}, 'avg_points': 0}
from espn-api.
Related Issues (20)
- Incorrect BoxPlayer.pro_opponent for traded players HOT 1
- NFL position mapping incorrect HOT 5
- Team Names not correct HOT 2
- Unable to access league data for 2018 season HOT 1
- Teams' names not updated HOT 1
- League current_week field returns 0 HOT 8
- meaning of statistics keys HOT 3
- Fix Team Data Change Working? HOT 1
- Add Owner info to Team
- Pulling League Data Errors in new season 23-24 HOT 1
- 'location' in data json doesn't exist anymore. Fix is provided HOT 2
- ESPN API Updated Key Names for Team Name HOT 1
- KeyError: 'location' in Fantasy BBall H2H Categories HOT 2
- Add back functionality to pull owner names HOT 4
- Getting "json.decoder.JSONDecodeError: Unterminated string" starting after NFL week 6 HOT 4
- Add accepted trade activity to fantasy basketball activity list HOT 3
- Player/Pick projected bid amount HOT 5
- slot_position only returning "PG" HOT 1
- Unable to get projected score of games of final completed week of season HOT 1
- Issue with Add full owner info to team commit HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from espn-api.