Models¶
Metrics¶
plot_confusion_matrix_multiclass(y_true, y_pred, labels, normalize=None, title=None)
¶
Plot a confusion matrix for a multiclass classification result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Ground-truth labels. |
required | |
y_pred
|
Predicted labels. |
required | |
labels
|
Ordered list of class labels for axis ticks. |
required | |
normalize
|
Normalization mode passed to
|
None
|
|
title
|
Figure title. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
|
Matplotlib Figure with a single confusion-matrix axis. |
Source code in src/models/metrics.py
multiclass_brier_score(y_true, proba, labels)
¶
Compute the mean multiclass Brier score (one-hot encoding).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Iterable of ground-truth class labels. |
required | |
proba
|
Predicted probability matrix, shape |
required | |
labels
|
Ordered list of class labels matching |
required |
Returns:
| Type | Description |
|---|---|
|
Mean Brier score across all samples (lower is better). |
Source code in src/models/metrics.py
compute_ece(y_true, proba, labels, n_bins=10)
¶
Compute macro-averaged multiclass Expected Calibration Error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray
|
Ground-truth class labels. |
required |
proba
|
ndarray
|
Predicted probability matrix, shape |
required |
labels
|
list
|
Ordered list of class labels matching |
required |
n_bins
|
int
|
Number of calibration bins. |
10
|
Returns:
| Type | Description |
|---|---|
float
|
Macro-averaged ECE across all classes (one-vs-rest, lower is better). |
Source code in src/models/metrics.py
extract_feature_importance(pipe, X_cols)
¶
Extract feature importances from the clf step of a sklearn Pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipe
|
Fitted sklearn Pipeline with a |
required | |
X_cols
|
list[str]
|
Feature column names in the order the pipeline was trained on. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
DataFrame with |
DataFrame | None
|
descending, or |
Source code in src/models/metrics.py
plot_feature_importance(df_imp, top_n=20, title='Feature Importance')
¶
Plot a horizontal bar chart of the top-N feature importances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_imp
|
DataFrame
|
DataFrame with |
required |
top_n
|
int
|
Number of top features to display. |
20
|
title
|
str
|
Chart title. |
'Feature Importance'
|
Returns:
| Type | Description |
|---|---|
Figure
|
Matplotlib Figure with a horizontal bar chart. |
Source code in src/models/metrics.py
compute_segment_metrics(y_true, proba, labels, segments, segment_cols, min_samples=1)
¶
Compute logloss and Brier score per segment value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Series
|
Ground-truth class labels. |
required |
proba
|
ndarray
|
Predicted probability matrix, shape |
required |
labels
|
list
|
Ordered list of class labels. |
required |
segments
|
DataFrame
|
DataFrame with segment columns aligned with y_true. |
required |
segment_cols
|
list[str]
|
Column names in segments to group by. |
required |
min_samples
|
int
|
Minimum segment size; smaller groups are skipped. |
1
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns |
DataFrame
|
|
Source code in src/models/metrics.py
plot_calibration_curves(y_true, proba, labels, label_names)
¶
Plot one-vs-rest calibration reliability diagrams for each class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Series
|
Ground-truth class labels. |
required |
proba
|
ndarray
|
Predicted probability matrix, shape |
required |
labels
|
list
|
Ordered list of class labels. |
required |
label_names
|
dict
|
Mapping from label value to human-readable name for subplot titles. |
required |
Returns:
| Type | Description |
|---|---|
Figure
|
Matplotlib Figure with one reliability diagram per class. |
Source code in src/models/metrics.py
evaluate_clf(y, proba, label_order)
¶
Evaluate a multiclass classifier and return a flat metrics dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
DataFrame
|
Ground-truth labels (Series or array-like). |
required |
proba
|
ndarray
|
Predicted probabilities, shape |
required |
label_order
|
list
|
Ordered list of class labels aligned with
|
required |
Returns:
| Type | Description |
|---|---|
Dict with keys
|
logloss, brier, ece, roc_auc_ovr, accuracy, |
dict
|
balanced_accuracy, f1_macro, f1_weighted, |
dict
|
precision_class_{label}, recall_class_{label}. |
Source code in src/models/metrics.py
Pipelines (sklearn)¶
WeightedXGBClassifier
¶
Bases: XGBClassifier
XGBClassifier extended to accept the sklearn-style class_weight parameter.
XGBoost does not support class_weight natively in its constructor.
This wrapper converts class_weight to a sample_weight array on
each :meth:fit call, mirroring the behaviour of sklearn estimators.
Source code in src/models/pipelines.py
get_xgb_params()
¶
Return XGBoost booster params, excluding sklearn-only class_weight.
fit(X, y, sample_weight=None, **kwargs)
¶
Fit the XGBoost model, computing sample weights when needed.
When class_weight was set in __init__ and no explicit
sample_weight is supplied, computes per-sample weights via
sklearn.utils.class_weight.compute_sample_weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Feature matrix. |
required | |
y
|
Target labels. |
required | |
sample_weight
|
Optional explicit sample weight array.
When provided, |
None
|
|
**kwargs
|
Additional arguments forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
|
Fitted estimator (self). |
Source code in src/models/pipelines.py
get_models_with_pipeline_for_clf(num_cols, cat_cols, enabled=None, class_weight=None)
¶
Build sklearn Pipelines for each supported classifier.
Available models: "baseline", "logreg", "sgd_logloss",
"hgb_numonly", "xgb".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_cols
|
list[str]
|
Numeric feature column names. |
required |
cat_cols
|
list[str]
|
Categorical feature column names. |
required |
enabled
|
list[str] | None
|
Optional allowlist of model keys to include. When
|
None
|
class_weight
|
Class-weight spec forwarded to each classifier
that supports it. Accepts |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Pipeline]
|
Dict mapping model name to a fitted-ready sklearn Pipeline. |
Source code in src/models/pipelines.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
Hyperparameter Tuning¶
Hyperparameter optimisation for model candidates via Optuna.
Design decisions¶
- One Optuna study per
(model, experiment_name, frac)combination so results are comparable across data-size ablations. - Each trial is a nested MLflow run so the full trial history is visible in the MLflow UI alongside the standard training runs.
- Objective: minimise mean CV log-loss across walk-forward folds
(identical evaluation protocol to
make_classification_runs). n_jobs=1inside XGBoost to prevent thread contention when Optuna spawns multiple trials (n_jobson the study controls parallelism).- Best parameters are written back to the parent run as
tuned.*tags so the register-model step can read them without additional MLflow queries. - Three model families are tuned independently and compared in
select_model: LogisticRegression, HistGradientBoosting, XGBoost.
run_xgb_tuning(experiment_name, tracking_uri, df_dataset, df_train_ids, df_folds, X_cols, y_col, num_cols, cat_cols, n_trials=20, frac=1.0, study_name=None, run_kind=None, feat_params=None)
¶
Run an Optuna study to tune XGBoost hyperparameters.
Each Optuna trial is logged as a nested MLflow run under a parent run
named xgb_tuning_frac-{frac}.
Parameters¶
experiment_name:
MLflow experiment name (same as the main classification experiment).
tracking_uri:
MLflow tracking server URI.
df_dataset:
Full dataset with features + target.
df_train_ids:
DataFrame with an id column marking training-set matches.
df_folds:
Walk-forward fold definitions from split_data stage.
X_cols:
Feature columns (cat + num).
y_col:
Target column name.
num_cols:
Numeric feature columns (for ColumnTransformer).
cat_cols:
Categorical feature columns (for ColumnTransformer).
n_trials:
Number of Optuna trials.
frac:
Fraction of training data to use (same semantics as main training).
study_name:
Optional Optuna study name. Defaults to
f"xgb_tuning_{experiment_name}_frac{frac}".
Returns¶
dict Best hyperparameters found by Optuna.
Source code in src/models/tuning.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
run_logreg_tuning(experiment_name, tracking_uri, df_dataset, df_train_ids, df_folds, X_cols, y_col, num_cols, cat_cols, n_trials=20, frac=1.0, study_name=None, run_kind=None, feat_params=None)
¶
Run an Optuna study to tune LogisticRegression hyperparameters.
Searches over regularisation strength (C) and penalty type.
Parameters¶
experiment_name:
MLflow experiment name.
tracking_uri:
MLflow tracking server URI.
df_dataset:
Full dataset with features, target, and split IDs.
df_train_ids:
DataFrame with id column for training matches.
df_folds:
Cross-validation fold definitions.
X_cols:
Feature column names.
y_col:
Target column name.
num_cols:
Numeric feature column names.
cat_cols:
Categorical feature column names.
n_trials:
Number of Optuna trials.
frac:
Fraction of training data to use.
study_name:
Optuna study name. Auto-generated when None.
run_kind:
MLflow run kind tag (e.g. "tuning" or "smoke").
feat_params:
Feature-selection params dict for MLflow logging.
Returns¶
dict
Best hyperparameters compatible with
sklearn.linear_model.LogisticRegression.
Source code in src/models/tuning.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
run_hgb_tuning(experiment_name, tracking_uri, df_dataset, df_train_ids, df_folds, X_cols, y_col, num_cols, cat_cols, n_trials=20, frac=1.0, study_name=None, run_kind=None, feat_params=None)
¶
Run an Optuna study to tune HistGradientBoostingClassifier hyperparameters.
Searches over max_depth, learning_rate, max_iter, and l2_regularization.
Parameters¶
experiment_name:
MLflow experiment name.
tracking_uri:
MLflow tracking server URI.
df_dataset:
Full dataset with features, target, and split IDs.
df_train_ids:
DataFrame with id column for training matches.
df_folds:
Cross-validation fold definitions.
X_cols:
Feature column names.
y_col:
Target column name.
num_cols:
Numeric feature column names.
cat_cols:
Categorical feature column names.
n_trials:
Number of Optuna trials.
frac:
Fraction of training data to use.
study_name:
Optuna study name. Auto-generated when None.
run_kind:
MLflow run kind tag (e.g. "tuning" or "smoke").
feat_params:
Feature-selection params dict for MLflow logging.
Returns¶
dict
Best hyperparameters compatible with
sklearn.ensemble.HistGradientBoostingClassifier.
Source code in src/models/tuning.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
Classification¶
make_classification_runs(experiment_name, tracking_uri, dataset_path, df_dataset, df_train_ids, df_test_ids, df_folds, X_cols, y_cols, models, frac, cat_cols, num_cols, experiment_hypothesis=None, dvc_params=None, run_name=None)
¶
Train and evaluate all model/frac combinations, log to MLflow.
Artifacts are NOT registered in the Model Registry here.
Registration (including alias assignment) is the responsibility of
the dedicated register_model pipeline stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
experiment_name
|
str
|
MLflow experiment name. |
required |
tracking_uri
|
str
|
MLflow tracking server URI. |
required |
dataset_path
|
str
|
Filesystem path to the dataset parquet (logged as MLflow input source). |
required |
df_dataset
|
DataFrame
|
Full dataset with features, target, and split IDs. |
required |
df_train_ids
|
DataFrame
|
DataFrame with |
required |
df_test_ids
|
DataFrame
|
DataFrame with |
required |
df_folds
|
DataFrame
|
Cross-validation fold definitions, logged as CSV. |
required |
X_cols
|
list
|
Feature column names in model-expected order. |
required |
y_cols
|
str
|
Target column name. |
required |
models
|
dict
|
Dict of model name → sklearn Pipeline. |
required |
frac
|
float
|
Fraction of training data to use (for smoke runs). |
required |
cat_cols
|
list
|
Categorical feature column names. |
required |
num_cols
|
list
|
Numeric feature column names. |
required |
experiment_hypothesis
|
str | None
|
Optional hypothesis tag for the MLflow run. |
None
|
dvc_params
|
dict | None
|
Full DVC params dict to flatten and log. |
None
|
run_name
|
str | None
|
Optional display name prefix for the run. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Tuple of (run_id, model_uri, model_name) for the best run (lowest |
str
|
holdout logloss). |
str
|
|
Source code in src/models/classification.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
Final Training¶
Final training stage: retrain the winning model on the full training set.
Design decisions¶
- This is the ONLY stage that evaluates on the holdout set for the purpose of reporting. All model selection (screening, tuning) is done exclusively on cross-validation to prevent test-set leakage.
best_paramsare applied via the sklearn Pipeline param convention (step__param) so they are compatible with any Pipeline-wrapped model.- For XGBoost the tuned params replace the defaults from
get_models_with_pipeline_for_clf. - When calibration is enabled, the model is trained on the chronologically
earliest (1 - calib_frac) portion of the training set, then a
CalibratedClassifierCVwrapper is fitted on the most recent calib_frac portion (temporal split — no random split on time-series data). - The calibrated pipeline is registered to MLflow; raw ECE is also logged for comparison so the calibration benefit is visible in the report.
make_final_train_run(experiment_name, tracking_uri, dataset_path, df_dataset, df_train_ids, df_test_ids, X_cols, y_col, model_name, best_params, num_cols, cat_cols, calibration_config=None, run_kind='final_train', feat_params=None)
¶
Retrain winning model on full training set; evaluate once on holdout.
Parameters¶
experiment_name:
MLflow experiment name (same as classification experiment).
tracking_uri:
MLflow tracking server URI.
dataset_path:
Filesystem path to the dataset parquet (logged as MLflow input source).
df_dataset:
Full dataset containing features, target, and split identifiers.
df_train_ids:
DataFrame with id column marking training-set matches.
df_test_ids:
DataFrame with id column marking holdout-set matches.
X_cols:
Feature columns (cat + num) in the order the model expects.
y_col:
Target column name.
model_name:
Key into get_models_with_pipeline_for_clf (e.g. "xgb").
best_params:
Hyperparameters from the tuning stage. Applied via sklearn Pipeline
step__param convention (e.g. {"n_estimators": 300} becomes
clf__n_estimators=300). Pass an empty dict to use defaults.
num_cols:
Numeric feature columns (passed to pipeline factory).
cat_cols:
Categorical feature columns (passed to pipeline factory).
calibration_config:
Optional dict with keys enabled (bool), method (str),
calib_frac (float), min_calib_samples (int).
When enabled=True a temporal calibration split is applied:
the model is trained on the earliest (1 - calib_frac) training rows,
then a CalibratedClassifierCV wrapper is fitted on the remaining
most-recent training rows. The calibrated pipeline is registered.
Returns¶
tuple[str, str]
(run_id, model_uri) for the final MLflow run.
Source code in src/models/final_train.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
ROI Simulation (Evaluation)¶
ROI simulation for portfolio evaluation.
Pure functions — no IO, no MLflow, no side effects. Called from the evaluation pipeline stage; IO is at the caller boundary.
Design notes¶
- No real betting odds are available in the dataset (WhoScored does not provide them). The baseline is therefore a uniform prior (1/3 per outcome), which represents the "naive bettor who bets every match equally".
- The Kelly-inspired flat-stake simulation places 1 unit on the outcome with the highest model-implied edge over the reference probability.
- Results are clearly labelled as a simulation on historical data; they carry no implication of live profitability.
- If market odds become available (e.g. from a Pinnacle / Betfair feed),
pass them as
reference_probato get a realistic edge estimate.
compute_flat_stake_roi(y_true, model_proba, label_order, reference_proba=None, actual_odds=None, stake=1.0)
¶
Simulate flat-stake ROI: bet on outcome where model edge > 0.
The model bets stake on the outcome with the largest positive edge
(model_proba - reference_proba). If no outcome has positive edge for
a match, no bet is placed.
Parameters¶
y_true:
True match outcomes, same encoding as label_order.
model_proba:
Model predicted probabilities, shape (n, n_classes).
label_order:
Ordered list of class labels matching model_proba columns.
reference_proba:
Reference probabilities used to compute edge. Defaults to uniform
(1 / n_classes) when None.
actual_odds:
Real bookmaker decimal odds, shape (n, n_classes) aligned to
model_proba. When provided, payout = stake * decimal_odd
(realistic). When None, payout = stake / model_proba
(optimistic model-implied). NaN values fall back to model-implied.
stake:
Flat stake per bet (in abstract units).
Returns¶
dict with keys:
- n_matches — total matches in slice
- n_bets — matches where edge > 0
- bet_rate — n_bets / n_matches
- n_correct_bets — bets placed on the correct outcome
- hit_rate — correct bets / total bets
- total_staked — n_bets * stake
- gross_return — sum of payouts for winning bets
- net_profit — gross_return - total_staked
- roi_pct — net_profit / total_staked * 100
Source code in src/models/evaluation/roi_simulation.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
compute_roi_by_segment(y_true, model_proba, label_order, segments, segment_col, reference_proba=None, actual_odds=None, stake=1.0, min_bets=10)
¶
Compute flat-stake ROI per segment value (e.g. per league / region).
Only segments with at least min_bets placed bets are returned.
Parameters¶
y_true:
True match outcomes, same encoding as label_order.
model_proba:
Model predicted probabilities, shape (n, n_classes).
label_order:
Ordered list of class labels matching model_proba columns.
segments:
DataFrame with segment columns aligned with y_true.
segment_col:
Column name in segments to group by.
reference_proba:
Reference probabilities used to compute edge. Defaults to uniform.
actual_odds:
Real bookmaker decimal odds, shape (n, n_classes).
stake:
Flat stake per bet.
min_bets:
Minimum number of placed bets for a segment to be included.
Returns¶
pd.DataFrame
One row per qualifying segment value, with columns from
compute_flat_stake_roi plus the segment identifier column.
Source code in src/models/evaluation/roi_simulation.py
compute_roi_by_threshold(y_true, model_proba, label_order, reference_proba=None, actual_odds=None, thresholds=None, stake=1.0, min_bets=20)
¶
Compute ROI for progressively stricter edge thresholds.
For each threshold t, only bets where best_edge > t are placed.
Helps identify the minimum edge required for positive expected value.
Parameters¶
thresholds: List of minimum-edge values to test. Defaults to [0.0, 0.02, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30]. min_bets: Skip a threshold row if fewer than this many bets would be placed.
Source code in src/models/evaluation/roi_simulation.py
vig_strip(odds)
¶
Convert decimal odds matrix to vig-stripped (fair) probabilities.
Parameters¶
odds:
Decimal odds, shape (n, n_classes). NaN values are propagated.
Returns¶
np.ndarray of shape (n, n_classes) where each row sums to 1.0.
Source code in src/models/evaluation/roi_simulation.py
compute_kelly_roi(y_true, model_proba, label_order, actual_odds, fraction=0.25, initial_bankroll=100.0, min_edge=0.02)
¶
Fractional Kelly staking simulation with real market odds.
Kelly formula per bet: f = edge / (odds - 1) where
edge = model_proba - market_proba (vig-stripped).
Actual stake = fraction * f * current_bankroll (fractional Kelly).
Bankroll is updated after each bet. No bet is placed when
edge <= min_edge or odds are NaN.
Parameters¶
y_true:
True match outcomes encoded with label_order.
model_proba:
Model probabilities, shape (n, n_classes).
label_order:
Class labels aligned with model_proba columns.
actual_odds:
Bookmaker decimal odds, shape (n, n_classes). Rows with all-NaN
odds are skipped.
fraction:
Kelly fraction (0 < fraction ≤ 1). Default 0.25 (quarter-Kelly).
initial_bankroll:
Starting bankroll in abstract units.
min_edge:
Minimum edge required to place a bet.
Returns¶
dict with:
n_matches, n_bets, bet_rate, n_correct_bets,
hit_rate, total_staked, gross_return, net_profit,
roi_pct, final_bankroll, bankroll_growth_pct.
Source code in src/models/evaluation/roi_simulation.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
compute_roi_timeseries(y_true, model_proba, label_order, actual_odds, dates=None, min_edge=0.0, stake=1.0)
¶
Build a bet-by-bet P&L record sorted chronologically.
Each row in the output corresponds to one match where a bet was placed (edge > min_edge and odds are available). Accumulating this DataFrame over time gives the strategy's running P&L curve.
Parameters¶
y_true:
True match outcomes encoded with label_order.
model_proba:
Model probabilities, shape (n, n_classes).
label_order:
Class labels aligned with model_proba columns.
actual_odds:
Bookmaker decimal odds, shape (n, n_classes).
dates:
Optional array of match dates (datetime or str) for chronological
ordering. When None, input order is preserved.
min_edge:
Minimum edge to place a bet.
stake:
Flat stake per bet.
Returns¶
pd.DataFrame with columns:
date, bet_outcome (label), true_outcome (label),
model_proba_bet, market_proba_bet, edge, odds,
stake, payout, profit,
cumulative_profit, cumulative_staked, cumulative_roi_pct,
cumulative_bets.
Source code in src/models/evaluation/roi_simulation.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | |