File size: 17,871 Bytes
cf62ef7 4ee078c cf62ef7 9147f5f cf62ef7 12c5ad7 cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 9147f5f cf62ef7 9147f5f cf62ef7 24ffe1d 9147f5f 24ffe1d 9147f5f cf62ef7 4ee078c cf62ef7 12c5ad7 cf62ef7 4ee078c cf62ef7 12c5ad7 cf62ef7 4ee078c cf62ef7 12c5ad7 4ee078c 24ffe1d 4ee078c cf62ef7 4ee078c cf62ef7 12c5ad7 cf62ef7 12c5ad7 cf62ef7 24ffe1d cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 24ffe1d cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 24ffe1d cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 8317e1e 4ee078c cf62ef7 4ee078c cf62ef7 12c5ad7 8317e1e 12c5ad7 cf62ef7 24ffe1d cf62ef7 4ee078c 12c5ad7 4ee078c cf62ef7 12c5ad7 4ee078c cf62ef7 12c5ad7 cf62ef7 4ee078c 24ffe1d 12c5ad7 9147f5f af07826 12c5ad7 8317e1e 12c5ad7 8317e1e 12c5ad7 8317e1e 12c5ad7 24ffe1d 12c5ad7 4ee078c 12c5ad7 4ee078c cf62ef7 4ee078c cf62ef7 4ee078c cf62ef7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 |
"""
Baseball statistics application with txtai and Streamlit.
Install txtai and streamlit (>= 1.23) to run:
pip install txtai streamlit
"""
import datetime
import math
import os
import random
import altair as alt
import numpy as np
import pandas as pd
import streamlit as st
from txtai.embeddings import Embeddings
class Stats:
"""
Base stats class. Contains methods for loading, indexing and searching baseball stats.
"""
def __init__(self):
"""
Creates a new Stats instance.
"""
# Load columns
self.columns = self.loadcolumns()
# Load stats data
self.stats = self.load()
# Load names
self.names = self.loadnames()
# Build index
self.vectors, self.data, self.embeddings = self.index()
def loadcolumns(self):
"""
Returns a list of data columns.
Returns:
list of columns
"""
raise NotImplementedError
def load(self):
"""
Loads and returns raw stats.
Returns:
stats
"""
raise NotImplementedError
def metric(self):
"""
Primary metric column.
Returns:
metric column name
"""
raise NotImplementedError
def vector(self, row):
"""
Build a vector for input row.
Args:
row: input row
Returns:
row vector
"""
raise NotImplementedError
def loadnames(self):
"""
Loads a name - player id dictionary.
Returns:
{player name: player id}
"""
# Get unique names
names = {}
rows = self.stats.sort_values(by=self.metric(), ascending=False)[["nameFirst", "nameLast", "playerID"]].drop_duplicates().reset_index()
for x, row in rows.iterrows():
# Name key
key = f"{row['nameFirst']} {row['nameLast']}"
key += f" ({row['playerID']})" if key in names else ""
if key not in names:
# Scale scores of top n players
exponent = 2 if ((len(rows) - x) / len(rows)) >= 0.95 else 1
# score = num seasons ^ exponent
score = math.pow(len(self.stats[self.stats["playerID"] == row["playerID"]]), exponent)
# Save name key - values pair
names[key] = (row["playerID"], score)
return names
def index(self):
"""
Builds an embeddings index to stats data. Returns vectors, input data and embeddings index.
Returns:
vectors, data, embeddings
"""
# Build data dictionary
vectors = {f'{row["yearID"]}{row["playerID"]}': self.transform(row) for _, row in self.stats.iterrows()}
data = {f'{row["yearID"]}{row["playerID"]}': dict(row) for _, row in self.stats.iterrows()}
embeddings = Embeddings(
{
"transform": self.transform,
}
)
embeddings.index((uid, vectors[uid], None) for uid in vectors)
return vectors, data, embeddings
def metrics(self, name):
"""
Looks up a player's active years, best statistical year and key metrics.
Args:
name: player name
Returns:
active, best, metrics
"""
if name in self.names:
# Get player stats
stats = self.stats[self.stats["playerID"] == self.names[name][0]]
# Build key metrics
metrics = stats[["yearID", self.metric()]]
# Get best year, sort by primary metric
best = int(stats.sort_values(by=self.metric(), ascending=False)["yearID"].iloc[0])
# Get years active, best year, along with metric trends
return metrics["yearID"].tolist(), best, metrics
return range(1871, datetime.datetime.today().year), 1950, None
def search(self, name=None, year=None, row=None, limit=10):
"""
Runs an embeddings search. This method takes either a player-year or stats row as input.
Args:
name: player name to search
year: year to search
row: row of stats to search
limit: max results to return
Returns:
list of results
"""
if row:
query = self.vector(row)
else:
# Lookup player key and build vector id
name = self.names.get(name)
query = f"{year}{name[0] if name else name}"
query = self.vectors.get(query)
results, ids = [], set()
if query is not None:
for uid, _ in self.embeddings.search(query, limit * 5):
# Only add unique players
if uid[4:] not in ids:
result = self.data[uid].copy()
result["link"] = f'https://www.baseball-reference.com/players/{result["nameLast"].lower()[0]}/{result["bbrefID"]}.shtml'
result["yearID"] = str(result["yearID"])
results.append(result)
ids.add(uid[4:])
if len(ids) >= limit:
break
return results
def transform(self, row):
"""
Transforms a stats row into a vector.
Args:
row: stats row
Returns:
vector
"""
if isinstance(row, np.ndarray):
return row
return np.array([0.0 if not row[x] or np.isnan(row[x]) else row[x] for x in self.columns])
class Batting(Stats):
"""
Batting stats.
"""
def loadcolumns(self):
return [
"birthMonth",
"yearID",
"age",
"height",
"weight",
"G",
"AB",
"R",
"H",
"1B",
"2B",
"3B",
"HR",
"RBI",
"SB",
"CS",
"BB",
"SO",
"IBB",
"HBP",
"SH",
"SF",
"GIDP",
"POS",
"AVG",
"OBP",
"TB",
"SLG",
"OPS",
"OPS+",
]
def load(self):
# Retrieve raw data from GitHub
players = pd.read_csv("https://raw.githubusercontent.com/chadwickbureau/baseballdatabank/master/core/People.csv")
batting = pd.read_csv("https://raw.githubusercontent.com/chadwickbureau/baseballdatabank/master/core/Batting.csv")
fielding = pd.read_csv("https://raw.githubusercontent.com/chadwickbureau/baseballdatabank/master/core/Fielding.csv")
# Merge player data in
batting = pd.merge(players, batting, how="inner", on=["playerID"])
# Require player to have at least 350 plate appearances.
batting = batting[((batting["AB"] + batting["BB"]) >= 350) & (batting["stint"] == 1)]
# Derive primary player positions
positions = self.positions(fielding)
# Calculated columns
batting["age"] = batting["yearID"] - batting["birthYear"]
batting["POS"] = batting.apply(lambda row: self.position(positions, row), axis=1)
batting["AVG"] = batting["H"] / batting["AB"]
batting["OBP"] = (batting["H"] + batting["BB"]) / (batting["AB"] + batting["BB"])
batting["1B"] = batting["H"] - batting["2B"] - batting["3B"] - batting["HR"]
batting["TB"] = batting["1B"] + 2 * batting["2B"] + 3 * batting["3B"] + 4 * batting["HR"]
batting["SLG"] = batting["TB"] / batting["AB"]
batting["OPS"] = batting["OBP"] + batting["SLG"]
batting["OPS+"] = 100 + (batting["OPS"] - batting["OPS"].mean()) * 100
return batting
def metric(self):
return "OPS+"
def vector(self, row):
row["TB"] = row["1B"] + 2 * row["2B"] + 3 * row["3B"] + 4 * row["HR"]
row["AVG"] = row["H"] / row["AB"]
row["OBP"] = (row["H"] + row["BB"]) / (row["AB"] + row["BB"])
row["SLG"] = row["TB"] / row["AB"]
row["OPS"] = row["OBP"] + row["SLG"]
row["OPS+"] = 100 + (row["OPS"] - self.stats["OPS"].mean()) * 100
return self.transform(row)
def positions(self, fielding):
"""
Derives primary positions for players.
Args:
fielding: fielding data
Returns:
{player id: (position, number of games)}
"""
positions = {}
for _, row in fielding.iterrows():
uid = f'{row["yearID"]}{row["playerID"]}'
position = row["POS"] if row["POS"] else 0
if position == "P":
position = 1
elif position == "C":
position = 2
elif position == "1B":
position = 3
elif position == "2B":
position = 4
elif position == "3B":
position = 5
elif position == "SS":
position = 6
elif position == "OF":
position = 7
# Save position if not set or player played more at this position
if uid not in positions or positions[uid][1] < row["G"]:
positions[uid] = (position, row["G"])
return positions
def position(self, positions, row):
"""
Looks up primary position for player row.
Arg:
positions: all player positions
row: player row
Returns:
primary player positions
"""
uid = f'{row["yearID"]}{row["playerID"]}'
return positions[uid][0] if uid in positions else 0
class Pitching(Stats):
"""
Pitching stats.
"""
def loadcolumns(self):
return [
"birthMonth",
"yearID",
"age",
"height",
"weight",
"W",
"L",
"G",
"GS",
"CG",
"SHO",
"SV",
"IPouts",
"H",
"ER",
"HR",
"BB",
"SO",
"BAOpp",
"ERA",
"IBB",
"WP",
"HBP",
"BK",
"BFP",
"GF",
"R",
"SH",
"SF",
"GIDP",
"WHIP",
"WADJ",
]
def load(self):
# Retrieve raw data from GitHub
players = pd.read_csv("https://raw.githubusercontent.com/chadwickbureau/baseballdatabank/master/core/People.csv")
pitching = pd.read_csv("https://raw.githubusercontent.com/chadwickbureau/baseballdatabank/master/core/Pitching.csv")
# Merge player data in
pitching = pd.merge(players, pitching, how="inner", on=["playerID"])
# Require player to have 20 appearances
pitching = pitching[(pitching["G"] >= 20) & (pitching["stint"] == 1)]
# Calculated columns
pitching["age"] = pitching["yearID"] - pitching["birthYear"]
pitching["WHIP"] = (pitching["BB"] + pitching["H"]) / (pitching["IPouts"] / 3)
pitching["WADJ"] = (pitching["W"] + pitching["SV"]) / (pitching["ERA"] + pitching["WHIP"])
return pitching
def metric(self):
return "WADJ"
def vector(self, row):
row["WHIP"] = (row["BB"] + row["H"]) / (row["IPouts"] / 3) if row["IPouts"] else None
row["WADJ"] = (row["W"] + row["SV"]) / (row["ERA"] + row["WHIP"]) if row["ERA"] and row["WHIP"] else None
return self.transform(row)
class Application:
"""
Main application.
"""
def __init__(self):
"""
Creates a new application.
"""
# Batting stats
self.batting = Batting()
# Pitching stats
self.pitching = Pitching()
def run(self):
"""
Runs a Streamlit application.
"""
st.title("⚾ Baseball Statistics")
st.markdown(
"""
This application finds the best matching historical players using vector search with [txtai](https://github.com/neuml/txtai).
Raw data is from the [Baseball Databank](https://github.com/chadwickbureau/baseballdatabank) GitHub project. Read [this
article](https://medium.com/neuml/explore-baseball-history-with-vector-search-5778d98d6846) for more details.
"""
)
self.player()
def player(self):
"""
Player tab.
"""
st.markdown("Match by player-season. Each player search defaults to the best season sorted by OPS or Wins Adjusted.")
# Get parameters
params = self.params()
# Category and stats
category = self.category(params.get("category"), "category")
stats = self.batting if category == "Batting" else self.pitching
# Player name
name = self.name(stats.names, params.get("name"))
# Player metrics
active, best, metrics = stats.metrics(name)
# Player year
year = self.year(active, params.get("year"), best)
# Display metrics chart
if len(active) > 1:
self.chart(category, metrics)
# Run search
results = stats.search(name, year)
# Display results
self.table(results, ["nameFirst", "nameLast", "teamID"] + stats.columns[1:] + ["link"])
# Save parameters
st.experimental_set_query_params(category=category, name=name, year=year)
def params(self):
"""
Get application parameters. This method combines URL parameters with session parameters.
Returns:
parameters
"""
# Get parameters
params = st.experimental_get_query_params()
params = {x: params[x][0] for x in params}
# Sync parameters with session state
if all(x in st.session_state for x in ["category", "name", "year"]):
# Copy session year if category and name are unchanged
params["year"] = str(st.session_state["year"]) if all(params.get(x) == st.session_state[x] for x in ["category", "name"]) else None
# Copy category and name from session state
params["category"] = st.session_state["category"]
params["name"] = st.session_state["name"]
return params
def category(self, category, key):
"""
Builds category input widget.
Args:
category: category parameter
key: widget key
Returns:
category component
"""
# List of stat categories
categories = ["Batting", "Pitching"]
# Get category parameter, default if not available or valid
default = categories.index(category) if category and category in categories else 0
# Radio box component
return st.radio("Stat", categories, index=default, horizontal=True, key=key)
def name(self, names, name):
"""
Builds name input widget.
Args:
names: list of all allowable names
Returns:
name component
"""
# Get name parameter, default to random weighted value if not valid
name = name if name and name in names else random.choices(list(names.keys()), weights=[names[x][1] for x in names])[0]
# Sort names for display
names = sorted(names)
# Select box component
return st.selectbox("Name", names, names.index(name), key="name")
def year(self, years, year, best):
"""
Builds year input widget.
Args:
years: active years for a player
year: year parameter
best: default to best year if year is invalid
Returns:
year component
"""
# Get year parameter, default if not available or valid
year = int(year) if year and year.isdigit() and int(year) in years else best
# Slider component
return int(st.select_slider("Year", years, year, key="year") if len(years) > 1 else years[0])
def chart(self, category, metrics):
"""
Displays a metric chart.
Args:
category: Batting or Pitching
metrics: player metrics to plot
"""
# Key metric
metric = self.batting.metric() if category == "Batting" else self.pitching.metric()
# Cast year to string
metrics["yearID"] = metrics["yearID"].astype(str)
# Metric over years
chart = (
alt.Chart(metrics)
.mark_line(interpolate="monotone", point=True, strokeWidth=2.5, opacity=0.75)
.encode(x=alt.X("yearID", title=""), y=alt.Y(metric, scale=alt.Scale(zero=False)))
)
# Create metric median rule line
rule = alt.Chart(metrics).mark_rule(color="gray", strokeDash=[3, 5], opacity=0.5).encode(y=f"median({metric})")
# Layered chart configuration
chart = (chart + rule).encode(y=alt.Y(title=metric)).properties(height=200).configure_axis(grid=False)
# Draw chart
st.altair_chart(chart + rule, theme="streamlit", use_container_width=True)
def table(self, results, columns):
"""
Displays a list of results as a table.
Args:
results: list of results
columns: column names
"""
if results:
st.dataframe(pd.DataFrame(results)[columns])
else:
st.write("Player-Year not found")
@st.cache_resource(show_spinner=False)
def create():
"""
Creates and caches a Streamlit application.
Returns:
Application
"""
return Application()
if __name__ == "__main__":
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Create and run application
app = create()
app.run()
|