env\Scripts\activate
Personal reference for implementing AI system to analyze FPL database and generate optimal teams.
- โ Database fully populated with real data (7,302 performance records across 10 gameweeks)
- โ AI model trained and working with real data (MAE: 1.28)
- โ Complete pricing integration and value analysis
- โ Organized project structure with dedicated database management
- โ Fast, optimized data refresh system (730x performance improvement)
src/
โโโ ai/ # AI/ML components
โ โโโ data_loader.py # Data loading with pagination
โ โโโ feature_engineering.py # Feature creation
โ โโโ point_predictor.py # ML model
โโโ config/ # Configuration
โ โโโ supabase_client.py # Database connection
โโโ database/ # Database management scripts
โ โโโ fast_performance_refresh.py # Optimized data refresh
โ โโโ update_player_prices.py # Price updates
โ โโโ check_database.py # Health checks
โ โโโ README.md # Database documentation
โโโ fpl/ # FPL-specific logic
โ โโโ player_recommender.py # Player recommendations
โโโ tests/ # Test files
- player_performances: 7,302 records (complete 10 gameweeks, 2024-25 season)
- historical_player_stats: 51,400 records (historical data)
- players: 743 current players with FPL mappings
- teams: 20 Premier League teams
- fixtures: 380 fixtures with results and difficulty ratings
- current_team_stats: Team performance metrics
# Easy database management interface
python database_manager.py
# Or run individual scripts:
python src/database/check_database.py # Check database health
python src/database/fast_performance_refresh.py # Refresh player data
python src/database/update_player_prices.py # Update current prices# Test AI with real Premier League players
python src/test_real_players.py- Player Performance: Goals, assists, minutes, points, form trends
- Current Pricing: Real FPL prices and ownership percentages
- Team Metrics: Wins, clean sheets, goals for/against
- Fixture Analysis: Difficulty ratings, home/away context
- Value Analysis: Points per million calculations
# TODO: Create functions to collect 3-5 seasons of data
def collect_historical_gameweek_data():
# Pull historical FPL data for seasons 2020-21 to 2024-25
# Store in new table: historical_player_stats
pass
def collect_historical_fixtures():
# Get 3+ seasons of match results with context
# Store in: historical_fixtures
pass
def collect_injury_suspension_data():
# Track injury/suspension patterns by player
# Store in: player_availability_history
pass# TODO: Create feature engineering pipeline
def create_rolling_averages():
# 3, 5, 10 gameweek rolling averages for all metrics
# Points, minutes, goals, assists, etc.
pass
def create_form_indicators():
# Trend analysis: improving/declining performance
# Rate of change in key metrics
pass
def create_matchup_features():
# Historical performance vs specific opponents
# Home/away split analysis
pass
def create_contextual_features():
# Days of rest, fixture congestion
# European competition participation
# International break effects
pass
def create_team_strength_features():
# Dynamic team strength ratings
# Attack/defense ratings by period
pass# TODO: Create ML data pipeline
def prepare_training_data():
"""
Steps:
1. Combine all feature tables into training dataset
2. Handle missing values and outliers
3. Create target variables (next gameweek points)
4. Split data chronologically (no future leakage)
5. Feature selection and correlation analysis
"""
pass
def create_position_datasets():
"""
Create separate datasets for each position:
- Goalkeepers (different scoring patterns)
- Defenders (clean sheet focus)
- Midfielders (balanced scoring)
- Forwards (goal-heavy scoring)
"""
pass# TODO: Implement multiple model types
from sklearn.ensemble import RandomForestRegressor
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
import tensorflow as tf
def train_position_models():
"""
Train separate models for each position:
1. XGBoost for tabular features (baseline)
2. Random Forest for feature importance
3. Neural Network for complex interactions
4. LSTM for time series patterns
"""
pass
def create_ensemble_model():
"""
Combine multiple models:
- Weight by recent performance
- Use stacking/blending techniques
- Cross-validation for robustness
"""
pass
def implement_uncertainty_quantification():
"""
Provide prediction confidence intervals:
- Quantile regression
- Monte Carlo dropout
- Ensemble variance
"""
pass# TODO: Implement advanced optimization
from scipy.optimize import linprog
import pulp # Linear programming
def implement_integer_programming():
"""
Use mathematical optimization for team selection:
- Exact solutions for budget/position constraints
- Handle discrete choices (player selection)
- Multi-objective optimization (points vs risk)
"""
pass
def implement_genetic_algorithm():
"""
Evolutionary algorithm for complex optimization:
- Population of potential teams
- Mutation and crossover operations
- Handle multiple objectives simultaneously
"""
pass
def implement_monte_carlo_simulation():
"""
Risk analysis through simulation:
- Generate thousands of possible outcomes
- Measure team performance variance
- Optimize for different risk profiles
"""
pass# TODO: Multi-gameweek planning
def implement_lookahead_optimization():
"""
Plan transfers for next 3-5 gameweeks:
- Consider fixture difficulty sequences
- Optimize transfer costs vs gains
- Plan around price changes
"""
pass
def implement_captaincy_optimization():
"""
Advanced captain selection:
- Separate model for captain multiplier
- Consider opponent matchups
- Risk/reward analysis for differential captains
"""
pass# TODO: Install ML packages
pip install scikit-learn xgboost lightgbm tensorflow
pip install optuna # Hyperparameter tuning
pip install pulp # Linear programming
pip install plotly # Visualizations
pip install shap # Model explanations-- TODO: Create additional tables for ML
CREATE TABLE historical_player_stats (
player_id INT,
gameweek_id INT,
season VARCHAR(10),
points INT,
minutes INT,
-- ... all FPL stats
);
CREATE TABLE feature_store (
player_id INT,
gameweek_id INT,
rolling_avg_3gw DECIMAL,
rolling_avg_5gw DECIMAL,
form_trend DECIMAL,
opponent_strength DECIMAL,
-- ... engineered features
);
CREATE TABLE model_predictions (
player_id INT,
gameweek_id INT,
predicted_points DECIMAL,
confidence_lower DECIMAL,
confidence_upper DECIMAL,
model_version VARCHAR(50)
);fpl-predictor/
โโโ ml/
โ โโโ data_pipeline/
โ โ โโโ feature_engineering.py
โ โ โโโ data_collection.py
โ โ โโโ data_validation.py
โ โโโ models/
โ โ โโโ player_models.py
โ โ โโโ ensemble_models.py
โ โ โโโ model_evaluation.py
โ โโโ optimization/
โ โ โโโ team_optimizer.py
โ โ โโโ transfer_optimizer.py
โ โ โโโ captaincy_optimizer.py
โ โโโ utils/
โ โโโ model_utils.py
โ โโโ evaluation_utils.py
โโโ trained_models/ # Saved model files
โโโ experiments/ # ML experiments and notebooks
โโโ config/ # ML configuration files
- Prediction Accuracy: Mean Absolute Error < 2.0 points
- Hit Rate: Top 3 predictions per position > 60% accuracy
- Value Prediction: Price change prediction > 70% accuracy
- Team Performance: Consistently rank in top 10% of FPL
# TODO: Implement validation framework
def time_series_cv():
"""
Walk-forward validation:
- Train on historical data
- Test on future gameweeks
- No data leakage from future
"""
pass
def backtest_team_performance():
"""
Historical team simulation:
- Run AI on past seasons
- Compare vs template teams
- Measure long-term performance
"""
pass- โ Database is ready - start here
- Implement historical data collection functions
- Create basic feature engineering pipeline
- Set up ML development environment
- Train simple XGBoost models per position
- Implement basic evaluation metrics
- Create prediction pipeline
- Test on recent gameweeks
- Add rolling averages and form indicators
- Implement ensemble models
- Add uncertainty quantification
- Optimize hyperparameters
- Implement mathematical optimization
- Add multi-gameweek planning
- Create transfer strategy logic
- Build complete AI pipeline
- Start Simple: Begin with XGBoost on basic features, then add complexity
- Position-Specific: Different models for GK/DEF/MID/FWD due to different scoring patterns
- Time Awareness: Always respect chronological order, no future leakage
- Validation First: Set up proper validation before optimizing models
- Incremental: Build each component separately, then integrate
- Database Integration: Leverage existing Supabase infrastructure
- Immediate: Set up
ml/folder structure and install ML packages - This Week: Implement historical data collection from FPL API
- Next: Create feature engineering pipeline using database data
- Goal: Replace current rule-based system with trained ML models
Create a .env file in the project root:
# Supabase Database Credentials
SUPABASE_URL=your_supabase_url_here
SUPABASE_KEY=your_supabase_anon_key_here
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key_here
# football-data.org API Key
API_KEY=your_football_data_api_key_hereGetting Your Credentials:
- Supabase: Sign up at supabase.com, create a project, get URL and keys from Settings โ API
- football-data.org: Register at football-data.org, get free API key (10 requests/minute)
The application will automatically create the required database schema on first run. Tables include:
teams- Premier League team dataplayers- Player information and mappingsgameweeks- Season gameweek informationfixtures- Match fixtures and resultscurrent_player_stats- Real-time player statisticscurrent_team_stats- Team performance metricsplayer_performances- Historical performance data
# Activate environment
env\Scripts\activate
# Run the predictor
python fpl-predictor.pyOn the first run, the application will:
- Create team mappings (instant - loads from database)
- Build player mappings (~20 minutes due to API rate limits)
- Maps 500+ players between FPL and football-data.org
- Only needs to be done once, then cached in database
- Populate database with current FPL data
- Generate predictions and optimal team
After initial setup, the predictor runs in seconds using cached database data.
Run this script to refresh data for new gameweeks:
python populate_db.pyThe predictor generates:
TOP 3 FORWARDS:
1. Erling Haaland - 8.2 pts (ยฃ15.1m, 45.2% owned)
2. Alexander Isak - 7.1 pts (ยฃ8.5m, 12.8% owned)
3. Darwin Nรบรฑez - 6.8 pts (ยฃ9.0m, 8.3% owned)
- Best Value Picks: Highest points per million ratio
- Highest Predicted Points: Top point scorers regardless of price
- Differential Picks: Low ownership (<5%) high potential players
BUDGET: ยฃ99.2m / ยฃ100.0m (ยฃ0.8m remaining)
FORMATION: 3-4-3
PREDICTED POINTS: 67.8
STARTING XI (3-4-3):
GK: โข Alisson (Liverpool) - 5.2pts - ยฃ5.5m
DEF: โข Virgil van Dijk (Liverpool) - 6.1pts - ยฃ6.0m
โข William Saliba (Arsenal) - 5.8pts - ยฃ5.5m
โข Joลกko Gvardiol (Man City) - 5.5pts - ยฃ5.5m
The current system uses sophisticated rule-based algorithms that analyze:
- Player Form: Recent performance trends and points per game
- Fixture Difficulty: Upcoming opponent strength analysis
- Team Strength: Overall team performance metrics
- Value Analysis: Points per million optimization
- Risk Assessment: Injury status, rotation risk, ownership levels
For implementing advanced machine learning models, the system is designed to support:
- Historical Data Collection: 3-5 seasons of player/team performance
- Feature Engineering: Rolling averages, form indicators, contextual features
- External Data: Weather, referee history, fixture congestion
- Gradient Boosting (XGBoost/LightGBM) for tabular prediction
- Neural Networks for complex pattern recognition
- Time Series Models (LSTM/GRU) for sequential performance
- Ensemble Methods for robust predictions
- Multi-Objective Optimization for balanced risk/reward
- Constraint Satisfaction for FPL rule compliance
- Transfer Strategy for long-term team planning
fpl-predictor/
โโโ fpl-predictor.py # Main application
โโโ populate_db.py # Data refresh script
โโโ .env # Environment variables
โโโ env/ # Virtual environment
โโโ cache/ # Legacy JSON cache (optional backup)
โโโ README.md # This file
- Budget: Default ยฃ100m (modify in
build_optimal_team()) - Player Mapping Threshold: 200+ players for instant loading
- API Rate Limits: 6.5 second delays for football-data.org
- Formation Options: 7 different formations tested for optimal points
- Database First: All data cached for instant access
- Efficient Queries: Optimized database lookups
- API Minimization: Reduce external API calls where possible
1. Slow Performance on First Run
- Normal! Player mapping takes ~20 minutes due to API rate limits
- This only happens once - subsequent runs are instant
2. Database Connection Errors
- Check
.envfile has correct Supabase credentials - Verify Supabase project is active and accessible
3. API Key Errors
- Ensure football-data.org API key is valid
- Free tier has 10 requests/minute limit
4. Missing Player Mappings
- Run
fpl-predictor.pyto rebuild mappings - Check API connectivity and rate limits
If you see 'python' is not recognized error:
# Windows
env\Scripts\activate
python fpl-predictor.py
# Or use full path
"C:\path\to\your\project\env\Scripts\python.exe" fpl-predictor.py- Data Processing: 743 players, 20 teams, 380+ fixtures
- Prediction Speed: <5 seconds for full team optimization
- Database Size: ~50MB for full season data
- API Efficiency: Minimal external calls after initial setup
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Fantasy Premier League API - Official FPL data source
- football-data.org - Comprehensive football statistics
- Supabase - Database infrastructure
- FPL Community - Inspiration and feedback
For questions or issues:
- Check the troubleshooting section
- Open an issue on GitHub
- Join the discussion in issues section
โก Quick Start:
git clone https://github.com/ritvikiscool9/fpl-predictor.git
cd fpl-predictor
python -m venv env
env\Scripts\activate
pip install requests pandas python-dotenv supabase
# Add your .env file
python fpl-predictor.pyHappy FPL managing! ๐โฝ