A small FastAPI app that discovers the most discussed F1 topics on Reddit, fetches related news, and shows current driver standings.
- 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
- Supports multiple subreddits:
- 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
- Python 3.11+ recommended
- Windows PowerShell commands below; adapt to your shell if needed
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txtuvicorn app.main:app --host 127.0.0.1 --port 8000 --reloadThen open http://127.0.0.1:8000.
- Controls
- Subreddits: comma‑separated list, e.g.
formula1,F1Technical,F1DataAnalysis - Time range: choose among
day,week,month,year,all - Optional filter: type
driverorteamwith a name (e.g.,Verstappen,Ferrari) to restrict posts - Click Refresh to apply
- Subreddits: comma‑separated list, e.g.
- Click a keyword chip to load related news articles
- “Detected Entities” shows drivers/teams found across loaded posts
Base URL: http://127.0.0.1:8000
-
GET
/api/reddit/top-topic- Query params:
subs(optional): comma‑separated subreddits. Default:formula1t(optional):day|week|month|year|all. Default:weekfilter_type(optional):driver|teamfilter_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" }] }
- Query params:
-
GET
/api/news- Query params:
topic(string) - Response:
{ topic, items: [{ title, link, published, source }] }
- Query params:
-
GET
/api/f1/standings- Response:
{ source, data, note? }(Ergast format when available)
- Response:
-
GET
/api/metadata- Response: lists of known drivers, teams, default subreddits, and available time ranges
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"- 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.
app/
main.py # FastAPI app, endpoints, Reddit/topic logic
static/
index.html # Minimal UI
requirements.txt # Python dependencies
README.md # This file
MIT (or your preferred license)
Utilities for downloading detailed Formula 1 session data with FastF1 and producing quick-turn performance analysis artifacts.
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.
- Python 3.10+ (tested with Python 3.11 / 3.12 / 3.13).
- System packages required by
matplotlibandpyarrow(on Windows these ship as wheels; on Linux install system libraries such aslibssl-dev,libstdc++, etc.).
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.txtTip:
pyarrowis optional but recommended; without it the export script falls back to CSV only.
python fetch_f1_data.py --year 2025 --event "Mexico City Grand Prix" --session Race --include-scheduleKey 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 toRace.--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 (defaultdata/).--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.
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).
After fetching data for a session, run:
python analyze_f1_data.py --session-dir data\2025_mexico_city_grand_prix_raceParameters:
--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 (INFOdefault).
Within the analysis directory you will find:
fastest_laps.csvandfastest_laps.png– Ranking by best lap time (shorter is better).drs_speeds.csvanddrs_top_speed.png– Highest and average speeds while DRS was active, per driver.tyre_usage.csvandtyre_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.
Both scripts are structured to make extension straightforward:
- Add more telemetry-derived metrics by augmenting
compute_*functions inanalyze_f1_data.py. For example, average sector times, braking zones, or delta comparisons across teammates. - Drop extra tables in
fetch_f1_data.pyby wiring newexport_*helpers. FastF1 exposessession.api_data,session.car_data, and other advanced feeds that can be persisted in a similar fashion.
- 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.
- Automate recurring exports (e.g., after each race weekend) via Task Scheduler, cron, or a CI pipeline using the CLI scripts.
- Feed the exported Parquet tables into a notebook or BI tool (Power BI, Tableau) for deeper historical analysis.
- 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!