Giter Club home page Giter Club logo

python-mlb-statsapi's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

python-mlb-statsapi's Issues

Error Occurred When Using 'get_stats' Method with 'MlbResult' Object in python-mlb-statsapi

I am trying to retrieve MLB-related data using the MLBStatsAPI. When I execute the following code, I encounter an error:

import mlbstatsapi
mlb = mlbstatsapi.Mlb()

y = 2022
stats_type = 'season'
group_type = 'hitting'
params = {'season':y, 'team':142}

year_stats = mlb.get_stats(stats=stats_type, groups=group_type)
print(year_stats)

error:

Traceback (most recent call last):
File "D:\pythonProject\get_stats__team.py", line 10, in
year_stats = mlb.get_stats(stats=stats_type, groups=group_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\GS\AppData\Local\Programs\Python\Python311\Lib\site-packages\mlbstatsapi\mlb_api.py", line 2258, in get_stats
splits = mlb_module.create_split_data(mlb_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\GS\AppData\Local\Programs\Python\Python311\Lib\site-packages\mlbstatsapi\mlb_module.py", line 110, in create_split_data
for stat in stat_data:
TypeError: 'MlbResult' object is not iterable

Issue with mlb.get_schedule() and mlb.get_scheduled_games_by_date() methods

Executed within a cell in Google Colab

! pip install python-mlb-statsapi==0.5.13
import mlbstatsapi
mlb = mlbstatsapi.Mlb()

mlb.get_schedule(date='2023-09-03')

#output

DEBUG:mlbstatsapi.mlb_dataadapter:url=https://statsapi.mlb.com/api/v1/schedule ,success={}, status_code={}, message={}, url={}
DEBUG:mlbstatsapi.mlb_dataadapter:url=https://statsapi.mlb.com/api/v1/schedule ,success=success, status_code=200, message=OK, url=https://statsapi.mlb.com/api/v1/schedule?date=2023-09-03&sportId=1

TypeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 mlb.get_schedule(date='2023-09-03')

6 frames
/usr/local/lib/python3.10/dist-packages/mlbstatsapi/models/schedules/attributes.py in (.0)
213
214 def post_init(self):
--> 215 self.games = [ScheduleGames(**game) for game in self.games ] if self.games else self.games
216
217 def repr(self):

TypeError: ScheduleGames.init() got an unexpected keyword argument 'gameguid'

The same output occurs with the get_scheduled_games_by_date() method.

ERROR: GameInfo.___init___() missing 2 required positional arguments: 'attendance' and 'gamedurationminutes'

@KCNilssen @Mattsface
Looks like another GameInfo.init() adjustment needs to be made.
Positional arguments attendance & gamedurationminutes, errors.

Call works for all but 2 gamePK's(745114 & 746083).

Input
mlb_games.csv

Output
mlb_games_ready.csv

image

Same code block as previous issue:

Function
#Function to get weather and venue for a given game_pk
def get_game_info(game_pk):
mlb = mlbstatsapi.Mlb()
try:
game = mlb.get_game(game_pk)
venue_id = game.gamedata.venue.id
venue_name = game.gamedata.venue.name
venue_lat = game.gamedata.venue.location.defaultcoordinates.latitude
venue_long = game.gamedata.venue.location.defaultcoordinates.longitude
venue_elevation = game.gamedata.venue.location.elevation
venue_surface = game.gamedata.venue.fieldinfo.turftype
return venue_id, venue_name, venue_lat, venue_long, venue_elevation, venue_surface
except Exception as e:
print(f"Error processing game_pk {game_pk}: {e}")
return "None", "None", "None", "None", "None", "None"

Code
#Add Game Venue and Location Detail
csv_file = 'mlb_games.csv'
df = pd.read_csv(csv_file)

Initialize new columns

df['venue_id'] = None
df['venue_name'] = None
df['venue_latitude'] = None
df['venue_longitude'] = None
df['venue_elevation'] = None
df['venue_surface'] = None

for index, row in df.iterrows():
game_pk = row['GamePk']
print(game_pk)
try:
venue_id, venue_name, venue_lat, venue_long, venue_elevation, venue_surface = get_game_info(game_pk)
df.at[index, 'venue_id'] = venue_id
df.at[index, 'venue_name'] = venue_name
df.at[index, 'venue_latitude'] = venue_lat
df.at[index, 'venue_longitude'] = venue_long
df.at[index, 'venue_elevation'] = venue_elevation
df.at[index, 'venue_surface'] = venue_surface
except Exception as e:
print(f"Error processing game_pk {game_pk}: {e}")

new_column_order = [
'Date', 'Time', 'GamePk', 'Away Team', 'Home Team', 'venue_id', 'venue_name', 'venue_latitude', 'venue_longitude', 'venue_elevation', 'venue_surface']

Check if all columns are included in new_column_order

assert set(new_column_order) == set(df.columns), "New column order does not match DataFrame columns"

Reindex the DataFrame with the new column order

df = df[new_column_order]

Save the updated DataFrame back to a CSV

updated_csv_file = 'mlb_games_ready.csv'
df.to_csv(updated_csv_file, index=False)

Venue is receiving a unexpected keyword argument

The periodic run of our pytest suit is raising an expectation.

TypeError: Venue.__init__() got an unexpected keyword argument 'season'

I believe the MLB REST API must have updated the venue model as this was not present before.

Python Version compatibility

I think this statement in the README is incorrect:

Python-mlb-statsapi written in python 3.7+

I was trying to run with v3.8.x but getting this error:

File "<my dir>/.local/lib/python3.8/site-packages/mlbstatsapi/models/people/__init__.py", line 2, in <module>
    from .people import Player, Coach, Person, Batter, Pitcher, DraftPick
  File "<my dir>/.local/lib/python3.8/site-packages/mlbstatsapi/models/people/people.py", line 170, in <module>
    @dataclass(kw_only=True, repr=False)
TypeError: dataclass() got an unexpected keyword argument 'kw_only'

KW_ONLY appears to be 3.10+

So that would make 3.10 the minimum python version.

Unless I'm mistaken! Not exactly a python expert here ๐Ÿ˜†

Ref: https://stackoverflow.com/questions/73732521/how-to-use-dataclass-kw-only-correctly

AssertionError: season, seasonAdvanced stats MLB API Issue

Output:

====================================== short test summary info ====================================== 

FAILED tests/external_tests/stats/test_catching.py::TestCatchingStats::test_catching_stat_attributes_player - AssertionError: 1 != 2
FAILED tests/external_tests/stats/test_catching.py::TestCatchingStats::test_catching_stat_attributes_team - AssertionError: 1 != 2
FAILED tests/external_tests/stats/test_fielding.py::TestPitchingStats::test_fielding_stat_attributes_player - AssertionError: 1 != 2
FAILED tests/external_tests/stats/test_fielding.py::TestPitchingStats::test_fielding_stat_attributes_team - AssertionError: 2 != 4
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_bydate_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_bydayofweek_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_bymonth_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_excepected_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_hotcoldzones_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_pitchArsenal_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_pitchlog_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_stat_attributes_player - AssertionError: 2 != 4
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_stat_attributes_team - AssertionError: 2 != 4
FAILED tests/external_tests/stats/test_hitting.py::TestHittingStats::test_hitting_vsteam_stats_team - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_bydate_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_bydayofweek_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_bymonth_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_excepected_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_hotcoldzones_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_pitchArsenal_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_pitchlog_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_playlog_stats_player - AssertionError: {} == {}
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_stat_attributes_player - AssertionError: 2 != 4
FAILED tests/external_tests/stats/test_pitching.py::TestPitchingStats::test_pitching_stat_attributes_team - AssertionError: 2 != 4

Issues:

Team endpoint that should return hitting stats for season:
https://statsapi.mlb.com/api/v1/teams/133/stats?stats=season,career&group=hitting

MLB api now returns Object not found when asked for season stats, which is a new output we have not seen before from the MLB api. When an addition stats type is included such as stats=season,career instead of just stats=season, we are returned a normal return but with only stats for career, it does not even include an empty season stats.

{
   "messageNumber":10,
   "message":"Object not found",
   "timestamp":"2023-02-28T20:31:24.076747546Z",
   "traceId":null
}

People endpoint that should return stats for season and seasonAdvanced:
https://statsapi.mlb.com/api/v1/people/660271/stats?stats=season,seasonAdvanced&group=pitching

MLB api returns an empty stats object, which unlike above, an empty stats object that I assume is meant to contain the pitching season and seasonAdvanced stats objects. When an additional group is added like above, stats=season,seasonAdvanced,career, only the career pitching stats are returned, missing both the season and seasonAdvanced.

{
   "copyright":"Copyright 2023 MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt",
   "stats":[]
}

Summery:
The failed tests are all tied with the season and seasonAdvanced stat types. Because of these issues when we ask for 4 stat types and two of which are the issued season types, only 2 stat types are returned. Meaning that with a test expecting 4 but only receiving two, it fails, creating an assertionError.
Example below where we ask for season and career catching stats. Since only one is returned when we check, 1 != 2 and thus the AssertionError:

def test_catching_stat_attributes_team(self):
        """mlb get stats should return pitching stats"""
        self.stats = ['season', 'career']
        self.group = ['catching']
        # let's get some stats
        stats = self.mlb.get_team_stats(self.al_team, stats=self.stats, groups=self.group)
    
        # check for empty dict
        self.assertNotEqual(stats, {})
    
        # the end point should give us 2 hitting
        self.assertTrue('catching' in stats)
        self.assertFalse('hitting' in stats)
>       self.assertEqual(len(stats['catching']), 2)
E       AssertionError: 1 != 2

Thoughts

I think this may have something to do with it being the offseason. Could this be how the MLB api handles its returns for between seasons or is this the result of a change or update with the MLB api and how they handle these endpoints? Due the the lack of api information that is publicly available at this time we have no real idea.

TypeError: DraftPick.__init__() got an unexpected keyword argument 'displaypicknumber'

Bi-Daily morning test failed.

Mlb Api updated to include extra parameter in draftpick data class 'displaypicknumber'.

with output:

============================ test session starts =============================
platform linux -- Python 3.10.12, pytest-7.4.0, pluggy-1.2.0
rootdir: /home/runner/work/python-mlb-statsapi/python-mlb-statsapi
plugins: requests-mock-1.11.0
collected 189 items

tests/external_tests/attendance/test_attendance.py ...                  [  1%]
tests/external_tests/awards/test_awards.py ...                          [  3%]
tests/external_tests/division/test_division.py ...                      [  4%]
tests/external_tests/drafts/test_draft.py F.F                           [  6%]
tests/external_tests/game/test_game.py ..                               [  7%]
tests/external_tests/homerunderby/test_homerunderby.py ..               [  8%]
tests/external_tests/league/test_league.py ...                          [ 10%]
tests/external_tests/mlb/test_mlb.py ................................   [ 28%]
tests/external_tests/mlbdataadapter/test_mlbadapter.py ........         [ 34%]
tests/external_tests/person/test_person.py ....                         [ 36%]
tests/external_tests/schedule/test_schedule.py ...                      [ 38%]
tests/external_tests/seasons/test_seasons.py ......                     [ 41%]
tests/external_tests/sport/test_sport.py ...                            [ 42%]
tests/external_tests/standings/test_standings.py ...                    [ 44%]
tests/external_tests/stats/test_catching.py ..                          [ 45%]
tests/external_tests/stats/test_fielding.py ..                          [ 46%]
tests/external_tests/stats/test_hitting.py .............                [ 53%]
tests/external_tests/stats/test_pitching.py ...........                 [ 59%]
tests/external_tests/stats/test_player_game_stats.py ....               [ 61%]
tests/external_tests/team/test_roster.py ....                           [ 63%]
tests/external_tests/team/test_team.py ...                              [ 65%]
tests/external_tests/venue/test_venue.py ...                            [ 66%]
tests/mock_tests/awards/test_awards_mock.py .                           [ 67%]
tests/mock_tests/drafts/test_draft_mock.py .                            [ 67%]
tests/mock_tests/gamepace/test_gamepace_mock.py .                       [ 68%]
tests/mock_tests/homerunderby/test_homerunderby_mock.py .               [ 68%]
tests/mock_tests/mlb/test_mlb_mock.py ...............................   [ 86%]
                                                                        [ 86%]
tests/mock_tests/schedules/test_schedule_mock.py ...                    [ 88%]
tests/mock_tests/standings/test_standings_mock.py .                     [ 88%]
tests/mock_tests/stats/test_game_player_stats_for_game.py ....          [ 91%]
tests/mock_tests/stats/test_hitting_stats_mock.py ......                [ 94%]
tests/mock_tests/stats/test_pitching_stats_mock.py .....                [ 96%]
tests/mock_tests/teams/test_roster_mock.py ..                           [ 97%]
tests/mock_tests/teams/test_team_mock.py ..                             [ 98%]
tests/mock_tests/teams/test_team_roster_mock.py ..                      [100%]

========================== short test summary info ===========================
FAILED tests/external_tests/drafts/test_draft.py::TestRound::test_get_draft_by_year_id
       - TypeError: DraftPick.__init__() got an unexpected keyword argument
       'displaypicknumber'
FAILED tests/external_tests/drafts/test_draft.py::TestRound::test_get_draft_with_params
       - TypeError: DraftPick.__init__() got an unexpected keyword argument
       'displaypicknumber'
======================= 2 failed, 187 passed in 42.62s =======================

TypeError: dataclass() got an unexpected keyword argument 'kw_only'

Just trying to start off simple to see how things work

from mlbstatsapi import Mlb

all_teams = Mlb.get_teams()

print(all_teams)

in running the above I get the error below:

Traceback (most recent call last):
  File "C:\Users\Matthew\PycharmProjects\MLB_data\main.py", line 2, in <module>
    from mlbstatsapi import Mlb
  File "C:\Users\Matthew\PycharmProjects\MLB_data\venv\lib\site-packages\mlbstatsapi\__init__.py", line 1, in <module>
    from .mlb_api import Mlb
  File "C:\Users\Matthew\PycharmProjects\MLB_data\venv\lib\site-packages\mlbstatsapi\mlb_api.py", line 6, in <module>
    from mlbstatsapi.models.people import Person, Player, Coach
  File "C:\Users\Matthew\PycharmProjects\MLB_data\venv\lib\site-packages\mlbstatsapi\models\people\__init__.py", line 2, in <module>
    from .people import Player, Coach, Person, Batter, Pitcher, DraftPick
  File "C:\Users\Matthew\PycharmProjects\MLB_data\venv\lib\site-packages\mlbstatsapi\models\people\people.py", line 163, in <module>
    @dataclass(kw_only=True)
TypeError: dataclass() got an unexpected keyword argument 'kw_only'

TypeError: Location.__init__() got an unexpected keyword argument 'azimuthangle'

Receive the following error when using: game = mlb. get_game('game_id')

live_game = mlb.get_game(game_id).livedata
            ^^^^^^^^^^^^^^^^^^^^^

File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/mlb_api.py", line 907, in get_game
return Game(**mlb_data.data)
^^^^^^^^^^^^^^^^^^^^^
File "", line 8, in init
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/models/game/game.py", line 43, in post_init
self.gamedata = GameData(**self.gamedata)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 20, in init
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/models/game/gamedata/gamedata.py", line 80, in post_init
self.venue = Venue(**self.venue)
^^^^^^^^^^^^^^^^^^^
File "", line 11, in init
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/models/venues/venue.py", line 39, in post_init
self.location = Location(**self.location) if self.location else self.location
^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Location.init() got an unexpected keyword argument 'azimuthangle'
ryanpate@Ryans-MacBook-Pro desktop % sudo python3 mlb2.py
Chicago Cubs @ Miami Marlins
Traceback (most recent call last):
File "/Users/ryanpate/Desktop/mlb2.py", line 32, in
live_game = mlb.get_get_livedata(game_id)
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Mlb' object has no attribute 'get_get_livedata'
ryanpate@Ryans-MacBook-Pro desktop % sudo python3 mlb2.py
Chicago Cubs @ Miami Marlins
Traceback (most recent call last):
File "/Users/ryanpate/Desktop/mlb2.py", line 32, in
live_game = mlb.get_livedata(game_id)
^^^^^^^^^^^^^^^^
AttributeError: 'Mlb' object has no attribute 'get_livedata'
ryanpate@Ryans-MacBook-Pro desktop % sudo python3 mlb2.py
Chicago Cubs @ Miami Marlins
Traceback (most recent call last):
File "/Users/ryanpate/Desktop/mlb2.py", line 32, in
live_game = mlb.get_game(game_id)
^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/mlb_api.py", line 907, in get_game
return Game(**mlb_data.data)
^^^^^^^^^^^^^^^^^^^^^
File "", line 8, in init
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/models/game/game.py", line 43, in post_init
self.gamedata = GameData(**self.gamedata)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 20, in init
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/models/game/gamedata/gamedata.py", line 80, in post_init
self.venue = Venue(**self.venue)
^^^^^^^^^^^^^^^^^^^
File "", line 11, in init
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/mlbstatsapi/models/venues/venue.py", line 39, in post_init
self.location = Location(**self.location) if self.location else self.location
^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Location.init() got an unexpected keyword argument 'azimuthangle'

calling get_game_box_score in loop

I've attached a screenshot of my traceback, the issue is related to PlayerDictsPerson.init()

I call this function in my if name == main block, and then try to pass the boxscores list into a pd Dataframe after.
I am looping through a series of game Ids to try and accomplish this, which is the ["gamepk"] pandas Series
def get_box_scores(self): boxscores = [] for g in self.game_df["gamepk"]: box = self.api.get_game_box_score(int(g)) boxscores.append(box) # all boxscores of season df return boxscores
It works however if I do a static call like this,
Mlb().get_game_box_score(1234556)

Screenshot 2023-06-01 135422

Processing game_pk information: PlayDetails.__init__() got an unexpected keyword argument 'violation'

Note: I'm using the latest version of:
python-mlb-statsapi 0.5.16
MLB-StatsAPI 1.7.1

This function broke after the topperformers class update 2 weeks ago:

For some game_pk's the information returns as expected, but for a few(errors below) I'm receiving a PlayDetails.init() error, and I can't find that class in the repository:
PlayDetails.init() got an unexpected keyword argument 'violation'

Code:
def get_game_info(game_pk):
mlb = mlbstatsapi.Mlb()
try:
game = mlb.get_game(game_pk)
venue_id = game.gamedata.venue.id
venue_name = game.gamedata.venue.name
venue_lat = game.gamedata.venue.location.defaultcoordinates.latitude
venue_long = game.gamedata.venue.location.defaultcoordinates.longitude
venue_elevation = game.gamedata.venue.location.elevation
venue_surface = game.gamedata.venue.fieldinfo.turftype
return venue_id, venue_name, venue_lat, venue_long, venue_elevation, venue_surface
except Exception as e:
print(f"Error processing game_pk {game_pk}: {e}")
return "None", "None", "None", "None", "None", "None"

ERROR(For example processing 2023-06-03 game_pk's):
717885
Error processing game_pk 717885: PlayDetails.init() got an unexpected keyword argument 'violation'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.