Spaces:
Sleeping
Sleeping
feat: initial deploy with bundled models
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +15 -10
- app/__init__.py +0 -0
- app/__pycache__/__init__.cpython-312.pyc +0 -0
- app/__pycache__/main.cpython-312.pyc +0 -0
- app/api/__init__.py +0 -0
- app/api/__pycache__/__init__.cpython-312.pyc +0 -0
- app/api/v1/__init__.py +0 -0
- app/api/v1/__pycache__/__init__.cpython-312.pyc +0 -0
- app/api/v1/endpoints/__init__.py +0 -0
- app/api/v1/endpoints/__pycache__/__init__.cpython-312.pyc +0 -0
- app/api/v1/endpoints/__pycache__/matches.cpython-312.pyc +0 -0
- app/api/v1/endpoints/__pycache__/pipeline.cpython-312.pyc +0 -0
- app/api/v1/endpoints/__pycache__/predict.cpython-312.pyc +0 -0
- app/api/v1/endpoints/matches.py +20 -0
- app/api/v1/endpoints/pipeline.py +43 -0
- app/api/v1/endpoints/predict.py +263 -0
- app/core/__init__.py +0 -0
- app/core/__pycache__/__init__.cpython-312.pyc +0 -0
- app/core/__pycache__/config.cpython-312.pyc +0 -0
- app/core/__pycache__/supabase_client.cpython-312.pyc +0 -0
- app/core/config.py +17 -0
- app/core/supabase_client.py +10 -0
- app/main.py +34 -0
- app/ml/__init__.py +0 -0
- app/ml/__pycache__/__init__.cpython-312.pyc +0 -0
- app/ml/__pycache__/stacking.cpython-312.pyc +0 -0
- app/ml/__pycache__/utils.cpython-312.pyc +0 -0
- app/ml/evaluation/__init__.py +0 -0
- app/ml/evaluation/metrics.py +9 -0
- app/ml/features/__init__.py +0 -0
- app/ml/features/__pycache__/__init__.cpython-312.pyc +0 -0
- app/ml/features/__pycache__/feature_columns.cpython-312.pyc +0 -0
- app/ml/features/feature_columns.py +65 -0
- app/ml/models/__init__.py +0 -0
- app/ml/models/__pycache__/__init__.cpython-312.pyc +0 -0
- app/ml/models/__pycache__/lgbm_model.cpython-312.pyc +0 -0
- app/ml/models/__pycache__/random_forest_model.cpython-312.pyc +0 -0
- app/ml/models/__pycache__/xgb_model.cpython-312.pyc +0 -0
- app/ml/models/lgbm_model.py +17 -0
- app/ml/models/random_forest_model.py +91 -0
- app/ml/models/xgb_model.py +18 -0
- app/ml/stacking.py +329 -0
- app/ml/utils.py +50 -0
- app/schemas/__init__.py +0 -0
- app/schemas/__pycache__/__init__.cpython-312.pyc +0 -0
- app/schemas/__pycache__/prediction.cpython-312.pyc +0 -0
- app/schemas/match.py +34 -0
- app/schemas/prediction.py +24 -0
- app/services/__init__.py +0 -0
- app/services/__pycache__/__init__.cpython-312.pyc +0 -0
README.md
CHANGED
|
@@ -1,11 +1,16 @@
|
|
| 1 |
-
|
| 2 |
-
title: Epl Predictor Api
|
| 3 |
-
emoji: 🐨
|
| 4 |
-
colorFrom: red
|
| 5 |
-
colorTo: red
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: false
|
| 8 |
-
short_description: EPL prediction
|
| 9 |
-
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# EPL Match Outcome Predictor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
A production-ready FastAPI backend that ingests historical EPL data from football-data.co.uk,
|
| 4 |
+
stores it in Supabase, engineers features, and serves predictions via a Random Forest model.
|
| 5 |
+
|
| 6 |
+
## Quick Start
|
| 7 |
+
```bash
|
| 8 |
+
cp .env.example .env # fill in your credentials
|
| 9 |
+
pip install -r requirements.txt
|
| 10 |
+
python scripts/ingest_seasons.py # loads all CSV seasons into Supabase
|
| 11 |
+
python scripts/train_model.py # trains and saves the model
|
| 12 |
+
uvicorn app.main:app --reload # start the API
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Seasons Available
|
| 16 |
+
1011, 1112, 1213, 1314, 1415, 1516, 1617, 1718, 1819, 1920, 2021, 2122, 2223, 2324, 2425
|
app/__init__.py
ADDED
|
File without changes
|
app/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (170 Bytes). View file
|
|
|
app/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (1.65 kB). View file
|
|
|
app/api/__init__.py
ADDED
|
File without changes
|
app/api/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (174 Bytes). View file
|
|
|
app/api/v1/__init__.py
ADDED
|
File without changes
|
app/api/v1/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (177 Bytes). View file
|
|
|
app/api/v1/endpoints/__init__.py
ADDED
|
File without changes
|
app/api/v1/endpoints/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (187 Bytes). View file
|
|
|
app/api/v1/endpoints/__pycache__/matches.cpython-312.pyc
ADDED
|
Binary file (1.77 kB). View file
|
|
|
app/api/v1/endpoints/__pycache__/pipeline.cpython-312.pyc
ADDED
|
Binary file (2.5 kB). View file
|
|
|
app/api/v1/endpoints/__pycache__/predict.cpython-312.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
app/api/v1/endpoints/matches.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException
|
| 2 |
+
from app.core.supabase_client import get_supabase
|
| 3 |
+
|
| 4 |
+
router = APIRouter()
|
| 5 |
+
|
| 6 |
+
@router.get("/matches")
|
| 7 |
+
def get_matches(season: str | None = None, limit: int = 50):
|
| 8 |
+
supabase = get_supabase()
|
| 9 |
+
query = supabase.table("match_results").select("*").limit(limit)
|
| 10 |
+
if season:
|
| 11 |
+
query = query.eq("season", season)
|
| 12 |
+
result = query.execute()
|
| 13 |
+
return {"count": len(result.data), "data": result.data}
|
| 14 |
+
|
| 15 |
+
@router.get("/matches/seasons")
|
| 16 |
+
def get_seasons():
|
| 17 |
+
supabase = get_supabase()
|
| 18 |
+
result = supabase.table("match_results").select("season").execute()
|
| 19 |
+
seasons = sorted(set(r["season"] for r in result.data))
|
| 20 |
+
return {"seasons": seasons}
|
app/api/v1/endpoints/pipeline.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/api/v1/endpoints/pipeline.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import subprocess
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from fastapi import APIRouter, BackgroundTasks
|
| 7 |
+
from app.services.ingest_service import ingest_all
|
| 8 |
+
from app.services.feature_service import build_and_save
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
router = APIRouter()
|
| 12 |
+
|
| 13 |
+
@router.post("/pipeline/ingest")
|
| 14 |
+
def trigger_ingest(background_tasks: BackgroundTasks):
|
| 15 |
+
background_tasks.add_task(ingest_all)
|
| 16 |
+
return {"message": "Ingestion started in background"}
|
| 17 |
+
|
| 18 |
+
@router.post("/pipeline/train")
|
| 19 |
+
def trigger_train(background_tasks: BackgroundTasks):
|
| 20 |
+
def run():
|
| 21 |
+
try:
|
| 22 |
+
# Step 1 — rebuild full feature parquet
|
| 23 |
+
df = build_and_save()
|
| 24 |
+
logger.info(f"✅ Features rebuilt: {df.shape}")
|
| 25 |
+
|
| 26 |
+
# Step 2 — retrain the model using your main train script
|
| 27 |
+
logger.info("🚀 Starting model training...")
|
| 28 |
+
result = subprocess.run(
|
| 29 |
+
["python", "scripts/train_model.py"],
|
| 30 |
+
capture_output=True,
|
| 31 |
+
text=True,
|
| 32 |
+
cwd="/home/scop/Betting AI/season specicific/EPL/epl_predictor"
|
| 33 |
+
)
|
| 34 |
+
if result.returncode == 0:
|
| 35 |
+
logger.info(f"✅ Model training complete:\n{result.stdout[-500:]}")
|
| 36 |
+
else:
|
| 37 |
+
logger.error(f"❌ Training failed:\n{result.stderr[-500:]}")
|
| 38 |
+
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Pipeline failed: {e}", exc_info=True)
|
| 41 |
+
|
| 42 |
+
background_tasks.add_task(run)
|
| 43 |
+
return {"message": "Pipeline started — rebuilding features then training model"}
|
app/api/v1/endpoints/predict.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import joblib
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from fastapi import APIRouter, HTTPException
|
| 7 |
+
|
| 8 |
+
from app.schemas.prediction import PredictionRequest, PredictionResponse
|
| 9 |
+
from app.services.feature_service import load_matches, engineer_features, get_current_elo
|
| 10 |
+
from app.ml.features.feature_columns import FEATURE_COLS
|
| 11 |
+
from app.services.ev_service import find_value_bets, format_ev_report
|
| 12 |
+
from app.services.odds_service import get_upcoming_epl_fixtures, get_b365_odds, normalise_name, calculate_ev
|
| 13 |
+
from app.utils.team_utils import normalise_team
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
router = APIRouter()
|
| 17 |
+
MODELS_DIR = Path("models/saved")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ── Load once at startup ──────────────────────────────────────────────────────
|
| 21 |
+
try:
|
| 22 |
+
_model = joblib.load(MODELS_DIR / "ensemble.pkl")
|
| 23 |
+
_imputer = joblib.load(MODELS_DIR / "imputer.pkl")
|
| 24 |
+
_feat_names = joblib.load(MODELS_DIR / "feature_names.pkl")
|
| 25 |
+
logger.info("✅ Models loaded successfully")
|
| 26 |
+
except FileNotFoundError as e:
|
| 27 |
+
logger.error(f"❌ Model file missing: {e}. Run train_model.py first.")
|
| 28 |
+
_model = _imputer = _feat_names = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ── Kelly criterion helper (Adjustment 2) ────────────────────────────────────
|
| 32 |
+
def _kelly_pct(prob: float, odd: float) -> float:
|
| 33 |
+
"""Kelly criterion as a percentage, capped at 15%."""
|
| 34 |
+
edge = (prob * odd) - 1
|
| 35 |
+
if edge <= 0 or odd <= 1:
|
| 36 |
+
return 0.0
|
| 37 |
+
return round(min((edge / (odd - 1)) * 100, 15), 2)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ── Shared prediction logic ───────────────────────────────────────────────────
|
| 41 |
+
def _run_prediction(home_team: str, away_team: str,
|
| 42 |
+
home_odd: float = None, draw_odd: float = None,
|
| 43 |
+
away_odd: float = None) -> dict:
|
| 44 |
+
"""Core prediction logic shared by /predict and /upcoming."""
|
| 45 |
+
|
| 46 |
+
home_norm = normalise_team(home_team) or home_team
|
| 47 |
+
away_norm = normalise_team(away_team) or away_team
|
| 48 |
+
|
| 49 |
+
home_elo = get_current_elo(home_norm)
|
| 50 |
+
away_elo = get_current_elo(away_norm)
|
| 51 |
+
|
| 52 |
+
parquet = Path("data/processed/features.parquet")
|
| 53 |
+
if parquet.exists():
|
| 54 |
+
df = pd.read_parquet(parquet)
|
| 55 |
+
else:
|
| 56 |
+
logger.info("Parquet not found — building features from Supabase...")
|
| 57 |
+
df = load_matches()
|
| 58 |
+
df = engineer_features(df)
|
| 59 |
+
|
| 60 |
+
home_row = df[df["home_team"] == home_norm].tail(1)
|
| 61 |
+
away_as_away = df[df["away_team"] == away_norm]
|
| 62 |
+
away_as_home = df[df["home_team"] == away_norm]
|
| 63 |
+
|
| 64 |
+
if home_row.empty:
|
| 65 |
+
raise ValueError(f"'{home_team}' not found. Check spelling.")
|
| 66 |
+
if away_as_away.empty and away_as_home.empty:
|
| 67 |
+
raise ValueError(f"'{away_team}' not found. Check spelling.")
|
| 68 |
+
|
| 69 |
+
away_row = away_as_away.tail(1) if not away_as_away.empty else away_as_home.tail(1)
|
| 70 |
+
|
| 71 |
+
home_row = home_row.copy()
|
| 72 |
+
away_row = away_row.copy()
|
| 73 |
+
home_row["home_elo"] = home_elo
|
| 74 |
+
away_row["away_elo"] = away_elo
|
| 75 |
+
|
| 76 |
+
feat_cols = _feat_names if _feat_names else FEATURE_COLS
|
| 77 |
+
row = {}
|
| 78 |
+
for col in feat_cols:
|
| 79 |
+
if col.startswith("h_") or col in ["home_elo", "home_cumpts",
|
| 80 |
+
"home_days_rest", "home_win_rate_hist",
|
| 81 |
+
"h_pi_hc", "h_pi_hd", "home_matchweek"]:
|
| 82 |
+
row[col] = home_row.iloc[0].get(col, np.nan)
|
| 83 |
+
elif col.startswith("a_") or col in ["away_elo", "away_cumpts",
|
| 84 |
+
"away_days_rest", "away_win_rate_hist",
|
| 85 |
+
"a_pi_ac", "a_pi_ad", "away_matchweek"]:
|
| 86 |
+
row[col] = away_row.iloc[0].get(col, np.nan)
|
| 87 |
+
else:
|
| 88 |
+
row[col] = home_row.iloc[0].get(col, np.nan)
|
| 89 |
+
|
| 90 |
+
if home_odd and draw_odd and away_odd:
|
| 91 |
+
total = (1/home_odd) + (1/draw_odd) + (1/away_odd)
|
| 92 |
+
row["odds_fair_h"] = (1/home_odd) / total
|
| 93 |
+
row["odds_fair_d"] = (1/draw_odd) / total
|
| 94 |
+
row["odds_fair_a"] = (1/away_odd) / total
|
| 95 |
+
row["odds_home_edge"] = row["odds_fair_h"] - row["odds_fair_a"]
|
| 96 |
+
|
| 97 |
+
X = pd.DataFrame([row])[feat_cols]
|
| 98 |
+
X_imp = pd.DataFrame(_imputer.transform(X), columns=feat_cols)
|
| 99 |
+
|
| 100 |
+
proba = _model.predict_proba(X_imp)[0]
|
| 101 |
+
probs = {
|
| 102 |
+
"H": round(float(proba[0]), 4),
|
| 103 |
+
"D": round(float(proba[1]), 4),
|
| 104 |
+
"A": round(float(proba[2]), 4),
|
| 105 |
+
}
|
| 106 |
+
predicted = max(probs, key=probs.get)
|
| 107 |
+
confidence = round(probs[predicted], 4)
|
| 108 |
+
|
| 109 |
+
ev_result = None
|
| 110 |
+
if home_odd and draw_odd and away_odd:
|
| 111 |
+
ev_result = find_value_bets(
|
| 112 |
+
model_probs=probs,
|
| 113 |
+
home_odd=home_odd,
|
| 114 |
+
draw_odd=draw_odd,
|
| 115 |
+
away_odd=away_odd,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
return {
|
| 119 |
+
"probabilities": probs,
|
| 120 |
+
"predicted": predicted,
|
| 121 |
+
"label": {"H": "Home Win", "D": "Draw", "A": "Away Win"}[predicted],
|
| 122 |
+
"confidence": confidence,
|
| 123 |
+
"ev_analysis": ev_result,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# ── POST / (prefix="/predict" in router.py → resolves to POST /predict) ───────
|
| 128 |
+
@router.post("/predict")
|
| 129 |
+
def predict(req: PredictionRequest):
|
| 130 |
+
if _model is None:
|
| 131 |
+
raise HTTPException(status_code=503,
|
| 132 |
+
detail="Model not loaded. Run: python scripts/train_model.py")
|
| 133 |
+
try:
|
| 134 |
+
result = _run_prediction(
|
| 135 |
+
home_team=req.home_team,
|
| 136 |
+
away_team=req.away_team,
|
| 137 |
+
home_odd=req.home_odd,
|
| 138 |
+
draw_odd=req.draw_odd,
|
| 139 |
+
away_odd=req.away_odd,
|
| 140 |
+
)
|
| 141 |
+
except ValueError as e:
|
| 142 |
+
raise HTTPException(status_code=404, detail=str(e))
|
| 143 |
+
|
| 144 |
+
if req.home_odd and req.draw_odd and req.away_odd:
|
| 145 |
+
logger.info(format_ev_report(result["ev_analysis"], req.home_team, req.away_team))
|
| 146 |
+
|
| 147 |
+
return {
|
| 148 |
+
"home_team": req.home_team,
|
| 149 |
+
"away_team": req.away_team,
|
| 150 |
+
**result,
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# ── GET /upcoming (prefix="/predict" → resolves to GET /predict/upcoming) ─────
|
| 155 |
+
@router.get("/predict/upcoming")
|
| 156 |
+
def predict_upcoming(limit: int = 20):
|
| 157 |
+
"""
|
| 158 |
+
Fetch upcoming EPL fixtures from OddsPapi, run ensemble model,
|
| 159 |
+
return predictions + EV + Kelly % per outcome. No ESPN needed.
|
| 160 |
+
"""
|
| 161 |
+
if _model is None:
|
| 162 |
+
raise HTTPException(status_code=503,
|
| 163 |
+
detail="Model not loaded. Run: python scripts/train_model.py")
|
| 164 |
+
|
| 165 |
+
try:
|
| 166 |
+
fixtures = get_upcoming_epl_fixtures()
|
| 167 |
+
except Exception as e:
|
| 168 |
+
raise HTTPException(status_code=502,
|
| 169 |
+
detail=f"Failed to fetch fixtures from OddsPapi: {e}")
|
| 170 |
+
|
| 171 |
+
results = []
|
| 172 |
+
|
| 173 |
+
for fix in fixtures[:limit]:
|
| 174 |
+
# Adjustment 3 — guard missing fixture ID
|
| 175 |
+
fixture_id = fix.get("id") or fix.get("fixtureId")
|
| 176 |
+
if not fixture_id:
|
| 177 |
+
logger.warning(f"Fixture missing ID, skipping: {fix}")
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
home = normalise_name(fix.get("participant1Name", ""))
|
| 181 |
+
away = normalise_name(fix.get("participant2Name", ""))
|
| 182 |
+
date = fix.get("startTime") or fix.get("startDate") or fix.get("date", "")
|
| 183 |
+
|
| 184 |
+
if not home or not away:
|
| 185 |
+
continue
|
| 186 |
+
|
| 187 |
+
odds = get_b365_odds(fixture_id)
|
| 188 |
+
if not odds:
|
| 189 |
+
logger.warning(f"No odds for {home} vs {away} — skipping")
|
| 190 |
+
continue
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
result = _run_prediction(
|
| 194 |
+
home_team=home,
|
| 195 |
+
away_team=away,
|
| 196 |
+
home_odd=odds["b365h"],
|
| 197 |
+
draw_odd=odds["b365d"],
|
| 198 |
+
away_odd=odds["b365a"],
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
ev_h = calculate_ev(result["probabilities"]["H"], odds["b365h"])
|
| 202 |
+
ev_d = calculate_ev(result["probabilities"]["D"], odds["b365d"])
|
| 203 |
+
ev_a = calculate_ev(result["probabilities"]["A"], odds["b365a"])
|
| 204 |
+
vig = round((1/odds["b365h"]) + (1/odds["b365d"]) + (1/odds["b365a"]) - 1, 4)
|
| 205 |
+
|
| 206 |
+
# Adjustment 2 — kelly_pct included in every outcome
|
| 207 |
+
all_outcomes = [
|
| 208 |
+
{
|
| 209 |
+
"outcome": "H",
|
| 210 |
+
"model_prob": result["probabilities"]["H"],
|
| 211 |
+
"decimal_odd": odds["b365h"],
|
| 212 |
+
"ev": round(ev_h, 4),
|
| 213 |
+
"kelly_pct": _kelly_pct(result["probabilities"]["H"], odds["b365h"]),
|
| 214 |
+
"is_value": ev_h > 0.05,
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"outcome": "D",
|
| 218 |
+
"model_prob": result["probabilities"]["D"],
|
| 219 |
+
"decimal_odd": odds["b365d"],
|
| 220 |
+
"ev": round(ev_d, 4),
|
| 221 |
+
"kelly_pct": _kelly_pct(result["probabilities"]["D"], odds["b365d"]),
|
| 222 |
+
"is_value": ev_d > 0.05,
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"outcome": "A",
|
| 226 |
+
"model_prob": result["probabilities"]["A"],
|
| 227 |
+
"decimal_odd": odds["b365a"],
|
| 228 |
+
"ev": round(ev_a, 4),
|
| 229 |
+
"kelly_pct": _kelly_pct(result["probabilities"]["A"], odds["b365a"]),
|
| 230 |
+
"is_value": ev_a > 0.05,
|
| 231 |
+
},
|
| 232 |
+
]
|
| 233 |
+
|
| 234 |
+
value_bets = [o for o in all_outcomes if o["is_value"]]
|
| 235 |
+
best_bet = max(value_bets, key=lambda x: x["ev"]) if value_bets else None
|
| 236 |
+
|
| 237 |
+
results.append({
|
| 238 |
+
"fixture_id": fixture_id,
|
| 239 |
+
"date": date,
|
| 240 |
+
"home_team": home,
|
| 241 |
+
"away_team": away,
|
| 242 |
+
"b365": {"h": odds["b365h"], "d": odds["b365d"], "a": odds["b365a"]},
|
| 243 |
+
"probabilities": result["probabilities"],
|
| 244 |
+
"predicted": result["predicted"],
|
| 245 |
+
"label": result["label"],
|
| 246 |
+
"confidence": result["confidence"],
|
| 247 |
+
"ev_analysis": {
|
| 248 |
+
"bookmaker_vig": vig,
|
| 249 |
+
"has_value": len(value_bets) > 0,
|
| 250 |
+
"best_bet": best_bet,
|
| 251 |
+
"value_bets": value_bets,
|
| 252 |
+
"all_outcomes": all_outcomes,
|
| 253 |
+
},
|
| 254 |
+
})
|
| 255 |
+
|
| 256 |
+
except ValueError as e:
|
| 257 |
+
logger.warning(f"Skipping {home} vs {away}: {e}")
|
| 258 |
+
continue
|
| 259 |
+
except Exception as e:
|
| 260 |
+
logger.error(f"Unexpected error for {home} vs {away}: {e}")
|
| 261 |
+
continue
|
| 262 |
+
|
| 263 |
+
return results
|
app/core/__init__.py
ADDED
|
File without changes
|
app/core/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (175 Bytes). View file
|
|
|
app/core/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (1.01 kB). View file
|
|
|
app/core/__pycache__/supabase_client.cpython-312.pyc
ADDED
|
Binary file (668 Bytes). View file
|
|
|
app/core/config.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings
|
| 2 |
+
|
| 3 |
+
class Settings(BaseSettings):
|
| 4 |
+
SUPABASE_URL: str
|
| 5 |
+
SUPABASE_KEY: str
|
| 6 |
+
APP_ENV: str = "development"
|
| 7 |
+
APP_HOST: str = "0.0.0.0"
|
| 8 |
+
APP_PORT: int = 8000
|
| 9 |
+
LOG_LEVEL: str = "INFO"
|
| 10 |
+
ODDSPAPI_KEY: str = ""
|
| 11 |
+
|
| 12 |
+
class Config:
|
| 13 |
+
env_file = ".env"
|
| 14 |
+
case_sensitive = True
|
| 15 |
+
extra = "forbid"
|
| 16 |
+
|
| 17 |
+
settings = Settings()
|
app/core/supabase_client.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from supabase import create_client, Client
|
| 2 |
+
from app.core.config import settings
|
| 3 |
+
|
| 4 |
+
_client: Client | None = None
|
| 5 |
+
|
| 6 |
+
def get_supabase() -> Client:
|
| 7 |
+
global _client
|
| 8 |
+
if _client is None:
|
| 9 |
+
_client = create_client(settings.SUPABASE_URL, settings.SUPABASE_KEY)
|
| 10 |
+
return _client
|
app/main.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from app.api.v1.endpoints import matches, predict, pipeline
|
| 4 |
+
from app.core.config import settings
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
logging.basicConfig(level=settings.LOG_LEVEL)
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
app = FastAPI(
|
| 11 |
+
title="EPL Match Outcome Predictor",
|
| 12 |
+
description="Predicts EPL match outcomes using Random Forest + engineered features",
|
| 13 |
+
version="1.0.0",
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
app.add_middleware(
|
| 17 |
+
CORSMiddleware,
|
| 18 |
+
allow_origins=[
|
| 19 |
+
"http://localhost:3000",
|
| 20 |
+
"https://your-vercel-app.vercel.app", # ← replace with real URL at deploy time
|
| 21 |
+
],
|
| 22 |
+
allow_credentials=True,
|
| 23 |
+
allow_methods=["*"],
|
| 24 |
+
allow_headers=["*"],
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Routers registered flat — endpoint decorators carry full sub-paths
|
| 28 |
+
app.include_router(matches.router, prefix="/api/v1", tags=["Matches"])
|
| 29 |
+
app.include_router(predict.router, prefix="/api/v1", tags=["Predictions"])
|
| 30 |
+
app.include_router(pipeline.router, prefix="/api/v1", tags=["Pipeline"])
|
| 31 |
+
|
| 32 |
+
@app.get("/health")
|
| 33 |
+
def health_check():
|
| 34 |
+
return {"status": "ok", "version": "1.0.0"}
|
app/ml/__init__.py
ADDED
|
File without changes
|
app/ml/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (173 Bytes). View file
|
|
|
app/ml/__pycache__/stacking.cpython-312.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
app/ml/__pycache__/utils.cpython-312.pyc
ADDED
|
Binary file (3.11 kB). View file
|
|
|
app/ml/evaluation/__init__.py
ADDED
|
File without changes
|
app/ml/evaluation/metrics.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
def evaluate(y_true, y_pred) -> dict:
|
| 5 |
+
return {
|
| 6 |
+
"accuracy": round(accuracy_score(y_true, y_pred), 4),
|
| 7 |
+
"report": classification_report(y_true, y_pred, output_dict=True),
|
| 8 |
+
"confusion_matrix": confusion_matrix(y_true, y_pred).tolist(),
|
| 9 |
+
}
|
app/ml/features/__init__.py
ADDED
|
File without changes
|
app/ml/features/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
app/ml/features/__pycache__/feature_columns.cpython-312.pyc
ADDED
|
Binary file (1.48 kB). View file
|
|
|
app/ml/features/feature_columns.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FEATURE_COLS = [
|
| 2 |
+
# ── Rolling goals ─────────────────────────────────────────────────────────
|
| 3 |
+
"h_goals_scored_3", "h_goals_scored_5", "h_goals_scored_10",
|
| 4 |
+
"h_goals_conceded_3", "h_goals_conceded_5", "h_goals_conceded_10",
|
| 5 |
+
"a_goals_scored_3", "a_goals_scored_5", "a_goals_scored_10",
|
| 6 |
+
"a_goals_conceded_3", "a_goals_conceded_5", "a_goals_conceded_10",
|
| 7 |
+
# ── Rolling form ──────────────────────────────────────────────────────────
|
| 8 |
+
"h_form_3", "h_form_5", "h_form_10",
|
| 9 |
+
"a_form_3", "a_form_5", "a_form_10",
|
| 10 |
+
# ── Rolling shots / corners / cards ───────────────────────────────────────
|
| 11 |
+
"h_sot_5", "a_sot_5",
|
| 12 |
+
"h_corners_5", "a_corners_5",
|
| 13 |
+
"h_cards_5", "a_cards_5",
|
| 14 |
+
# ── Elo ───────────────────────────────────────────────────────────────────
|
| 15 |
+
"home_elo", "away_elo", "elo_diff",
|
| 16 |
+
# ── Pi-ratings ────────────────────────────────────────────────────────────
|
| 17 |
+
"h_pi_hc", "h_pi_hd",
|
| 18 |
+
"a_pi_ac", "a_pi_ad",
|
| 19 |
+
"pi_atk_diff", "pi_def_diff", "pi_total_diff",
|
| 20 |
+
# ── xG rolling ────────────────────────────────────────────────────────────
|
| 21 |
+
"h_xg_3", "h_xg_5",
|
| 22 |
+
"a_xg_3", "a_xg_5",
|
| 23 |
+
"h_npxg_3", "h_npxg_5",
|
| 24 |
+
"a_npxg_3", "a_npxg_5",
|
| 25 |
+
"h_xgd_5",
|
| 26 |
+
# ── Parity / draw signal ──────────────────────────────────────────────────
|
| 27 |
+
"xg_parity_5",
|
| 28 |
+
"goals_parity_3", "goals_parity_5",
|
| 29 |
+
"def_parity_5", "form_parity_5",
|
| 30 |
+
"pi_parity",
|
| 31 |
+
|
| 32 |
+
# ── NEW: Draw propensity features ─────────────────────────────────────────
|
| 33 |
+
"h_draw_rate_5", # home team draw rate last 5 matches
|
| 34 |
+
"a_draw_rate_5", # away team draw rate last 5 matches
|
| 35 |
+
"h_draw_rate_10", # home team draw rate last 10 matches
|
| 36 |
+
"a_draw_rate_10", # away team draw rate last 10 matches
|
| 37 |
+
"h2h_draw_rate", # % of H2H matches that ended draw
|
| 38 |
+
"draw_propensity", # combined (h_draw_rate_5 + a_draw_rate_5) / 2
|
| 39 |
+
"elo_parity", # 1 / (1 + |elo_diff|) — 1.0 = perfectly equal teams
|
| 40 |
+
# ── Squad strength ────────────────────────────────────────────────────────
|
| 41 |
+
"h_squad_xg", "h_squad_xa", "h_squad_npxg",
|
| 42 |
+
"h_squad_goals","h_squad_ast", "h_squad_min",
|
| 43 |
+
"a_squad_xg", "a_squad_xa", "a_squad_npxg",
|
| 44 |
+
"a_squad_goals","a_squad_ast", "a_squad_min",
|
| 45 |
+
"squad_xg_diff",
|
| 46 |
+
# ── Contextual ────────────────────────────────────────────────────────────
|
| 47 |
+
"home_days_rest", "away_days_rest",
|
| 48 |
+
"home_cumpts", "away_cumpts",
|
| 49 |
+
"is_derby", "h2h_home_win_rate",
|
| 50 |
+
"matchweek",
|
| 51 |
+
# ── Home advantage ────────────────────────────────────────────────────────
|
| 52 |
+
"home_win_rate_hist","away_win_rate_hist",
|
| 53 |
+
"cumpts_diff",
|
| 54 |
+
"combined_goals_5",
|
| 55 |
+
"sot_balance",
|
| 56 |
+
# ── Bookmaker odds (market wisdom — strongest draw signal available) ──────
|
| 57 |
+
"odds_fair_h", # vig-adjusted implied P(Home Win)
|
| 58 |
+
"odds_fair_d", # vig-adjusted implied P(Draw) ← strongest draw feature
|
| 59 |
+
"odds_fair_a", # vig-adjusted implied P(Away Win)
|
| 60 |
+
"odds_home_edge", # market-implied home advantage
|
| 61 |
+
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
TARGET_COL = "ftr"
|
| 65 |
+
LABEL_MAP = {"H": 0, "D": 1, "A": 2}
|
app/ml/models/__init__.py
ADDED
|
File without changes
|
app/ml/models/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (180 Bytes). View file
|
|
|
app/ml/models/__pycache__/lgbm_model.cpython-312.pyc
ADDED
|
Binary file (687 Bytes). View file
|
|
|
app/ml/models/__pycache__/random_forest_model.cpython-312.pyc
ADDED
|
Binary file (5.58 kB). View file
|
|
|
app/ml/models/__pycache__/xgb_model.cpython-312.pyc
ADDED
|
Binary file (732 Bytes). View file
|
|
|
app/ml/models/lgbm_model.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lightgbm import LGBMClassifier
|
| 2 |
+
|
| 3 |
+
def build_lgbm() -> LGBMClassifier:
|
| 4 |
+
return LGBMClassifier(
|
| 5 |
+
n_estimators=500,
|
| 6 |
+
learning_rate=0.05,
|
| 7 |
+
max_depth=6,
|
| 8 |
+
num_leaves=31,
|
| 9 |
+
min_child_samples=20,
|
| 10 |
+
subsample=0.8,
|
| 11 |
+
colsample_bytree=0.8,
|
| 12 |
+
scale_pos_weight=None,
|
| 13 |
+
is_unbalance=False,
|
| 14 |
+
random_state=42,
|
| 15 |
+
n_jobs=1,
|
| 16 |
+
verbose=-1,
|
| 17 |
+
)
|
app/ml/models/random_forest_model.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Trains, evaluates, saves, and loads the EPL Random Forest model.
|
| 3 |
+
Two-stage approach: first predict Draw vs Non-Draw, then Home vs Away.
|
| 4 |
+
"""
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import joblib
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import numpy as np
|
| 10 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 11 |
+
from sklearn.model_selection import TimeSeriesSplit, RandomizedSearchCV
|
| 12 |
+
from sklearn.preprocessing import LabelEncoder
|
| 13 |
+
from sklearn.metrics import classification_report, accuracy_score
|
| 14 |
+
from scipy.stats import randint
|
| 15 |
+
from app.ml.features.feature_columns import FEATURE_COLS, TARGET_COL
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
MODEL_PATH = "models/saved/rf_epl_model.joblib"
|
| 20 |
+
ENCODER_PATH = "models/saved/label_encoder.joblib"
|
| 21 |
+
VERSION = "1.0.0"
|
| 22 |
+
|
| 23 |
+
def train(df: pd.DataFrame) -> dict:
|
| 24 |
+
from app.ml.utils import impute # import your existing impute()
|
| 25 |
+
|
| 26 |
+
available_feat_cols = [c for c in FEATURE_COLS if c in df.columns]
|
| 27 |
+
missing_cols = [c for c in FEATURE_COLS if c not in df.columns]
|
| 28 |
+
if missing_cols:
|
| 29 |
+
logger.warning(f"⚠️ {len(missing_cols)} feature cols missing: {missing_cols[:5]}...")
|
| 30 |
+
|
| 31 |
+
df = df.dropna(subset=[TARGET_COL]) # ✅ already correct, keep as-is
|
| 32 |
+
logger.info(f"🔢 RF training rows after dropna: {len(df)}")
|
| 33 |
+
logger.info(f"Training rows: {len(df)}")
|
| 34 |
+
|
| 35 |
+
X = df[available_feat_cols]
|
| 36 |
+
y = df[TARGET_COL]
|
| 37 |
+
weights = df.get("time_weight", pd.Series(np.ones(len(df)), index=df.index))
|
| 38 |
+
|
| 39 |
+
# ✅ Split FIRST, then impute (no data leakage)
|
| 40 |
+
from sklearn.model_selection import train_test_split
|
| 41 |
+
X_tr, X_te, y_tr, y_te, w_tr, w_te = train_test_split(
|
| 42 |
+
X, y, weights, test_size=0.2, random_state=42, shuffle=False
|
| 43 |
+
)
|
| 44 |
+
X_tr, X_te, imp = impute(X_tr, X_te) # ← fills xG NaNs, adds _present cols
|
| 45 |
+
|
| 46 |
+
tscv = TimeSeriesSplit(n_splits=5)
|
| 47 |
+
param_dist = {
|
| 48 |
+
"n_estimators": randint(300, 1000),
|
| 49 |
+
"max_depth": randint(8, 20),
|
| 50 |
+
"min_samples_split": randint(10, 25),
|
| 51 |
+
"min_samples_leaf": randint(5, 15),
|
| 52 |
+
"max_features": ["sqrt", "log2"],
|
| 53 |
+
}
|
| 54 |
+
base_rf = RandomForestClassifier(class_weight="balanced", random_state=42, n_jobs=-1)
|
| 55 |
+
search = RandomizedSearchCV(
|
| 56 |
+
base_rf, param_dist, n_iter=80, cv=tscv,
|
| 57 |
+
scoring="accuracy", n_jobs=-1, random_state=42
|
| 58 |
+
)
|
| 59 |
+
search.fit(X_tr, y_tr, sample_weight=w_tr) # ← train on imputed X_tr
|
| 60 |
+
best = search.best_estimator_
|
| 61 |
+
|
| 62 |
+
# Evaluate on held-out test set (not last fold)
|
| 63 |
+
preds = best.predict(X_te)
|
| 64 |
+
acc = accuracy_score(y_te, preds)
|
| 65 |
+
report = classification_report(y_te, preds, output_dict=True)
|
| 66 |
+
|
| 67 |
+
os.makedirs("models/saved", exist_ok=True)
|
| 68 |
+
joblib.dump(best, MODEL_PATH)
|
| 69 |
+
joblib.dump(imp, "models/saved/rf_imputer.joblib") # save for inference
|
| 70 |
+
logger.info(f"Model saved → {MODEL_PATH} | Accuracy: {acc:.4f}")
|
| 71 |
+
|
| 72 |
+
return {"accuracy": round(acc, 4), "best_params": search.best_params_, "report": report}
|
| 73 |
+
|
| 74 |
+
def load_model() -> RandomForestClassifier:
|
| 75 |
+
return joblib.load(MODEL_PATH)
|
| 76 |
+
|
| 77 |
+
def predict_match(home_features: dict) -> dict:
|
| 78 |
+
model = load_model()
|
| 79 |
+
X = pd.DataFrame([home_features])[FEATURE_COLS]
|
| 80 |
+
proba = model.predict_proba(X)[0]
|
| 81 |
+
classes = model.classes_ # alphabetical: A, D, H
|
| 82 |
+
class_map = {c: p for c, p in zip(classes, proba)}
|
| 83 |
+
predicted = classes[np.argmax(proba)]
|
| 84 |
+
return {
|
| 85 |
+
"predicted_outcome": predicted,
|
| 86 |
+
"prob_home_win": round(class_map.get("H", 0), 4),
|
| 87 |
+
"prob_draw": round(class_map.get("D", 0), 4),
|
| 88 |
+
"prob_away_win": round(class_map.get("A", 0), 4),
|
| 89 |
+
"confidence": round(float(np.max(proba)), 4),
|
| 90 |
+
"model_version": VERSION,
|
| 91 |
+
}
|
app/ml/models/xgb_model.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from xgboost import XGBClassifier
|
| 2 |
+
|
| 3 |
+
def build_xgb() -> XGBClassifier:
|
| 4 |
+
return XGBClassifier(
|
| 5 |
+
n_estimators=400,
|
| 6 |
+
learning_rate=0.05,
|
| 7 |
+
max_depth=4,
|
| 8 |
+
subsample=0.8,
|
| 9 |
+
colsample_bytree=0.7,
|
| 10 |
+
reg_alpha=0.1, # ← add L1 regularisation
|
| 11 |
+
reg_lambda=1.5, # ← add L2 regularisation
|
| 12 |
+
use_label_encoder=False,
|
| 13 |
+
eval_metric="mlogloss",
|
| 14 |
+
scale_pos_weight=1,
|
| 15 |
+
random_state=42,
|
| 16 |
+
n_jobs=-1, # XGBoost doesn't have the OpenMP deadlock
|
| 17 |
+
verbosity=0,
|
| 18 |
+
)
|
app/ml/stacking.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Out-of-Fold stacking ensemble for EPL match outcome prediction.
|
| 3 |
+
Uses TimeSeriesSplit to avoid future data leakage.
|
| 4 |
+
"""
|
| 5 |
+
import copy
|
| 6 |
+
import logging
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
import joblib
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
|
| 14 |
+
from sklearn.linear_model import LogisticRegression
|
| 15 |
+
from sklearn.metrics import (
|
| 16 |
+
accuracy_score,
|
| 17 |
+
classification_report,
|
| 18 |
+
confusion_matrix,
|
| 19 |
+
log_loss,
|
| 20 |
+
)
|
| 21 |
+
from sklearn.model_selection import TimeSeriesSplit
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
# ── Constants ────────────────────────────────────────────────────────────────
|
| 26 |
+
MODEL_DIR = Path("models")
|
| 27 |
+
ENSEMBLE_FILENAME = "stacking_ensemble.joblib"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ── 1. OOF Meta-Feature Builder ───────────────────────────────────────────────
|
| 31 |
+
def build_oof_meta_features(
|
| 32 |
+
models: dict,
|
| 33 |
+
X_train: pd.DataFrame,
|
| 34 |
+
y_train: pd.Series,
|
| 35 |
+
n_splits: int = 5,
|
| 36 |
+
) -> np.ndarray:
|
| 37 |
+
"""
|
| 38 |
+
Generate OOF probability predictions from each base model.
|
| 39 |
+
|
| 40 |
+
Returns array of shape (n_train_rows, n_models * 3).
|
| 41 |
+
Respects temporal order via TimeSeriesSplit.
|
| 42 |
+
"""
|
| 43 |
+
tscv = TimeSeriesSplit(n_splits=n_splits)
|
| 44 |
+
n_models = len(models)
|
| 45 |
+
oof = np.zeros((len(X_train), n_models * 3))
|
| 46 |
+
|
| 47 |
+
for fold_idx, (tr_idx, val_idx) in enumerate(tscv.split(X_train)):
|
| 48 |
+
X_tr = X_train.iloc[tr_idx]
|
| 49 |
+
X_val = X_train.iloc[val_idx]
|
| 50 |
+
y_tr = y_train.iloc[tr_idx]
|
| 51 |
+
|
| 52 |
+
logger.info(
|
| 53 |
+
f" OOF fold {fold_idx + 1}/{n_splits} "
|
| 54 |
+
f"— train: {len(tr_idx)}, val: {len(val_idx)}"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
col = 0
|
| 58 |
+
for name, model in models.items():
|
| 59 |
+
fold_model = copy.deepcopy(model)
|
| 60 |
+
fold_model.fit(X_tr, y_tr)
|
| 61 |
+
proba = fold_model.predict_proba(X_val) # shape (val, 3)
|
| 62 |
+
oof[val_idx, col : col + 3] = proba
|
| 63 |
+
col += 3
|
| 64 |
+
|
| 65 |
+
# Guard: warn if any OOF rows were never filled (e.g. first fold gap)
|
| 66 |
+
unfilled = np.where(oof.sum(axis=1) == 0)[0]
|
| 67 |
+
if len(unfilled):
|
| 68 |
+
logger.warning(
|
| 69 |
+
f" {len(unfilled)} OOF rows have zero probabilities "
|
| 70 |
+
"(likely first-fold gap). Filling with uniform 1/3."
|
| 71 |
+
)
|
| 72 |
+
oof[unfilled] = 1.0 / 3.0
|
| 73 |
+
|
| 74 |
+
return oof
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ── 2. Meta-Learner Trainer ───────────────────────────────────────────────────
|
| 78 |
+
def build_meta_learner(
|
| 79 |
+
oof: np.ndarray,
|
| 80 |
+
y_train: pd.Series,
|
| 81 |
+
) -> LogisticRegression:
|
| 82 |
+
"""
|
| 83 |
+
Train a regularised multinomial logistic regression on OOF predictions.
|
| 84 |
+
|
| 85 |
+
C=0.1 keeps the meta-learner from over-fitting to base-model quirks.
|
| 86 |
+
"""
|
| 87 |
+
meta = LogisticRegression(
|
| 88 |
+
C=0.1,
|
| 89 |
+
max_iter=1000,
|
| 90 |
+
random_state=42,
|
| 91 |
+
multi_class="multinomial",
|
| 92 |
+
solver="lbfgs",
|
| 93 |
+
class_weight=None, # ← remove the draw weight
|
| 94 |
+
)
|
| 95 |
+
meta.fit(oof, y_train)
|
| 96 |
+
oof_pred = meta.predict(oof)
|
| 97 |
+
logger.info(
|
| 98 |
+
f" Meta-learner OOF accuracy : {accuracy_score(y_train, oof_pred):.4f}"
|
| 99 |
+
)
|
| 100 |
+
logger.info(
|
| 101 |
+
f" Meta-learner OOF log-loss : {log_loss(y_train, meta.predict_proba(oof)):.4f}"
|
| 102 |
+
)
|
| 103 |
+
return meta
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ── 3. Test Meta-Feature Builder ──────────────────────────────────────────────
|
| 107 |
+
def make_test_meta_features(
|
| 108 |
+
models: dict,
|
| 109 |
+
X_test: pd.DataFrame,
|
| 110 |
+
) -> np.ndarray:
|
| 111 |
+
"""
|
| 112 |
+
Generate meta-features for the holdout set from final fitted base models.
|
| 113 |
+
|
| 114 |
+
NOTE: base models must already be refitted on the full training set
|
| 115 |
+
before calling this function.
|
| 116 |
+
"""
|
| 117 |
+
parts = []
|
| 118 |
+
for name, model in models.items():
|
| 119 |
+
proba = model.predict_proba(X_test) # shape (n_test, 3)
|
| 120 |
+
parts.append(proba)
|
| 121 |
+
return np.hstack(parts) # shape (n_test, n_models * 3)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# ── 4. Calibrated Wrapper ─────────────────────────────────────────────────────
|
| 125 |
+
def calibrate_meta_learner(
|
| 126 |
+
meta: LogisticRegression,
|
| 127 |
+
oof: np.ndarray,
|
| 128 |
+
y_train: pd.Series,
|
| 129 |
+
method: str = "sigmoid",
|
| 130 |
+
) -> CalibratedClassifierCV:
|
| 131 |
+
"""
|
| 132 |
+
Wrap the already-fitted meta-learner in sigmoid / Platt calibration.
|
| 133 |
+
|
| 134 |
+
Uses cv='prefit' because the meta-learner was trained on OOF preds,
|
| 135 |
+
so we must NOT re-cross-validate here to avoid data leakage.
|
| 136 |
+
|
| 137 |
+
Parameters
|
| 138 |
+
----------
|
| 139 |
+
method : 'isotonic' — non-parametric, better with >1000 samples
|
| 140 |
+
'sigmoid' — Platt scaling, better with small datasets
|
| 141 |
+
"""
|
| 142 |
+
calibrated = CalibratedClassifierCV(estimator=meta, cv="prefit", method=method)
|
| 143 |
+
calibrated.fit(oof, y_train)
|
| 144 |
+
logger.info(f" Meta-learner calibrated with method='{method}'")
|
| 145 |
+
return calibrated
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ── 5. Save / Load Helpers ────────────────────────────────────────────────────
|
| 149 |
+
def save_ensemble(artifact: dict, path: Optional[Path] = None) -> Path:
|
| 150 |
+
"""
|
| 151 |
+
Persist the full ensemble artifact to disk via joblib.
|
| 152 |
+
|
| 153 |
+
artifact keys expected:
|
| 154 |
+
meta_model : fitted (and optionally calibrated) meta-learner
|
| 155 |
+
base_models : dict of refitted base models
|
| 156 |
+
feature_columns : list[str] used during training
|
| 157 |
+
class_order : list of class labels (e.g. ['A', 'D', 'H'])
|
| 158 |
+
train_accuracy : float
|
| 159 |
+
train_log_loss : float
|
| 160 |
+
test_accuracy : float
|
| 161 |
+
test_log_loss : float
|
| 162 |
+
"""
|
| 163 |
+
path = path or MODEL_DIR / ENSEMBLE_FILENAME
|
| 164 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 165 |
+
joblib.dump(artifact, path, compress=3)
|
| 166 |
+
logger.info(f" Ensemble saved → {path}")
|
| 167 |
+
return path
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def load_ensemble(path: Optional[Path] = None) -> dict:
|
| 171 |
+
"""Load a previously saved ensemble artifact from disk."""
|
| 172 |
+
path = path or MODEL_DIR / ENSEMBLE_FILENAME
|
| 173 |
+
if not path.exists():
|
| 174 |
+
raise FileNotFoundError(f"No ensemble found at {path}")
|
| 175 |
+
artifact = joblib.load(path)
|
| 176 |
+
logger.info(f" Ensemble loaded ← {path}")
|
| 177 |
+
return artifact
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ── 6. Full Training Pipeline ─────────────────────────────────────────────────
|
| 181 |
+
def train_stacking_ensemble(
|
| 182 |
+
base_models: dict,
|
| 183 |
+
X_train: pd.DataFrame,
|
| 184 |
+
y_train: pd.Series,
|
| 185 |
+
X_test: pd.DataFrame,
|
| 186 |
+
y_test: pd.Series,
|
| 187 |
+
n_splits: int = 7,
|
| 188 |
+
calibrate: bool = True,
|
| 189 |
+
calibration_method: str = "sigmoid",
|
| 190 |
+
save_path: Optional[Path] = None,
|
| 191 |
+
) -> dict:
|
| 192 |
+
"""
|
| 193 |
+
Full OOF stacking pipeline with optional calibration and persistence.
|
| 194 |
+
|
| 195 |
+
Parameters
|
| 196 |
+
----------
|
| 197 |
+
base_models : dict e.g. {"RF": rf, "LGBM": lgbm, "CB": cb}
|
| 198 |
+
X_train, y_train : temporally-ordered training features + labels
|
| 199 |
+
X_test, y_test : holdout set (must be strictly after training period)
|
| 200 |
+
n_splits : number of TimeSeriesSplit folds
|
| 201 |
+
calibrate : whether to sigmoid/Platt-calibrate the meta-learner
|
| 202 |
+
calibration_method: 'sigmoid' or 'sigmoid'
|
| 203 |
+
save_path : override default save location (optional)
|
| 204 |
+
|
| 205 |
+
Returns
|
| 206 |
+
-------
|
| 207 |
+
dict with keys:
|
| 208 |
+
meta_model, base_models, oof_array,
|
| 209 |
+
test_accuracy, test_log_loss,
|
| 210 |
+
y_pred, y_proba, class_order
|
| 211 |
+
"""
|
| 212 |
+
logger.info("=" * 60)
|
| 213 |
+
logger.info(" OOF STACKING ENSEMBLE")
|
| 214 |
+
logger.info("=" * 60)
|
| 215 |
+
|
| 216 |
+
# ── Step 1: OOF meta-features ─────────────────────────────────────────────
|
| 217 |
+
logger.info("Step 1 — Generating OOF meta-features...")
|
| 218 |
+
oof = build_oof_meta_features(base_models, X_train, y_train, n_splits)
|
| 219 |
+
logger.info(f" OOF meta-feature matrix: {oof.shape}")
|
| 220 |
+
|
| 221 |
+
# ── Step 2: Meta-learner ──────────────────────────────────────────────────
|
| 222 |
+
logger.info("Step 2 — Training meta-learner on OOF predictions...")
|
| 223 |
+
meta = build_meta_learner(oof, y_train)
|
| 224 |
+
|
| 225 |
+
# ── Step 3: Optional calibration ─────────────────────────────────────────
|
| 226 |
+
if calibrate:
|
| 227 |
+
logger.info("Step 3 — Calibrating meta-learner...")
|
| 228 |
+
meta = calibrate_meta_learner(meta, oof, y_train, method=calibration_method)
|
| 229 |
+
else:
|
| 230 |
+
logger.info("Step 3 — Skipping calibration (calibrate=False)")
|
| 231 |
+
|
| 232 |
+
# ── Step 4: Refit ALL base models on full training set ────────────────────
|
| 233 |
+
logger.info("Step 4 — Refitting base models on full training set...")
|
| 234 |
+
for name, model in base_models.items():
|
| 235 |
+
model.fit(X_train, y_train)
|
| 236 |
+
train_acc = accuracy_score(y_train, model.predict(X_train))
|
| 237 |
+
logger.info(f" ✅ {name} refitted | train acc: {train_acc:.4f}")
|
| 238 |
+
|
| 239 |
+
# ── Step 5: Test meta-features ────────────────────────────────────────────
|
| 240 |
+
logger.info("Step 5 — Generating test meta-features...")
|
| 241 |
+
test_meta = make_test_meta_features(base_models, X_test)
|
| 242 |
+
|
| 243 |
+
# ── Step 6: Evaluate on holdout ───────────────────────────────────────────
|
| 244 |
+
logger.info("Step 6 — Evaluating stacking ensemble on holdout set...")
|
| 245 |
+
y_pred = meta.predict(test_meta)
|
| 246 |
+
y_proba = meta.predict_proba(test_meta)
|
| 247 |
+
acc = accuracy_score(y_test, y_pred)
|
| 248 |
+
ll = log_loss(y_test, y_proba)
|
| 249 |
+
|
| 250 |
+
class_names = ["Home Win", "Draw", "Away Win"] # ← hardcoded, safe
|
| 251 |
+
|
| 252 |
+
logger.info(f"\n{'='*50}")
|
| 253 |
+
logger.info(f" Stacking Ensemble — Holdout Results")
|
| 254 |
+
logger.info(f" Accuracy : {acc:.4f}")
|
| 255 |
+
logger.info(f" Log Loss : {ll:.4f}")
|
| 256 |
+
logger.info(f"\n{classification_report(y_test, y_pred, target_names=class_names)}")
|
| 257 |
+
logger.info(f"\nConfusion Matrix:\n{confusion_matrix(y_test, y_pred)}")
|
| 258 |
+
logger.info(f"{'='*50}")
|
| 259 |
+
|
| 260 |
+
# ── Step 7: Base model individual scores for comparison ───────────────────
|
| 261 |
+
logger.info("Step 7 — Individual base model scores on holdout:")
|
| 262 |
+
for name, model in base_models.items():
|
| 263 |
+
bm_pred = model.predict(X_test)
|
| 264 |
+
bm_proba = model.predict_proba(X_test)
|
| 265 |
+
bm_acc = accuracy_score(y_test, bm_pred)
|
| 266 |
+
bm_ll = log_loss(y_test, bm_proba)
|
| 267 |
+
logger.info(f" {name:<10} acc: {bm_acc:.4f} log-loss: {bm_ll:.4f}")
|
| 268 |
+
|
| 269 |
+
# ── Step 8: Persist artifact ──────────────────────────────────────────────
|
| 270 |
+
artifact = {
|
| 271 |
+
"meta_model": meta,
|
| 272 |
+
"base_models": base_models,
|
| 273 |
+
"oof_array": oof,
|
| 274 |
+
"feature_columns": list(X_train.columns),
|
| 275 |
+
"class_order": class_names,
|
| 276 |
+
"test_accuracy": acc,
|
| 277 |
+
"test_log_loss": ll,
|
| 278 |
+
"y_pred": y_pred,
|
| 279 |
+
"y_proba": y_proba,
|
| 280 |
+
"calibrated": calibrate,
|
| 281 |
+
"calibration_method": calibration_method if calibrate else None,
|
| 282 |
+
"n_splits": n_splits,
|
| 283 |
+
}
|
| 284 |
+
save_ensemble(artifact, save_path)
|
| 285 |
+
|
| 286 |
+
return {
|
| 287 |
+
"meta_model": meta,
|
| 288 |
+
"base_models": base_models,
|
| 289 |
+
"oof": oof,
|
| 290 |
+
"accuracy": acc, # ← was "test_accuracy", rename to "accuracy"
|
| 291 |
+
"log_loss": ll, # ← keep as is
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# ── 7. Inference Helper ───────────────────────────────────────────────────────
|
| 296 |
+
def predict_with_ensemble(
|
| 297 |
+
artifact: dict,
|
| 298 |
+
X: pd.DataFrame,
|
| 299 |
+
) -> dict:
|
| 300 |
+
"""
|
| 301 |
+
Run inference on new data using a loaded ensemble artifact.
|
| 302 |
+
|
| 303 |
+
Parameters
|
| 304 |
+
----------
|
| 305 |
+
artifact : loaded via load_ensemble()
|
| 306 |
+
X : DataFrame with the same feature columns used during training
|
| 307 |
+
|
| 308 |
+
Returns
|
| 309 |
+
-------
|
| 310 |
+
dict:
|
| 311 |
+
predicted_class : np.ndarray of class labels
|
| 312 |
+
probabilities : np.ndarray shape (n, 3) — [Away, Draw, Home]
|
| 313 |
+
class_order : list of class label names
|
| 314 |
+
"""
|
| 315 |
+
expected_cols = artifact["feature_columns"]
|
| 316 |
+
missing = set(expected_cols) - set(X.columns)
|
| 317 |
+
if missing:
|
| 318 |
+
raise ValueError(f"Missing feature columns at inference: {missing}")
|
| 319 |
+
|
| 320 |
+
X_aligned = X[expected_cols]
|
| 321 |
+
test_meta = make_test_meta_features(artifact["base_models"], X_aligned)
|
| 322 |
+
y_proba = artifact["meta_model"].predict_proba(test_meta)
|
| 323 |
+
y_pred = artifact["meta_model"].predict(test_meta)
|
| 324 |
+
|
| 325 |
+
return {
|
| 326 |
+
"predicted_class": y_pred,
|
| 327 |
+
"probabilities": y_proba,
|
| 328 |
+
"class_order": artifact["class_order"],
|
| 329 |
+
}
|
app/ml/utils.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shared ML utilities — importable by both train_model.py and model modules
|
| 3 |
+
without circular imports.
|
| 4 |
+
"""
|
| 5 |
+
import logging
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from sklearn.impute import SimpleImputer
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def impute(X_train: pd.DataFrame, X_test: pd.DataFrame):
|
| 13 |
+
X_train = X_train.copy()
|
| 14 |
+
X_test = X_test.copy()
|
| 15 |
+
|
| 16 |
+
# Pre-fill to avoid empty-slice warnings on sparse CV folds
|
| 17 |
+
train_medians = X_train.median()
|
| 18 |
+
X_train = X_train.fillna(train_medians).fillna(0)
|
| 19 |
+
X_test = X_test.fillna(train_medians).fillna(0)
|
| 20 |
+
|
| 21 |
+
null_rates = X_train.isna().mean()
|
| 22 |
+
all_nan_cols = null_rates[null_rates == 1.0].index.tolist()
|
| 23 |
+
if all_nan_cols:
|
| 24 |
+
logger.warning(f"Dropping {len(all_nan_cols)} all-NaN cols: {all_nan_cols}")
|
| 25 |
+
X_train = X_train.drop(columns=all_nan_cols)
|
| 26 |
+
X_test = X_test.drop(columns=all_nan_cols, errors="ignore")
|
| 27 |
+
null_rates = null_rates.drop(index=all_nan_cols)
|
| 28 |
+
|
| 29 |
+
sparse_cols = null_rates[null_rates > 0.15].index.tolist()
|
| 30 |
+
if sparse_cols:
|
| 31 |
+
train_indicators = pd.DataFrame(
|
| 32 |
+
{f"{c}_present": X_train[c].notna().astype(int) for c in sparse_cols},
|
| 33 |
+
index=X_train.index
|
| 34 |
+
)
|
| 35 |
+
test_indicators = pd.DataFrame(
|
| 36 |
+
{f"{c}_present": X_test[c].notna().astype(int) for c in sparse_cols},
|
| 37 |
+
index=X_test.index
|
| 38 |
+
)
|
| 39 |
+
X_train = pd.concat([X_train, train_indicators], axis=1)
|
| 40 |
+
X_test = pd.concat([X_test, test_indicators], axis=1)
|
| 41 |
+
logger.info(f"Added {len(sparse_cols)} missingness indicator columns")
|
| 42 |
+
|
| 43 |
+
imp = SimpleImputer(strategy="median")
|
| 44 |
+
X_train_imp = pd.DataFrame(
|
| 45 |
+
imp.fit_transform(X_train), columns=X_train.columns
|
| 46 |
+
)
|
| 47 |
+
X_test_imp = pd.DataFrame(
|
| 48 |
+
imp.transform(X_test), columns=X_train.columns
|
| 49 |
+
)
|
| 50 |
+
return X_train_imp, X_test_imp, imp
|
app/schemas/__init__.py
ADDED
|
File without changes
|
app/schemas/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
app/schemas/__pycache__/prediction.cpython-312.pyc
ADDED
|
Binary file (1.24 kB). View file
|
|
|
app/schemas/match.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from datetime import date
|
| 4 |
+
|
| 5 |
+
class MatchBase(BaseModel):
|
| 6 |
+
season: str
|
| 7 |
+
date: date
|
| 8 |
+
home_team: str
|
| 9 |
+
away_team: str
|
| 10 |
+
ftr: Optional[str] = None # H / D / A
|
| 11 |
+
fthg: Optional[int] = None
|
| 12 |
+
ftag: Optional[int] = None
|
| 13 |
+
hthg: Optional[int] = None
|
| 14 |
+
htag: Optional[int] = None
|
| 15 |
+
hs: Optional[int] = None # home shots
|
| 16 |
+
as_: Optional[int] = None # away shots (aliased)
|
| 17 |
+
hst: Optional[int] = None # home shots on target
|
| 18 |
+
ast: Optional[int] = None
|
| 19 |
+
hc: Optional[int] = None # home corners
|
| 20 |
+
ac: Optional[int] = None
|
| 21 |
+
hy: Optional[int] = None # home yellows
|
| 22 |
+
ay: Optional[int] = None
|
| 23 |
+
hr: Optional[int] = None # home reds
|
| 24 |
+
ar: Optional[int] = None
|
| 25 |
+
referee: Optional[str] = None
|
| 26 |
+
time_weight: Optional[float] = 1.0
|
| 27 |
+
|
| 28 |
+
class MatchCreate(MatchBase):
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
class MatchOut(MatchBase):
|
| 32 |
+
id: int
|
| 33 |
+
class Config:
|
| 34 |
+
from_attributes = True
|
app/schemas/prediction.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
|
| 3 |
+
class PredictionRequest(BaseModel):
|
| 4 |
+
home_team: str
|
| 5 |
+
away_team: str
|
| 6 |
+
season: str = "2526"
|
| 7 |
+
home_odd: float | None = None # optional — enables +EV analysis
|
| 8 |
+
draw_odd: float | None = None
|
| 9 |
+
away_odd: float | None = None
|
| 10 |
+
|
| 11 |
+
class PredictionResponse(BaseModel):
|
| 12 |
+
home_team: str
|
| 13 |
+
away_team: str
|
| 14 |
+
predicted_outcome: str # "H" | "D" | "A"
|
| 15 |
+
prob_home_win: float
|
| 16 |
+
prob_draw: float
|
| 17 |
+
prob_away_win: float
|
| 18 |
+
confidence: float
|
| 19 |
+
model_version: str
|
| 20 |
+
probabilities: dict # {"H": 0.48, "D": 0.28, "A": 0.24}
|
| 21 |
+
predicted: str # "H", "D", or "A"
|
| 22 |
+
label: str
|
| 23 |
+
confidence: float
|
| 24 |
+
ev_analysis: dict | None = None # populated when odds are provided
|
app/services/__init__.py
ADDED
|
File without changes
|
app/services/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (179 Bytes). View file
|
|
|