Skip to content

Repository files navigation

F1 Reddit Trends

A small FastAPI app that discovers the most discussed F1 topics on Reddit, fetches related news, and shows current driver standings.

Features

  • Detect trending keywords from Reddit top posts
    • Supports multiple subreddits: r/formula1, r/F1Technical, r/F1DataAnalysis, etc.
    • Supports time ranges: day, week, month, year, all
  • Rule‑based entity extraction (drivers and teams)
  • Clickable keyword chips to load related news (Google News RSS)
  • Current driver standings (Ergast API; graceful fallback if unavailable)
  • Minimal, fast frontend

Requirements

  • Python 3.11+ recommended
  • Windows PowerShell commands below; adapt to your shell if needed

Setup

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

Run

uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload

Then open http://127.0.0.1:8000.

Using the UI

  • Controls
    • Subreddits: comma‑separated list, e.g. formula1,F1Technical,F1DataAnalysis
    • Time range: choose among day, week, month, year, all
    • Optional filter: type driver or team with a name (e.g., Verstappen, Ferrari) to restrict posts
    • Click Refresh to apply
  • Click a keyword chip to load related news articles
  • “Detected Entities” shows drivers/teams found across loaded posts

API

Base URL: http://127.0.0.1:8000

  • GET /api/reddit/top-topic

    • Query params:
      • subs (optional): comma‑separated subreddits. Default: formula1
      • t (optional): day|week|month|year|all. Default: week
      • filter_type (optional): driver|team
      • filter_name (optional): free text to match in title/body
    • Response:
      {
        "keywords": ["red bull", "team orders", "..."],
        "entities": { "drivers": ["Max Verstappen", "..."], "teams": ["Ferrari", "..."] },
        "subreddits": ["formula1", "F1Technical"],
        "timeRange": "week",
        "samplePosts": [{ "title": "...", "permalink": "...", "score": 123, "subreddit": "formula1" }]
      }
  • GET /api/news

    • Query params: topic (string)
    • Response: { topic, items: [{ title, link, published, source }] }
  • GET /api/f1/standings

    • Response: { source, data, note? } (Ergast format when available)
  • GET /api/metadata

    • Response: lists of known drivers, teams, default subreddits, and available time ranges

Curl examples

curl "http://127.0.0.1:8000/api/reddit/top-topic?subs=formula1,F1Technical&t=week"

curl "http://127.0.0.1:8000/api/reddit/top-topic?subs=formula1&t=month&filter_type=driver&filter_name=Verstappen"

curl "http://127.0.0.1:8000/api/news?topic=Ferrari"

curl "http://127.0.0.1:8000/api/f1/standings"

Notes

  • Reddit access uses public JSON endpoints with a custom User-Agent. Heavy usage may require authenticated API access.
  • News is sourced via Google News RSS search; links point to publishers.
  • Standings are requested from the Ergast API. If the service is down or unavailable, the app returns an empty list with a note.

Project structure

app/
  main.py              # FastAPI app, endpoints, Reddit/topic logic
  static/
    index.html         # Minimal UI
requirements.txt       # Python dependencies
README.md              # This file

License

MIT (or your preferred license)

F1 Data Pipeline

Utilities for downloading detailed Formula 1 session data with FastF1 and producing quick-turn performance analysis artifacts.

Project Layout

  • fetch_f1_data.py – CLI helper that hydrates a FastF1 session (laps, telemetry, weather, race control messages) and stores the results as CSV/Parquet plus JSON metadata under a structured directory.
  • analyze_f1_data.py – CLI that reads a previously exported session, computes key metrics (fastest laps, DRS top speeds, tyre usage), and saves summary CSV tables alongside PNG charts.
  • requirements.txt – Python dependencies needed for both scripts.
  • .fastf1-cache/ – (created automatically) persistent cache for the upstream timing data, so repeat runs are faster and reduce load on the timing servers.
  • data/ – default destination for exported session datasets.

Prerequisites

  • Python 3.10+ (tested with Python 3.11 / 3.12 / 3.13).
  • System packages required by matplotlib and pyarrow (on Windows these ship as wheels; on Linux install system libraries such as libssl-dev, libstdc++, etc.).

Installation

Create and activate a virtual environment (recommended), then install dependencies:

python -m venv .venv
.venv\Scripts\activate  # Windows
# source .venv/bin/activate  # macOS / Linux

pip install -r requirements.txt

Tip: pyarrow is optional but recommended; without it the export script falls back to CSV only.

Fetching Session Data

python fetch_f1_data.py --year 2025 --event "Mexico City Grand Prix" --session Race --include-schedule

Key flags:

  • --year (required) – Championship season (e.g., 2024).
  • Choose one of:
    • --event "Event Name" – Friendly event name (case-insensitive, partial matches allowed by FastF1).
    • --round 19 – Round number in the championship.
  • --session – Target session (Race, Qualifying, Sprint, FP1, etc.). Defaults to Race.
  • --drivers VER PER – Limit per-driver telemetry export to these three-letter codes. Omit to export everyone.
  • --skip-telemetry – Skip per-driver telemetry to reduce runtime and disk usage.
  • --include-schedule – Also dump the full season schedule table for the requested year to the output directory.
  • --output-dir – Override the root output folder (default data/).
  • --cache-dir – Override the FastF1 cache location (default .fastf1-cache/).

The script enables the FastF1 on-disk cache automatically. The first download for a session may take a few minutes; reruns reuse cached data.

Output Structure

For the example above, artifacts land under data/2025_mexico_city_grand_prix_race/:

  • session_info.json – Metadata (event, drivers, circuit info, availability flags).
  • session_results.* – Classification / results table (if available).
  • laps.* – Lap-by-lap dataset, including timing, compound, stint details.
  • timing_data.*, timing_app_data.*, weather.*, race_control_messages.* – Additional session telemetry and timing fields when provided.
  • telemetry/<DRIVER>_car_data.* – Per-driver telemetry series (speed, throttle, brake, gear, etc.).
  • telemetry/<DRIVER>_position_data.* – XY track mapping for each driver.
  • telemetry/<DRIVER>_telemetry.* – High-frequency telemetry channels (DRS, steering, differential, etc.).
  • <year>_season_schedule.* – (optional via --include-schedule) championship event schedule.

All tables are stored as .parquet and .csv (falls back to CSV if Parquet export fails). JSON serialisation gracefully handles pandas-specific datatypes (Timestamp, Timedelta, numpy scalars).

Analysing Exported Sessions

After fetching data for a session, run:

python analyze_f1_data.py --session-dir data\2025_mexico_city_grand_prix_race

Parameters:

  • --session-dir (required) – Directory created by the fetch script for a specific session.
  • --output-dir – Override where analysis outputs should be written (defaults to <session-dir>/analysis/).
  • --prefer-csv – Force CSV inputs if you encounter Parquet compatibility issues.
  • --log-level – Adjust verbosity (INFO default).

Analysis Outputs

Within the analysis directory you will find:

  • fastest_laps.csv and fastest_laps.png – Ranking by best lap time (shorter is better).
  • drs_speeds.csv and drs_top_speed.png – Highest and average speeds while DRS was active, per driver.
  • tyre_usage.csv and tyre_usage.png – Stacked bar chart showing laps completed on each tyre compound by driver (highlights strategic differences).

All charts are saved as PNG (150 dpi) for quick sharing; CSV counterparts support downstream analytics or visualisation tooling.

Extending the Analysis

Both scripts are structured to make extension straightforward:

  • Add more telemetry-derived metrics by augmenting compute_* functions in analyze_f1_data.py. For example, average sector times, braking zones, or delta comparisons across teammates.
  • Drop extra tables in fetch_f1_data.py by wiring new export_* helpers. FastF1 exposes session.api_data, session.car_data, and other advanced feeds that can be persisted in a similar fashion.

Troubleshooting

  • Missing session data: Some older seasons or non-Championship sessions may not provide all timing feeds. The scripts log warnings and continue where possible.
  • JSON serialization errors: The metadata exporter now handles pandas/numpy/timedelta objects, but if a new type appears, note the type in the exception and add a handler to safe_json_default.
  • Telemetry gaps: If car telemetry is absent (e.g., practice sessions without full data), the exporter logs which driver failed; analysis functions will skip missing datasets gracefully.
  • SSL or HTTP errors: Occasionally the upstream API throttles requests. Rerun after a short delay; the cache ensures already-downloaded artifacts are reused.

Suggested Next Steps

  1. Automate recurring exports (e.g., after each race weekend) via Task Scheduler, cron, or a CI pipeline using the CLI scripts.
  2. Feed the exported Parquet tables into a notebook or BI tool (Power BI, Tableau) for deeper historical analysis.
  3. Integrate team/constructor metadata or driver standings from other APIs to enrich comparative studies across events.

Happy analysing, and enjoy visualising the story behind every lap!

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages