Baseball Files

gameday

Python MLB GameDay API Basic Classes.

data:
    ForceRefresh            - always do http GET for XML file
    StatsYear               - current year
    YearList                - list of years with valid online GameDay XML
    TeamCode                - default team
    BasePath                - base path (pyBB install path)
    DataPath                - path for system data files
    SavePath                - path for saved XML files
    ListPath                - path for listing files
    SitePath                - path for HTML files (for /pub/bb)
    ImgsPath                - path for image files (for /pub/bb)
    HtmlPath                - path for HTML files (MSB, Boxscore, etc.)
    XsltPath                - path for XSLT files
    CssPrefix               - website path for CSS pages
    JsPrefix                - website path for JavaScript pages
    HostName                - "gd2.mlb.com"
    HostBase                - "/components/game/mlb"
    Leagues{}               - LeagueName [league_id]
    Divisions[]             - (league_id, division_id, text)
    TeamNames{}             - (TeamAbbr, TeamName, TeamPlace) [TeamCode]
    PitchTypes{}            - PitchName [code]
    BaseballPlayers[]       - array of PlayerDB entries
    BaseballPlayersDB       - global instance of PlayersDB

functions:
    BaseBallSeasons  (year)             - return season dates tuple (start, end)
    GetPlayer        (pid)              - get PlayerDB entry for player 'pid'
    FindPlayer       (name)             - find PlayerDB entry for player
    IsRegularGame    (gm)               - game is in regular season
    IsOtherGame      (gm)               - game is spring training or exhibition
    IsPostSeasonGame (gm)               - game is in post-season
    HasFinalStatus   (gm)               - game is in final status
    IsHomeGame       (gm,tc)            - game is a home game for team 'tc'
    IsAwayGame       (gm,tc)            - game is an away game for team 'tc'
    IsTeamGame       (gm,tc)            - game is a game for team 'tc'
    InningsTuple     (outs)             - return an IP tuple (innings,outs)
    AVG              (bstats)           - batting average
    OBP              (bstats)           - on-base percentage
    SLG              (bstats)           - slugging percentage
    CalculateOutsERA (outs,er)          - earned run average
    WinPercent       (w,l)              - win percentage
    GamesBack        (a, b)             - games back a from b tuples (wins, losses)
    SafeDivide       (a, b)             - error-free divide a/b; return 0 if error
    SafePercentage   (a, b)             - error-free percentage; return 0 if error
    StrPct           (n)                - convert n to "batting avg" string
    Str2Int          (s [,nz])          - convert string to int
    Str2Long         (s [,nz])          - convert string to long
    Str2Float        (s [,nz])          - convert string to float
    StrFlatten       (name)             - force lowercase; replace spaces with underbars.
    Zulu2Date        (s)                - convert Zulu Date string to datetime
    FilenameSuffix   (fn, suffix)       - insert filename suffix
    domGetElement    (elem, name)       - return the (single) DOM element
    domGetElementZ   (elem, name)       - return the (single) DOM element (or None)
    domGetElement1   (elem, name)       - return first DOM element (or None)
    AddAttributes    (obj, elem, flds)  - Add XML DOM element attributes to an object
    GenerateHTMLFile (xml, xslt)        - generate HTML from XML

classes:
    GameDayXML                          - Game Day Base Class
    GameDayGameInfo                     - Game Day Game Base Class
    GameDayPlayer                       - Game Day Player Base Class
    GameDayPitcher (GameDayPlayer)      - Game Day Pitcher Base Class
    PlayersDB                           - PlayersDB Class
    BattingStats                        - Basic batting stats Class
    BatterStats (BattingStats)          - Batter batting stats Class

Developer@Sonnack.com
December 2011

PlayersDB BaseballPlayersDB

function AddAttributes

Add DOM element's attributes to an object's properties using a list of names.

function BaseBallSeasons

Baseball Seasons (2007-current) Start/End Dates.

Returns a Dictionary with Season Start and End Dates as well
as Start and End dates for the Twins. Dates surrounding the
All-Star Break are also included.

properties:
    first       - first day of the MLB season
    last        - last day of the MLB season (or today, if current season)
    min_first   - first day of the Twins' season
    min_last    - last day of the Twins' season (or today, if current season)
    post_first  - first day of post-season
    post_last   - last day of post-season
    asb_last    - last day of play before the All-Star Break
    asb_first   - first day of play after the All-Star Break
    asg         - date of All-Star Game
    current     - [current season only] today's date
    final       - [current season only] last day of the MLB season
    min_final   - [current season only] last day of the Twins' season

If the Dict is for the current season, the 'current' property
exists and contains the current date. The 'last' properties
also point to this date. To obtain the actual last dates for
the season, use the 'final' properties.

Known Seasons:
==============
2007: 04/01 - 10/01  (04/02 - 09/30)  {10/01 - 10/31}  [7/08, 7/10, 7/12]
2008: 03/25 - 09/30  (03/31 - 09/30)  {10/01 - 10/31}  [7/13, 7/15, 7/17]
2009: 04/05 - 10/06  (04/06 - 10/06)  {10/07 - 10/31}  [7/12, 7/14, 7/16]
2010: 04/04 - 10/03  (04/05 - 10/03)  {10/06 - 11/01}  [7/11, 7/13, 7/15]
2011: 03/31 - 09/28  (04/01 - 09/28)  {09/30 - 10/28}  [7/10, 7/12, 7/14]
2012: 03/28 - 10/03  (04/06 - 10/03)  {10/05 - 10/28}  [7/08, 7/10, 7/13]
2013: 04/01 - 09/29  (04/01 - 09/29)  {10/01 - 10/30}  [7/14, 7/16, 7/19]
2014: 03/22 - 09/28  (03/31 - 09/28)  {09/30 - 10/29}  [7/13, 7/15, 7/18]
2015: 04/05 - 10/04  (04/06 - 10/04)  {10/06 - 11/04}  [7/12, 7/14, 7/17]
2016: 04/03 - 10/02  (04/04 - 10/02)  {10/04 - 11/02}  [7/10, 7/12, 7/15]
2017: 04/02 - 10/01  (04/02 - 10/01)  {10/03 - 11/01}  [7/09, 7/11, 7/14]
2018: 03/29 - 10/01  (03/29 - 09/30)  {10/02 - 10/31}  [7/15, 7/17, 7/20]
2019: 03/28 - 09/29  (03/28 - 09/29)  {10/01 - 10/31}  [7/07, 7/09, 7/12]
2020: messed up!

function FilenameSuffix

Insert {suffix} into filename before the extension.

function FindPlayer

Get Player Record using Player Name.

function GenerateHTMLFile

Generate HTML File from XML.

Given an XML filename and the filename for an XSLT document, invoke the XSLT engine.

function GetPlayer

Get Player Record using Player ID.

function SafeDivide

function SafePercentage

function Str2Float

Exception-free convert string to float.

function Str2Int

Exception-free convert string to int.

function Str2Long

Exception-free convert string to long.

function Zulu2Date

Exception-free convert Zulu date string (2013-04-21T23:09:34Z) to a datetime.

function domGetElement

Get a single DOM element by name.

function domGetElement1

Get first DOM element by name (or None).

function domGetElementZ

Get a single DOM element by name (or None).

lambda AVG

lambda CalculateOutsERA

lambda GamesBack

lambda HasFinalStatus

lambda InningsTuple

lambda IsAwayGame

lambda IsHomeGame

lambda IsOtherGame

lambda IsPostSeasonGame

lambda IsRegularGame

lambda IsTeamGame

lambda OBP

lambda SLG

lambda StrFlatten

lambda StrPct

lambda WinPercent

type BatterStats

Batter Stats Accumulation Class (extends BattingStats).
Use this class to accumulate batting stats for a specific batter.

Note that there is a class property, a global BattingStats instance
that sums the batting stats of all BatterStats instances.

type BattingStats

Basic Batting Stats Accumulation Class.
Use this class to accumulate general batting stats.

properties:
    .pa     - Plate Appearances
    .ab     - At Bats
    .h      - Hits
    .d      - Doubles
    .t      - Triples
    .hr     - Home Runs
    .r      - Runs
    .rbi    - Runs Batted In
    .bb     - Base on Balls (Walk)
    .hbp    - Hit By Pitch
    .sf     - Sacrifice Fly
    .so     - Strike Outs
    .avg    - batting AVeraGe
    .obp    - On-Base Percentage
    .slg    - SLuGging percentage

methods:
    update(obj, batter)     - Add to stats using {batter}

    str(obj)                - String
    len(obj)                - Plate Appearances
    cmp(obj)                - Compare
    repr(obj)               - JSON (sort of)

type GameDayGameInfo

GameDay Game base Class.
An object instance that encapsulates a '<game>' DOM Element.

properties:
    .tag            "id"
    .gid            "gameday"
    .gtype          "game_type"
    .descr          "description"
    .league         "league"
    .day            "day"
    .time           "time"
    .ampm           "ampm"
    .tz             "time_zone"
    .innings        "scheduled_innings"
    .resumes        "resume_date"
    .game_pk        "game_pk"
    .gd_sw          "gameday_sw"
    .venue          "venue"
    .venueId        "venue_id"
    .awayId         "away_team_id"
    .awayCity       "away_team_city"
    .awayName       "away_team_name"
    .awayAbbr       "away_abbrev"
    .awayCode       "away_code"
    .awayNick       "away_file_code"
    .awayDiv        "away_division"
    .awayLg         "away_league_id"
    .awayWin        "away_win"
    .awayLoss       "away_loss"
    .awayGB         "away_games_back"
    .homeId         "home_team_id"
    .homeCity       "home_team_city"
    .homeName       "home_team_name"
    .homeAbbr       "home_abbrev"
    .homeCode       "home_code"
    .homeNick       "home_file_code"
    .homeDiv        "home_division"
    .homeLg         "home_league_id"
    .homeWin        "home_win"
    .homeLoss       "home_loss"
    .homeGB         "home_games_back"

methods:
    .brief_str()    - short string
    .long_str()     - long string
    str(obj)        - s/a .long_str()
    repr(obj)       - JSON (sort of)

type GameDayPitcher

GameDay Player base Class.
An object instance that encapsulates a '<pitcher>' DOM Element.

properties:
    .era        "era"
    .w          "wins"
    .l          "losses"
    .sv         "saves"
    .svo        "svo"

methods:
    str(obj)                - String
    repr(obj)               - JSON (sort of)

type GameDayPlayer

GameDay Player base Class.
An object instance that encapsulates a '<player>' DOM Element.

properties:
    .pid        "id"
    .fname      "first"
    .lname      "last"
    .pnmbr      "number"

methods:
    .fullname()
    str(obj)                - String
    repr(obj)               - JSON (sort of)

type GameDayXML

GameDay XML Data Fetch Base Class.

Implements the http fetch of the XML document from the MLB GameDay site.

Global properties:
    .UseCache       - check cache for XML file
    .UseDatabase    - check Database for XML file

Properties:
    .url            - URL object
    .filebase       - GameDay files base path
    .hostpath       - http URL path
    .savename       - XML filename
    .txt            - http response text
    .xml            - XML DOM object
    .statusCode     - http response code
    .statusText     - http response message
    .headers        - dict of response headers

Methods:
    .filename()     - XML document filename
    .pathname()     - http sub-directory
    .refresh()      - re-download XML document
    .save_xml()     - save dowloaded XML document to disk
    .save_html()    - make HTML using XSLT on saved XML document
    str(obj)        - URL
    len(obj)        - length of XML text
    repr(obj)       - JSON (sort of)

type PlayersDB

Baseball Players Database Class.