Showing posts with label sports. Show all posts
Showing posts with label sports. Show all posts

Wednesday, March 20, 2019

March Madness 2019

Last year I went into significant depth in developing a method for optimizing March Madness brackets. I'm now focused on other projects, but since the code is easily reused, I decided to run it again this year. Aside from some under-the-hood improvements, I used the same method, incorporating one tweak from my baseball prediction model: accounting for home field advantage. This lumps together the effect of players, referees, and fans collectively tilting the odds slightly in favor of the home team. In the 2018-2019 NCAA season, the win rate for home teams was 51.22%, so the home field confers a 1.22% win probability advantage to the home team. While minor, this does slightly affect bracket outcomes this year as deep as the Final Four. This also demonstrates how famously unpredictable this tournament is, as a small tweak can ripple outward with significant effects. For the sake of expedience, I skipped bracket polling and used the "centrist" parameter set from last year.

Here's a view of the regular season:



And a view of the postseason:



Like last year, I built my bracket in reverse, selecting the winner of each game as the team that has the highest probability of eventually winning the championship:

Round of 32       Round of 16       Round of 8      ...of 4   ...of 2  ...of 1
Duke              Duke                                                       
VCU                                 Duke                                     
Liberty           Liberty                                                    
Virginia Tech                                       Duke                     
Belmont           LSU                                                        
LSU                                 Michigan State                           
Minnesota         Michigan State                                             
Michigan State                                                Duke           
Gonzaga           Gonzaga                                                    
Syracuse                            Gonzaga                                  
Murray State      Florida State                                              
Florida State                                       Gonzaga                  
Buffalo           Buffalo                                                    
Texas Tech                          Buffalo                                  
Nevada            Michigan                                                   
Michigan                                                               Duke  
Virginia          Virginia                                                   
Oklahoma                            Virginia                                 
Wisconsin         UC Irvine                                                  
UC Irvine                                           Virginia                 
Villanova         Villanova                                                  
Old Dominion                        Tennessee                                
Cincinnati        Tennessee                                                  
Tennessee                                                     Houston        
UNC               UNC                                                        
Utah State                          UNC                                      
New Mexico State  New Mexico State                                           
Kansas                                              Houston                  
Iowa State        Houston                                                    
Houston                             Houston                                  
Wofford           Kentucky                                                   
Kentucky

Source code is stored on my GitHub.

Tuesday, October 2, 2018

MLB Postseason Predictions

Following up on my post "Predicting Baseball's Postseason", here is my prediction for the outcome of the 2018 MLB Postseason. I originally planned to develop two brackets, one optimized for percentage and the other for points (where the point value per correct prediction doubles with each successive round), but surprisingly the two systems produced the same result, and so I have only this one unified bracket to venture:


In the last month leading up to the playoffs, the clear outlier is the Brewers, who became very hot, culminating in a very strong finish, winning 11 of their last 12 games. Another surprising result comes from the Red Sox; they had the best regular-season record but finished relatively cold, losing 5 of their last 10, which quickly relegated them to the peloton of average teams.





Can the Brewers win their first-ever World Series? The odds look good for them this year. I ran Monte Carlo simulations with both "dynamic" and "static" Elo ratings, aka "hot" and "cold", and although they produced different rankings, the bracket outcomes were identical.

=====================================

Elo_K = 0.08;
Elo_k = 11;
h_f_a = 0.03;

Probability of winning World Series:
Elo_state: dynamic
Runtime: 10 sec
Simulations: 119140

1: Milwaukee Brewers, 42.66%
2: Colorado Rockies, 11.36%
3: Houston Astros, 8.53%
4: Chicago Cubs, 8.07%
5: Cleveland Indians, 7.57%
6: New York Yankees, 7.19%
7: Los Angeles Dodgers, 6.2%
8: Oakland Athletics, 4.5%
9: Boston Red Sox, 3.27%
10: Atlanta Braves, 0.65%

=====================================

Probability of winning World Series:
Elo_state: static
Runtime: 10 sec
Simulations: 121221

1: Milwaukee Brewers, 54.19%
2: Houston Astros, 8.6%
3: Los Angeles Dodgers, 8.09%
4: Cleveland Indians, 7.77%
5: Colorado Rockies, 7.04%
6: New York Yankees, 4.6%
7: Chicago Cubs, 4.3%
8: Boston Red Sox, 3%
9: Oakland Athletics, 2.02%
10: Atlanta Braves, 0.39%

Note: the predictions in this post were published at 2018-10-02 7:35 pm EST.

Sunday, September 23, 2018

Softball Optimization Revisited

About a year ago, I wrote about using a computer program to optimize softball lineups by putting players in their preferred fielding positions, to the greatest extent possible. In this post I'll discuss how my philosophy as team captain has evolved since then, and how I've matured my optimization program to match.



the team after the spring 2018 championship, a narrow loss
back row, left to right: Shayna, Evan, Daniel, Paul, Mike, Brett, Peter, Josh
front row, left to right: Buddy, Hannah, Emily, Kayla

My Philosophy on Ideal Lineups

What is the ideal strategy when making lineups? Two approaches I've tried are to maximize team strength, and to maximize player satisfaction. I've found that both approaches have issues if taken to the extreme: maximizing team strength marginalizes weaker players, and maximizing player satisfaction decreases overall team strength, e.g. if certain players are allowed to monopolize their few preferred positions.

Rather than optimizing solely for team strength or player satisfaction, I now believe the ideal strategy is to maximize team morale by simultaneously optimizing and balancing:
  1. satisfaction: players' satisfaction with their assignments
  2. strength: the team's probability of winning games
Why do I think morale is the right unifying value to be maximized? In short, because I think that's what people seek in sports teams, especially at the rec level. I also believe that explicitly trying to win at all costs often has the opposite effect, by burning players out, creating rifts, and generally causing disengagement. I think the best way to maximize team strength is to arrive at it by creating the right atmosphere, and that ultimately comes from morale. This sort of environment also fosters camaraderie and keeps people happy, a obviously desirable outcome that also further improves team performance.

So ideally, every player is assigned to a position they like, they perform well, and the team wins. This leads to individual and team satisfaction, and ultimately to positive morale. But how to optimize for this?

Quantifying Team Strength

Quantifying team strength requires additional information beyond where people like to play. It requires a more fundamental breakdown of which skills underpin the various positions, how the positions compare at skill requirements, and how individual players compare at these skills. It also requires knowledge of the strategic importance of the various positions, which are significantly uneven.

In our league, with the fast pace of the game and relatively low level of seriousness, it's far too cumbersome to maintain player stats, so I had to rule out an absolute assessment of skill such as fielding percentage of batting average. Instead, I settled on relative assessments. I may not know Player A's top throw speed, but I can venture with some confidence if it's higher or lower than Player B's. Similarly, I may not know how much throw strength is required to play shortstop, but I know it's higher than second base.

Bringing this together, I brainstormed seven fairly independent skills that I think underpin the various positions, in varying amounts. I then ranked every player by their aptitude for these skills, and every position by its requirements for these skills.

player and position rankings; pseudonyms used for anonymity

There's a good deal of subjectivity here, as the rankings rely on my informal and unscientific judgement, and it's also significantly subject to confirmation bias. On the other hand, this approach is simple, lightweight, and easy to maintain - in my opinion, the right fit for a rec league. But what about the strategic importance of each position? For example, it's clearly more valuable to have a strong pitcher than a strong catcher, since the pitcher has a much greater effect on the game outcome.

Weighting for Strategic Importance

For this, I use defensive outs generated by each position as a metric for strategic importance. I estimated that 2/3rds of our outs are unassisted, e.g. fly outs or line outs, and 1/3rd of our outs involved two positions, e.g. groundouts. Then, I estimated how many outs each position generates in a typical game, noting that the result should sum to ((2/3)*1 + (1/3)*2 players per out)*(3 outs per inning)*(6 innings per game) = 24 player-outs per game. I estimated these weights based on my league experience:

outs by position per game, estimated

Scoring a Lineup For Strength

My lineup generator reads the rankings shown above, and converts them to a matrix, where the strongest player for each skill is given a 1.0, and the weakest a 0.0, and so on with the positions. Linear interpolation is used for the players and positions between the extremes. Then, evaluating the strength of a lineup is fairly straightforward:
  1. Initialize team strength = 0
  2. Pick the first player on the field
  3. Take the dot product of the player's skill with the requirements for this position
  4. Multiply by the weight for this position
  5. Add this number to the team strength
  6. Repeat Steps 3-5 for all remaining players

Down-Selecting to a Single Lineup

From my prior work, I have a method of quantifying player satisfaction with assignments, based on survey results asking players to classify each position as "like", "neutral", or "dislike". From this, I generate a "satisfaction" score, 0-100%. For example, 93% might represent nine players liking their assignments, and one player disliking their assignment.

I believe that in the regular season, ideally, all players should sit the bench an equal amount. To this end, I have also incorporated manual constraints that allow me to constrain players to arbitrary positions and optimize the remaining positions.

What is the upper bound on team strength? The numbers used are dimensionless, so to approximate an upper bound, I temporarily discard all positional constraints and survey data, and seek only to optimize the strength score. I then take the best result as the upper bound, and use it to normalize subsequent lineup strength scores, also 0-100%.

Incorporating player preferences reduces team strength slightly by reducing the solution space, so there's a trade-off to be made. I think the sweet spot is enforcing a minimum satisfaction of around 90-95%, and then optimizing strength given this lower bound. Typically the survey has a fairly minor penalty on team strength of around 5-10%. This is due to players generally liking positions where they are strong, and disliking positions where they are weak. Constraints can have a more significant impact on strength, particularly when the benched player is relatively strong, by as much as 10-20%.

Generating a Sample Lineup

As an example, I'll show the process of generating a lineup using the sample rankings shown above. Suppose that Oscar and Alan have not sat the bench yet, Earl has asked to play second base due to a mild injury, and Marvin will be absent.

...

Constraints = {
                 'Oscar','Benched'
                 'Earl', 'Benched'
                 'Alan', 'Second base'
              };

players_absent = {
                    'Marvin'
                 };

...

Suppose I also set:

satisfaction_minimum  = 0.90; % 0-1

After evaluating about 1,500 random lineups per second for a few seconds, the optimized result is returned:

Satisfaction: 93%
Strength: 95%

Pitcher: Andrew
Catcher: Ryan
First base: Samuel
Second base: Earl
Shortstop: Igor
Third base: Isaac
Left field: Aaron
Left-center field: Vlad
Right-center field: Eddie
Right field: Ulrich

Benched:
Oscar
Alan

Note that the constraints were enforced on Oscar, Earl, and Alan, and that Marvin was dropped from the roster due to being absent. Due to the astronomically large solution space, it's dubious to extract high-level meaning from this lineup other than "it achieves the highest strength score for the specified minimum satisfaction". Still, by brute force, the program generates a lineup that seems to have some real thought behind it:

  • Andrew was assigned to pitcher due to his strong throw accuracy, preference for the position, and the added fact that it was otherwise unpopular in the survey
  • Igor was assigned to shortstop due to being the all-around strongest player, suitably assigned to the most important defensive position, which he fittingly prefers
  • Isaac, who has the strongest glove, was assigned to the "hot corner" of third base, a low-weighted position, but one he enjoys despite his weak throw accuracy
  • Stronger runners were assigned to the left-hand side of the outfield, which sees more line drives that the right side
  • Weaker runners were assigned to the right-hand side of the outfield, which sees more pop and fly balls than the left side

Saturday, August 25, 2018

Predicting Baseball's Postseason

Having recently tried my hand at numerically predicting the notoriously unpredictable March Madness basketball tournament, with moderate success, it was only natural that I would next attempt to predict the outcome of the MLB postseason, with baseball being dearer to my heart and its historical data being so plentiful. In this post I'll describe the groundwork I've done toward this goal so that I'll be ready to generate an optimized bracket when the postseason rolls around. Specifically I'll be focusing on Elo ratings and how I've tailored them on a team-by-team basis from first principles specifically for predicting MLB postseasons.

Identifying free parameters in Elo

Typically, implementations of the Elo rating system tune the K-factor only, which controls the speed at which ratings respond to performance. This is well-documented and values have been published for numerous competitive sports. However, focusing only the K-factor only ignores a few important considerations that improve predictive performance:
  • The relationship between rating difference and prediction certainty
  • The effect of home field advantage
More sophisticated models also take into account weather conditions, individual players (particularly pitchers), and other progressively finer factors. However, for the sake of keeping scope manageable, I'll be looking only at game logs showing the teams, home field, and game score. Everything will be inferred from this basic data.

Relationship between rating differences and prediction certainty

At the heart of the Elo system is the logistic function or "S-curve":


Logistic function; L = 1, k = 1, x_o = 0; source: Wikipedia


Equally-rated teams should have equal win probabilities, so x_o must be set to 0. Similarly, a team's probability cannot exceed 100%, so L must be set to 1. This leaves only a single free parameter, k, which controls the slope of the curve. Essentially it represents the slope of the S-curve, or the rate at which prediction confidence changes as the rating gap between the two teams widens.

The effect of home field advantage

Historically, teams win about 54.1% of their home games, and 45.9% of their away games. In other words, for evenly-matched teams, being home confers about a 4.1% win probability advantage, and the same amount as a disadvantage to the away team when compared to a theoretical neutral field.


Despite seasonal noise, this value has been remarkably consistent over the live-ball era. The modern game, which I'm arbitrarily defining as the last 10 years, falls neatly in line with this apparent historical constant:


Supposing home field advantage was set at 4.1%, when calculating Elo, I subtract this from the away team's probability of winning, and add it to the home team's win probability. This has the intuitive effect of making away wins slightly more consequential than home wins, and so on with losses.

Optimizing Elo for predictive accuracy

With all this in mind, I define an "Elo configuration" as a set of three values:
  1. K: controls the speed at which ratings adjust to performance
  2. k: controls the relationship between prediction confidence and rating difference
  3. h_f_a: controls how significant the home field advantage is
To optimize these parameters for predictive accuracy, my approach is:
  1. Pick a set of parameters that define an Elo configuration
  2. With this configuration, calculate day-by-day Elo ratings for all teams from the start of the live-ball era, 1920, to present
  3. For each year requested, extract the final game of each postseason series, representing a team being eliminated
  4. For each of these games, look up the regular-season-end Elo ratings for both teams, and predict the winner to be the one with the higher Elo rating
  5. Compare the prediction to the actual result
  6. Loop back to step 1 and repeat with another Elo configuration
  7. ...
  8. After running a sufficiently large number of Elo configurations, select the one that maximizes prediction accuracy over the requested time domain
A few other notes on my Elo calculation:
  • Elo mean is arbitrarily set at 1,000
  • Ratings are initialized in 1920, the start of the live-ball era
  • Ratings are carried over directly between seasons, without regressions or resets
  • Postseason games count toward Elo ratings, but only in subsequent seasons, i.e. the predictor uses a snapshot of Elo right before the requested postseason to generate predictions, and does not "peek ahead"
Each Elo configuration takes about 1 second to evaluate on my Dell Precision 5520, which is fairly time-expensive. I approached the optimization by first sweeping the three parameters over logarithmically-spaced ranges to get in the right ballpark (pun intended), then sweeping them over linearly-spaced ranges around the best configuration found in the prior step.

With this approach, a time domain window is necessary to optimize the Elo parameters. I consider two cases, and show the results below:

"Live-ball" era: 1920-present
  • K = 0.075
  • k = 11.0714
  • h_f_a = 0.017857
This configuration has an overall prediction accuracy of 70%. The breakdown by decade is:
  • 1920s: 100%
  • 1930s: 80%
  • 1940s: 80%
  • 1950s: 70%
  • 1960s: 67%
  • 1970s: 83%
  • 1980s: 68%
  • 1990s: 64%
  • 2000s: 69%
  • 2010s: 65%
An interesting trend here is that baseball seems to be becoming progressively less predictable, especially starting in the 1980s. Causes for this would be an interesting topic for research in and of itself.

"Modern" era: 2008-2017
  • K = 0.08
  • k = 11
  • h_f_a = 0.03
This configuration has an overall prediction accuracy of 68%. The breakdown by year is:
  • 2008: 86%
  • 2009: 71%
  • 2010: 57%
  • 2011: 71%
  • 2012: 66%
  • 2013: 44%
  • 2014: 67%
  • 2015: 78%
  • 2016: 56%
  • 2017: 89%
It's worth noting that using the "live ball" configuration in the prior section is very nearly as accurate, and the configuration values are very close. The "modern" configuration correctly predicts 56 of 82 matches, compared to 55 of 82 for the "live ball" configuration. So they're nearly interchangeable.

Snapshot of today's teams

What do these Elo configurations say about predicting the postseason? To get some intuition, let's look at how today's teams have fared in the last month:



The ratings here can be thought of as a metric for how well the teams would fare in the postseason if it were to start immediately, i.e. their postseason strength. What's interesting to note is how quickly teams can rise above the pack with a strong win streak or regress to mediocrity with a slump. For example, look at the Pirates, who went from 2nd best to 2nd worst in the last month due to a slump. My takeaway here is that postseason strength is highly dependent on "hotness" - that is, how well a team has been performing recently, as opposed to how well they've done all season. Here's the full breakdown:



Some historical perspectives



The 2017 postseason was an especially predictable one, in the sense that the teams that finished the regular season on top also generally finished the postseason on top, i.e. there were few upsets.

By comparison, look at 2013's postseason:



The Red Sox finished the regular season with mediocre strength, but caught fire and upset several teams on their way to win the World Series.

Plans

Once the 2018 postseason bracket is finalized (including the Wild Card games), I'll generate two bracket predictions: one optimized for points (where the value per correct prediction doubles with each successive round), and another optimized for percentage. For the point-optimized bracket, I'll use Monte Carlo simulations in conjunction with the Elo method developed here to account for the probabilistic difficulty of each team's path to the World Series.

Source code

Available on my GitHub, minus the scraper. 

Sunday, June 3, 2018

Swim the Charles!

Yesterday I raced in the Charles River One-Mile Swim, setting a new personal record with a time of 29:48. The water was 68-69 °F, just right for my 2-5 mm wetsuit. The water was surprisingly opaque - looking down in the water, I couldn't see my feet! Visually, it was like swimming in dark beer. In a way, it was pretty when the sun shined through splashed water, illuminating its deep golden-brown color. It's a bit like how urban haze can make sunsets more spectacular. The race organizers closely monitored water quality leading up to the event to ensure that levels of pollutants and bacteria were sufficiently low. The main issue is that rainfall causes runoff, temporarily degrading water quality. With no significant rain preceding the event, we were good to go.


crowd starting to trickle in

post-race merriment

coat hanger-like course shape

Here's how the results stacked up:



The race was staggered into two waves based on estimated finish time. I was placed into the first wave. Finishing with a very average time, I was slower than most in the first wave and faster than most in the second wave.


Where did people come from? Primarily Cambridge, Boston, Somerville, Brookline, and Belmont, in that order.



The biggest surprise I found in the data was how closely a person's bib number correlated to their race time. The trend is very clear in the plot above. In fact, the data indicates that a person's bib number is a significantly better predictor of their performance than any other factor, including their age and how far they traveled to the race. How interesting!

Looking to dig deeper, I performed a sexually bi-modal multi-linear regression for finish time based on age, bib number, and distance traveled to the race from each athlete's hometown using Google's Geocoding API. The error between predicted and actual times had a mean of about 0 minutes and standard deviation of about 3.9 minutes, which is not bad considering the sparseness of the data. I then ranked the results by "surprising-ness", taking the normalized regression error as a metric for how surprising a performance was:

Top 10 Surprising Performances
RankNameAge, yearsStateGenderTime, min.Reg. error, norm., %
1Kirkham Wood63CAM24.7126.4
2Rafael Irizarry46MAM26.3821.8
3Don Haut52MAM23.6220.1
4Donald Kaiser67MAM27.6420.0
5Darryl Starr49RIM24.0219.1
6Ursula Hester47COF29.7718.4
7Len Van Greuning50MAM22.1818.1
8Alex Meyer29MAM18.8117.9
9Louis Harwood28MAM29.9916.9
10Haruka Uchida22MAF23.7416.2

This is neat, but it's easily gamed, as a person could increase their "surprising-ness" significantly by registering at the last minute, making them appear statistically as more of an underdog, for example. To this end, I also characterized pure athletic performance by excluding bib number and hometown data, looking only at gender and age, which increased the error standard deviation to 5.6 minutes. In effect, this is similar to awarding prizes by division, but in a continuous sense rather than a discrete one with arbitrarily-defined brackets such as "Men 30-39".

Top 10 Athletic Performances
RankNameAge, yearsStateGenderTime, min.Reg. err., norm., %
1Alex Meyer29MAM18.8131.70
2Eric Nilsson30MAM18.9331.55
3Anton McKee24MAM19.7726.62
4Jessica Stokes41MAF22.1826.61
5Jen Olsen47MAF22.6326.39
6Len Van Greuning50MAM22.1826.14
7Kathleen Tetreault56MAF23.5225.39
8Gail Fricano44MAF22.7725.31
9Christophe Graefe44MAM22.0924.65
10Ed Baker39MAM21.9123.70

A major aspect of this swim is changing public opinion on the feasibility of the Charles as a public recreation area for swimming. A great deal of work has been to study, improve, and monitor its water quality. A 2016 report said that the prospect of a permanent swimming facility on the Charles "could potentially be feasible" and included this tantalizing photo below. It's a very intriguing possibility. Getting the river to a point where urban swimming is once again feasible would have significant benefits aside from enabling the creation of a forward-looking, yet retro swimming site.

artist's rendering of an urban swimming site on the Charles