apexgrid 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. apexgrid-1.0.0/LICENSE +21 -0
  2. apexgrid-1.0.0/PKG-INFO +290 -0
  3. apexgrid-1.0.0/README.md +269 -0
  4. apexgrid-1.0.0/apexgrid.egg-info/PKG-INFO +290 -0
  5. apexgrid-1.0.0/apexgrid.egg-info/SOURCES.txt +104 -0
  6. apexgrid-1.0.0/apexgrid.egg-info/dependency_links.txt +1 -0
  7. apexgrid-1.0.0/apexgrid.egg-info/entry_points.txt +2 -0
  8. apexgrid-1.0.0/apexgrid.egg-info/requires.txt +12 -0
  9. apexgrid-1.0.0/apexgrid.egg-info/top_level.txt +1 -0
  10. apexgrid-1.0.0/pyproject.toml +37 -0
  11. apexgrid-1.0.0/setup.cfg +4 -0
  12. apexgrid-1.0.0/src/__init__.py +1 -0
  13. apexgrid-1.0.0/src/cli/__init__.py +4 -0
  14. apexgrid-1.0.0/src/cli/historical_menu.py +861 -0
  15. apexgrid-1.0.0/src/cli/menu.py +2617 -0
  16. apexgrid-1.0.0/src/cli/terminal_ui.py +705 -0
  17. apexgrid-1.0.0/src/cli/typer_app.py +1413 -0
  18. apexgrid-1.0.0/src/config/model_config.json +151 -0
  19. apexgrid-1.0.0/src/config/settings.json +15 -0
  20. apexgrid-1.0.0/src/config/strategy_config.json +165 -0
  21. apexgrid-1.0.0/src/config/tracks.json +580 -0
  22. apexgrid-1.0.0/src/data/__init__.py +1 -0
  23. apexgrid-1.0.0/src/data/calendar_service.py +309 -0
  24. apexgrid-1.0.0/src/data/collect_season.py +1091 -0
  25. apexgrid-1.0.0/src/data/collect_track.py +379 -0
  26. apexgrid-1.0.0/src/data/data_loader.py +770 -0
  27. apexgrid-1.0.0/src/data/data_manager.py +650 -0
  28. apexgrid-1.0.0/src/data/data_validator.py +135 -0
  29. apexgrid-1.0.0/src/data/deletion_audit.py +87 -0
  30. apexgrid-1.0.0/src/data/grid_retriever.py +1377 -0
  31. apexgrid-1.0.0/src/data/roster_resolver.py +584 -0
  32. apexgrid-1.0.0/src/data/season_discovery.py +241 -0
  33. apexgrid-1.0.0/src/data/session_validation.py +107 -0
  34. apexgrid-1.0.0/src/features/__init__.py +43 -0
  35. apexgrid-1.0.0/src/features/build_features.py +1086 -0
  36. apexgrid-1.0.0/src/features/grid_conversion.py +183 -0
  37. apexgrid-1.0.0/src/features/grid_features.py +611 -0
  38. apexgrid-1.0.0/src/features/race_pace.py +342 -0
  39. apexgrid-1.0.0/src/features/season_features.py +336 -0
  40. apexgrid-1.0.0/src/features/teammate_features.py +261 -0
  41. apexgrid-1.0.0/src/features/tire_degradation.py +353 -0
  42. apexgrid-1.0.0/src/features/track_features.py +79 -0
  43. apexgrid-1.0.0/src/features/weather_features.py +179 -0
  44. apexgrid-1.0.0/src/features/weekend_features.py +285 -0
  45. apexgrid-1.0.0/src/historical/__init__.py +86 -0
  46. apexgrid-1.0.0/src/historical/analytics/__init__.py +58 -0
  47. apexgrid-1.0.0/src/historical/analytics/circuit_analytics.py +185 -0
  48. apexgrid-1.0.0/src/historical/analytics/dominance.py +132 -0
  49. apexgrid-1.0.0/src/historical/analytics/driver_analytics.py +425 -0
  50. apexgrid-1.0.0/src/historical/analytics/eras.py +149 -0
  51. apexgrid-1.0.0/src/historical/analytics/models.py +158 -0
  52. apexgrid-1.0.0/src/historical/analytics/qualifying_analytics.py +179 -0
  53. apexgrid-1.0.0/src/historical/analytics/race_analytics.py +175 -0
  54. apexgrid-1.0.0/src/historical/analytics/records.py +160 -0
  55. apexgrid-1.0.0/src/historical/analytics/reliability.py +76 -0
  56. apexgrid-1.0.0/src/historical/analytics/season_analytics.py +209 -0
  57. apexgrid-1.0.0/src/historical/analytics/session_results.py +518 -0
  58. apexgrid-1.0.0/src/historical/analytics/teammate_analytics.py +199 -0
  59. apexgrid-1.0.0/src/historical/api_client.py +244 -0
  60. apexgrid-1.0.0/src/historical/circuits_service.py +151 -0
  61. apexgrid-1.0.0/src/historical/classification_service.py +236 -0
  62. apexgrid-1.0.0/src/historical/events_service.py +260 -0
  63. apexgrid-1.0.0/src/historical/grid_service.py +176 -0
  64. apexgrid-1.0.0/src/historical/in_memory_cache.py +102 -0
  65. apexgrid-1.0.0/src/historical/models.py +287 -0
  66. apexgrid-1.0.0/src/historical/qualifying_service.py +345 -0
  67. apexgrid-1.0.0/src/historical/rate_limiter.py +121 -0
  68. apexgrid-1.0.0/src/models/__init__.py +6 -0
  69. apexgrid-1.0.0/src/models/dnf_hazard.py +125 -0
  70. apexgrid-1.0.0/src/models/evaluate.py +748 -0
  71. apexgrid-1.0.0/src/models/predict.py +382 -0
  72. apexgrid-1.0.0/src/models/train.py +152 -0
  73. apexgrid-1.0.0/src/pipeline/__init__.py +4 -0
  74. apexgrid-1.0.0/src/pipeline/race_prediction_pipeline.py +1779 -0
  75. apexgrid-1.0.0/src/simulation/__init__.py +4 -0
  76. apexgrid-1.0.0/src/simulation/monte_carlo.py +363 -0
  77. apexgrid-1.0.0/src/simulation/race_control_model.py +162 -0
  78. apexgrid-1.0.0/src/simulation/strategy_simulator.py +341 -0
  79. apexgrid-1.0.0/src/utils/__init__.py +1 -0
  80. apexgrid-1.0.0/src/utils/circuit_mapping.py +139 -0
  81. apexgrid-1.0.0/src/utils/driver_mapping.py +197 -0
  82. apexgrid-1.0.0/src/utils/logging_utils.py +70 -0
  83. apexgrid-1.0.0/src/utils/paths.py +81 -0
  84. apexgrid-1.0.0/src/utils/team_mapping.py +43 -0
  85. apexgrid-1.0.0/src/utils/timing.py +58 -0
  86. apexgrid-1.0.0/tests/test_availability_history.py +110 -0
  87. apexgrid-1.0.0/tests/test_cli_menu.py +76 -0
  88. apexgrid-1.0.0/tests/test_collectors_availability.py +131 -0
  89. apexgrid-1.0.0/tests/test_core_features.py +226 -0
  90. apexgrid-1.0.0/tests/test_data_manager.py +33 -0
  91. apexgrid-1.0.0/tests/test_dnf_hazard.py +41 -0
  92. apexgrid-1.0.0/tests/test_dynamic_roster.py +198 -0
  93. apexgrid-1.0.0/tests/test_feature_schema.py +76 -0
  94. apexgrid-1.0.0/tests/test_grid_race_logic.py +127 -0
  95. apexgrid-1.0.0/tests/test_historical.py +65 -0
  96. apexgrid-1.0.0/tests/test_historical_intelligence_v2.py +262 -0
  97. apexgrid-1.0.0/tests/test_logging_coordination.py +151 -0
  98. apexgrid-1.0.0/tests/test_ml_integrity.py +122 -0
  99. apexgrid-1.0.0/tests/test_monte_carlo.py +115 -0
  100. apexgrid-1.0.0/tests/test_podium_and_grid_display.py +225 -0
  101. apexgrid-1.0.0/tests/test_race_strategy.py +66 -0
  102. apexgrid-1.0.0/tests/test_remediation_integrity.py +384 -0
  103. apexgrid-1.0.0/tests/test_report_generation.py +86 -0
  104. apexgrid-1.0.0/tests/test_terminal_ui.py +231 -0
  105. apexgrid-1.0.0/tests/test_walk_forward.py +115 -0
  106. apexgrid-1.0.0/tests/test_weekend_only_pipeline.py +285 -0
apexgrid-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dinesh Dhayfule
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,290 @@
1
+ Metadata-Version: 2.4
2
+ Name: apexgrid
3
+ Version: 1.0.0
4
+ Summary: Formula 1 race outcome prediction engine using FastF1 telemetry and Monte Carlo simulation
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy<3.0.0,>=1.26.0
10
+ Requires-Dist: pandas<3.0.0,>=2.1.0
11
+ Requires-Dist: scipy<2.0.0,>=1.11.0
12
+ Requires-Dist: scikit-learn<2.0.0,>=1.3.0
13
+ Requires-Dist: xgboost<4.0.0,>=2.0.0
14
+ Requires-Dist: fastf1<4.0.0,>=3.4.0
15
+ Requires-Dist: typer<1.0.0,>=0.12.0
16
+ Requires-Dist: rich<15.0.0,>=13.7.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest<9.0.0,>=8.0.0; extra == "dev"
19
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ <div align="center">
23
+
24
+ # ApexGrid — Formula 1 Race Prediction & Motorsport Intelligence Engine
25
+
26
+ **ML-powered Formula 1 race predictions using FastF1 telemetry ingestion, a calibrated multi-model ensemble (Random Forest, XGBoost, Ridge Regression), and 25,000-iteration stochastic Monte Carlo simulation with stage-aware qualifying grid blending.**
27
+
28
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://www.python.org/)
29
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
30
+ [![Tests](https://img.shields.io/badge/tests-183%20passed%20%E2%9C%93-brightgreen.svg)](tests/)
31
+ [![ML Ensemble](https://img.shields.io/badge/ensemble-RF%20%2B%20XGB%20%2B%20Ridge-orange.svg)](src/models/)
32
+ [![Monte Carlo](https://img.shields.io/badge/Monte%20Carlo-25%2C000%20runs-purple.svg)](src/simulation/)
33
+
34
+ </div>
35
+
36
+ ---
37
+
38
+ ApexGrid is a production-grade Formula 1 race prediction platform that forecasts finishing positions, win probabilities, podium chances, and points finishes across all 23 championship rounds. It ingests real-time practice and qualifying telemetry via FastF1 and OpenF1, engineers 25+ predictive features (fuel-corrected pace, tire degradation curves, weather dynamics, safety car hazard priors), blends them through a calibrated multi-model ML ensemble of Random Forest, XGBoost, and Ridge Regression, and runs 25,000 stochastic Monte Carlo race simulations with empirical DNF hazard modeling — all behind strict stage-aware temporal boundaries that prevent future-session data leakage from qualifying or race results contaminating earlier predictions.
39
+
40
+ ```
41
+ FastF1 / OpenF1 ──► Feature Engineering ──► ML Ensemble ──► 25,000 Monte Carlo ──► Predictions
42
+ Telemetry (25+ features) (RF+XGB+Ridge) (DNF, weather, (Win%, Podium%,
43
+ (FP1–Quali) SC hazards) ExpectedFinish)
44
+ ```
45
+
46
+ ---
47
+
48
+ ## Table of Contents
49
+
50
+ - [Key Features](#key-features)
51
+ - [Quick Start](#quick-start)
52
+ - [Interactive Menu](#interactive-menu)
53
+ - [CLI Usage Recipes](#cli-usage-recipes)
54
+ - [Technical Architecture](#technical-architecture)
55
+ - [Configuration](#configuration)
56
+ - [Verification & Testing](#verification--testing)
57
+ - [Tech Stack](#tech-stack)
58
+ - [Contributing](#contributing)
59
+ - [License](#license)
60
+
61
+ ---
62
+
63
+ ## Key Features
64
+
65
+ - **Calibrated 3-Way ML Ensemble** — Random Forest (40%) + XGBoost (30%) + Ridge Regression (30%), tuned via chronological walk-forward validation. Also supports a 2-way hybrid mode (60/40 RF/XGB) and fully custom weight splits.
66
+ - **Circuit-Aware Starting-Grid Blending** — Dynamically adjusts grid vs. ML weighting by circuit topology: street circuits (Monaco, Baku, Singapore) at 50/50, permanent tracks (Spa, Monza, Silverstone) at 35/65, temporary venues (Melbourne, Montreal) at 45/55.
67
+ - **Stage-Gated Anti-Leakage** — Seven temporal stages (`pre_fp1`, `after_fp1`, `after_fp2`, `after_fp3`, `after_sprint_qualifying`, `after_sprint_race`, `after_qualifying`) strictly prevent qualifying or race data from contaminating earlier-stage predictions.
68
+ - **25,000-Run Monte Carlo Engine** — Stochastic race simulation with residual-calibrated pace variance, empirical DNF hazard modeling, wet-skill differentials, field compression dynamics, and venue-specific safety car disruption probabilities.
69
+ - **Zero-Leakage Walk-Forward Validation** — Shuffled k-fold is strictly prohibited. Models train on rounds {1…r−1} and test on out-of-sample round r, with blocked residual arrays on any fold failure.
70
+ - **Historical Intelligence (1950–2026)** — 11 analytics modules: driver career stats, teammate H2H, qualifying performance, race craft, circuit records, championship standings, session results, constructor dominance, all-time records, reliability analysis, and regulatory era comparisons.
71
+
72
+ ---
73
+
74
+ ## Quick Start
75
+
76
+ ```bash
77
+ git clone https://github.com/dineshdhayfule/F1-Race-Predictions.git
78
+ cd F1-Race-Predictions
79
+ python -m venv .venv
80
+ ```
81
+
82
+ Activate the virtual environment:
83
+
84
+ ```powershell
85
+ # Windows (PowerShell)
86
+ .venv\Scripts\Activate.ps1
87
+ ```
88
+
89
+ ```bash
90
+ # macOS / Linux
91
+ source .venv/bin/activate
92
+ ```
93
+
94
+ Install dependencies and launch:
95
+
96
+ ```bash
97
+ pip install -r requirements.txt
98
+ pip install -e . # enables the `apexgrid` CLI binary
99
+ ```
100
+
101
+ ```bash
102
+ python main.py # argparse entrypoint
103
+ # or
104
+ apexgrid # Typer entrypoint (requires editable install)
105
+ ```
106
+
107
+ ---
108
+
109
+ ## Interactive Menu
110
+
111
+ `python main.py` launches a guided Rich terminal interface with eight workflows:
112
+
113
+ | # | Option | Description |
114
+ |---|--------|-------------|
115
+ | 1 | **Predict a Race** | Circuit → weekend stage → model selection → forecast |
116
+ | 2 | **Load / Collect Data** | Ingest FastF1 practice, qualifying, and race telemetry |
117
+ | 3 | **Evaluate a Prediction** | Score forecast accuracy against official classifications |
118
+ | 4 | **View Previous Predictions** | Browse saved prediction tables and Markdown reports |
119
+ | 5 | **Historical Statistics** | 11 analytics modules spanning 1950–2026 |
120
+ | 6 | **System Health** | Diagnostic checks and data readiness audit |
121
+ | 7 | **Configuration** | View circuit parameters, track types, model settings |
122
+ | 8 | **Data Management** | Preview and prune cached telemetry files safely |
123
+
124
+ ---
125
+
126
+ ## CLI Usage Recipes
127
+
128
+ ### Race Predictions
129
+
130
+ ```bash
131
+ # Full 3-way ensemble, pre-qualifying stage
132
+ python main.py predict --track monza --year 2026 --stage pre_fp1 --model ensemble
133
+
134
+ # Default hybrid (60% RF / 40% XGB), post-qualifying
135
+ python main.py predict --track silverstone --year 2026 --stage after_qualifying
136
+
137
+ # Enhanced physics (race pace, tire deg, pit strategy, weather, race control)
138
+ python main.py predict --track monaco --year 2026 --stage after_fp3 --model ensemble --enhanced
139
+
140
+ # Custom ensemble weights (70% RF / 30% XGB)
141
+ python main.py predict --track baku --year 2026 --stage after_qualifying --model hybrid --rf-weight 70 --xgb-weight 30
142
+ ```
143
+
144
+ ### Walk-Forward Validation
145
+
146
+ ```bash
147
+ python main.py evaluate --track sepang --year 2026
148
+ python main.py validate --track baku --year 2026 --stage after_qualifying
149
+ ```
150
+
151
+ ### Historical Analytics
152
+
153
+ ```bash
154
+ python main.py history
155
+ ```
156
+
157
+ Subcommands: `driver` · `h2h` · `qualifying` · `race` · `circuit` · `standings` · `session` · `dominance` · `records` · `reliability` · `eras`
158
+
159
+ ### Data Collection & Cleanup
160
+
161
+ ```bash
162
+ python main.py collect-season --year 2026 # Full season ingestion
163
+ python main.py clean --target cache --preview # Dry-run preview
164
+ python main.py clean --target cache --force # Execute cleanup
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Technical Architecture
170
+
171
+ <details>
172
+ <summary><b>Technical Methodology & Mathematical Formulation</b></summary>
173
+
174
+ ### Stage-Gated Grid Blending
175
+
176
+ Starting grid positions heavily influence race outcomes, but using qualifying data before qualifying introduces catastrophic lookahead bias. ApexGrid resolves this with stage-aware gating:
177
+
178
+ **Post-Qualifying:** Official FIA grid positions (including penalty cascades and pit-lane starts) blend with pure ML pace scores using circuit-topology weights:
179
+
180
+
181
+ $$
182
+ \text{Score}_{\text{blended}} = w_{\text{ml}} \cdot \text{Score}_{\text{ML}} + w_{\text{grid}} \cdot \text{Grid}_{\text{actual}}
183
+ $$
184
+
185
+
186
+ | Circuit Type | $w_{\text{grid}}$ | $w_{\text{ml}}$ | Examples |
187
+ |---|---|---|---|
188
+ | Street | 0.50 | 0.50 | Monaco, Baku, Singapore |
189
+ | Permanent | 0.35 | 0.65 | Spa, Monza, Silverstone |
190
+ | Temporary | 0.45 | 0.55 | Melbourne, Montreal |
191
+
192
+ **Pre-Qualifying:** Grid data is masked to NaN. The pipeline generates provisional qualifying forecasts (displayed as `~P1`, `~P2`, etc.) or cleanly disables blending ($w_{\text{grid}} = 0$, $w_{\text{ml}} = 1$).
193
+
194
+ ---
195
+
196
+ ### Dual-View Outcome Presentation
197
+
198
+ Monte Carlo simulations produce full finishing distributions, presented in two views:
199
+
200
+ - **Podium Banner:** Top 3 drivers selected by Win% ↓, then Podium% ↓, then ExpectedFinish ↑ (tie-breaker).
201
+ - **Full Field Table:** All drivers ranked by DNF-adjusted ExpectedFinish. Non-finishers receive a +1000.0 penalty, ensuring they rank behind all classified finishers.
202
+
203
+ ---
204
+
205
+ ### Walk-Forward Validation
206
+
207
+ Shuffled k-fold is strictly prohibited. For each validation round $r > \text{min\_train\_rounds}$, models train exclusively on rounds $\{1 \dots r{-}1\}$ and test on out-of-sample round $r$. If any fold fails, validation transitions to `BLOCKED` and all residual arrays are cleared to prevent partial contamination.
208
+
209
+ ---
210
+
211
+ ### Residual-Calibrated Pace Volatility
212
+
213
+ Monte Carlo variance is empirically calibrated from walk-forward residuals using Median Absolute Deviation:
214
+
215
+
216
+ $$
217
+ \sigma = \max\!\left(1.5,\; 1.4826 \cdot \text{MAD}(\text{residuals})\right)
218
+ $$
219
+
220
+
221
+ Under wet-weather sampling: volatility scales by 1.35×, DNF hazard scales by 1.40×.
222
+
223
+ ---
224
+
225
+ ### Decoupled Two-Stage Modeling
226
+
227
+ ML regressors (RF, XGBoost, Ridge) train exclusively on classified finishers — mechanical retirements and lap-1 incidents are excluded so pace signal stays uncorrupted. DNF hazards are modeled separately via binomial draws during Monte Carlo simulation.
228
+
229
+ ---
230
+
231
+ ### EWMA Form Tracking
232
+
233
+ Driver and constructor rolling form uses exponentially weighted moving average with decay $\alpha = 0.30$, heavily weighting the most recent 3–5 rounds to capture mid-season aerodynamic upgrades while maintaining baseline stability.
234
+
235
+ </details>
236
+
237
+ ---
238
+
239
+ ## Configuration
240
+
241
+ JSON configuration files in [`config/`](config/):
242
+
243
+ | File | Purpose |
244
+ |------|---------|
245
+ | [`model_config.json`](config/model_config.json) | Ensemble weights, hyperparameters, feature sets, circuit blending weights |
246
+ | [`tracks.json`](config/tracks.json) | 23 championship circuits — lengths, types, calendar mappings |
247
+ | [`strategy_config.json`](config/strategy_config.json) | Tire compounds, pit loss times, 15 circuit-specific strategy priors |
248
+ | [`settings.json`](config/settings.json) | Cache paths, logging thresholds, output directories |
249
+
250
+ ---
251
+
252
+ ## Verification & Testing
253
+
254
+ **183 tests** across 21 modules — 100% pass rate:
255
+
256
+ ```bash
257
+ pytest # Full suite
258
+ pytest tests/test_walk_forward.py # Walk-forward validation
259
+ pytest tests/test_core_features.py # Stage isolation & anti-leakage
260
+ pytest tests/test_dynamic_roster.py # Driver substitution handling
261
+ pytest tests/test_weekend_only_pipeline.py # Weekend-only ML pipeline
262
+ ```
263
+
264
+ ---
265
+
266
+ ## Tech Stack
267
+
268
+ | Component | Technologies |
269
+ |-----------|-------------|
270
+ | **Language** | Python 3.10 – 3.13 |
271
+ | **Machine Learning** | Scikit-Learn (Random Forest, Ridge), XGBoost |
272
+ | **Scientific** | NumPy, SciPy, Pandas |
273
+ | **Telemetry** | FastF1, OpenF1 REST API |
274
+ | **CLI / TUI** | Typer, Rich |
275
+ | **Testing** | Pytest |
276
+
277
+ ---
278
+
279
+ ## Contributing
280
+
281
+ 1. Fork the repository and create a feature branch
282
+ 2. Add tests matching existing conventions in [`tests/`](tests/)
283
+ 3. Confirm `pytest` exits with code 0 (zero regressions)
284
+ 4. Open a PR against `main` with verification logs
285
+
286
+ ---
287
+
288
+ ## License
289
+
290
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,269 @@
1
+ <div align="center">
2
+
3
+ # ApexGrid — Formula 1 Race Prediction & Motorsport Intelligence Engine
4
+
5
+ **ML-powered Formula 1 race predictions using FastF1 telemetry ingestion, a calibrated multi-model ensemble (Random Forest, XGBoost, Ridge Regression), and 25,000-iteration stochastic Monte Carlo simulation with stage-aware qualifying grid blending.**
6
+
7
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://www.python.org/)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
9
+ [![Tests](https://img.shields.io/badge/tests-183%20passed%20%E2%9C%93-brightgreen.svg)](tests/)
10
+ [![ML Ensemble](https://img.shields.io/badge/ensemble-RF%20%2B%20XGB%20%2B%20Ridge-orange.svg)](src/models/)
11
+ [![Monte Carlo](https://img.shields.io/badge/Monte%20Carlo-25%2C000%20runs-purple.svg)](src/simulation/)
12
+
13
+ </div>
14
+
15
+ ---
16
+
17
+ ApexGrid is a production-grade Formula 1 race prediction platform that forecasts finishing positions, win probabilities, podium chances, and points finishes across all 23 championship rounds. It ingests real-time practice and qualifying telemetry via FastF1 and OpenF1, engineers 25+ predictive features (fuel-corrected pace, tire degradation curves, weather dynamics, safety car hazard priors), blends them through a calibrated multi-model ML ensemble of Random Forest, XGBoost, and Ridge Regression, and runs 25,000 stochastic Monte Carlo race simulations with empirical DNF hazard modeling — all behind strict stage-aware temporal boundaries that prevent future-session data leakage from qualifying or race results contaminating earlier predictions.
18
+
19
+ ```
20
+ FastF1 / OpenF1 ──► Feature Engineering ──► ML Ensemble ──► 25,000 Monte Carlo ──► Predictions
21
+ Telemetry (25+ features) (RF+XGB+Ridge) (DNF, weather, (Win%, Podium%,
22
+ (FP1–Quali) SC hazards) ExpectedFinish)
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Table of Contents
28
+
29
+ - [Key Features](#key-features)
30
+ - [Quick Start](#quick-start)
31
+ - [Interactive Menu](#interactive-menu)
32
+ - [CLI Usage Recipes](#cli-usage-recipes)
33
+ - [Technical Architecture](#technical-architecture)
34
+ - [Configuration](#configuration)
35
+ - [Verification & Testing](#verification--testing)
36
+ - [Tech Stack](#tech-stack)
37
+ - [Contributing](#contributing)
38
+ - [License](#license)
39
+
40
+ ---
41
+
42
+ ## Key Features
43
+
44
+ - **Calibrated 3-Way ML Ensemble** — Random Forest (40%) + XGBoost (30%) + Ridge Regression (30%), tuned via chronological walk-forward validation. Also supports a 2-way hybrid mode (60/40 RF/XGB) and fully custom weight splits.
45
+ - **Circuit-Aware Starting-Grid Blending** — Dynamically adjusts grid vs. ML weighting by circuit topology: street circuits (Monaco, Baku, Singapore) at 50/50, permanent tracks (Spa, Monza, Silverstone) at 35/65, temporary venues (Melbourne, Montreal) at 45/55.
46
+ - **Stage-Gated Anti-Leakage** — Seven temporal stages (`pre_fp1`, `after_fp1`, `after_fp2`, `after_fp3`, `after_sprint_qualifying`, `after_sprint_race`, `after_qualifying`) strictly prevent qualifying or race data from contaminating earlier-stage predictions.
47
+ - **25,000-Run Monte Carlo Engine** — Stochastic race simulation with residual-calibrated pace variance, empirical DNF hazard modeling, wet-skill differentials, field compression dynamics, and venue-specific safety car disruption probabilities.
48
+ - **Zero-Leakage Walk-Forward Validation** — Shuffled k-fold is strictly prohibited. Models train on rounds {1…r−1} and test on out-of-sample round r, with blocked residual arrays on any fold failure.
49
+ - **Historical Intelligence (1950–2026)** — 11 analytics modules: driver career stats, teammate H2H, qualifying performance, race craft, circuit records, championship standings, session results, constructor dominance, all-time records, reliability analysis, and regulatory era comparisons.
50
+
51
+ ---
52
+
53
+ ## Quick Start
54
+
55
+ ```bash
56
+ git clone https://github.com/dineshdhayfule/F1-Race-Predictions.git
57
+ cd F1-Race-Predictions
58
+ python -m venv .venv
59
+ ```
60
+
61
+ Activate the virtual environment:
62
+
63
+ ```powershell
64
+ # Windows (PowerShell)
65
+ .venv\Scripts\Activate.ps1
66
+ ```
67
+
68
+ ```bash
69
+ # macOS / Linux
70
+ source .venv/bin/activate
71
+ ```
72
+
73
+ Install dependencies and launch:
74
+
75
+ ```bash
76
+ pip install -r requirements.txt
77
+ pip install -e . # enables the `apexgrid` CLI binary
78
+ ```
79
+
80
+ ```bash
81
+ python main.py # argparse entrypoint
82
+ # or
83
+ apexgrid # Typer entrypoint (requires editable install)
84
+ ```
85
+
86
+ ---
87
+
88
+ ## Interactive Menu
89
+
90
+ `python main.py` launches a guided Rich terminal interface with eight workflows:
91
+
92
+ | # | Option | Description |
93
+ |---|--------|-------------|
94
+ | 1 | **Predict a Race** | Circuit → weekend stage → model selection → forecast |
95
+ | 2 | **Load / Collect Data** | Ingest FastF1 practice, qualifying, and race telemetry |
96
+ | 3 | **Evaluate a Prediction** | Score forecast accuracy against official classifications |
97
+ | 4 | **View Previous Predictions** | Browse saved prediction tables and Markdown reports |
98
+ | 5 | **Historical Statistics** | 11 analytics modules spanning 1950–2026 |
99
+ | 6 | **System Health** | Diagnostic checks and data readiness audit |
100
+ | 7 | **Configuration** | View circuit parameters, track types, model settings |
101
+ | 8 | **Data Management** | Preview and prune cached telemetry files safely |
102
+
103
+ ---
104
+
105
+ ## CLI Usage Recipes
106
+
107
+ ### Race Predictions
108
+
109
+ ```bash
110
+ # Full 3-way ensemble, pre-qualifying stage
111
+ python main.py predict --track monza --year 2026 --stage pre_fp1 --model ensemble
112
+
113
+ # Default hybrid (60% RF / 40% XGB), post-qualifying
114
+ python main.py predict --track silverstone --year 2026 --stage after_qualifying
115
+
116
+ # Enhanced physics (race pace, tire deg, pit strategy, weather, race control)
117
+ python main.py predict --track monaco --year 2026 --stage after_fp3 --model ensemble --enhanced
118
+
119
+ # Custom ensemble weights (70% RF / 30% XGB)
120
+ python main.py predict --track baku --year 2026 --stage after_qualifying --model hybrid --rf-weight 70 --xgb-weight 30
121
+ ```
122
+
123
+ ### Walk-Forward Validation
124
+
125
+ ```bash
126
+ python main.py evaluate --track sepang --year 2026
127
+ python main.py validate --track baku --year 2026 --stage after_qualifying
128
+ ```
129
+
130
+ ### Historical Analytics
131
+
132
+ ```bash
133
+ python main.py history
134
+ ```
135
+
136
+ Subcommands: `driver` · `h2h` · `qualifying` · `race` · `circuit` · `standings` · `session` · `dominance` · `records` · `reliability` · `eras`
137
+
138
+ ### Data Collection & Cleanup
139
+
140
+ ```bash
141
+ python main.py collect-season --year 2026 # Full season ingestion
142
+ python main.py clean --target cache --preview # Dry-run preview
143
+ python main.py clean --target cache --force # Execute cleanup
144
+ ```
145
+
146
+ ---
147
+
148
+ ## Technical Architecture
149
+
150
+ <details>
151
+ <summary><b>Technical Methodology & Mathematical Formulation</b></summary>
152
+
153
+ ### Stage-Gated Grid Blending
154
+
155
+ Starting grid positions heavily influence race outcomes, but using qualifying data before qualifying introduces catastrophic lookahead bias. ApexGrid resolves this with stage-aware gating:
156
+
157
+ **Post-Qualifying:** Official FIA grid positions (including penalty cascades and pit-lane starts) blend with pure ML pace scores using circuit-topology weights:
158
+
159
+
160
+ $$
161
+ \text{Score}_{\text{blended}} = w_{\text{ml}} \cdot \text{Score}_{\text{ML}} + w_{\text{grid}} \cdot \text{Grid}_{\text{actual}}
162
+ $$
163
+
164
+
165
+ | Circuit Type | $w_{\text{grid}}$ | $w_{\text{ml}}$ | Examples |
166
+ |---|---|---|---|
167
+ | Street | 0.50 | 0.50 | Monaco, Baku, Singapore |
168
+ | Permanent | 0.35 | 0.65 | Spa, Monza, Silverstone |
169
+ | Temporary | 0.45 | 0.55 | Melbourne, Montreal |
170
+
171
+ **Pre-Qualifying:** Grid data is masked to NaN. The pipeline generates provisional qualifying forecasts (displayed as `~P1`, `~P2`, etc.) or cleanly disables blending ($w_{\text{grid}} = 0$, $w_{\text{ml}} = 1$).
172
+
173
+ ---
174
+
175
+ ### Dual-View Outcome Presentation
176
+
177
+ Monte Carlo simulations produce full finishing distributions, presented in two views:
178
+
179
+ - **Podium Banner:** Top 3 drivers selected by Win% ↓, then Podium% ↓, then ExpectedFinish ↑ (tie-breaker).
180
+ - **Full Field Table:** All drivers ranked by DNF-adjusted ExpectedFinish. Non-finishers receive a +1000.0 penalty, ensuring they rank behind all classified finishers.
181
+
182
+ ---
183
+
184
+ ### Walk-Forward Validation
185
+
186
+ Shuffled k-fold is strictly prohibited. For each validation round $r > \text{min\_train\_rounds}$, models train exclusively on rounds $\{1 \dots r{-}1\}$ and test on out-of-sample round $r$. If any fold fails, validation transitions to `BLOCKED` and all residual arrays are cleared to prevent partial contamination.
187
+
188
+ ---
189
+
190
+ ### Residual-Calibrated Pace Volatility
191
+
192
+ Monte Carlo variance is empirically calibrated from walk-forward residuals using Median Absolute Deviation:
193
+
194
+
195
+ $$
196
+ \sigma = \max\!\left(1.5,\; 1.4826 \cdot \text{MAD}(\text{residuals})\right)
197
+ $$
198
+
199
+
200
+ Under wet-weather sampling: volatility scales by 1.35×, DNF hazard scales by 1.40×.
201
+
202
+ ---
203
+
204
+ ### Decoupled Two-Stage Modeling
205
+
206
+ ML regressors (RF, XGBoost, Ridge) train exclusively on classified finishers — mechanical retirements and lap-1 incidents are excluded so pace signal stays uncorrupted. DNF hazards are modeled separately via binomial draws during Monte Carlo simulation.
207
+
208
+ ---
209
+
210
+ ### EWMA Form Tracking
211
+
212
+ Driver and constructor rolling form uses exponentially weighted moving average with decay $\alpha = 0.30$, heavily weighting the most recent 3–5 rounds to capture mid-season aerodynamic upgrades while maintaining baseline stability.
213
+
214
+ </details>
215
+
216
+ ---
217
+
218
+ ## Configuration
219
+
220
+ JSON configuration files in [`config/`](config/):
221
+
222
+ | File | Purpose |
223
+ |------|---------|
224
+ | [`model_config.json`](config/model_config.json) | Ensemble weights, hyperparameters, feature sets, circuit blending weights |
225
+ | [`tracks.json`](config/tracks.json) | 23 championship circuits — lengths, types, calendar mappings |
226
+ | [`strategy_config.json`](config/strategy_config.json) | Tire compounds, pit loss times, 15 circuit-specific strategy priors |
227
+ | [`settings.json`](config/settings.json) | Cache paths, logging thresholds, output directories |
228
+
229
+ ---
230
+
231
+ ## Verification & Testing
232
+
233
+ **183 tests** across 21 modules — 100% pass rate:
234
+
235
+ ```bash
236
+ pytest # Full suite
237
+ pytest tests/test_walk_forward.py # Walk-forward validation
238
+ pytest tests/test_core_features.py # Stage isolation & anti-leakage
239
+ pytest tests/test_dynamic_roster.py # Driver substitution handling
240
+ pytest tests/test_weekend_only_pipeline.py # Weekend-only ML pipeline
241
+ ```
242
+
243
+ ---
244
+
245
+ ## Tech Stack
246
+
247
+ | Component | Technologies |
248
+ |-----------|-------------|
249
+ | **Language** | Python 3.10 – 3.13 |
250
+ | **Machine Learning** | Scikit-Learn (Random Forest, Ridge), XGBoost |
251
+ | **Scientific** | NumPy, SciPy, Pandas |
252
+ | **Telemetry** | FastF1, OpenF1 REST API |
253
+ | **CLI / TUI** | Typer, Rich |
254
+ | **Testing** | Pytest |
255
+
256
+ ---
257
+
258
+ ## Contributing
259
+
260
+ 1. Fork the repository and create a feature branch
261
+ 2. Add tests matching existing conventions in [`tests/`](tests/)
262
+ 3. Confirm `pytest` exits with code 0 (zero regressions)
263
+ 4. Open a PR against `main` with verification logs
264
+
265
+ ---
266
+
267
+ ## License
268
+
269
+ This project is licensed under the [MIT License](LICENSE).