Skip to content

timjwsmith/fpl-assistant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

570 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ‰ NRL Fantasy Edge

AI-Powered NRL Fantasy Predictions & Optimization

A comprehensive web application that helps NRL Fantasy coaches predict player scores, optimize their squads, and make data-driven decisions using advanced machine learning and statistical analysis.

FastAPI Python License


✨ Features

Phase 1 - MVP (βœ… Complete)

  • βœ… Fantasy Scoring Engine: Accurate implementation of 2024 NRL Fantasy scoring rules
  • βœ… Basic Predictions: Weighted average predictions using last 3-5 games
  • βœ… Captain Suggestions: AI-powered captain and vice-captain recommendations
  • βœ… Trade Optimizer: Smart trade suggestions based on value and projected points
  • βœ… Value Picks: Find the best points-per-dollar players by position
  • βœ… REST API: Fast, documented FastAPI with auto-generated OpenAPI docs
  • βœ… Web Interface: Clean, responsive UI for testing and exploring predictions

Phase 2 - Advanced (βœ… Complete)

  • βœ… Real Data Ingestion: Import from NRL-Data GitHub repository
  • βœ… ML Predictions: Gradient Boosting model with opponent/venue context
  • βœ… Opponent Analysis: Defensive strength ratings by team and position
  • βœ… Home/Away Adjustments: Venue-specific advantage calculations
  • βœ… Bye Round Planner: Multi-week optimization for rounds 13-17
  • βœ… PostgreSQL Support: Production-ready database with migration path
  • βœ… Automated Tests: Pytest suite for scoring accuracy and predictions
  • βœ… Logging & Monitoring: Centralized logging with file and console output

πŸš€ Quick Start

1. Initialize Database

python -m nrl_fantasy.init_db

2. Generate Sample Data (for testing)

python -m nrl_fantasy.utils.sample_data

3. Generate Projections

from nrl_fantasy.data.storage.database import get_db
from nrl_fantasy.models.predictor import PlayerPredictor

with get_db() as db:
    predictor = PlayerPredictor(db)
    count = predictor.generate_all_projections(2024, 6)
    print(f"Generated {count} projections")

4. Run the API

The app automatically runs on port 5000:


πŸ“š API Documentation

Core Endpoints

Get Player Projection

GET /api/players/{player_id}/projection?round=6

Project Team

POST /api/team/project
{
  "players": [
    {"player_id": 1, "position": "FRF"},
    {"player_id": 2, "position": "HOK"}
  ],
  "bank_balance": 100.0,
  "trades_remaining": 2
}

Get Value Picks

GET /api/players/value-picks?position=HLF&limit=5

Advanced Endpoints (Phase 2)

Advanced ML Prediction

POST /api/advanced/predict
{
  "player_id": 1,
  "round": 15,
  "opponent": "Melbourne Storm",
  "is_home": true,
  "venue": "Penrith Stadium"
}

Train ML Model

POST /api/advanced/train-model?season=2024

Team Defensive Strength

GET /api/advanced/defensive-strength/Melbourne%20Storm?position=HLF

Bye Round Planning

POST /api/advanced/bye-plan
{
  "squad": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
  "current_round": 10,
  "trades_available": 10
}

Import External Data

POST /api/advanced/import-data/2024

πŸ—οΈ Architecture

nrl_fantasy/
β”œβ”€β”€ api/                     # API schemas and advanced endpoints
β”‚   β”œβ”€β”€ schemas.py          # Pydantic models
β”‚   └── advanced_endpoints.py # Phase 2 endpoints
β”œβ”€β”€ config/                  # Configuration
β”‚   └── database_config.py  # DB connection management
β”œβ”€β”€ data/                    # Data layer
β”‚   β”œβ”€β”€ ingestion/          # External data fetchers
β”‚   └── storage/            # Database models & connection
β”œβ”€β”€ models/                  # Prediction engines
β”‚   β”œβ”€β”€ predictor.py        # Basic weighted average
β”‚   └── advanced_predictor.py # ML with context
β”œβ”€β”€ optimization/            # Team optimization
β”‚   β”œβ”€β”€ team_optimizer.py   # Captain & trade suggestions
β”‚   └── bye_planner.py      # Multi-week bye planning
β”œβ”€β”€ scoring/                 # Fantasy scoring
β”‚   └── engine.py           # Points calculator
β”œβ”€β”€ tests/                   # Automated tests
β”‚   β”œβ”€β”€ test_scoring_engine.py
β”‚   └── test_predictor.py
β”œβ”€β”€ utils/                   # Utilities
β”‚   β”œβ”€β”€ sample_data.py      # Sample data generator
β”‚   └── logger.py           # Centralized logging
└── main.py                  # FastAPI application

🧠 Prediction Models

1. Basic Predictor (Weighted Average)

  • Uses last 3-5 games with exponential weighting
  • Adjusts for minutes played
  • Confidence based on consistency
  • MAE: ~8-10 fantasy points

2. Advanced ML Predictor (Gradient Boosting)

  • 16 engineered features including:
    • Recent form (last 3, 5, 10 games)
    • Consistency and trend analysis
    • Minutes, tackles, metres averages
    • Opponent defensive strength
    • Home/away venue factors
  • MAE: ~5-7 fantasy points (when trained)
  • Sklearn GradientBoostingRegressor with 100 estimators

πŸ“Š Data Sources

Match Statistics

Fantasy Prices

  • FootyStatistics.com - Prices, break-evens, ownership
  • Unofficial NRL Fantasy JSON endpoints (undocumented)

See DATA_SOURCES.md for detailed research.


πŸ§ͺ Testing

Run Tests

# All tests
python -m pytest nrl_fantasy/tests/ -v

# Specific test
python -m pytest nrl_fantasy/tests/test_scoring_engine.py -v

# With coverage
python -m pytest nrl_fantasy/tests/ --cov=nrl_fantasy --cov-report=html

Current Test Coverage

  • βœ… Scoring engine accuracy tests
  • βœ… Prediction logic tests
  • βœ… Edge cases (no history, negative scores, premium scorers)

πŸ’Ύ Database Options

Development: SQLite (default)

# Automatic - just run init_db
python -m nrl_fantasy.init_db

Production: PostgreSQL

Option 1: Replit PostgreSQL

# Enable in Replit, then:
export NRL_DATABASE_URL=$DATABASE_URL
python -m nrl_fantasy.init_db

Option 2: External (Neon, Supabase, etc.)

export NRL_DATABASE_URL="postgresql://user:pass@host:5432/dbname"
python -m nrl_fantasy.init_db

See nrl_fantasy/config/database_config.py for migration guide.


πŸ“ˆ Sample Data

The app includes a realistic sample data generator with:

  • 128 players across 16 NRL teams
  • 40 matches over 5 rounds (2024 season)
  • 320 player performances with detailed stats
  • 640 price history records
  • Realistic stat distributions by position (forwards, backs, playmakers)

πŸ”§ Tech Stack

Component Technology
Backend Python 3.11 + FastAPI
Database SQLite (dev) / PostgreSQL (prod)
ORM SQLAlchemy 2.0
ML scikit-learn, NumPy, Pandas
Server Uvicorn with auto-reload
Testing Pytest
Frontend HTML/CSS/JavaScript (vanilla)

πŸ“ Environment Variables

# Database (optional - defaults to SQLite)
NRL_DATABASE_URL="sqlite:///nrl_fantasy.db"

# API Configuration
API_HOST="0.0.0.0"
API_PORT=5000

# Season
CURRENT_SEASON=2024

# Logging
LOG_LEVEL="INFO"

🚦 Roadmap

Phase 3 - Production Enhancement

  • User authentication (JWT tokens)
  • Saved teams and watchlists
  • Email/push notifications for price changes
  • Historical performance analytics dashboard
  • Automated weekly data updates (cron jobs)
  • Advanced ensemble models (XGBoost + LightGBM)
  • Full season optimization with integer programming
  • Mobile app (React Native / Flutter)

Phase 4 - Advanced Features

  • Live score tracking during matches
  • League analysis & competitor modeling
  • Weather impact analysis
  • Injury probability modeling
  • Custom scoring league support
  • Transfer market trends
  • Social features (leagues, challenges)

πŸ“œ License

MIT License - see LICENSE file


πŸ™ Acknowledgments

  • NRL-Data by beauhobba - Historical match statistics
  • uselessnrlstats - Comprehensive historical data
  • FootyStatistics.com - Community fantasy tools
  • Rugby League Project - Match data archive

πŸ“ž Support

For questions or issues:

  • Check /docs for interactive API documentation
  • Review replit.md for project details
  • See DATA_SOURCES.md for data information

Built with ❀️ for the NRL Fantasy community

About

FPL Assistant - AI-powered Fantasy Premier League tool

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages