NBA Betting App with AI Prediction
Below is a Python implementation of a betting app that uses AI to predict NBA game outcomes. This app combines historical data analysis with machine learning to suggest high-probability bets.
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import requests
from datetime import datetime, timedelta
import streamlit as st
# API keys and configurations (in a real app, these would be environment variables)
NBA_API_KEY = "your_nba_api_key" # Replace with actual API key
ODDS_API_KEY = "your_odds_api_key" # Replace with actual API key
class NBABettingApp:
def __init__(self):
self.model = None
self.features = ['home_win_pct', 'away_win_pct', 'home_last5', 'away_last5',
'home_pts_avg', 'away_pts_avg', 'home_def_rating', 'away_def_rating']
self.target = 'home_team_win'
self.load_data()
self.train_model()
def load_data(self):
"""Load historical NBA data (in a real app, this would come from an API/database)"""
try:
# Try to load from local cache
self.historical_data = pd.read_csv('nba_historical_data.csv')
except:
# Fallback to sample data
st.warning("Using sample data as historical data couldn't be loaded")
self.historical_data = self._generate_sample_data()
def _generate_sample_data(self):
"""Generate sample data for demonstration purposes"""
np.random.seed(42)
num_games = 1000
data = {
'home_win_pct': np.random.uniform(0.2, 0.8, num_games),
'away_win_pct': np.random.uniform(0.2, 0.8, num_games),
'home_last5': np.random.uniform(0.0, 1.0, num_games),
'away_last5': np.random.uniform(0.0, 1.0, num_games),
'home_pts_avg': np.random.uniform(90, 120, num_games),
'away_pts_avg': np.random.uniform(90, 120, num_games),
'home_def_rating': np.random.uniform(90, 115, num_games),
'away_def_rating': np.random.uniform(90, 115, num_games),
'home_team_win': np.random.randint(0, 2, num_games)
}
return pd.DataFrame(data)
def train_model(self):
"""Train the AI prediction model"""
X = self.historical_data[self.features]
y = self.historical_data[self.target]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
self.model = RandomForestClassifier(n_estimators=100, random_state=42)
self.model.fit(X_train, y_train)
# Evaluate model
y_pred = self.model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
st.sidebar.write(f"Model Accuracy: {accuracy:.2f}")
def fetch_current_games(self):
"""Fetch current NBA games (mock implementation)"""
# In a real app, this would call the NBA API
today = datetime.now().strftime('%Y-%m-%d')
games = [
{'id': 1, 'home_team': 'Lakers', 'away_team': 'Warriors', 'date': today},
{'id': 2, 'home_team': 'Celtics', 'away_team': 'Bucks', 'date': today},
{'id': 3, 'home_team': 'Nets', 'away_team': '76ers', 'date': today}
]
return games
def fetch_team_stats(self, team_name):
"""Fetch team statistics (mock implementation)"""
# In a real app, this would call the NBA API
stats = {
'win_pct': np.random.uniform(0.3, 0.7),
'last5': np.random.uniform(0.2, 0.8),
'pts_avg': np.random.uniform(100, 115),
'def_rating': np.random.uniform(100, 110)
}
return stats
def fetch_odds(self, game_id):
"""Fetch betting odds (mock implementation)"""
# In a real app, this would call an odds API
return {
'home_odds': np.random.choice([-110, -120, -150, +110, +120]),
'away_odds': np.random.choice([-110, -120, -150, +110, +120]),
'over_under': np.random.uniform(200, 230)
}
def predict_game_outcome(self, home_stats, away_stats):
"""Use AI model to predict game outcome"""
input_data = {
'home_win_pct': home_stats['win_pct'],
'away_win_pct': away_stats['win_pct'],
'home_last5': home_stats['last5'],
'away_last5': away_stats['last5'],
'home_pts_avg': home_stats['pts_avg'],
'away_pts_avg': away_stats['pts_avg'],
'home_def_rating': home_stats['def_rating'],
'away_def_rating': away_stats['def_rating']
}
input_df = pd.DataFrame([input_data])
home_win_prob = self.model.predict_proba(input_df)[0][1]
return home_win_prob
def calculate_expected_value(self, probability, odds):
"""Calculate expected value of a bet"""
if odds > 0:
payout = odds / 100
else:
payout = 100 / abs(odds)
ev = (probability * payout) - ((1 - probability) * 1)
return ev
def get_best_bets(self, games):
"""Analyze all games and return best bets"""
best_bets = []
for game in games:
home_stats = self.fetch_team_stats(game['home_team'])
away_stats = self.fetch_team_stats(game['away_team'])
odds = self.fetch_odds(game['id'])
home_win_prob = self.predict_game_outcome(home_stats, away_stats)
away_win_prob = 1 - home_win_prob
# Calculate expected values
home_ev = self.calculate_expected_value(home_win_prob, odds['home_odds'])
away_ev = self.calculate_expected_value(away_win_prob, odds['away_odds'])
# Determine best bet for this game
if home_ev > away_ev and home_ev > 0:
best_bets.append({
'game': f"{game['away_team']} @ {game['home_team']}",
'bet': f"{game['home_team']} to win",
'odds': odds['home_odds'],
'probability': home_win_prob,
'expected_value': home_ev
})
elif away_ev > 0:
best_bets.append({
'game': f"{game['away_team']} @ {game['home_team']}",
'bet': f"{game['away_team']} to win",
'odds': odds['away_odds'],
'probability': away_win_prob,
'expected_value': away_ev
})
# Sort by expected value
best_bets.sort(key=lambda x: x['expected_value'], reverse=True)
return best_bets
def main():
st.title("🏀 NBA Betting Assistant with AI")
st.write("Using machine learning to identify high-value bets")
app = NBABettingApp()
st.sidebar.header("Settings")
min_ev = st.sidebar.slider("Minimum Expected Value", 0.0, 0.5, 0.1, 0.05)
st.header("Today's Games")
games = app.fetch_current_games()
if st.button("Analyze Games"):
st.subheader("AI-Powered Bet Recommendations")
best_bets = app.get_best_bets(games)
# Filter by minimum EV
filtered_bets = [bet for bet in best_bets if bet['expected_value'] >= min_ev]
if not filtered_bets:
st.warning("No high-value bets found based on current criteria")
else:
for bet in filtered_bets:
with st.expander(f"🔍 {bet['game']}"):
st.write(f"**Recommended Bet:** {bet['bet']}")
st.write(f"**Odds:** {bet['odds']}")
st.write(f"**Win Probability:** {bet['probability']:.1%}")
st.write(f"**Expected Value:** {bet['expected_value']:.2f}")
# AI reasoning
st