Spaces:
Sleeping

otito254 commited on
Commit
81163d9
·
1 Parent(s): cb49361

adding cache functionality

Browse files
app/api/v1/endpoints/pipeline.py CHANGED
@@ -1,29 +1,31 @@
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"],
@@ -33,6 +35,9 @@ def trigger_train(background_tasks: BackgroundTasks):
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
 
@@ -40,4 +45,49 @@ def trigger_train(background_tasks: BackgroundTasks):
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"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
  import subprocess
3
+ import os
4
  from pathlib import Path
5
+ from fastapi import APIRouter, BackgroundTasks, HTTPException
6
  from app.services.ingest_service import ingest_all
7
  from app.services.feature_service import build_and_save
8
+ from app.services.cache_service import invalidate_cache, get_cache_status
9
+ from app.core.config import LEAGUE_CONFIG
10
 
11
  logger = logging.getLogger(__name__)
12
  router = APIRouter()
13
 
14
+
15
+ # ── Existing endpoints — unchanged ────────────────────────────────────────────
16
  @router.post("/pipeline/ingest")
17
  def trigger_ingest(background_tasks: BackgroundTasks):
18
  background_tasks.add_task(ingest_all)
19
  return {"message": "Ingestion started in background"}
20
 
21
+
22
  @router.post("/pipeline/train")
23
  def trigger_train(background_tasks: BackgroundTasks):
24
  def run():
25
  try:
 
26
  df = build_and_save()
27
  logger.info(f"✅ Features rebuilt: {df.shape}")
28
 
 
29
  logger.info("🚀 Starting model training...")
30
  result = subprocess.run(
31
  ["python", "scripts/train_model.py"],
 
35
  )
36
  if result.returncode == 0:
37
  logger.info(f"✅ Model training complete:\n{result.stdout[-500:]}")
38
+ # ── Auto-invalidate cache after retraining ─────────────────
39
+ invalidate_cache("epl")
40
+ logger.info("🗑️ Cache invalidated after retraining")
41
  else:
42
  logger.error(f"❌ Training failed:\n{result.stderr[-500:]}")
43
 
 
45
  logger.error(f"Pipeline failed: {e}", exc_info=True)
46
 
47
  background_tasks.add_task(run)
48
+ return {"message": "Pipeline started — rebuilding features then training model"}
49
+
50
+
51
+ # ── New cache management endpoints ───────────────────────────────────────────
52
+ @router.get("/cache/status")
53
+ def cache_status(league: str = "epl"):
54
+ """Check current cache state for a league."""
55
+ if league not in LEAGUE_CONFIG:
56
+ raise HTTPException(
57
+ status_code=400,
58
+ detail=f"Unknown league '{league}'. Valid: {list(LEAGUE_CONFIG.keys())}"
59
+ )
60
+ return get_cache_status(league)
61
+
62
+
63
+ @router.get("/cache/status/all")
64
+ def all_cache_status():
65
+ """Overview of cache state across all configured leagues."""
66
+ return {
67
+ league: get_cache_status(league)
68
+ for league in LEAGUE_CONFIG
69
+ }
70
+
71
+
72
+ @router.post("/cache/invalidate")
73
+ def bust_cache(league: str = "epl", secret: str = ""):
74
+ """
75
+ Force-bust the predictions cache for a league.
76
+ Requires ADMIN_SECRET env var to prevent abuse.
77
+ Next request to /predict/upcoming will trigger a fresh OddsPapi fetch.
78
+ """
79
+ admin_secret = os.getenv("ADMIN_SECRET", "changeme")
80
+ if secret != admin_secret:
81
+ raise HTTPException(status_code=403, detail="Invalid admin secret")
82
+
83
+ if league not in LEAGUE_CONFIG:
84
+ raise HTTPException(
85
+ status_code=400,
86
+ detail=f"Unknown league '{league}'. Valid: {list(LEAGUE_CONFIG.keys())}"
87
+ )
88
+
89
+ invalidate_cache(league)
90
+ return {
91
+ "message": f"Cache invalidated for '{league}'",
92
+ "effect": "Next /predict/upcoming request will fetch fresh data from OddsPapi",
93
+ }
app/api/v1/endpoints/predict.py CHANGED
@@ -4,6 +4,8 @@ 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
@@ -11,11 +13,11 @@ 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:
@@ -161,6 +163,13 @@ def predict_upcoming(limit: int = 20):
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()
@@ -260,4 +269,9 @@ def predict_upcoming(limit: int = 20):
260
  logger.error(f"Unexpected error for {home} vs {away}: {e}")
261
  continue
262
 
 
 
 
 
 
263
  return results
 
4
  import pandas as pd
5
  from pathlib import Path
6
  from fastapi import APIRouter, HTTPException
7
+ # Add this line after the existing imports
8
+ from app.services.cache_service import get_cached, set_cache
9
 
10
  from app.schemas.prediction import PredictionRequest, PredictionResponse
11
  from app.services.feature_service import load_matches, engineer_features, get_current_elo
 
13
  from app.services.ev_service import find_value_bets, format_ev_report
14
  from app.services.odds_service import get_upcoming_epl_fixtures, get_b365_odds, normalise_name, calculate_ev
15
  from app.utils.team_utils import normalise_team
16
+ import os
17
+ MODELS_DIR = Path(os.getenv("MODELS_DIR", "models/saved"))
18
 
19
  logger = logging.getLogger(__name__)
20
  router = APIRouter()
 
 
21
 
22
  # ── Load once at startup ──────────────────────────────────────────────────────
23
  try:
 
163
  if _model is None:
164
  raise HTTPException(status_code=503,
165
  detail="Model not loaded. Run: python scripts/train_model.py")
166
+
167
+ # ── Serve from cache if available ─────────────────────────────────────────
168
+ cached = get_cached("epl")
169
+ if cached is not None:
170
+ logger.info(f"⚡ Serving {len(cached)} fixtures from cache")
171
+ return cached[:limit]
172
+ logger.info("📡 Cache miss — fetching from OddsPapi...")
173
 
174
  try:
175
  fixtures = get_upcoming_epl_fixtures()
 
269
  logger.error(f"Unexpected error for {home} vs {away}: {e}")
270
  continue
271
 
272
+ # ── Save to cache before returning ────────────────────────────────────────
273
+ if results:
274
+ set_cache("epl", results)
275
+ logger.info(f"💾 Cached {len(results)} fixtures")
276
+
277
  return results
app/core/config.py CHANGED
@@ -1,5 +1,6 @@
1
  from pydantic_settings import BaseSettings
2
 
 
3
  class Settings(BaseSettings):
4
  SUPABASE_URL: str
5
  SUPABASE_KEY: str
@@ -14,4 +15,18 @@ class Settings(BaseSettings):
14
  case_sensitive = True
15
  extra = "forbid"
16
 
 
17
  settings = Settings()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from pydantic_settings import BaseSettings
2
 
3
+
4
  class Settings(BaseSettings):
5
  SUPABASE_URL: str
6
  SUPABASE_KEY: str
 
15
  case_sensitive = True
16
  extra = "forbid"
17
 
18
+
19
  settings = Settings()
20
+
21
+
22
+ # ── League registry ────────────────────────────────────────────────────────────
23
+ LEAGUE_CONFIG = {
24
+ "epl": {
25
+ "name": "English Premier League",
26
+ "fdco_code": "E0",
27
+ "tournament_id": 17,
28
+ "supabase_table": "matches_epl",
29
+ "models_dir": "models/saved/epl",
30
+ "season_format": "aug_may",
31
+ },
32
+ }
app/services/cache_service.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from datetime import datetime, timezone, timedelta
3
+ from typing import Optional
4
+ from app.core.supabase_client import get_supabase # ← was: from app.core.supabase_client import supabase
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ _memory_cache: dict[str, dict] = {}
9
+
10
+
11
+ def _make_cache_key(league: str) -> str:
12
+ return f"upcoming_{league}"
13
+
14
+
15
+ def _calc_ttl_hours(league: str = "epl") -> int:
16
+ now = datetime.now(timezone.utc)
17
+ weekday = now.weekday()
18
+ if weekday in (1, 2, 5, 6):
19
+ return 1
20
+ return 6
21
+
22
+
23
+ def get_cached(league: str = "epl") -> Optional[list]:
24
+ key = _make_cache_key(league)
25
+ now = datetime.now(timezone.utc)
26
+
27
+ # ── 1. Memory cache ───────────────────────────────────────────────────────
28
+ if key in _memory_cache:
29
+ entry = _memory_cache[key]
30
+ if entry["expires_at"] > now:
31
+ logger.info(f"⚡ Memory cache hit for {key} "
32
+ f"(expires in {int((entry['expires_at'] - now).seconds / 60)} min)")
33
+ return entry["payload"]
34
+ else:
35
+ logger.info(f"⏰ Memory cache expired for {key}")
36
+ del _memory_cache[key]
37
+
38
+ # ── 2. Supabase cache ─────────────────────────────────────────────────────
39
+ try:
40
+ supabase = get_supabase() # ← call the function each time needed
41
+ result = (
42
+ supabase.table("predictions_cache")
43
+ .select("*")
44
+ .eq("cache_key", key)
45
+ .gt("expires_at", now.isoformat())
46
+ .execute()
47
+ )
48
+ if result.data:
49
+ row = result.data[0]
50
+ expires_at = datetime.fromisoformat(row["expires_at"])
51
+
52
+ _memory_cache[key] = {
53
+ "payload": row["payload"],
54
+ "expires_at": expires_at,
55
+ }
56
+
57
+ supabase.table("predictions_cache").update(
58
+ {"hit_count": row["hit_count"] + 1}
59
+ ).eq("cache_key", key).execute()
60
+
61
+ logger.info(f"🗄️ Supabase cache hit for {key} "
62
+ f"(expires in {int((expires_at - now).seconds / 60)} min, "
63
+ f"hit #{row['hit_count'] + 1})")
64
+ return row["payload"]
65
+
66
+ except Exception as e:
67
+ logger.warning(f"Cache read failed for {key}: {e}")
68
+
69
+ return None
70
+
71
+
72
+ def set_cache(league: str, payload: list) -> None:
73
+ key = _make_cache_key(league)
74
+ now = datetime.now(timezone.utc)
75
+ ttl_hours = _calc_ttl_hours(league)
76
+ expires_at = now + timedelta(hours=ttl_hours)
77
+ fixture_ids = [str(f.get("fixture_id", "")) for f in payload]
78
+
79
+ _memory_cache[key] = {
80
+ "payload": payload,
81
+ "expires_at": expires_at,
82
+ }
83
+
84
+ try:
85
+ supabase = get_supabase() # ← call the function each time needed
86
+ supabase.table("predictions_cache").upsert({
87
+ "cache_key": key,
88
+ "league": league,
89
+ "payload": payload,
90
+ "fixture_ids": fixture_ids,
91
+ "fetched_at": now.isoformat(),
92
+ "expires_at": expires_at.isoformat(),
93
+ "hit_count": 0,
94
+ }, on_conflict="cache_key").execute()
95
+
96
+ logger.info(f"💾 Cache saved for {key} — "
97
+ f"{len(payload)} fixtures, TTL {ttl_hours}h "
98
+ f"(expires {expires_at.strftime('%H:%M UTC')})")
99
+ except Exception as e:
100
+ logger.warning(f"Cache write failed for {key}: {e}")
101
+
102
+
103
+ def invalidate_cache(league: str) -> None:
104
+ key = _make_cache_key(league)
105
+
106
+ if key in _memory_cache:
107
+ del _memory_cache[key]
108
+
109
+ try:
110
+ supabase = get_supabase() # ← call the function each time needed
111
+ supabase.table("predictions_cache").delete().eq("cache_key", key).execute()
112
+ logger.info(f"🗑️ Cache invalidated for {key}")
113
+ except Exception as e:
114
+ logger.warning(f"Cache invalidation failed for {key}: {e}")
115
+
116
+
117
+ def get_cache_status(league: str) -> dict:
118
+ key = _make_cache_key(league)
119
+ now = datetime.now(timezone.utc)
120
+
121
+ if key in _memory_cache:
122
+ entry = _memory_cache[key]
123
+ expires_in = int((entry["expires_at"] - now).seconds / 60)
124
+ return {
125
+ "source": "memory",
126
+ "cached": True,
127
+ "fixture_count": len(entry["payload"]),
128
+ "expires_in_mins": expires_in,
129
+ }
130
+
131
+ try:
132
+ supabase = get_supabase() # ← call the function each time needed
133
+ result = (
134
+ supabase.table("predictions_cache")
135
+ .select("fetched_at, expires_at, hit_count, fixture_ids")
136
+ .eq("cache_key", key)
137
+ .execute()
138
+ )
139
+ if result.data:
140
+ row = result.data[0]
141
+ expires_at = datetime.fromisoformat(row["expires_at"])
142
+ is_fresh = expires_at > now
143
+ return {
144
+ "source": "supabase",
145
+ "cached": is_fresh,
146
+ "fixture_count": len(row["fixture_ids"]),
147
+ "fetched_at": row["fetched_at"],
148
+ "expires_in_mins": int((expires_at - now).seconds / 60) if is_fresh else 0,
149
+ "total_hits": row["hit_count"],
150
+ }
151
+ except Exception as e:
152
+ logger.warning(f"Cache status check failed: {e}")
153
+
154
+ return {"cached": False, "source": None}
scripts/predict_upcoming.py CHANGED
@@ -1,28 +1,77 @@
1
  import logging
2
- import sys, os
 
 
3
  sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
4
- from app.services.odds_service import get_upcoming_epl_fixtures, get_b365_odds, calculate_ev, normalise_name
 
 
 
5
  from app.services.feature_service import build_live_features
6
  from app.services.model_service import load_model, predict_proba
7
-
8
 
9
  logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  model = load_model()
13
  print("✅ Ensemble model loaded")
14
 
15
  fixtures = get_upcoming_epl_fixtures()
16
  logger.info(f"Found {len(fixtures)} upcoming EPL fixtures")
17
 
 
 
18
  for fix in fixtures:
19
- fixture_id = fix["fixtureId"]
20
- home = normalise_name(fix.get("participant1Name", str(fix["participant1Id"])))
21
- away = normalise_name(fix.get("participant2Name", str(fix["participant2Id"])))
22
- start_time = fix["startTime"]
23
- ...
 
 
 
24
 
25
- odds = get_b365_odds(fixture_id) # ← separate API call per fixture
26
 
27
  if not odds:
28
  logger.warning(f" ⚠️ No 1X2 odds for fixture {fixture_id}, skipping")
@@ -32,19 +81,61 @@ for fix in fixtures:
32
  print(f" B365: H={odds['b365h']} D={odds['b365d']} A={odds['b365a']}")
33
 
34
  features = build_live_features(home, away, odds)
35
- probs = predict_proba(model, features) # [p_home, p_draw, p_away]
36
 
37
  ev_h = calculate_ev(probs[0], odds["b365h"])
38
  ev_d = calculate_ev(probs[1], odds["b365d"])
39
  ev_a = calculate_ev(probs[2], odds["b365a"])
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  print(f"\n{'='*50}")
42
  print(f" {home} vs {away}")
43
  print(f" Model: H={probs[0]:.1%} D={probs[1]:.1%} A={probs[2]:.1%}")
44
  print(f" B365: H={odds['b365h']} D={odds['b365d']} A={odds['b365a']}")
45
  print(f" EV: H={ev_h:+.3f} D={ev_d:+.3f} A={ev_a:+.3f}")
46
- if max(ev_h, ev_d, ev_a) > 0.05:
47
- best = ["Home", "Draw", "Away"][[ev_h, ev_d, ev_a].index(max(ev_h, ev_d, ev_a))]
48
- print(f" 🟢 VALUE BET → {best}")
49
  else:
50
- print(f" 🔴 No value — skip")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
+ import sys
3
+ import os
4
+
5
  sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
6
+
7
+ from app.services.odds_service import (
8
+ get_upcoming_epl_fixtures, get_b365_odds, calculate_ev, normalise_name
9
+ )
10
  from app.services.feature_service import build_live_features
11
  from app.services.model_service import load_model, predict_proba
12
+ from app.services.cache_service import get_cached, set_cache, get_cache_status
13
 
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
+ LEAGUE = "epl"
18
+
19
+ # ── Check cache first — avoids burning API quota on every run ─────────────────
20
+ status = get_cache_status(LEAGUE)
21
+ if status.get("cached"):
22
+ print(f"\n⚡ Serving from cache "
23
+ f"({status['source']}, "
24
+ f"expires in {status.get('expires_in_mins', '?')} min, "
25
+ f"{status.get('fixture_count', '?')} fixtures)\n")
26
+
27
+ cached_results = get_cached(LEAGUE)
28
+ if cached_results:
29
+ for fix in cached_results:
30
+ probs = fix["probabilities"]
31
+ odds = fix["b365"]
32
+ ev = fix["ev_analysis"]
33
+
34
+ ev_h = next((o["ev"] for o in ev["all_outcomes"] if o["outcome"] == "H"), 0)
35
+ ev_d = next((o["ev"] for o in ev["all_outcomes"] if o["outcome"] == "D"), 0)
36
+ ev_a = next((o["ev"] for o in ev["all_outcomes"] if o["outcome"] == "A"), 0)
37
+
38
+ print(f"\n{'='*50}")
39
+ print(f" {fix['home_team']} vs {fix['away_team']} ({fix['date']})")
40
+ print(f" Model: H={probs['H']:.1%} D={probs['D']:.1%} A={probs['A']:.1%}")
41
+ print(f" B365: H={odds['h']} D={odds['d']} A={odds['a']}")
42
+ print(f" EV: H={ev_h:+.3f} D={ev_d:+.3f} A={ev_a:+.3f}")
43
+
44
+ if ev["has_value"] and ev["best_bet"]:
45
+ bb = ev["best_bet"]
46
+ print(f" 🟢 VALUE BET → {bb['outcome']} "
47
+ f"EV={bb['ev']:+.3f} Kelly={bb['kelly_pct']}%")
48
+ else:
49
+ print(" 🔴 No value — skip")
50
+
51
+ sys.exit(0)
52
+
53
+ # ── Cache miss — fetch fresh from OddsPapi ────────────────────────────────────
54
+ print("\n📡 Cache miss — fetching live data from OddsPapi...\n")
55
+
56
  model = load_model()
57
  print("✅ Ensemble model loaded")
58
 
59
  fixtures = get_upcoming_epl_fixtures()
60
  logger.info(f"Found {len(fixtures)} upcoming EPL fixtures")
61
 
62
+ results = []
63
+
64
  for fix in fixtures:
65
+ fixture_id = fix.get("id") or fix.get("fixtureId")
66
+ if not fixture_id:
67
+ logger.warning(f"Fixture missing ID, skipping: {fix}")
68
+ continue
69
+
70
+ home = normalise_name(fix.get("participant1Name", str(fix.get("participant1Id", ""))))
71
+ away = normalise_name(fix.get("participant2Name", str(fix.get("participant2Id", ""))))
72
+ start_time = fix.get("startTime") or fix.get("startDate", "")
73
 
74
+ odds = get_b365_odds(fixture_id)
75
 
76
  if not odds:
77
  logger.warning(f" ⚠️ No 1X2 odds for fixture {fixture_id}, skipping")
 
81
  print(f" B365: H={odds['b365h']} D={odds['b365d']} A={odds['b365a']}")
82
 
83
  features = build_live_features(home, away, odds)
84
+ probs = predict_proba(model, features) # [p_home, p_draw, p_away]
85
 
86
  ev_h = calculate_ev(probs[0], odds["b365h"])
87
  ev_d = calculate_ev(probs[1], odds["b365d"])
88
  ev_a = calculate_ev(probs[2], odds["b365a"])
89
 
90
+ all_outcomes = [
91
+ {"outcome": "H", "model_prob": round(probs[0], 4),
92
+ "decimal_odd": odds["b365h"], "ev": round(ev_h, 4),
93
+ "kelly_pct": round(max(((probs[0]*odds["b365h"]-1)/(odds["b365h"]-1))*100, 0), 2),
94
+ "is_value": ev_h > 0.05},
95
+ {"outcome": "D", "model_prob": round(probs[1], 4),
96
+ "decimal_odd": odds["b365d"], "ev": round(ev_d, 4),
97
+ "kelly_pct": round(max(((probs[1]*odds["b365d"]-1)/(odds["b365d"]-1))*100, 0), 2),
98
+ "is_value": ev_d > 0.05},
99
+ {"outcome": "A", "model_prob": round(probs[2], 4),
100
+ "decimal_odd": odds["b365a"], "ev": round(ev_a, 4),
101
+ "kelly_pct": round(max(((probs[2]*odds["b365a"]-1)/(odds["b365a"]-1))*100, 0), 2),
102
+ "is_value": ev_a > 0.05},
103
+ ]
104
+ value_bets = [o for o in all_outcomes if o["is_value"]]
105
+ best_bet = max(value_bets, key=lambda x: x["ev"]) if value_bets else None
106
+
107
  print(f"\n{'='*50}")
108
  print(f" {home} vs {away}")
109
  print(f" Model: H={probs[0]:.1%} D={probs[1]:.1%} A={probs[2]:.1%}")
110
  print(f" B365: H={odds['b365h']} D={odds['b365d']} A={odds['b365a']}")
111
  print(f" EV: H={ev_h:+.3f} D={ev_d:+.3f} A={ev_a:+.3f}")
112
+
113
+ if best_bet:
114
+ print(f" 🟢 VALUE BET → {best_bet['outcome']} EV={best_bet['ev']:+.3f}")
115
  else:
116
+ print(" 🔴 No value — skip")
117
+
118
+ results.append({
119
+ "fixture_id": fixture_id,
120
+ "date": start_time,
121
+ "league": LEAGUE,
122
+ "home_team": home,
123
+ "away_team": away,
124
+ "b365": {"h": odds["b365h"], "d": odds["b365d"], "a": odds["b365a"]},
125
+ "probabilities": {
126
+ "H": round(probs[0], 4),
127
+ "D": round(probs[1], 4),
128
+ "A": round(probs[2], 4)
129
+ },
130
+ "ev_analysis": {
131
+ "has_value": len(value_bets) > 0,
132
+ "best_bet": best_bet,
133
+ "value_bets": value_bets,
134
+ "all_outcomes": all_outcomes,
135
+ },
136
+ })
137
+
138
+ # ── Save to cache so API and future runs serve from cache ─────────────────────
139
+ if results:
140
+ set_cache(LEAGUE, results)
141
+ print(f"\n💾 {len(results)} fixtures cached — next run serves instantly")