Final Proj

Question at Hand

Ever heard about the famed “home field advantage” in sports? It’s a phrase thrown around a lot, and rightly so—it holds a certain mystique. In my data research within the NFL, I’m diving deep into this concept to investigate whether there’s any truth behind it, especially in the realm of betting. The big question: just how accurate are Vegas odds when it comes to predicting outcomes based on home team advantage? My hypothesis is that Vegas is going to be extremely accurate, and there may be a very small home field advantage, if any. I’m out to uncover whether home teams not only hold the edge but perhaps even surpass Vegas predictions. Armed with a comprehensive dataset spanning every NFL game ever played, inclusive of game spreads, scores, venue types (indoor, outdoor, retractable), and team distinctions between home and away, my aim is to scrutinize the numbers. What’s intriguing is that if this “home field advantage” holds true, I will test the theory firsthand putting my money on the line based on the insights drawn from this exploration.

Loading in the Data

library(tidyverse)
Warning: package 'forcats' was built under R version 4.3.2
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(rvest)
Warning: package 'rvest' was built under R version 4.3.2

Attaching package: 'rvest'

The following object is masked from 'package:readr':

    guess_encoding
library(lubridate)
library(httr) 
library(magrittr) 
Warning: package 'magrittr' was built under R version 4.3.2

Attaching package: 'magrittr'

The following object is masked from 'package:purrr':

    set_names

The following object is masked from 'package:tidyr':

    extract
library(XML)
Warning: package 'XML' was built under R version 4.3.2
library(ggplot2)
library(dplyr)
library(rvest)
library(tidyr)
library(tidytext)
Warning: package 'tidytext' was built under R version 4.3.2
library(stopwords)
Warning: package 'stopwords' was built under R version 4.3.2
library(udpipe)
Warning: package 'udpipe' was built under R version 4.3.2
library(textdata)
Warning: package 'textdata' was built under R version 4.3.2

Attaching package: 'textdata'

The following object is masked from 'package:httr':

    cache_info
nfl <- read_csv("https://myxavier-my.sharepoint.com/:x:/g/personal/bielskij_xavier_edu/EX5AbUny06dLnl-LpMhzWGcBt7evWqtNNMNF9g9Ea1DVsw?download=1")
New names:
Rows: 12400 Columns: 98
── Column specification
──────────────────────────────────────────────────────── Delimiter: "," chr
(38): game_id, schedule_week, team_home, team_away, team_favorite_id, s... dbl
(46): ...1, schedule_season, score_home, score_away, spread_favorite, o... lgl
(13): schedule_playoff, stadium_neutral, schedule_week_1, schedule_week... date
(1): schedule_date
ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
Specify the column types or set `show_col_types = FALSE` to quiet this message.
• `` -> `...1`
nfl<-nfl %>% 
  select(schedule_date,schedule_season,schedule_week,schedule_playoff,team_home,score_home,score_away,team_away,team_favorite_id,spread_favorite,over_under_line,stadium,stadium_neutral,stadium_type,weather_temperature,weather_wind_mph,weather_humidity,weather_detail,team_home_id,team_away_id,schedule_day,schedule_month,schedule_sunday,division_matchup,team_home_favorite,spread_home,spread_away,spread_type,spread_outlier,tie,team_winner,team_loser,team_home_result,team_away_result,team_winner_ats,score_total) %>% 
  filter(schedule_season>2001)
nfl <- nfl %>%
  mutate(team_winner_ats1 = substr(team_winner_ats, 1, 3),
         vegas = ifelse(team_favorite_id == team_winner, "right", "wrong"))

Data Dictionary

  • schedule_date: Date of the scheduled game

  • schedule_season: Year/season of the scheduled game

  • schedule_week: Week number of the season for the scheduled game

  • schedule_playoff: Indicates if the game is a playoff game

  • team_home: Home team participating in the game

  • score_home: Score of the home team

  • score_away: Score of the away team

  • team_away: Away team participating in the game

  • team_favorite_id: ID of the favored team

  • spread_favorite: Point spread favoring the favored team

  • over_under_line: Over/Under line for total points scored in the game

  • stadium: Name of the stadium where the game is played

  • stadium_neutral: Indicates if the stadium is neutral or not

  • stadium_type: Type of stadium (e.g., outdoor, indoor)

  • weather_temperature: Temperature during the game

  • weather_wind_mph: Wind speed during the game

  • weather_humidity: Humidity during the game

  • weather_detail: Details about weather conditions

  • team_home_id: ID of the home team

  • team_away_id: ID of the away team

  • schedule_day: Day of the scheduled game

  • schedule_month: Month of the scheduled game

  • schedule_sunday: Indicates if the game is scheduled on a Sunday

  • division_matchup: Indicates if it’s a division matchup

  • team_home_favorite: Indicates if the home team is the favorite

  • spread_home: Point spread favoring the home team

  • spread_away: Point spread favoring the away team

  • spread_type: Type of spread

  • spread_outlier: Indicates if the spread is an outlier

  • tie: Indicates if the game resulted in a tie

  • team_winner: Winning team

  • team_loser: Losing team

  • team_home_result: Result of the home team

  • team_away_result: Result of the away team

  • team_winner_ats: Winner against the spread

  • score_total: Total score of the game

  • team_winner_ats1: Just shows which team covered the spread without showing the spread

  • Vegas: Tells us if the favorite Vegas made was right or wrong

    Variable Minimum Median Mean Maximum
    score_total 3.00 43.00 44.12 106.00
    spread_favorite 26.50 -4.50 -5.38 0.00
    spread_home -26.50 -3.00 -2.45 18.50
    spread_away -18.50 3.00 2.45 26.50
    score_home 0.00 23.00 23.34 62.00
    score_away 0.00 20.00 20.77 59.00

    Home Field vs Vegas Spread

ggplot(data = nfl, aes(x = cut(spread_favorite, breaks = seq(-28, 28, by = 3.5)), 
                       y = score_home - score_away)) +
  geom_boxplot() +
  labs(title = "Home Field Advantage vs. Vegas Spread",
       x = "Point Spread Ranges (Favored Team)",
       y = "Actual Score Difference (Home Score - Away Score)") +
  scale_y_continuous(breaks = seq(-50, 50, by = 5))  # Adjust y-axis scale

The box plot illustrates home team performance when favored, categorized by point spread ranges of 3.5. One significant observation is that whenever the home team is favored by 24.5 points or more, they have never successfully covered the spread. This pattern strongly suggests that when Vegas heavily favors the home team, they consistently fall short of meeting those expectations. Additionally, a broader assessment indicates that home teams generally struggle to cover the spread when favored by 14 points or more. Across these scenarios, the median values consistently fall below the favoring spread, indicating that while covering such substantial spreads is possible, it’s less probable.

The focus here is on specific point spread ranges, particularly those representing closely contested games where the favored home team is within one possession of the away team. These ranges include (-7, -3.5] and (-3.5, 0], signifying scenarios with relatively narrow point spreads, hinting at close match odds.

These medians reflect the central measures within these specific spread ranges, offering insights into typical score differences. In the (-3.5, 0] range, the median of approximately one indicates highly competitive matches, where the actual score difference between home and away teams hovered around one in half of the games.

Contrastingly, the (-7, -3.5] range exhibits a median around three, slightly below the spread’s range. This suggests that in games with slightly wider point spreads, the median actual score difference was approximately three, indicating a moderate victory margin favoring the home team.

Ultimately, these medians provide valuable context regarding the competitiveness of games where the point spread is close or slightly wider, shedding light on the expected closeness or advantage of the home team in such scenarios. By examining all the medians across different spreads, a consistent trend emerges, indicating that the home team isn’t covering the spread as frequently as anticipated.

Is there an advantage for Home Teams if They Have an Indoor vs Outdoor Stadium

nfl <- nfl %>%
  filter(!is.na(stadium_type)) %>%
  mutate(stadium_type = factor(stadium_type))

ggplot(data = nfl, aes(x = stadium_type, y = score_home - score_away)) +
  geom_boxplot() +
  labs(title = "Stadium Type vs. Score Difference (Home Score - Away Score)",
       x = "Stadium Type",
       y = "Score Difference") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +  
  scale_y_continuous(breaks = seq(min(nfl$score_home - nfl$score_away),
                                  max(nfl$score_home - nfl$score_away), by = 4))  

In examining the relationship between Stadium Type and Score Difference for the home teams, a trend emerges suggesting a home team advantage across different stadium types. Surprisingly, the specific stadium type seems to have little influence on this advantage, as evidenced by similar median values across the stadium types. However, there are noteworthy differences observed, particularly with the outdoor stadiums. The boxplot reveals a wider spread in the score differences for losses in outdoor stadiums compared to indoor and retractable ones, indicating higher variability or unpredictability in outcomes for the losing home teams in outdoor stadiums. Additionally, the presence of more outliers in the outdoor stadiums suggests extreme or unusual instances of score differences.

Focusing on indoor stadiums, the boxplot portrays a symmetric distribution with the median aligning centrally within the box. This symmetry indicates a balanced spread of data around the median, suggesting that roughly half of the data lies above and half below the median score difference. This symmetry in the data distribution highlights a consistency in performance for the home team within indoor stadiums, where the median score difference leans in favor of the home team by an average of -3. This balance implies a more predictable or consistent performance for the home team within indoor stadiums compared to the other types, where outcomes might exhibit less variability or extreme differences.

Top Home Teams ATS since 2002

top_10teamsATS <- nfl %>%
  filter(!is.na(team_winner_ats1)) %>%
  count(team_winner_ats1) %>%
  arrange(desc(n)) %>%
  slice_head(n = 10)

top_10teamsATS
# A tibble: 10 × 2
   team_winner_ats1     n
   <chr>            <int>
 1 "ARI"              171
 2 "SF "              168
 3 "CHI"              165
 4 "NYJ"              162
 5 "CAR"              161
 6 "IND"              159
 7 "LVR"              154
 8 "WAS"              154
 9 "BUF"              152
10 "TEN"              152
#All of the teams ats
all_teams_ats <- nfl %>%
  filter(!is.na(team_winner_ats1)) %>%
  count(team_winner_ats1) 
all_teams_ats
# A tibble: 33 × 2
   team_winner_ats1     n
   <chr>            <int>
 1 ARI                171
 2 ATL                145
 3 BAL                139
 4 BUF                152
 5 CAR                161
 6 CHI                165
 7 CIN                148
 8 CLE                138
 9 DAL                 95
10 DEN                126
# ℹ 23 more rows

This data sheds light on the top-performing teams covering the spread since 2002. It’s fascinating because it highlights the top 10 teams that have consistently excelled at covering the spread, underscoring their dominance against the spread. One surprising discovery is that among these teams, only one managed to secure a Super Bowl victory during this period. It’s eye-opening because it challenges the common belief that winning championship team would also be dominant and cover spreads. This goes against the grain, especially considering the Patriots’ strong run with Tom Brady, a team that almost always secured a playoff spot. Another intriguing inclusion is the New York Jets being on this list, as they are often considered a big market team. All of these teams faced phases of difficulty or rebuilding, situations that likely making it hard on Vegas to make accurate odds. However, despite all of these teams challenges they had on the field, these teams consistently outperformed expectations against the spread, showcasing their resilience and ability to defy betting odds even during tough seasons.

Toughest Stadiums to Play in vs the Spread

specified_teams <- c("KC", "GB", "PIT", "SEA", "NE")


team_wins_ats <- nfl %>%
  filter(team_home_id %in% specified_teams & !is.na(team_winner_ats1)) %>%
  count(team_home_id, team_winner_ats1) %>%
  arrange(desc(n)) %>% 
  head(5)

ggplot(team_wins_ats, aes(x = reorder(team_home_id, n), y = n, fill = team_home_id)) +
  geom_bar(stat = "identity") +
  labs(
    title = "Total Wins Against the Spread (ATS) for Specific Home Teams",
    x = "Stadium Name",  # Update x-axis label
    y = "Total Wins ATS"
  ) +
  geom_text(aes(label = n), vjust = -0.5, size = 3) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_x_discrete(labels = c("Arrowhead Stadium", "Lambeau Field", "Heinz Field", "CenturyLink Field", "Gillette Stadium"))

The analysis presents an intriguing view into some of the most formidable stadiums in the NFL: Arrowhead Stadium (KC), Lambeau Field (GB), Heinz Field (PIT), CenturyLink Field (SEA), and Gillette Stadium (NE), showcasing their performance against Vegas spread lines. This comparison sheds light on the effectiveness of these home teams in covering the spread, offering a glimpse into their prowess in challenging atmospheres. Among these renowned venues, Gillette Stadium emerges as the most successful against Vegas expectations. Remarkably, during the 2002-2018 period, the teams associated with these stadiums exhibited remarkable success, despite not ranking in the top 10 ATS at home. This anomaly highlights Vegas’ astuteness in setting odds against these formidable teams, where even though these stadiums stand as renowned fortresses for their home teams, Vegas consistently managed to set sharp odds. The absence of these teams in the top 10 ATS at home further emphasizes the intricate nature of betting lines against such dominant teams.

How Accurate Vegas Favorites are

ggplot(data = nfl, aes(x = vegas))+
  geom_bar() +
  labs(title = "How Often Vegas Predictions are Correct",
       x = "Correctness",
       y = "Frequency")

The data paints a vivid picture of Vegas predictive mastery, revealing a staggering trend: teams favored by Vegas or predicted to win boast an almost 2-1 success rate. This standout statistic truly showcases the uncanny accuracy of Vegas odds, urging caution for anyone considering betting against these favored teams. It’s a wakeup call, highlighting the uphill battle for those favoring the underdogs in betting scenarios. This glimpse into Vegas’ expertise shines a light on the daunting task of outplaying the bookmakers’ set lines. The precision with which Vegas crafts these odds stands as a testament to their skill, making it a real challenge for bettors to outmaneuver or surpass the system. It’s a vivid reminder of the uncertainties inherent in gambling, where the precision of odds plays a pivotal role in determining betting outcomes.

Secondary Source

My secondary source aims to delve into team season reviews to gauge the prevailing sentiment—whether it leans toward possitivity or negativity. But here’s where it gets really intriguing: I’m honing in on the sentiment analysis of the top three teams that outshone others against the spread in the 2014 season. My hunch is that despite their stellar spread performance, these top dogs might have earned a positive sentiment analysis score. However, I suspect they might’ve fallen just short at season’s end or perhaps remained slightly above average throughout the season. This analysis aims to unearth the correlation between betting performance and the overall sentiment surrounding a team’s season performance.

# Filter data for the year 2014
nfl_2014 <- nfl %>%
  filter(schedule_season == 2014)


team_wins_ats_2014 <- nfl_2014 %>%
  filter(!is.na(team_winner_ats1)) %>%
  count(team_winner_ats1) %>%
  arrange(desc(n))


top_team_ats_2014 <- team_wins_ats_2014 %>%
  slice_head(n = 3)

top_team_ats_2014
# A tibble: 3 × 2
  team_winner_ats1     n
  <chr>            <int>
1 ARI                 17
2 CAR                 15
3 LAC                 14
library(rvest)
library(dplyr)
library(tidyr)
library(tidytext)
library(stopwords)
library(udpipe)
library(textdata)

# Scrape the Wikipedia page
nfl_url <- "https://en.wikipedia.org/wiki/2014_Arizona_Cardinals_season"
nfl_page <- read_html(nfl_url)

# Extract text from the Wikipedia page
card_text <- nfl_page %>%
  html_nodes(".mw-parser-output p") %>%  # Update this selector based on the HTML structure
  html_text() %>%
  paste(collapse = " ")

# Perform sentiment analysis
bing <- get_sentiments("bing")

# Tokenize the text and clean it for analysis
card_tokens <- card_text %>%
  data_frame(text = .) %>%
  unnest_tokens(word, text) %>%
  anti_join(stop_words)
Warning: `data_frame()` was deprecated in tibble 1.1.0.
ℹ Please use `tibble()` instead.
Joining with `by = join_by(word)`
# Count sentiment words
card_sentiment_counts <- card_tokens %>%
  inner_join(bing) %>%
  count(word, sentiment)
Joining with `by = join_by(word)`
positive_negative_counts <- card_sentiment_counts %>%
  filter(sentiment %in% c("positive", "negative")) %>%
  group_by(sentiment) %>%
  summarise(total = sum(n))



ggplot(positive_negative_counts, aes(x = sentiment, y = total, fill = sentiment)) +
  geom_bar(stat = "identity") +
  labs(
    title = "Arizona Cardnials Positive vs. Negative Sentiments",
    x = "Sentiment",
    y = "Total Count"
  ) +
  theme_minimal() +
  scale_fill_manual(values = c("positive" = "maroon", "negative" = "darkgrey"))

panthers_url <- "https://en.wikipedia.org/wiki/2014_Carolina_Panthers_season"
panthers_page <- read_html(panthers_url)

# Extract text from the Wikipedia page
panthers_text <- panthers_page %>%
  html_nodes(".mw-parser-output p") %>%
  html_text() %>%
  paste(collapse = " ")

# Perform sentiment analysis
bing <- get_sentiments("bing")

# Tokenize the text and clean it for analysis
panthers_tokens <- tibble(text = panthers_text) %>%
  unnest_tokens(word, text) %>%
  anti_join(stop_words)
Joining with `by = join_by(word)`
# Count sentiment words
panthers_sentiment_counts <- panthers_tokens %>%
  inner_join(bing) %>%
  count(word, sentiment)
Joining with `by = join_by(word)`
positive_negative_counts <- panthers_sentiment_counts %>%
  filter(sentiment %in% c("positive", "negative")) %>%
  group_by(sentiment) %>%
  summarise(total = sum(n))

# Visualize positive vs. negative sentiments
ggplot(positive_negative_counts, aes(x = sentiment, y = total, fill = sentiment)) +
  geom_bar(stat = "identity") +
  labs(
    title = "Caronlina Panthers Positive vs. Negative Sentiments",
    x = "Sentiment",
    y = "Total Count"
  ) +
  theme_minimal() +
  scale_fill_manual(values = c("positive" = "lightblue", "negative" = "darkgrey"))

# URL for the San Diego Chargers 2014 season Wikipedia page
chargers_url <- "https://en.wikipedia.org/wiki/2014_San_Diego_Chargers_season#:~:text=It%20was%20the%20second%20time,were%201%E2%80%935%20in%202003."

# Read HTML content from the Wikipedia page
chargers_page <- read_html(chargers_url)

# Extract text from the Wikipedia page
chargers_text <- chargers_page %>%
  html_nodes(".mw-parser-output p") %>%
  html_text() %>%
  paste(collapse = " ")

# Perform sentiment analysis
bing <- get_sentiments("bing")

# Tokenize the text and clean it for analysis
chargers_tokens <- tibble(text = chargers_text) %>%
  unnest_tokens(word, text) %>%
  anti_join(stop_words)
Joining with `by = join_by(word)`
# Count sentiment words
chargers_sentiment_counts <- chargers_tokens %>%
  inner_join(bing) %>%
  count(word, sentiment)
Joining with `by = join_by(word)`
positive_negative_counts <- chargers_sentiment_counts %>%
  filter(sentiment %in% c("positive", "negative")) %>%
  group_by(sentiment) %>%
  summarise(total = sum(n))

# Visualize positive vs. negative sentiments
ggplot(positive_negative_counts, aes(x = sentiment, y = total, fill = sentiment)) +
  geom_bar(stat = "identity") +
  labs(
    title = "San Diego Chargers Positive vs. Negative Sentiments",
    x = "Sentiment",
    y = "Total Count"
  ) +
  theme_minimal() +
  scale_fill_manual(values = c("positive" = "#0072CE", "negative" = "gold"))

So, here’s the scoop: I dug deep into the 2014 NFL season and spotlighted the top three spread superheroes: the Arizona Cardinals, Carolina Panthers, and San Diego Chargers. But, here’s the twist: we didn’t just stop at their game records. Nope! I looked at these teams season reviews to see if there’s a link between how the season reviews positivity/negativity scores are and how well they did against the spread. The Arizona Cardinals, despite their spread prowess, had a more negative vibe in their reviews. Hold on, though—here’s the plot twist. Their review was way shorter than the others, so we might not be getting the full picture there. Now, when we checked out the Carolina Panthers and San Diego Chargers reviews, it was all sunshine and rainbows! Their sentiment was overwhelmingly positive compared to the negative vibes. So, here’s where it gets really juicy: could this positivity actually connect with their amazing spread performance? Here’s my take: those top spread performers might just be the ones who sneakily fall a bit short not really a superbowl contender but having a wildcard’s team success. It’s like they’re the dark horses in the race, exceeding expectations but not quite taking the trophy leaving people the season review to be more positive.

Conclusion

This comprehensive data-driven investigation into the NFL’s “home field advantage” and Vegas predictions challenges initial assumptions. It uncovers key insights: heavily favored home teams often fall short of Vegas expectations, indicating struggles when odds heavily favor them. Narrower point spreads signal highly competitive matches, while slightly wider spreads hint at moderate home team advantages. Stadium type analysis shows consistent home team advantages across venues, with outdoor stadiums displaying more unpredictability. Surprisingly, top spread-performing teams didn’t always secure Super Bowl victories, challenging assumptions. Despite renowned stadiums, Vegas consistently set sharp odds against dominant teams, reflecting the complexity of betting lines. Teams favored by Vegas showcased a remarkable 2-1 success rate, emphasizing the challenge for underdog bettors. The correlation between sentiment and spread performance highlights intriguing connections. Overall, this analysis deepens our understanding of betting complexities, home field dynamics, and the intricate nature of sports betting’s unpredictability.