### Install Development Dependencies Source: https://github.com/jldbc/pybaseball/blob/master/contributing.md Installs the package in editable mode for development purposes. ```bash pip install -e . ``` -------------------------------- ### Install pybaseball Source: https://github.com/jldbc/pybaseball/blob/master/README.md Installation methods for the pybaseball library using pip or the source repository. ```bash pip install pybaseball ``` ```bash git clone https://github.com/jldbc/pybaseball cd pybaseball pip install -e . ``` -------------------------------- ### Retrieve Pitching Stats by Date Range Source: https://github.com/jldbc/pybaseball/blob/master/docs/pitching_stats_range.md Use this function to fetch pitching data for a specific start and end date. If the end date is omitted, it defaults to the start date. ```python from pybaseball import pitching_stats_range # retrieve all players' pitching stats for the month of May, 2017 data = pitching_stats_range("2017-05-01", "2017-05-28") # retrieve pitching stats for only August 24, 2016 data = pitching_stats_range("2016-08-24",) ``` -------------------------------- ### GET /pitching_stats Source: https://github.com/jldbc/pybaseball/blob/master/README.md Retrieves league-wide season-level pitching data from FanGraphs. ```APIDOC ## GET /pitching_stats ### Description Retrieves league-wide season-level pitching data from FanGraphs for a specified range of seasons. ### Parameters #### Query Parameters - **start_season** (int) - Required - The starting season year. - **end_season** (int) - Required - The ending season year. ### Request Example from pybaseball import pitching_stats data = pitching_stats(2014, 2016) ``` -------------------------------- ### Get Salaries Data Source: https://github.com/jldbc/pybaseball/blob/master/docs/lahman.md Fetches salary data for players by year. ```python salaries = salaries() ``` -------------------------------- ### Retrieve Pitching Statistics Source: https://github.com/jldbc/pybaseball/blob/master/docs/pitching_stats.md Examples of querying pitching data using various parameters like season ranges, qualification thresholds, and aggregation settings. ```python from pybaseball import pitching_stats # get all of this season's pitching data so far data = pitching_stats(2017) # retrieve data on only players who have pitched 50+ innings this year data = pitching_stats(2017, qual=50) # retrieve one row per player per season since 2000 (i.e.: who had the single most dominant season over this period?) data = pitching_stats(2010, 2016) # retrieve aggregate player statistics from 2000 to 2016 (i.e.: who has the most wins over this period?) data = pitching_stats(2010, 2016, ind=0) ``` -------------------------------- ### Initialize New Relic Agent Source: https://github.com/jldbc/pybaseball/blob/master/tests/pybaseball/data/team_pitching.html Initializes the New Relic agent with license key and application ID. This is typically done once at the start of the application. ```javascript window.NREUM||(NREUM={});NREUM.info = {"beacon":"bam.nr-data.net","errorBeacon":"bam.nr-data.net","licenseKey":"8c8459e5ba","applicationID":"2284934","transactionName":"ZlMHMEtVDUdTW0ZQC18ZJDdpGw9RU1xXSxcfVxYUQQ==","queueTime":0,"applicationTime":325,"agent":"","atts":""} ``` ```javascript (window.NREUM||(NREUM={})).loader_config={licenseKey:"8c8459e5ba",applicationID:"2284934"} ``` -------------------------------- ### Get Fielding Stats Source: https://github.com/jldbc/pybaseball/blob/master/docs/lahman.md Fetches fielding statistics for players by year. ```python fielding = fielding() ``` -------------------------------- ### Get All Pitching WAR Stats Source: https://github.com/jldbc/pybaseball/blob/master/docs/bwar_pitch.md Fetches all available fields from the war_daily_pitch table, including additional data not typically needed. Set `return_all` to True to use this. ```python # get war stats plus additional fields from this table data = bwar_pitch(return_all=True) ``` -------------------------------- ### Get Pitching Stats (Regular Season) Source: https://github.com/jldbc/pybaseball/blob/master/docs/lahman.md Fetches historical regular season pitching statistics for players by year. ```python pitching = pitching() ``` -------------------------------- ### Get Pitching Stats Bref for Current Season Source: https://github.com/jldbc/pybaseball/blob/master/docs/pitching_stats_bref.md Fetches all pitching data for the current calendar year's season. No arguments are needed. ```python from pybaseball import pitching_stats_bref # get all of this season's pitching data so far data = pitching_stats_bref() ``` -------------------------------- ### Get Pitching WAR Stats (Default) Source: https://github.com/jldbc/pybaseball/blob/master/docs/bwar_pitch.md Fetches a subset of WAR stats from Baseball Reference. Use this for standard use cases. ```python from pybaseball import bwar_pitch # get war stats from baseball reference data = bwar_pitch() ``` -------------------------------- ### Clone and Configure Repository Source: https://github.com/jldbc/pybaseball/blob/master/contributing.md Initializes the local repository and sets the upstream remote for tracking changes. ```bash git clone git@github.com:/pybaseball.git cd pybaseball git remote add upstream git@github.com:jldbc/pybaseball.git ``` -------------------------------- ### Get Team Batting Stats (Multiple Seasons) Source: https://github.com/jldbc/pybaseball/blob/master/docs/team_batting_bref.md Use this function to retrieve a dataframe of team-level batting stats for a specified team across a range of seasons. Ensure the `pybaseball` library is installed and imported. ```python from pybaseball import team_batting # get the Yankees (NYY) seasonal batting stats from 2010 through 2013 data = team_batting_bref('NYY', 2010, 2013) ``` -------------------------------- ### Get Statcast Pitcher Spin Data for a Single Day Source: https://github.com/jldbc/pybaseball/blob/master/docs/statcast_pitcher_spin.md Fetch Statcast pitcher spin data for a specific date by providing only the `start_dt`. The `end_dt` parameter should be omitted. ```python # get data for July 15th, 2017 data = statcast_pitcher_spin('2019-05-03', player_id = 543294) ``` -------------------------------- ### Get Park Data Source: https://github.com/jldbc/pybaseball/blob/master/docs/lahman.md Fetches data on baseball parks, including their IDs, names, aliases, and geographical locations. ```python parks = parks() ``` -------------------------------- ### Initialize Ad Serving Configuration Source: https://github.com/jldbc/pybaseball/blob/master/tests/pybaseball/data/team_fielding.html Configures Prebid.js with price granularity, bid settings, and targeting controls. Use this to set up Prebid's core functionalities before requesting bids. ```javascript var assertive_entityId = 'icEJRauCAzF8SFWAw'; var assertive_debug = 0; // append the query string 'assertiveYield=debug' or add this local storage entry 'localStorage.setItem("assertiveYield", "debug")' to enable dynamically var assertive_sampleRate = 1; // 1 = 100%, 0.2 = 20%... var assertive_timeout = null; var assertive_layout = null; var assertive_userState = null; assertive_timeout = PREBID_TIMEOUT; var googletag = googletag || {}; ggoogletag.cmd = googletag.cmd || []; ggoogletag.cmd.push(function () { googletag.pubads().disableInitialLoad(); }); pbjs.que.push(function () { pbjs.addAdUnits(adUnits); pbjs.setConfig({ priceGranularity: customConfigObject, enableSendAllBids: false, targetingControls: { alwaysIncludeDeals: true } }); pbjs.requestBids({ bidsBackHandler: sendAdserverRequest }); }); ``` -------------------------------- ### Get All-Star Full Data Source: https://github.com/jldbc/pybaseball/blob/master/docs/lahman.md Retrieves data for all-star rosters, including player, year, team, league, and position. ```python allstar = all_star_full() ``` -------------------------------- ### Initialize Environment and Fetch Team Data Source: https://github.com/jldbc/pybaseball/blob/master/EXAMPLES/comparing_legendary_teams.ipynb Imports necessary libraries and retrieves historical schedule and record data for specific MLB teams. ```python from pybaseball import schedule_and_record import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ```python yankees = schedule_and_record(1927, 'NYY') reds = schedule_and_record(1976, 'CIN') mariners = schedule_and_record(2001, 'SEA') ``` -------------------------------- ### Get Bwar Batting Stats Source: https://github.com/jldbc/pybaseball/blob/master/docs/bwar_bat.md Retrieves WAR batting statistics from Baseball Reference. You can choose to get all available fields or a subset of common columns. ```APIDOC ## GET /bwar_bat ### Description Retrieves Baseball Reference's WAR stats from its `war_daily_bat` table, along with some other data not included in the `batting_stats_bref` function. ### Method GET ### Endpoint /bwar_bat ### Parameters #### Query Parameters - **return_all** (bool) - Optional - Returns all fields from `war_daily_bat` table if True, returns only a subset of columns if False. Defaults to False. ### Request Example ```python from pybaseball import bwar_bat # Get default WAR stats data = bwar_bat() # Get WAR stats with all fields data = bwar_bat(return_all=True) ``` ### Response #### Success Response (200) - **data** (DataFrame) - A pandas DataFrame containing the WAR batting statistics. The columns included depend on the `return_all` parameter. #### Response Example ```json { "data": [ { "Player": "Player Name", "WAR": 5.2, "G": 150, "AB": 600 // ... other columns if return_all=True } ] } ``` ``` -------------------------------- ### Initialize Main Navigation Menu Source: https://github.com/jldbc/pybaseball/blob/master/tests/pybaseball/data/amateur_draft.html Sets up the main navigation toggle functionality, including analytics tracking and browser compatibility checks. ```javascript function sr_menus_setupMainNav_button_inline () { if (sr_detect_operaMini || !("classList" in document.createElement("_"))) { return false; } var nav_trigger = document.getElementById('nav_trigger'); if(!nav_trigger || nav_trigger.triggered) { return false; } nav_trigger.triggered = true; var nav = document.getElementById('nav'); var nav_trigger_a = nav_trigger.querySelector('a'); if (nav_trigger_a) { nav_trigger_a.setAttribute('href','javascript:void(0)'); nav_trigger.onclick = function (event) { nav.classList.toggle('open'); var is_open = nav.classList.contains('open'); if (is_open) { nav_trigger.classList.add('open'); } else { nav_trigger.classList.remove('open'); } event.preventDefault(); try { sr_record_analytics_event('MainNavButtonClick_inline',sr_record_directory(),sr_record_page());} catch(err) {} }; } return true; } sr_menus_setupMainNav_button_inline(); ``` -------------------------------- ### Get Pitching Stats by Season Source: https://github.com/jldbc/pybaseball/blob/master/README.md Retrieves league-wide season-level pitching data from FanGraphs. Returns one row per player per season with all available metrics. ```python from pybaseball import pitching_stats data = pitching_stats(2014,2016) data.columns Index(['IDfg', 'Season', 'Name', 'Team', 'Age', 'W', 'L', 'WAR', 'ERA', 'G', 'LA', 'Barrels', 'Barrel%', 'maxEV', 'HardHit', 'HardHit%', 'Events', 'CStr%', 'CSW%', 'xERA'], dtype='object', length=334) ``` -------------------------------- ### Initializing Projection Models Source: https://github.com/jldbc/pybaseball/blob/master/EXAMPLES/marcels_projections.ipynb Load the player database and instantiate the pitching and batting projection objects. ```python ppl = people() # for merging player names onto the projections ppl['Player'] = ppl['nameFirst'].str.cat(ppl['nameLast'], ' ') marcel_batting = MarcelProjectionsBatting() marcel_pitching = MarcelProjectionsPitching() ``` -------------------------------- ### Get Aggregate Batting Stats Over a Range Source: https://github.com/jldbc/pybaseball/blob/master/docs/batting_stats.md Retrieve aggregated batting statistics for players over a specified range of seasons. Set 'ind=0' to get a single row per player with their stats summed or averaged across the period. ```python from pybaseball import batting_stats data = batting_stats(2010, 2016, ind=0) ``` -------------------------------- ### GET /standings Source: https://github.com/jldbc/pybaseball/blob/master/README.md Retrieves division standings for a given season. ```APIDOC ## GET /standings ### Description Returns division standings for a given season. If the current season is chosen, it returns the most current standings; otherwise, it returns end-of-season standings. ### Parameters #### Query Parameters - **season** (int) - Required - The season year. ### Request Example from pybaseball import standings data = standings(2016) ``` -------------------------------- ### Initialize Assertive Analytics Client Source: https://github.com/jldbc/pybaseball/blob/master/tests/pybaseball/data/batting_leaders.html The client initializes by setting up local storage keys and tracking page views or session data. ```javascript !function(){function w(e){console.error(e);var t=new XMLHttpRequest;t.open("POST",N+"/error.php",!0),t.setRequestHeader("Content-Type","application/json"),t.send(JSON.stringify(e,Object.getOwnPropertyNames(e)))}try{var U="1.9",N="https://api.assertcom.de",t="assertive_analytics_",R=P(),T=[],S=[],n=n||localStorage.getItem("assertiveYield")&&-1!==localStorage.getItem("assertiveYield").indexOf("debug")||-1!==u("assertiveYield").indexOf("debug");function i(e){return t.concat(e)}function a(e,t){return localStorage.setItem(i(e),t)}function D(e){return localStorage.getItem(i(e))}function d(e){return localStorage.removeItem(i(e))}function E(e){e=i(e);var t=Number(localStorage.getItem(e))||0;return localStorage.setItem(e,++t),t}function e(e){if(E(e+"PageViewN"),"client"!==e||!D(e+"UUID")){if("session"===e){if(D(e+"UUID")&&D(e+"Timeout")&&Date.now()0&&d("lcp",[t[t.length-1]])}function o(e){e.getEntries().forEach(function(e){e.hadRecentInput||d("cls",[e])})}function a(e){if(e instanceof m&&!g){var n=Math.round(e.timeStamp),t={type:e.type};n<=p.now()?t.fid=p.now()-n:n>p.offset&&n<=Date.now()?(n-=p.offset,t.fid=p.now()-n):n=p.now(),g=!0,d("timing",["fi",n,t])}}function c(e){d("pageHide",[p.now(),e])}if(!("init"in NREUM&&"page_view_timing"in NREUM.init&&"enabled"in NREUM.init.page_view_timing&&NREUM.init.page_view_timing.enabled===!1)){var f,u,s,d=e("handle"),p=e("loader"),l=e(4),m=NREUM.o.EV;if("PerformanceObserver"in window&&"function"==typeof window.PerformanceObserver){f=new PerformanceObserver(r);try{f.observe({entryTypes:["paint"]})}catch(v){}u=new PerformanceObserver(i);try{u.observe({entryTypes:["largest-contentful-paint"]})}catch(v){}s=new PerformanceObserver(o);try{s.observe({type:"layout-shift",buffered:!0})}catch(v){}}}if("addEventListener"in document){var g=!1,y=["click","keydown","mousedown","pointerdown","touchstart"];y.forEach(function(e){document.addEventListener(e,a,!1)})}l(c)}},{}]}),3:[function(e,n,t){function r(e,n){if(!i)return!1;if(e!==i)return!1;if(!n)return!0;if(!o)return!1;for(var t=o.split("."),r=n.split("."),a=0;a0&&d("lcp",[t[t.length-1]])}function o(e){e.getEntries().forEach(function(e){e.hadRecentInput||d("cls",[e])})}function a(e){if(e instanceof m&&!g){var n=Math.round(e.timeStamp),t={type:e.type};n<=p.now()?t.fid=p.now()-n:n>p.offset&&n<=Date.now()?(n-=p.offset,t.fid=p.now()-n):n=p.now(),g=!0,d("timing",["fi",n,t])}}function c(e){d("pageHide",[p.now(),e])}if(!("init"in NREUM&&"page_view_timing"in NREUM.init&&"enabled"in NREUM.init.page_view_timing&&NREUM.init.page_view_timing.enabled===!1)){var f,u,s,d=e("handle"),p=e("loader"),l=e(4),m=NREUM.o.EV;if("PerformanceObserver"in window&&"function"==typeof window.PerformanceObserver){f=new PerformanceObserver(r);try{f.observe({entryTypes:["paint"]})}catch(v){}u=new PerformanceObserver(i);try{u.observe({entryTypes:["largest-contentful-paint"]})}catch(v){}s=new PerformanceObserver(o);try{s.observe({type:"layout-shift",buffered:!0})}catch(v){}}}if("addEventListener"in document){var g=!1,y=["click","keydown","mousedown","pointerdown","touchstart"];y.forEach(function(e){document.addEventListener(e,a,!1)})}l(c)}},{}]}),3:[function(e,n,t){function r(e,n){if(!i)return!1;if(e!==i)return!1;if(!n)return!0;if(!o)return!1;for(var t=o.split("."),r=n.split("."),a=0;a 3 && args[2] === 2 && typeof args[3] === 'boolean' ) { gdprApplies = args[3]; if (typeof args[2] === 'function') { args[2]('set', true); } } } else if (args[0] === 'ping') { var retr = { gdprApplies: gdprApplies, cmpLoaded: false, cmpStatus: 'stub' }; if (typeof args[2] === 'function') { args[2](retr); } } else { if(args[0] === 'init' && typeof args[3] === 'object') { args[3] = Object.assign(args[3], { tag_version: 'V2' }); } queue.push(args); } } function postMessageEventHandler(event) { var msgIsString = typeof event.data === 'string'; var json = {}; try { if (msgIsString) { json = JSON.parse(event.data); } else { json = event.data; } } catch (ignore) {} var payload = json.__tcfapiCall; if (payload) { window.__tcfapi( payload.command, payload.version, function(retValue, success) { var returnMsg = { __tcfapiReturn: { returnValue: retValue, success: success, callId: payload.callId } }; if (msgIsString) { returnMsg = JSON.stringify(returnMsg); } if (event && event.source && event.source.postMessage) { event.source.postMessage(returnMsg, '*'); } }, payload.parameter ); } } while (win) { try { if (win.frames[TCF_LOCATOR_NAME]) { cmpFrame = win; break; } } catch (ignore) {} if (win === window.top) { break; } win = win.parent; } if (!cmpFrame) { addFrame(); win.__tcfapi = tcfAPIHandler; win.addEventListener('message', postMessageEventHandler, false); } }; makeStub(); var uspStubFunction = function() { var arg = arguments; if (typeof window.__uspapi !== uspStubFunction) { setTimeout(function() { if (typeof window.__uspapi !== 'undefined') { window.__uspapi.apply(window.__uspapi, arg); } }, 500); } }; var checkIfUspIsReady = function() { uspTries++; if (window.__uspapi === uspStubFunction && uspTries < uspTriesLimit) { console.warn('USP is not accessible'); } else { clearInterval(uspInterval); } }; if (typeof window.__uspapi === 'undefined') { window.__uspapi = uspStubFunction; var uspInterval = setInterval(checkIfUspIsReady, 6000); } })(); ```