Skip to content
/ F1-Dash Public

A Python-backed D3.js web application for F1 enthusiasts to visualize lap times, tire strategies, driver/team performance, telemetry, and race analytics.

License

Notifications You must be signed in to change notification settings

rhtnr/F1-Dash

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

17 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🏎️ F1-Dash

Live Demo Python FastAPI D3.js License: MIT

Buy Me A Coffee

A Python-backed D3.js web application for F1 enthusiasts to visualize lap times, tire strategies, driver/team performance, telemetry, and race analytics with ML-powered race predictions.

🌐 Live Demo: https://f1-dash.live/

✨ Features

  • πŸ“Š Lap Time Analysis - Scatter plots, box plots, lap-by-lap progression with outlier filtering
  • πŸ›ž Tire Strategy Visualization - Stint bars with compound colors, pit stop timing
  • πŸ“ˆ Telemetry Overlays - Speed traces, throttle/brake, gear shifts, multi-channel comparison
  • 🏁 Driver Comparisons - Head-to-head lap times, sector comparisons
  • πŸ“‰ Race Progression - Position changes over laps, gap analysis
  • ⏱️ Stint Analysis - Tire degradation curves, compound performance
  • πŸ€– Race Predictions (ML) - XGBoost-powered race predictions based on practice session data

πŸ—οΈ Architecture

flowchart TB
    subgraph Frontend["πŸ–₯️ Frontend (Static Site)"]
        UI[D3.js Visualizations]
        API_Client[API Client]
    end

    subgraph Backend["βš™οΈ Backend (FastAPI)"]
        Routes[API Routes]
        Services[Service Layer]
        Repos[Repository Layer]
        ML[ML Prediction Service]
    end

    subgraph External["🌐 External Data"]
        FastF1[FastF1 API]
        F1_Official[F1 Timing Data]
    end

    subgraph Storage["πŸ’Ύ Storage"]
        FileStore[File Storage JSON]
        Cache[FastF1 Cache]
        Models[ML Models]
    end

    UI --> API_Client
    API_Client -->|REST API| Routes
    Routes --> Services
    Services --> Repos
    Services --> ML
    Repos --> FileStore
    Services -->|Data Ingestion| FastF1
    FastF1 --> F1_Official
    FastF1 --> Cache
    ML --> Models
Loading

πŸ”„ Component Flow

sequenceDiagram
    participant User
    participant Frontend
    participant API
    participant Service
    participant FastF1
    participant Storage

    User->>Frontend: Select Session
    Frontend->>API: POST /ingest/session
    API->>Service: Ingest Request
    Service->>FastF1: Fetch Session Data
    FastF1-->>Service: Lap Times, Telemetry
    Service->>Storage: Save JSON
    Service-->>API: Session Created
    API-->>Frontend: Session ID
    Frontend->>API: GET /laps/{session_id}
    API->>Storage: Read Laps
    Storage-->>API: Lap Data
    API-->>Frontend: JSON Response
    Frontend->>User: Render D3 Chart
Loading

πŸ› οΈ Tech Stack

Backend

  • ⚑ FastAPI - Modern Python web framework with async support
  • 🏎️ FastF1 - F1 data access library (2018+ seasons)
  • βœ… Pydantic - Data validation and serialization
  • πŸ€– XGBoost - Machine learning for race predictions
  • πŸ—„οΈ Repository Pattern - Pluggable storage (file-based JSON, ready for DynamoDB)

Frontend

  • πŸ“Š D3.js - Data visualization library
  • 🌐 Vanilla JavaScript - No framework dependencies
  • πŸ“¦ ES Modules - Modern JavaScript architecture

πŸ”’ Security

  • Security headers middleware (CSP, X-Frame-Options, etc.)
  • Rate limiting (100 req/min API, 5 req/min ingestion)
  • CORS configuration with explicit origins
  • API key authentication for sensitive endpoints
  • XSS prevention (safe DOM manipulation)
  • Path traversal protection

πŸš€ Quick Start

Prerequisites

  • 🐍 Python 3.11+
  • πŸ“¦ Node.js (optional, for frontend development server)

Backend Setup

cd backend

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Configure environment (optional)
cp .env.example .env

# Run the server
uvicorn app.main:app --reload

The API will be available at http://localhost:8000

  • πŸ“š API Documentation: http://localhost:8000/docs
  • πŸ“‹ OpenAPI Schema: http://localhost:8000/openapi.json
  • πŸ’š Health Check: http://localhost:8000/health

Frontend Setup

cd frontend

# Option 1: Python simple server
python -m http.server 3000

# Option 2: Any static file server
npx serve -l 3000

The frontend will be available at http://localhost:3000

☁️ Deployment

Render (Recommended)

This project includes a render.yaml blueprint for easy deployment:

  1. πŸ“€ Push your code to GitHub
  2. 🌐 Go to render.com and create a new Blueprint
  3. πŸ”— Connect your GitHub repository
  4. ✨ Render will auto-detect the render.yaml and create both services

After deployment, configure environment variables in the Render dashboard:

  • F1_CORS_ORIGINS - Your frontend URL (e.g., https://f1-dash.live)
  • F1_API_KEYS - Optional API keys for protected endpoints

Update frontend/config.js with your backend URL:

window.F1_API_URL = 'https://f1-dash-api.onrender.com/api/v1';

βš™οΈ Environment Variables

Variable Description Default
F1_ENVIRONMENT development, staging, or production development
F1_CORS_ORIGINS Comma-separated allowed origins http://localhost:3000
F1_API_KEYS Comma-separated API keys (none)
F1_API_KEY_AUTH_ENABLED Enable API key auth false
F1_RATE_LIMIT_ENABLED Enable rate limiting true
F1_TRUSTED_HOSTS Allowed hosts (production) localhost

πŸ“‘ API Endpoints

πŸ“… Schedule (FastF1 Available Data)

  • GET /api/v1/schedule/years - Get available years
  • GET /api/v1/schedule/events/{year} - Get events for a year
  • GET /api/v1/schedule/sessions/{year}/{round} - Get sessions for an event

🏁 Sessions (Ingested Data)

  • GET /api/v1/sessions - List sessions (filterable by year)
  • GET /api/v1/sessions/years - Get available years
  • GET /api/v1/sessions/events/{year} - Get events for a year
  • GET /api/v1/sessions/id/{session_id} - Get specific session
  • GET /api/v1/sessions/{year}/{round} - Get event sessions

⏱️ Laps

  • GET /api/v1/laps/{session_id} - Get session laps
  • GET /api/v1/laps/{session_id}/fastest - Get fastest laps
  • GET /api/v1/laps/{session_id}/distribution - Lap time distribution
  • GET /api/v1/laps/{session_id}/compound-performance - Compound analysis

πŸ›ž Strategy

  • GET /api/v1/strategy/{session_id}/stints - Get tire stints
  • GET /api/v1/strategy/{session_id}/summary - Strategy summary

πŸ“ˆ Telemetry

  • GET /api/v1/telemetry/{session_id}/{driver}/{lap} - Get lap telemetry
  • POST /api/v1/telemetry/{session_id}/compare - Compare multiple laps

πŸ€– Predictions (ML)

  • GET /api/v1/predictions/race/{year}/{round} - Get race prediction
  • GET /api/v1/predictions/backtest/{year}/{round} - Backtest with actual results
  • GET /api/v1/predictions/model/info - Model status and info
  • POST /api/v1/predictions/train - Train the prediction model

πŸ“₯ Data Ingestion

  • GET /api/v1/ingest/status/{year}/{round}/{session} - Check ingestion status
  • POST /api/v1/ingest/session - Ingest session data
  • POST /api/v1/ingest/telemetry - Ingest telemetry data

πŸ‘¨β€πŸ’» Development

πŸ§ͺ Running Tests

cd backend
source venv/bin/activate

# Run all tests
pytest

# Run with coverage
pytest --cov=app

# Run specific test file
pytest tests/unit/test_services.py -v

πŸ“ Project Structure

f1-dash/
β”œβ”€β”€ README.md
β”œβ”€β”€ render.yaml              # Render deployment blueprint
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/             # FastAPI routes
β”‚   β”‚   β”‚   β”œβ”€β”€ schemas/     # Request/Response schemas
β”‚   β”‚   β”‚   └── v1/          # API version 1 endpoints
β”‚   β”‚   β”œβ”€β”€ config.py        # Settings management
β”‚   β”‚   β”œβ”€β”€ dependencies.py  # Dependency injection
β”‚   β”‚   β”œβ”€β”€ domain/          # Domain models and enums
β”‚   β”‚   β”‚   β”œβ”€β”€ enums/
β”‚   β”‚   β”‚   └── models/
β”‚   β”‚   β”œβ”€β”€ ingestion/       # FastF1 data fetching
β”‚   β”‚   β”œβ”€β”€ main.py          # Application entry point
β”‚   β”‚   β”œβ”€β”€ middleware/      # Security middleware
β”‚   β”‚   β”œβ”€β”€ repositories/
β”‚   β”‚   β”‚   β”œβ”€β”€ file/        # File-based implementations
β”‚   β”‚   β”‚   └── interfaces/  # Abstract repository interfaces
β”‚   β”‚   └── services/        # Business logic layer
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   └── models/          # Pre-trained ML models
β”‚   β”œβ”€β”€ tests/
β”‚   └── requirements.txt
└── frontend/
    β”œβ”€β”€ index.html
    β”œβ”€β”€ config.js            # API URL configuration
    β”œβ”€β”€ css/
    └── js/
        β”œβ”€β”€ api/             # API client
        β”œβ”€β”€ charts/          # D3.js chart components
        └── utils/           # Utilities (colors, formatters, security)

πŸ€– ML Predictions

The prediction model uses XGBoost trained on historical race data (2023-2024 seasons):

πŸ“Š Features (15 total):

  • Best lap delta, average pace delta, consistency (std dev) for FP1, FP2, FP3
  • Session positions for each practice session
  • Long run pace delta for each session

πŸ“ˆ Model Performance:

  • MAE: ~0.49 positions (training data)
  • 87% of predictions within 1 position

Pre-trained model files are included in backend/data/models/ for production deployment.

πŸ“Š Data Sources

Data is fetched from the official F1 timing system via the FastF1 library. Available data includes:

  • πŸ“… Sessions from 2018 onwards
  • ⏱️ Lap timing and sector times
  • πŸ›ž Tire compound and stint information
  • πŸ“ˆ Car telemetry (speed, throttle, brake, gear)
  • 🌀️ Weather conditions
  • 🚩 Race control messages

πŸ”’ Security Considerations

For production deployment:

  • Set F1_ENVIRONMENT=production
  • Configure F1_CORS_ORIGINS to your specific frontend domain
  • Enable API key authentication for ingestion endpoints
  • Use HTTPS (handled automatically by Render)
  • Review and configure F1_TRUSTED_HOSTS

πŸ’– Support

If you find this project useful, consider supporting its development:

Buy Me A Coffee

πŸ“„ License

MIT

About

A Python-backed D3.js web application for F1 enthusiasts to visualize lap times, tire strategies, driver/team performance, telemetry, and race analytics.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published