Skip to content

Repository files navigation

โšฝ Premier League AI Predictor

Project Status Python React FastAPI Accuracy

A context-aware machine learning system that predicts Premier League match outcomes with 62.76% accuracy โ€” beating random chance (33%), the "always home" strategy (46%), and basic form-based models (56%).

Unlike traditional predictors, this engine considers momentum, fixture congestion, derby matches, and Expected Goals (xG) to generate probabilities that reflect real-world football dynamics.


๐ŸŽฏ What Makes This Different?

Most prediction models just look at "who won last week." This one asks:

  • ๐Ÿ”ฅ "Are they on a hot streak or declining?" (Momentum analysis)
  • ๐Ÿ˜ด "Are they playing their 3rd game in 7 days?" (Fatigue tracking)
  • โš”๏ธ "Is this a derby match?" (High-stakes context)
  • ๐ŸŽฒ "What does xG say about their luck?" (Performance vs Results)

Result: A 62.76% accurate ensemble model trained on 2,390 historical matches.


๐Ÿ“ธ Features Overview

Live Predictions Custom Match Simulator Context-Aware Analysis
Upcoming Matches Custom Match Context

๐Ÿ—๏ธ System Architecture

graph TB
    A[FBref Scraper] --> B[PostgreSQL Database]
    C[Football-Data API] --> B
    B --> D[Feature Engineer]
    D --> E[Draw Detector Model]
    D --> F[Winner Predictor Model]
    E --> G[Ensemble Predictor]
    F --> G
    G --> H[FastAPI Backend]
    H --> I[React Frontend]
    I --> J[User]
    K[Scheduler] --> A
    K --> L[Model Retrainer]
    L --> E
    L --> F
Loading

Three-Layer Architecture

1. Data Collection Layer

  • FBref Scraper: Historical match data (scores, xG, shots, possession)
  • Football-Data.org API: Live fixtures, team info, real-time updates
  • PostgreSQL Database: Stores 2,390+ matches, 20 teams, user predictions

2. Machine Learning Layer

A two-stage ensemble system:

Stage 1: Draw Detector

  • Specialized Random Forest model
  • Trained to identify draw patterns (evenly matched teams, defensive tactics)
  • Accuracy: 71% overall, 24% recall on draws

Stage 2: Winner Predictor

  • Predicts home or away win when draw is unlikely
  • Balanced for home/away bias
  • Accuracy: 69% (73% home, 64% away)

Ensemble Strategy:

if draw_probability > 0.40:
    return "DRAW"
else:
    return winner_predictor.predict()

Final Performance: 62.76% accuracy

3. Application Layer

  • Backend: FastAPI serves predictions, manages users, stores history
  • Frontend: React + Vite UI with interactive charts (Recharts)

๐Ÿง  Feature Engineering (39 Features)

The model doesn't just see "Arsenal won 2-1." It sees:

Form Features (Rolling 5-Match Averages)

  • Goals scored/conceded per match
  • Expected Goals (xG) for/against
  • Win rate, Points Per Game (PPG)

Context Features โญ (Secret Sauce)

Feature Why It Matters
Derby Match Arsenal vs Tottenham is more unpredictable than stats suggest
Fixture Congestion Teams playing 3 games in 7 days underperform by ~15%
Momentum Comparing recent 5 vs previous 5 matches (improving or declining?)
League Position Top 6 clash? Relegation battle? Stakes change behavior

Head-to-Head Features

  • Historical win/loss/draw record between these specific teams
  • Some teams just have a "bogey team"

Market Features

  • Betting odds probabilities (wisdom of the crowd)

Output: A 39-dimensional feature vector for each match.


๐Ÿš€ Getting Started

Prerequisites

  • Python 3.11+
  • Node.js 18+
  • Docker (optional, for PostgreSQL)

1. Clone the Repository

git clone https://github.com/YOUR_USERNAME/football-predictor-ai.git
cd football-predictor-ai

2. Backend Setup

Start PostgreSQL (Docker)

docker run --name postgres-predictor \
  -e POSTGRES_PASSWORD=yourpassword \
  -e POSTGRES_DB=football_prediction \
  -p 5432:5432 \
  -d postgres:15

Install Python Dependencies

cd backend
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt

Initialize Database

# Create tables
python -c "from models.database import Base, engine; Base.metadata.create_all(engine)"

# Seed teams
python scripts/seed_teams.py

# Import historical data
python scripts/import_history.py

# Fetch upcoming fixtures
python scripts/seed_upcoming.py

Train the AI Model

python ml/train_ensemble.py

This will create draw_detector_model.pkl, winner_predictor_model.pkl, and scaler.pkl in /models/.

Start the API

uvicorn main:app --reload

Backend runs at http://localhost:8000

3. Frontend Setup

Open a new terminal:

cd frontend
npm install
npm run dev

Frontend runs at http://localhost:5173


๐Ÿ“Š Model Performance

Accuracy Comparison

Strategy Accuracy Description
Random Guess 33.3% Pick home/draw/away randomly
Always Home 46% Always predict home win
Basic Form Model 56% Just recent results
Our Ensemble 62.76% Context + xG + Momentum

Detailed Breakdown

              precision    recall  f1-score   support

    Home Win       0.72      0.79      0.76       227
        Draw       0.23      0.16      0.19       106
    Away Win       0.66      0.71      0.69       145

    accuracy                           0.63       478

Where the Model Excels

โœ… Home Wins: 79% recall (very reliable)
โœ… Away Wins: 71% recall (solid)
โš ๏ธ Draws: 16% recall (the eternal struggle)

Why are draws hard?
Draws are inherently unpredictable (only 22% of matches). The model correctly avoids false draw predictions but misses real ones.


๐Ÿ”„ Automation

The system runs autonomously with a background scheduler:

python backend/tasks/scheduler.py

Schedule:

  • Daily (02:00 AM): Scrape yesterday's results, update database
  • Weekly (Monday 03:00 AM): Retrain models with new data

๐Ÿ› ๏ธ Tech Stack

Backend

  • Framework: FastAPI (async Python web framework)
  • Database: PostgreSQL + SQLAlchemy ORM
  • ML: Scikit-Learn (Random Forest), Pandas, NumPy
  • Data: BeautifulSoup (scraping), Requests (API calls)
  • Automation: Python schedule library

Frontend

  • Framework: React 18 + Vite
  • Styling: Tailwind CSS
  • Charts: Recharts
  • State: React Hooks

DevOps

  • Containerization: Docker (PostgreSQL)
  • Version Control: Git

๐Ÿ“ก API Endpoints

Method Endpoint Description
GET /teams List all 20 Premier League teams
GET /upcoming-matches Next 10 fixtures with AI predictions
POST /predict Custom match simulator (any 2 teams)
GET /match/{id}/prediction Get prediction for specific match
POST /match/{id}/user-prediction Submit your own prediction
GET /user/{id}/history View your prediction accuracy

Example: Custom Prediction

curl -X POST "http://localhost:8000/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "home_team_id": 1,
    "away_team_id": 5,
    "date": "2025-01-15"
  }'

Response:

{
  "home_win_probability": 0.55,
  "draw_probability": 0.28,
  "away_win_probability": 0.17,
  "predicted_outcome": "HOME_WIN",
  "confidence": "MEDIUM",
  "reasoning": {
    "home_momentum": 0.5,
    "away_momentum": -0.2,
    "fixture_congestion": "Home team played 3 games in 7 days"
  }
}

๐Ÿ”ฎ Future Roadmap

  • Player Injury Integration: Adjust predictions when key players are missing
  • Live Match Updates: Real-time probability adjustments during matches
  • Betting Value Finder: Compare AI odds vs bookmaker odds
  • Multi-League Support: Extend to La Liga, Bundesliga, Serie A
  • Mobile App: React Native version
  • Explainable AI: SHAP values to explain each prediction

๐Ÿค Contributing

Contributions are welcome! Here's how:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

๐Ÿ“ˆ Model Insights

Top 5 Most Important Features

  1. Away xG Average (5.47%) - How dangerous is the away team?
  2. Away xG Against (5.25%) - How leaky is the away defense?
  3. Home Momentum (xG Change) (5.12%) - Is the home team improving?
  4. Away Momentum (xG Change) (5.00%) - Is the away team peaking?
  5. Home Momentum Trend (4.91%) - Overall trajectory

Key Insight: Momentum features (context-aware) dominate the top 10, proving the value of looking beyond basic stats.


๐Ÿ“ License

Distributed under the MIT License. See LICENSE for more information.


๐Ÿ™ Acknowledgments


๐Ÿ“ง Contact

Dylan Mascarenhas
GitHub: @dylanmascarenhas
Project Link: https://github.com/dylanmascarenhas/football-predictor-ai


Built with โšฝ and ๐Ÿค– | Predicting the beautiful game, one match at a time.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages