gamedayapi

package module
v0.0.0-...-aaa2f39 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2020 License: MIT Imports: 16 Imported by: 3

README

gamedayapi - an mlb gameday api for go

gamedayapi is an API for interacting with MLB Gameday files using the go programming language.

Included is a simple command-line utility for fetching and saving Gameday files to your local filesystem.

Prerequisites: go

To build and run from the command line

In your go workspace, under a directory github.com/ecopony/

git clone git@github.com:ecopony/gamedayapi.git
cd gamedayapi
go build gameday/mlbgd.go

To fetch files for a single game:

./mlbgd game sea 2014-07-22

To fetch files for a full season for a team:

./mlbgd games-for-team-and-year sea 2014 

To fetch files for multiple seasons for a team:

./mlbgd games-for-team-and-years sea 2012 2013 2014

To fetch all games for all teams for a given year:

./mlbgd games-for-year 2014

To see a list of valid team codes for a given year:

./mlbgd valid-teams-for-year 2014

Using the API from your own go code

Import the API.

import "github.com/ecopony/gamedayapi"

To work with a game:

date, _ := time.Parse("2006-01-02", "2014-06-02")
game, _ := gamedayapi.GameFor("sea", date)
fmt.Println(game.Venue)
fmt.Println(game.HomeTeamName)
...

To operate on all games in a season:

gamedayapi.FetchByTeamAndYears("sea", []int{2012, 2013, 2014}, exampleOfNavigatingAllPitches)

func exampleOfNavigatingAllPitches(game *gamedayapi.Game) {
     log.Println(">>>> " + game.ID + " <<<<")
     for _, inning := range game.AllInnings().Innings {
          for _, atBat := range inning.AtBats() {
               for _, pitch := range atBat.Pitches {
                    log.Println("> " + pitch.Des)
               }
          }
     }
}

The function passed into FetchByTeamAndYears will be passed each game. This could be used to do analysis to save data to an alternate format or something else fun and entertaining and within the limitations of the usage restrictions.

Adding schedule files

The schedule files come from Retrosheet. Updated schedule files can be found here:

https://www.retrosheet.org/schedule/

Add them as needed to your local repo. Feel free to submit a PR for new files.

Usage Restriction

All documents fetched by this API clearly state: Copyright 2011 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

Which furthermore states: "The accounts, descriptions, data and presentation in the referring page (the “Materials”) are proprietary content of MLB Advanced Media, L.P (“MLBAM”). Only individual, non-commercial, non-bulk use of the Materials is permitted and any other use of the Materials is prohibited without prior written authorization from MLBAM. Authorized users of the Materials are prohibited from using the Materials in any commercial manner other than as expressly authorized by MLBAM."

Naturally, these terms are passed on to any who use this API. It is your responsibility to abide by them.

Documentation

Index

Constants

View Source
const (
	// GamedayHostname is the hostname of the MLB gameday site
	GamedayHostname = "http://gd2.mlb.com"

	// GamedayBaseURL is the base URL of the MLB gameday files
	GamedayBaseURL = "http://gd2.mlb.com/components/game/mlb"

	// GamedayBasePath is the base path of the MLB gameday files
	GamedayBasePath = "/components/game/mlb"
)

Variables

This section is empty.

Functions

func BaseCachePath

func BaseCachePath() string

BaseCachePath returns the local directory where gameday files are cached.

func FetchByTeamAndYear

func FetchByTeamAndYear(teamCode string, year int, fetchFunc FetchFunc)

FetchByTeamAndYear takes a year and a team code and will roll through all the games for that season. The fetchFunc will be passed each game for the year so clients can pull data, compute stats, etc.

func FetchByTeamAndYears

func FetchByTeamAndYears(teamCode string, years []int, fetchFunc FetchFunc)

FetchByTeamAndYears takes a collection of years and a team code and will concurrently roll through all the games for the seasons. The fetchFunc will be passed each game for the year so clients can pull data, compute stats, etc.

func OpeningAndFinalDatesForYear

func OpeningAndFinalDatesForYear(year int) (time.Time, time.Time)

OpeningAndFinalDatesForYear will inspect the schedule for the year and return dates for opening day and the final day of the season

func TeamsForYear

func TeamsForYear(year int) []string

TeamsForYear returns a list of valid team codes for the given year, sorted in alphabetical order.

Types

type AllInnings

type AllInnings struct {
	XMLName xml.Name `xml:"game"`
	AtBat   string   `xml:"atBat,attr"`
	Deck    string   `xml:"deck,attr"`
	Hole    string   `xml:"hole,attr"`
	Ind     string   `xml:"ind,attr"`
	Innings []Inning `xml:"inning"`
}

AllInnings is the representation of the innings/innings_all.xml file. From here, clients can iterate through all innings, at bats, and pitches in a game.

type AtBat

type AtBat struct {
	XMLName      xml.Name `xml:"atbat"`
	Num          string   `xml:"num,attr"`
	B            string   `xml:"b,attr"`
	S            string   `xml:"s,attr"`
	O            string   `xml:"o,attr"`
	StartTFS     string   `xml:"start_tfs,attr"`
	StartTFSZulu string   `xml:"start_tfs_zulu,attr"`
	Batter       string   `xml:"batter,attr"`
	Stand        string   `xml:"stand,attr"`
	BHeight      string   `xml:"b_height,attr"`
	Pitcher      string   `xml:"pitcher,attr"`
	PThrows      string   `xml:"p_throws,attr"`
	Des          string   `xml:"des,attr"`
	DesEs        string   `xml:"des_es,attr"`
	Event        string   `xml:"event,attr"`
	HomeTeamRuns string   `xml:"home_team_runs,attr"`
	AwayTeamRuns string   `xml:"away_team_runs,attr"`

	Pitches []Pitch `xml:"pitch"`
}

AtBat represents each at bat in an inning, and will have all the pitches thrown.

type Batter

type Batter struct {
	XMLName              xml.Name `xml:"batter"`
	ID                   string   `xml:"id,attr"`
	Name                 string   `xml:"name,attr"`
	NameDisplayFirstLast string   `xml:"name_display_first_last,attr"`
	Pos                  string   `xml:"pos,attr"`
	BO                   string   `xml:"bo,attr"`
	AB                   string   `xml:"ab,attr"`
	PO                   string   `xml:"po,attr"`
	R                    string   `xml:"r,attr"`
	A                    string   `xml:"a,attr"`
	BB                   string   `xml:"bb,attr"`
	SAC                  string   `xml:"sac,attr"`
	T                    string   `xml:"t,attr"`
	SF                   string   `xml:"sf,attr"`
	H                    string   `xml:"h,attr"`
	E                    string   `xml:"e,attr"`
	D                    string   `xml:"d,attr"`
	HBP                  string   `xml:"hbp,attr"`
	SO                   string   `xml:"so,attr"`
	HR                   string   `xml:"hr,attr"`
	RBI                  string   `xml:"rbi,attr"`
	LOB                  string   `xml:"lob,attr"`
	FLDG                 string   `xml:"fldg,attr"`
	SB                   string   `xml:"sb,attr"`
	CS                   string   `xml:"cs,attr"`
	SHR                  string   `xml:"s_hr,attr"`
	SRBI                 string   `xml:"s_rbi,attr"`
	SH                   string   `xml:"s_h,attr"`
	SBB                  string   `xml:"s_bb,attr"`
	SR                   string   `xml:"s_r,attr"`
	SSO                  string   `xml:"s_so,attr"`
	AVG                  string   `xml:"savg,attr"`
	GO                   string   `xml:"go,attr"`
	AO                   string   `xml:"ao,attr"`
}

Batter represents the batter elements in the boxscore.

type Batting

type Batting struct {
	XMLName  xml.Name `xml:"batting"`
	TeamFlag string   `xml:"team_flag,attr"`
	AB       string   `xml:"ab,attr"`
	R        string   `xml:"r,attr"`
	H        string   `xml:"h,attr"`
	D        string   `xml:"d,attr"`
	T        string   `xml:"t,attr"`
	HR       string   `xml:"hr,attr"`
	RBI      string   `xml:"rbi,attr"`
	BB       string   `xml:"bb,attr"`
	PO       string   `xml:"po,attr"`
	DA       string   `xml:"da,attr"`
	SO       string   `xml:"so,attr"`
	LOB      string   `xml:"lob,attr"`
	AVG      string   `xml:"avg,attr"`

	Batters []Batter `xml:"batter"`
}

Batting represents the batting elements in the boxscore.

type Bottom

type Bottom struct {
	XMLName xml.Name `xml:"bottom"`
	AtBats  []AtBat  `xml:"atbat"`
}

Bottom corresponds to the bottom half of an inning.

type Boxscore

type Boxscore struct {
	XMLName       xml.Name `xml:"boxscore"`
	AwayFName     string   `xml:"away_fname,attr"`
	AwayID        string   `xml:"away_id,attr"`
	AwayLoss      string   `xml:"away_loss,attr"`
	AwaySName     string   `xml:"away_sname,attr"`
	AwayTeamCode  string   `xml:"away_team_code,attr"`
	AwayWins      string   `xml:"away_wins,attr"`
	Date          string   `xml:"date,attr"`
	GameID        string   `xml:"game_id,attr"`
	GamePk        string   `xml:"game_pk,attr"`
	HomeFName     string   `xml:"home_fname,attr"`
	HomeID        string   `xml:"home_id,attr"`
	HomeLoss      string   `xml:"home_loss,attr"`
	HomeSName     string   `xml:"home_sname,attr"`
	HomeSportCode string   `xml:"home_sport_code,attr"`
	HomeTeamCode  string   `xml:"home_team_code,attr"`
	HomeWins      string   `xml:"home_wins,attr"`
	StatusInd     string   `xml:"status_ind,attr"`
	VenueID       string   `xml:"venue_id,attr"`
	VenueName     string   `xml:"venue_name,attr"`

	Linescore Linescore  `xml:"linescore"`
	Batting   []Batting  `xml:"batting"`
	Pitching  []Pitching `xml:"pitching"`
}

Boxscore is the representation of the boxscore.xml file.

type Epg

type Epg struct {
	Date            string `xml:"date,attr"`
	LastModified    string `xml:"last_modified,attr"`
	DisplayTimeZone string `xml:"display_time_zone,attr"`
	Games           []Game `xml:"game"`
}

Epg represents the epg.xml file that is in the root of each day's directory. It is essentially the schedule for the day.

func EpgFor

func EpgFor(date time.Time) *Epg

EpgFor returns a pointer to the Epg for the given day. The Epg is how the API finds the game directory for a game on a given day.

func (*Epg) GameForTeam

func (epg *Epg) GameForTeam(teamCode string) (*Game, error)

GameForTeam will return the first game for the given team based on the state of the Epg. Does not support doubleheaders. If support for doubleheaders is needed, use GamesForTeam.

func (*Epg) GamesForTeam

func (epg *Epg) GamesForTeam(teamCode string) ([]*Game, error)

GamesForTeam will return a collection of the team's games for the day. Supports days where the team played in a doubleheader.

type FetchFunc

type FetchFunc func(game *Game)

FetchFunc is a function passed into fetchers in order to operate on the games fetched.

type Game

type Game struct {
	AwayAPMP        string `xml:"away_ampm,attr"`
	AwayCode        string `xml:"away_code,attr"`
	AwayFileCode    string `xml:"away_file_code,attr"`
	AwayLoss        string `xml:"away_loss,attr"`
	AwayTeamCity    string `xml:"away_team_city,attr"`
	AwayTeamID      string `xml:"away_team_id,attr"`
	AwayTeamName    string `xml:"away_team_name,attr"`
	AwayTime        string `xml:"away_time,attr"`
	AwayTimezone    string `xml:"away_time_zone,attr"`
	AwayWin         string `xml:"away_win,attr"`
	CalendarEventID string `xml:"calendar_event_id,attr"`
	HomeAMPM        string `xml:"home_ampm,attr"`
	HomeCode        string `xml:"home_code,attr"`
	HomeFileCode    string `xml:"home_file_code,attr"`
	HomeLoss        string `xml:"home_loss,attr"`
	HomeTeamCity    string `xml:"home_team_city,attr"`
	HomeTeamID      string `xml:"home_team_id,attr"`
	HomeTeamName    string `xml:"home_team_name,attr"`
	HomeTime        string `xml:"home_time,attr"`
	HomeTimezone    string `xml:"home_time_zone,attr"`
	HomeWin         string `xml:"home_win,attr"`
	ID              string `xml:"id,attr"`
	Gameday         string `xml:"gameday,attr"`
	GamePk          string `xml:"game_pk,attr"`
	GameType        string `xml:"game_type,attr"`
	Status          string `xml:"status,attr"`
	TimeDate        string `xml:"time_date,attr"`
	Timezone        string `xml:"time_zone,attr"`
	Venue           string `xml:"venue,attr"`

	// GameDataDirectory does not always point to where the files are.
	// Use FetchableDataDirectory for building requests to gameday servers.
	GameDataDirectory string `xml:"game_data_directory,attr"`
	// contains filtered or unexported fields
}

Game is the top-level abstraction, the starting point for clients. A game is obtained using the GameFor function. From a game, clients can navigate to all data: Innings, Boxscore, etc.

func GameFor

func GameFor(teamCode string, date time.Time) (*Game, error)

GameFor will return a pointer to a game instance for the team code and date provided. This is the place to start for interacting with a game. Does not account for doubleheaders. Use GamesFor if doubleheader support is needed.

func GamesFor

func GamesFor(teamCode string, date time.Time) ([]*Game, error)

GamesFor will return a collection of pointers to games for the team code and date provided. Accounts for doubleheaders. In most cases, the collection will only have one game in it.

func (*Game) AllInnings

func (game *Game) AllInnings() *AllInnings

AllInnings fetches the inning/innings_all.xml file from gameday servers and fills in all the structs beneath, all the way down to the pitches.

func (*Game) Boxscore

func (game *Game) Boxscore() *Boxscore

Boxscore fetches the boxscore.xml file from the gameday servers and fills in all the structs beneath.

func (*Game) EagerLoad

func (game *Game) EagerLoad()

EagerLoad will eagerly load all of the files that the library pulls from the MLB gameday servers. Otherwise, files are lazily loaded as clients interact with the API.

func (Game) FetchableDataDirectory

func (game Game) FetchableDataDirectory() string

FetchableDataDirectory builds a data directory to the game files using the game's ID. GameDataDirectory is not always reliable (see epg on 2013-04-11 vs 2013-04-10 as an example).

func (*Game) HitChart

func (game *Game) HitChart() *HitChart

HitChart fetches the inning/inning_hit.xml file from gameday servers

func (*Game) IsFinal

func (game *Game) IsFinal() bool

IsFinal returns true if the game status is Final.

func (*Game) Players

func (game *Game) Players() *Players

Players fetches the players.xml file from gameday servers

func (*Game) Year

func (game *Game) Year() int

Year returns the year in which the game was played. Convenience method. Not a direct Gameday attribute.

type Hip

type Hip struct {
	XMLName xml.Name `xml:"hip"`
	Des     string   `xml:"des,attr"`
	X       string   `xml:"x,attr"`
	Y       string   `xml:"y,attr"`
	Batter  string   `xml:"batter,attr"`
	Pitcher string   `xml:"pitcher,attr"`
	Type    string   `xml:"type,attr"`
	Team    string   `xml:"team,attr"`
	Inning  string   `xml:"inning,attr"`
}

Hip represents the fragments in the HitChart

type HitChart

type HitChart struct {
	XMLName xml.Name `xml:"hitchart"`
	Hips    []Hip    `xml:"hip"`
}

HitChart is the representation of the innings/inning_hit.xml file.

type Inning

type Inning struct {
	XMLName  xml.Name `xml:"inning"`
	AwayTeam string   `xml:"away_team,attr"`
	HomeTeam string   `xml:"home_team,attr"`
	Next     string   `xml:"next,attr"`
	Num      string   `xml:"num,attr"`

	Top    Top    `xml:"top"`
	Bottom Bottom `xml:"bottom"`
}

Inning represents the inning structure in the innings/innings_all.xml file.

func (*Inning) AtBats

func (inning *Inning) AtBats() []AtBat

AtBats returns all at bats from the inning level. A convenience method to save clients from having to deal with the Top and Bottom halves.

type InningLineScore

type InningLineScore struct {
	XMLName xml.Name `xml:"inning_line_score"`
	Away    string   `xml:"away,attr"`
	Home    string   `xml:"home,attr"`
	Inning  string   `xml:"inning,attr"`
}

InningLineScore represents the individual innings in the linescore.

type Linescore

type Linescore struct {
	XMLName      xml.Name `xml:"linescore"`
	AwayTeamRuns string   `xml:"away_team_runs,attr"`
	HomeTeamRuns string   `xml:"home_team_runs,attr"`

	InningLineScores []InningLineScore `xml:"inning_line_score"`
}

Linescore represents the linescore under the boxscore, not the individual linescore.xml file.

type Pitch

type Pitch struct {
	XMLName        xml.Name `xml:"pitch"`
	ID             string   `xml:"id,attr"`
	Type           string   `xml:"type,attr"`
	Des            string   `xml:"des,attr"`
	DesEs          string   `xml:"des_es,attr"`
	TFS            string   `xml:"tfs,attr"`
	TFSZulu        string   `xml:"tfs_zulu,attr"`
	X              string   `xml:"x,attr"`
	Y              string   `xml:"y,attr"`
	SvID           string   `xml:"sv_id,attr"`
	StartSpeed     string   `xml:"start_speed,attr"`
	EndSpeed       string   `xml:"end_speed,attr"`
	SzTop          string   `xml:"sz_top,attr"`
	SzBottom       string   `xml:"sz_bot,attr"`
	PFXX           string   `xml:"pfx_x,attr"`
	PFXZ           string   `xml:"pfx_z,attr"`
	PX             string   `xml:"px,attr"`
	PZ             string   `xml:"pz,attr"`
	X0             string   `xml:"x0,attr"`
	Y0             string   `xml:"y0,attr"`
	Z0             string   `xml:"z0,attr"`
	VX0            string   `xml:"vx0,attr"`
	VY0            string   `xml:"vy0,attr"`
	VZ0            string   `xml:"vz0,attr"`
	AX             string   `xml:"ax,attr"`
	AY             string   `xml:"ay,attr"`
	AZ             string   `xml:"az,attr"`
	BreakY         string   `xml:"break_y,attr"`
	BreakAngle     string   `xml:"break_angle,attr"`
	BreakLength    string   `xml:"break_length,attr"`
	PitchType      string   `xml:"pitch_type,attr"`
	TypeConfidence string   `xml:"type_confidence,attr"`
	Zone           string   `xml:"zone,attr"`
	Nasty          string   `xml:"nasty,attr"`
	SpinDir        string   `xml:"spin_dir,attr"`
	SpinRate       string   `xml:"spin_rate,attr"`
	CC             string   `xml:"cc,attr"`
	MT             string   `xml:"mt,attr"`
}

Pitch represents the pitch fragments in inning/innings_all.xml

type Pitcher

type Pitcher struct {
	XMLName              xml.Name `xml:"pitcher"`
	ID                   string   `xml:"id,attr"`
	Name                 string   `xml:"name,attr"`
	NameDisplayFirstLast string   `xml:"name_display_first_last,attr"`
	Pos                  string   `xml:"pos,attr"`
	Out                  string   `xml:"out,attr"`
	BF                   string   `xml:"bf,attr"`
	ER                   string   `xml:"er,attr"`
	R                    string   `xml:"r,attr"`
	H                    string   `xml:"h,attr"`
	SO                   string   `xml:"so,attr"`
	HR                   string   `xml:"hr,attr"`
	BB                   string   `xml:"bb,attr"`
	NP                   string   `xml:"np,attr"`
	S                    string   `xml:"s,attr"`
	W                    string   `xml:"w,attr"`
	L                    string   `xml:"l,attr"`
	SV                   string   `xml:"sv,attr"`
	BS                   string   `xml:"bs,attr"`
	HLD                  string   `xml:"hld,attr"`
	SIP                  string   `xml:"s_ip,attr"`
	SH                   string   `xml:"s_h,attr"`
	SR                   string   `xml:"s_r,attr"`
	SER                  string   `xml:"s_er,attr"`
	SBB                  string   `xml:"s_bb,attr"`
	SSO                  string   `xml:"s_so,attr"`
	ERA                  string   `xml:"era,attr"`
	Win                  string   `xml:"win,attr"`
	Note                 string   `xml:"note,attr"`
}

Pitcher represents the pitcher elements in the boxscore.

type Pitching

type Pitching struct {
	XMLName  xml.Name `xml:"pitching"`
	TeamFlag string   `xml:"team_flag,attr"`
	Out      string   `xml:"out,attr"`
	H        string   `xml:"h,attr"`
	R        string   `xml:"r,attr"`
	ER       string   `xml:"er,attr"`
	BB       string   `xml:"bb,attr"`
	SO       string   `xml:"so,attr"`
	HR       string   `xml:"hr,attr"`
	BF       string   `xml:"bf,attr"`
	ERA      string   `xml:"era,attr"`

	Pitchers []Pitcher `xml:"pitcher"`
}

Pitching represents the pitching elements in the boxscore.

type Player

type Player struct {
	XMLName          xml.Name `xml:"player"`
	ID               string   `xml:"id,attr"`
	First            string   `xml:"first,attr"`
	Last             string   `xml:"last,attr"`
	Num              string   `xml:"num,attr"`
	Boxname          string   `xml:"boxname,attr"`
	Rl               string   `xml:"rl,attr"`
	Bats             string   `xml:"bats,attr"`
	Position         string   `xml:"position,attr"`
	CurrentPosition  string   `xml:"current_position,attr"`
	Status           string   `xml:"status,attr"`
	TeamAbbrev       string   `xml:"team_abbrev,attr"`
	TeamID           string   `xml:"team_id,attr"`
	ParentTeamAbbrev string   `xml:"parent_team_abbrev,attr"`
	ParentTeamID     string   `xml:"parent_team_id,attr"`
	BatOrder         string   `xml:"bat_order,attr"`
	GamePosition     string   `xml:"game_position,attr"`
	Avg              string   `xml:"avg,attr"`
	HR               string   `xml:"hr,attr"`
	RBI              string   `xml:"rbi,attr"`
	Wins             string   `xml:"wins,attr"`
	Losses           string   `xml:"losses,attr"`
	ERA              string   `xml:"era,attr"`
}

Player is the player fragment in the players.xml file.

type Players

type Players struct {
	XMLName xml.Name `xml:"game"`
	Date    string   `xml:"date,attr"`
	Teams   []Team   `xml:"team"`
}

Players is the representation of the players.xml file.

type Team

type Team struct {
	XMLName xml.Name `xml:"team"`
	Type    string   `xml:"type,attr"`
	ID      string   `xml:"id,attr"`
	Name    string   `xml:"name,attr"`
	Players []Player `xml:"player"`
}

Team is the team fragment in the players.xml file.

type Top

type Top struct {
	XMLName xml.Name `xml:"top"`
	AtBats  []AtBat  `xml:"atbat"`
}

Top corresponds to the top half of an inning.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL