Predicts Formula 1 podium finishes (top 3) from qualifying pace and rolling
driver/team form, using 2024–2025 data pulled from the FastF1
API. Ships as a f1ml command-line pipeline and a browser dashboard with a
built-in console that runs those same commands.
This started as a set of Jupyter notebooks + copy-pasted scripts. It was
refactored into one installable package (src/f1_ml/) with the notebooks'
logic fixed and de-duplicated:
- Honest evaluation. Podium prediction is imbalanced (~15% of entries make the podium), so plain accuracy is misleading — always guessing "no podium" scores ~85%. We now report PR-AUC, ROC-AUC, per-class precision/recall, Brier score, and a top-3-per-race hit rate measured against the obvious baseline of picking the three fastest qualifiers.
- Leakage fixes. Rolling driver averages are now computed per driver (the old code rolled over a round-sorted frame and blended neighbouring drivers' results). Season stats reset per year and are shifted by one race.
- No fake rows. Entries with no race classification (DNS, or races that haven't run) are dropped instead of being filled in as fake P20 finishes.
- Better features. Qualifying position and grid position are now included (they're known before the race and are the strongest legitimate signal), plus qualifying gap-to-pole, a corrected street-circuit flag, and rolling team form. Driver renames (e.g. Andrea Kimi Antonelli → Kimi Antonelli) are normalised so a driver's history doesn't reset mid-season.
- Reproducible. No more hardcoded absolute paths; a single
f1mlCLI; a pytest suite; artifacts written tomodels/.
On a walk-forward backtest (retrain before every race, then score the top-3 picks) the model roughly matches the pick-the-top-3-qualifiers baseline — ~74% top-3 hit rate in 2025, ~63% in 2024. That's the point of the Model tab: in modern F1, grid position is brutally predictive, and the honest story is that beating it is hard. The model's real value is calibrated podium probabilities for the whole field, not just three names. The numbers you see are generated by the code, not typed into this README.
./run.sh # easiest — installs deps via uv, self-builds data, serves
make serve # same thing via make
docker build -t pitwall . && docker run --rm -p 5173:5173 pitwall # no Python neededThen open http://127.0.0.1:5173. The first launch self-builds the feature table and trains the models from the bundled CSVs (offline, a few seconds) — a fresh clone "just works".
To use the f1ml command directly, either prefix with uv run
(uv run f1ml info) or activate the venv first
(source .venv/bin/activate). A bare f1ml outside the venv will say
"command not found" — that's the venv, not a broken install.
The repo ships with 2024–2025 results. The one-shot way to bring everything current — pull the latest races, rebuild features, retrain, refresh the backtests — is:
uv run f1ml refresh # this season; add --year 2025 to pin onerefresh is idempotent and safe to run on a schedule: if there's no new data
(or no internet) it just rebuilds and retrains from what's on disk. Fetching a
live season is safe too — rounds that haven't happened yet are skipped — so
mid-2026 it pulls only the races that have run and retrains on them. To do the
steps by hand instead:
uv run f1ml fetch --year 2025 # download race + qualifying via FastF1
uv run f1ml merge --year 2025 # raw CSVs -> data/processed/*.csv
uv run f1ml features # rebuild the feature table
uv run f1ml train --model all # retrain, save models/ + metrics.jsonThe Docker image sets PITWALL_AUTO_REFRESH=24, so the running container
refreshes itself every 24 h: it pulls the season's latest results and retrains,
with no restart needed (predictions read the model files fresh each request).
As the 2026 races run, the live app fetches each new one and the model learns
from it automatically. Set the env var to another number of hours to change the
cadence, or to empty to turn it off. Each deploy starts from the data and
models in the image and the first refresh (about a minute in) catches the
season up; in the Oracle deploy the FastF1 download cache is kept on a Docker
volume so that catch-up is quick.
| Command | What it does |
|---|---|
f1ml info |
dataset & model status |
f1ml fetch --year 2025 [--session race|qualifying|both] |
download a season from FastF1 |
f1ml merge --year 2025 |
merge raw qualifying + race CSVs into a master file |
f1ml features |
build the model-ready feature table |
f1ml train [--model rf|gbdt|all] [--cutoff 2025:18] [--test-last 6] [--tune] |
train & evaluate on held-out races |
f1ml evaluate [--model rf|gbdt] |
reprint saved metrics + race-by-race picks |
f1ml predict --year 2025 --round 23 |
podium probabilities for one race |
f1ml backtest --year 2025 |
walk-forward backtest over a whole season |
f1ml standings --year 2025 |
driver & constructor standings |
f1ml weekend [--top 10] |
next Grand Prix + form-based podium projection |
f1ml fantasy [--budget 100] |
optimise an F1 Fantasy team within budget |
f1ml h2h --year 2024 --round 8 --d1 VER --d2 LEC [--session Q] |
telemetry head-to-head between two drivers |
f1ml raceline --image track.png [--length-km 5.3] [--out out.png] |
racing line + lap time from a track map (needs the vision extra) |
f1ml refresh [--year 2025] [--no-fetch] |
pull latest data, rebuild features, retrain, refresh backtests |
f1ml snapshot [--out site] |
pre-render a self-contained static site (for GitHub Pages) |
f1ml serve [--port 5173] |
launch the web dashboard |
Every command except serve is also runnable from the Console tab in the
web UI — the browser shells out to the exact same CLI (whitelisted, no shell
metacharacters) and streams the output back live. It only answers requests from
the same machine, so it is off inside Docker and on hosted deploys.
f1ml serve starts a Flask app (styled after F1 broadcast timing screens) with:
- Dashboard — season summary, championship leader, last-race podium, and a clickable strip of every round.
- Weekend — a race-weekend hub for the next Grand Prix: live countdown + session schedule in your local time, a circuit guide (the track's racing line auto-traced from last year's pole telemetry), a track-specific podium projection (recent form blended with each driver's record at this circuit), past winners here, this-race fantasy picks, and teammate battles. Driver names anywhere in the app open a profile card (season stats + best result + teammate head-to-head).
- Races — full classification per race with grid-to-finish deltas.
- Standings — computed driver & constructor tables.
- Telemetry — pick two drivers and a session: overlaid speed / throttle / brake traces, the time delta, sector comparison, and a track-dominance map coloured by who's quicker at each point of the lap.
- Strategy — every driver's tyre stints across a race, plus clean-lap race pace (gap to the fastest median).
- Model — honest metric tiles, model comparison, race-by-race picks, feature importance, and the walk-forward backtest grid.
- Predict — pick a race, retrain on everything before it, see ranked podium probabilities against the actual result.
- Fantasy — projected points and prices per driver/constructor, and the best-value F1 Fantasy team the budget can buy (with captain pick).
- Racing Line — upload a schematic track map and get the optimal line, the corners, and an idealised lap time (see below).
- Console — the
f1mlCLI, in the browser.
The Telemetry, Strategy and Weekend tabs pull live session data from FastF1, so the first load of a given session can take ~20–30 s while it downloads and caches. Everything runs locally; no data leaves your machine.
Upload a schematic track map (the tarmac drawn as a closed loop) and the analyzer will:
- segment the track and find its outer + inner edges,
- solve for the minimum-curvature racing line — a convex, globally-optimal geometric line, drawn straight onto your image and coloured by speed,
- detect every corner and, for each, show the three ways through it — early apex (early braking), optimal (geometric), and late apex (late braking) — which you can step through one by one,
- estimate an idealised lap time in minutes from a quasi-steady-state point-mass model with speed-dependent grip (mechanical + downforce), so slow corners are properly slow. On the bundled real circuits it lands within a few seconds of real qualifying pole (Silverstone ~1:25, Hungaroring ~1:16, Red Bull Ring ~1:04).
f1ml raceline --image my_track.png --length-km 5.3
# or use the Racing Line tab in `f1ml serve`Honest scope. The minimum-curvature line is the classic "textbook" racing
line — on a clean map it is at most slightly sub-optimal. It is not a full
minimum-lap-time trajectory (that needs a real vehicle/aero model), and the lap
time, while calibrated to be realistic, is still an idealised point-mass
estimate, not a simulation of a specific car. Best results come from clean,
closed-loop track maps with the tarmac as a filled band or clear outline;
arbitrary ground-level photos are out of scope. Very tight hairpins can merge
their in/out lanes on a low-resolution map — render the map larger or with a
thinner track so the corner stays open (see samples/build_real_tracks.py).
The dashboard can run as a fully static site with no server. f1ml snapshot
pre-renders every API response the core needs (standings, model, predictions,
the race-weekend hub, driver profiles) into JSON, and a small static-shim.js
makes the same frontend read those files when there's no backend:
uv run f1ml snapshot --out site
python -m http.server -d site 8000 # preview at http://localhost:8000.github/workflows/pages.yml does this on a schedule (every Monday, after the
race) and on every push: it runs f1ml refresh to pull the latest results,
f1ml snapshot, and publishes site/ to GitHub Pages — a permanent, free,
no-card public URL that stays current on its own.
One-time setup: in the repo, Settings → Pages → Build and deployment →
Source: GitHub Actions. Push to main (or run the workflow manually) and the
site goes live at https://<you>.github.io/<repo>/.
The live-FastF1 features (telemetry duels, strategy, racing-line upload) need
the Python backend, so on the static build those tabs show a short notice and
point to f1ml serve. Everything else is live from the snapshot. To keep those
features public too, deploy the container instead — see DEPLOY.md.
src/f1_ml/ the package
config.py paths & constants (project-root relative)
data.py FastF1 fetch, merge, load, standings
features.py feature engineering (leakage-safe)
modeling.py training, time-ordered splits, artifacts
evaluate.py metrics incl. top-3-per-race hit rate
predict.py single-race prediction
backtest.py walk-forward season backtest
telemetry.py FastF1 telemetry / tyres / race pace (fan features)
weekend.py next race + form-based podium projection
fantasy.py F1 Fantasy points projection + team optimiser
racingline.py track-map → racing line + lap time (needs 'vision' extra)
cli.py the `f1ml` command
server.py Flask API + console runner + auto-refresh scheduler
pipeline.py fetch → rebuild → retrain → backtest (shared refresh loop)
snapshot.py pre-render the app to a static site (for GitHub Pages)
web/ dashboard frontend (no build step)
index.html styles.css app.js charts.js telemetry.js companion.js racingline.js
static-shim.js lets the same frontend run backendless off the snapshot
tests/ pytest suite
e2e/ Playwright frontend smoke tests
data/ raw/ and processed/ CSVs
models/ trained artifacts + metrics.json (git-ignored)
notebooks/ original exploration notebooks (uv sync --group notebooks)
pytest # Python: 42 tests
npm ci && npx playwright test # frontend smoke tests (boots f1ml serve)Python covers the leakage guards, no-fake-row dropping, driver/team
normalisation, the top-3-per-race metric, time-ordered splits, and CLI parsing.
The Playwright suite (e2e/) drives the real dashboard: every tab loads without
console errors, the core data views render, the driver modal is keyboard
accessible (open, Esc, focus return), and the telemetry scrubber responds to the
keyboard. Both run in CI (.github/workflows/ci.yml).
- Data source: FastF1. First fetch is slow; results are cached in
fastf1_cache_dir/. - Models: scikit-learn
RandomForestClassifierandHistGradientBoostingClassifier, both withclass_weight="balanced". - Reproducibility:
random_state=42throughout; splits are strictly time ordered by(Year, Round)so the model never trains on the future.