File size: 40,555 Bytes
4c0ae1e
1357529
 
d16206c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ded5da6
1357529
26a07d3
d16206c
 
 
 
 
 
 
 
 
 
 
 
42ffad9
d16206c
 
42ffad9
d16206c
42ffad9
d16206c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
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
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
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
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from sklearn.ensemble import RandomForestRegressor

# Configuración
st.set_page_config(page_title="Análisis de Ligas", layout="wide")

# --- PARÁMETROS DE CONFIGURACIÓN ---
URL_FIXTURES = "https://www.football-data.co.uk/fixtures.csv"
URL_HISTORICO_BASE = "https://www.football-data.co.uk/mmz4281/2526/{liga}.csv"
ARCHIVO_DATASET = "dataset_partidos_procesados.csv"

COLS_LOCAL = {
    'FTHG': 'Goles (FT)', 'HTHG': 'Goles (HT)',
    'HS': 'Tiros', 'HST': 'Tiros a Puerta',
    'HC': 'Córners', 'HF': 'Faltas',
    'HY': 'Tarjetas Amarillas', 'HR': 'Tarjetas Rojas',
}
COLS_VISITANTE = {
    'FTAG': 'Goles (FT)', 'HTAG': 'Goles (HT)',
    'AS': 'Tiros', 'AST': 'Tiros a Puerta',
    'AC': 'Córners', 'AF': 'Faltas',
    'AY': 'Tarjetas Amarillas', 'AR': 'Tarjetas Rojas',
}
COLS_CUOTAS = {
    'B365H': 'Bet365 Local', 'B365D': 'Bet365 Empate', 'B365A': 'Bet365 Visitante',
}
RENAME_PARTIDOS = {
    'Date': 'Fecha', 'Div': 'Liga', 'HomeTeam': 'Local', 'AwayTeam': 'Visitante',
    'FTHG': 'Goles Local (FT)', 'FTAG': 'Goles Visitante (FT)', 'FTR': 'Resultado',
    'HTHG': 'Goles Local (HT)', 'HTAG': 'Goles Visitante (HT)',
    'HS': 'Tiros Local', 'AS': 'Tiros Visitante',
    'HST': 'Tiros a Puerta Local', 'AST': 'Tiros a Puerta Visitante',
    'HC': 'Córners Local', 'AC': 'Córners Visitante',
    'HF': 'Faltas Local', 'AF': 'Faltas Visitante',
    'HY': 'Amarillas Local', 'AY': 'Amarillas Visitante',
    'HR': 'Rojas Local', 'AR': 'Rojas Visitante',
    'B365H': 'Bet365 Local', 'B365D': 'Bet365 Empate', 'B365A': 'Bet365 Visitante',
    'Referee': 'Árbitro',
}
PARES_ATAQUE_LOCAL = [
    ('Goles (FT)', 'FTHG', 'FTHG'), ('Goles (HT)', 'HTHG', 'HTHG'),
    ('Tiros', 'HS', 'HS'), ('Tiros a Puerta', 'HST', 'HST'),
    ('Córners', 'HC', 'HC'), ('Faltas', 'HF', 'HF'),
]
PARES_ATAQUE_VISITANTE = [
    ('Goles (FT)', 'FTAG', 'FTAG'), ('Goles (HT)', 'HTAG', 'HTAG'),
    ('Tiros', 'AS', 'AS'), ('Tiros a Puerta', 'AST', 'AST'),
    ('Córners', 'AC', 'AC'), ('Faltas', 'AF', 'AF'),
]
FEATURE_COLS = ['FTHG', 'FTAG', 'HTHG', 'HTAG', 'HS', 'AS', 'HST', 'AST',
                'HC', 'AC', 'HF', 'AF', 'HY', 'AY', 'HR', 'AR']
RF_TARGETS_LOCAL = {
    'FTHG': 'Goles Anotados', 'FTAG': 'Goles Recibidos',
    'HTHG': 'Goles Anotados (HT)', 'HTAG': 'Goles Recibidos (HT)',
    'HS': 'Tiros', 'HST': 'Tiros a Puerta',
    'HC': 'Córners', 'HF': 'Faltas', 'HY': 'Amarillas', 'HR': 'Rojas',
}
RF_TARGETS_VISIT = {
    'FTAG': 'Goles Anotados', 'FTHG': 'Goles Recibidos',
    'HTAG': 'Goles Anotados (HT)', 'HTHG': 'Goles Recibidos (HT)',
    'AS': 'Tiros', 'AST': 'Tiros a Puerta',
    'AC': 'Córners', 'AF': 'Faltas', 'AY': 'Amarillas', 'AR': 'Rojas',
}


# ============================================================
# FUNCIONES DE CARGA
# ============================================================
@st.cache_data
def cargar_fixtures(url):
    try:
        df = pd.read_csv(url)
        df.to_csv(ARCHIVO_DATASET, index=False)
        return df
    except Exception as e:
        st.error(f"Error al cargar fixtures: {e}")
        return None

@st.cache_data
def cargar_historico(liga):
    try:
        return pd.read_csv(URL_HISTORICO_BASE.format(liga=liga))
    except Exception as e:
        st.warning(f"No se pudieron cargar datos históricos para '{liga}': {e}")
        return None

def ultimos_n(df, n):
    return df if n == 0 else df.tail(n)


# ============================================================
# FUNCIONES DE ESTADÍSTICAS
# ============================================================
def calcular_estadisticas(df, cols_dict):
    cols_validas = {k: v for k, v in cols_dict.items() if k in df.columns}
    if not cols_validas:
        return None
    df_num = df[list(cols_validas.keys())].apply(pd.to_numeric, errors='coerce')
    filas = []
    for col_orig, col_nombre in cols_validas.items():
        serie = df_num[col_orig].dropna()
        if serie.empty:
            continue
        m, mo, s = serie.mean(), serie.mode(), serie.std()
        cv = (s / m * 100) if m != 0 else np.nan
        filas.append({'Estadística': col_nombre, 'Promedio': round(m, 2),
                      'Moda': mo.iloc[0] if not mo.empty else np.nan,
                      'Desv. Estándar': round(s, 2), 'CV (%)': round(cv, 1)})
    return pd.DataFrame(filas)

def colorear_cv(val):
    try:
        if float(val) < 10:
            return 'background-color: #2e7d32; color: white; font-weight: bold'
    except (ValueError, TypeError):
        pass
    return ''

def mostrar_estadisticas_coloreadas(df_stats):
    if df_stats is None or df_stats.empty:
        st.warning("No hay datos suficientes.")
        return
    styled = (df_stats.style.applymap(colorear_cv, subset=['CV (%)'])
              .format({'Promedio': '{:.2f}', 'Moda': '{}', 'Desv. Estándar': '{:.2f}', 'CV (%)': '{:.1f}%'}))
    st.dataframe(styled, use_container_width=True, hide_index=True)

def mostrar_tabla_partidos(df, cols_extra=None):
    base = ['Date', 'HomeTeam', 'AwayTeam']
    if cols_extra:
        base += [c for c in cols_extra if c in df.columns]
    cols_mostrar = [c for c in base if c in df.columns]
    st.dataframe(df[cols_mostrar].copy().rename(columns=RENAME_PARTIDOS).reset_index(drop=True),
                 use_container_width=True)

def promedio_col(df, col):
    if col not in df.columns:
        return np.nan
    s = pd.to_numeric(df[col], errors='coerce').dropna()
    return s.mean() if not s.empty else np.nan

def construir_comparacion(nombre_local, nombre_visitante, df_local, df_visit, pares, tipo):
    filas = []
    for nombre_stat, col_atq, col_def in pares:
        if tipo == 'ataque_local':
            va, vd = promedio_col(df_local, col_atq), promedio_col(df_visit, col_def)
            la, ld = f"{nombre_local} genera", f"{nombre_visitante} recibe"
        else:
            va, vd = promedio_col(df_visit, col_atq), promedio_col(df_local, col_def)
            la, ld = f"{nombre_visitante} genera", f"{nombre_local} recibe"
        diff = va - vd if not (np.isnan(va) or np.isnan(vd)) else np.nan
        filas.append({'Estadística': nombre_stat,
                      la: round(va, 2) if not np.isnan(va) else '-',
                      ld: round(vd, 2) if not np.isnan(vd) else '-',
                      'Diferencia': round(diff, 2) if not np.isnan(diff) else '-'})
    return pd.DataFrame(filas)

def colorear_diferencia(val):
    try:
        n = float(val)
        if n > 0: return 'background-color: #2e7d32; color: white; font-weight: bold'
        elif n < 0: return 'background-color: #c62828; color: white; font-weight: bold'
        else: return 'background-color: #616161; color: white'
    except (ValueError, TypeError):
        return ''

def mostrar_comparacion(df_comp):
    if df_comp is None or df_comp.empty:
        st.warning("No hay datos para la comparación.")
        return
    st.dataframe(df_comp.style.applymap(colorear_diferencia, subset=['Diferencia']),
                 use_container_width=True, hide_index=True)


# ============================================================
# GRÁFICOS
# ============================================================
def grafico_radar(df_local, df_visit, eq_local, eq_visit):
    cats = ['Goles', 'Tiros', 'Tiros a Puerta', 'Córners', 'Faltas', 'Amarillas']
    ch = ['FTHG', 'HS', 'HST', 'HC', 'HF', 'HY']
    ca = ['FTAG', 'AS', 'AST', 'AC', 'AF', 'AY']
    vl = [0 if np.isnan(v) else v for v in [promedio_col(df_local, c) for c in ch]]
    vv = [0 if np.isnan(v) else v for v in [promedio_col(df_visit, c) for c in ca]]
    if all(v == 0 for v in vl + vv):
        return None
    mx = [max(a, b, 0.01) for a, b in zip(vl, vv)]
    nl = [v / m * 100 for v, m in zip(vl, mx)]
    nv = [v / m * 100 for v, m in zip(vv, mx)]
    fig = go.Figure()
    fig.add_trace(go.Scatterpolar(r=nl + [nl[0]], theta=cats + [cats[0]], fill='toself',
                                   name=f'{eq_local} (Local)', line=dict(color='#1E88E5', width=2),
                                   fillcolor='rgba(30,136,229,0.15)',
                                   customdata=[f'{v:.2f}' for v in vl] + [f'{vl[0]:.2f}'],
                                   hovertemplate='%{theta}: %{customdata}<extra></extra>'))
    fig.add_trace(go.Scatterpolar(r=nv + [nv[0]], theta=cats + [cats[0]], fill='toself',
                                   name=f'{eq_visit} (Visitante)', line=dict(color='#E53935', width=2),
                                   fillcolor='rgba(229,57,53,0.15)',
                                   customdata=[f'{v:.2f}' for v in vv] + [f'{vv[0]:.2f}'],
                                   hovertemplate='%{theta}: %{customdata}<extra></extra>'))
    fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 110], showticklabels=False)),
                      showlegend=True, height=420, title=dict(text="Comparación de Promedios", x=0.5),
                      margin=dict(l=60, r=60, t=60, b=40),
                      legend=dict(orientation="h", yanchor="bottom", y=-0.15, xanchor="center", x=0.5))
    return fig

def grafico_barras_comp(df_atq, df_def, pares, titulo):
    noms, va, vd = [], [], []
    for ns, ca, cd in pares:
        a, d = promedio_col(df_atq, ca), promedio_col(df_def, cd)
        if not np.isnan(a) and not np.isnan(d):
            noms.append(ns); va.append(round(a, 2)); vd.append(round(d, 2))
    if not noms:
        return None
    fig = go.Figure()
    fig.add_trace(go.Bar(y=noms, x=va, orientation='h', name='Genera', marker_color='#43A047',
                          text=[f'{v:.2f}' for v in va], textposition='outside'))
    fig.add_trace(go.Bar(y=noms, x=vd, orientation='h', name='Recibe', marker_color='#E53935',
                          text=[f'{v:.2f}' for v in vd], textposition='outside'))
    fig.update_layout(barmode='group', height=350, title=dict(text=titulo, x=0.5), xaxis_title="Promedio",
                      margin=dict(l=20, r=20, t=50, b=40),
                      legend=dict(orientation="h", yanchor="bottom", y=-0.25, xanchor="center", x=0.5))
    return fig

def grafico_tendencia_goles(df, col_anot, col_rec, titulo):
    dc = df.copy().reset_index(drop=True)
    for c in [col_anot, col_rec]:
        if c in dc.columns:
            dc[c] = pd.to_numeric(dc[c], errors='coerce')
    if col_anot not in dc.columns or dc.empty:
        return None
    dc = dc.dropna(subset=[col_anot])
    dc['J'] = range(1, len(dc) + 1)
    dc['PM_A'] = dc[col_anot].rolling(3, min_periods=1).mean()
    fig = go.Figure()
    fig.add_trace(go.Bar(x=dc['J'], y=dc[col_anot], name='Anotados', marker_color='rgba(30,136,229,0.4)'))
    if col_rec in dc.columns:
        dc['PM_R'] = dc[col_rec].rolling(3, min_periods=1).mean()
        fig.add_trace(go.Bar(x=dc['J'], y=dc[col_rec], name='Recibidos', marker_color='rgba(229,57,53,0.4)'))
    fig.add_trace(go.Scatter(x=dc['J'], y=dc['PM_A'], name='Prom. Anot. (3)', line=dict(color='#1565C0', width=3)))
    if 'PM_R' in dc.columns:
        fig.add_trace(go.Scatter(x=dc['J'], y=dc['PM_R'], name='Prom. Rec. (3)',
                                  line=dict(color='#C62828', width=3, dash='dash')))
    fig.update_layout(barmode='group', height=320, title=dict(text=titulo, x=0.5),
                      xaxis_title='Jornada', yaxis_title='Goles', margin=dict(l=20, r=20, t=50, b=40),
                      legend=dict(orientation="h", yanchor="bottom", y=-0.3, xanchor="center", x=0.5))
    return fig

def grafico_dist_goles(df, col, titulo, color):
    if col not in df.columns or df.empty:
        return None
    s = pd.to_numeric(df[col], errors='coerce').dropna()
    if s.empty:
        return None
    cnt = s.value_counts().sort_index()
    fig = go.Figure()
    fig.add_trace(go.Bar(x=cnt.index.astype(int), y=cnt.values, marker_color=color,
                          text=cnt.values, textposition='outside'))
    fig.add_vline(x=s.mean(), line_dash="dash", line_color="#FFD600", line_width=2,
                  annotation_text=f"Prom: {s.mean():.2f}", annotation_position="top right")
    fig.update_layout(height=280, title=dict(text=titulo, x=0.5), xaxis_title='Goles',
                      yaxis_title='Frecuencia', xaxis=dict(dtick=1), margin=dict(l=20, r=20, t=50, b=40))
    return fig

def grafico_pred_equipo(df_rf, equipo, color):
    if df_rf is None or df_rf.empty:
        return None
    fig = go.Figure()
    fig.add_trace(go.Bar(x=df_rf['Estadística'], y=df_rf['Predicción RF'], name='Predicción RF',
                          marker_color=color, text=[f'{v:.2f}' for v in df_rf['Predicción RF']],
                          textposition='outside'))
    fig.add_trace(go.Bar(x=df_rf['Estadística'], y=df_rf['Promedio Histórico'], name='Promedio',
                          marker_color='#78909C', text=[f'{v:.2f}' for v in df_rf['Promedio Histórico']],
                          textposition='outside'))
    my = max(df_rf['Predicción RF'].max(), df_rf['Promedio Histórico'].max()) * 1.4
    fig.update_layout(barmode='group', height=400, title=dict(text=f'Predicción RF — {equipo}', x=0.5),
                      xaxis_tickangle=-35, yaxis=dict(range=[0, my]), margin=dict(l=20, r=20, t=60, b=80),
                      legend=dict(orientation="h", yanchor="bottom", y=-0.35, xanchor="center", x=0.5))
    return fig

def grafico_gauge_kelly(val, titulo, color):
    v = max(0, min(val, 50))
    fig = go.Figure(go.Indicator(
        mode="gauge+number", value=v, number={'suffix': '%', 'font': {'size': 36}},
        title={'text': titulo, 'font': {'size': 14}},
        gauge={'axis': {'range': [0, 50]}, 'bar': {'color': color}, 'bgcolor': 'white', 'borderwidth': 1,
               'steps': [{'range': [0, 5], 'color': '#E8F5E9'}, {'range': [5, 15], 'color': '#C8E6C9'},
                         {'range': [15, 30], 'color': '#FFF9C4'}, {'range': [30, 50], 'color': '#FFCDD2'}],
               'threshold': {'line': {'color': "red", 'width': 3}, 'thickness': 0.8, 'value': 25}}
    ))
    fig.update_layout(height=250, margin=dict(l=20, r=20, t=50, b=20))
    return fig

def grafico_kelly_barras(df_kelly):
    cols = {'Local': '#1E88E5', 'Empate': '#78909C', 'Visitante': '#E53935'}
    fig = go.Figure()
    for _, r in df_kelly.iterrows():
        k = max(r['Kelly (%)'], 0)
        fig.add_trace(go.Bar(y=[r['Resultado']], x=[k], orientation='h',
                              marker_color=cols.get(r['Resultado'], '#666'),
                              text=f"{k:.2f}%", textposition='outside', showlegend=False))
    fig.update_layout(height=200, title=dict(text='Kelly Criterion — % Óptimo', x=0.5),
                      xaxis_title='Kelly %', xaxis=dict(range=[0, max(df_kelly['Kelly (%)'].max() * 1.5, 10)]),
                      margin=dict(l=20, r=20, t=50, b=30))
    return fig


# ============================================================
# RANDOM FOREST POR EQUIPO
# ============================================================
def preparar_dataset_rf(df_hist, n_rolling=5):
    df = df_hist.copy().reset_index(drop=True)
    for c in FEATURE_COLS:
        if c in df.columns:
            df[c] = pd.to_numeric(df[c], errors='coerce')
    filas = []
    for idx in range(len(df)):
        row = df.iloc[idx]
        prev = df.iloc[:idx]
        if len(prev) < n_rolling:
            continue
        feat = {}
        for c in FEATURE_COLS:
            if c in df.columns:
                dh = prev[prev['HomeTeam'] == row['HomeTeam']].tail(n_rolling)
                feat[f'H_{c}_avg'] = dh[c].mean() if not dh.empty else 0
                da = prev[prev['AwayTeam'] == row['AwayTeam']].tail(n_rolling)
                feat[f'A_{c}_avg'] = da[c].mean() if not da.empty else 0
        feat['H_n'] = len(pd.concat([prev[prev['HomeTeam'] == row['HomeTeam']],
                                      prev[prev['AwayTeam'] == row['HomeTeam']]]).tail(n_rolling))
        feat['A_n'] = len(pd.concat([prev[prev['HomeTeam'] == row['AwayTeam']],
                                      prev[prev['AwayTeam'] == row['AwayTeam']]]).tail(n_rolling))
        for c in FEATURE_COLS:
            if c in df.columns:
                feat[f'target_{c}'] = row[c]
        filas.append(feat)
    return pd.DataFrame(filas)

@st.cache_data
def entrenar_rf_equipo(df_hist, eq_local, eq_visit, n_rolling, targets_dict):
    df_rf = preparar_dataset_rf(df_hist, n_rolling)
    if df_rf.empty or len(df_rf) < 10:
        return None
    fnames = [c for c in df_rf.columns if c.startswith('H_') or c.startswith('A_')]
    df_rf[fnames] = df_rf[fnames].fillna(0)
    fp = {}
    for c in FEATURE_COLS:
        if c in df_hist.columns:
            dh = df_hist[df_hist['HomeTeam'] == eq_local].tail(n_rolling)
            fp[f'H_{c}_avg'] = pd.to_numeric(dh[c], errors='coerce').mean() if not dh.empty else 0
            da = df_hist[df_hist['AwayTeam'] == eq_visit].tail(n_rolling)
            fp[f'A_{c}_avg'] = pd.to_numeric(da[c], errors='coerce').mean() if not da.empty else 0
    fp['H_n'] = len(pd.concat([df_hist[df_hist['HomeTeam'] == eq_local],
                                df_hist[df_hist['AwayTeam'] == eq_local]]).tail(n_rolling))
    fp['A_n'] = len(pd.concat([df_hist[df_hist['HomeTeam'] == eq_visit],
                                df_hist[df_hist['AwayTeam'] == eq_visit]]).tail(n_rolling))
    Xp = pd.DataFrame([fp])[fnames].fillna(0)
    res = []
    for col_real, nombre in targets_dict.items():
        tc = f'target_{col_real}'
        if tc not in df_rf.columns:
            continue
        y = df_rf[tc].dropna()
        X = df_rf.loc[y.index, fnames]
        if len(y) < 5:
            continue
        try:
            rf = RandomForestRegressor(n_estimators=100, max_depth=6, min_samples_split=4,
                                       random_state=42, n_jobs=-1)
            rf.fit(X, y)
            pred = rf.predict(Xp)[0]
            res.append({'Estadística': nombre, 'Predicción RF': round(pred, 2),
                        'Promedio Histórico': round(y.mean(), 2),
                        'Diferencia': round(pred - y.mean(), 2), 'R² (ajuste)': round(rf.score(X, y), 3)})
        except Exception:
            continue
    return pd.DataFrame(res) if res else None

def mostrar_rf_equipo(df_rf, equipo, color):
    fig = grafico_pred_equipo(df_rf, equipo, color)
    if fig:
        st.plotly_chart(fig, use_container_width=True)

    def cr2(val):
        try:
            n = float(val)
            if n >= 0.5: return 'background-color: #2e7d32; color: white; font-weight: bold'
            elif n >= 0.3: return 'background-color: #f9a825; color: black; font-weight: bold'
            else: return 'background-color: #c62828; color: white; font-weight: bold'
        except: return ''
    def cd(val):
        try:
            n = float(val)
            if n > 0: return 'color: #2e7d32; font-weight: bold'
            elif n < 0: return 'color: #c62828; font-weight: bold'
        except: pass
        return ''

    styled = (df_rf.style.applymap(cr2, subset=['R² (ajuste)']).applymap(cd, subset=['Diferencia'])
              .format({'Predicción RF': '{:.2f}', 'Promedio Histórico': '{:.2f}',
                       'Diferencia': '{:+.2f}', 'R² (ajuste)': '{:.3f}'}))
    st.dataframe(styled, use_container_width=True, hide_index=True)

    cols_m = st.columns(min(len(df_rf), 5))
    for i, (_, row) in enumerate(df_rf.iterrows()):
        if i >= len(cols_m):
            break
        with cols_m[i]:
            st.metric(row['Estadística'], f"{row['Predicción RF']:.1f}", f"{row['Diferencia']:+.2f}")


# ============================================================
# KELLY CRITERION
# ============================================================
def calc_probs(df_hist, eq_local, eq_visit):
    if 'FTR' not in df_hist.columns or len(df_hist) == 0:
        return None
    t = len(df_hist)
    pl = {'H': (df_hist['FTR'] == 'H').sum() / t, 'D': (df_hist['FTR'] == 'D').sum() / t,
          'A': (df_hist['FTR'] == 'A').sum() / t}
    dh = df_hist[df_hist['HomeTeam'] == eq_local]
    if len(dh) >= 3:
        ph = {'H': (dh['FTR'] == 'H').sum() / len(dh), 'D': (dh['FTR'] == 'D').sum() / len(dh),
              'A': (dh['FTR'] == 'A').sum() / len(dh)}
    else:
        ph = pl.copy()
    da = df_hist[df_hist['AwayTeam'] == eq_visit]
    if len(da) >= 3:
        pa = {'H': (da['FTR'] == 'H').sum() / len(da), 'D': (da['FTR'] == 'D').sum() / len(da),
              'A': (da['FTR'] == 'A').sum() / len(da)}
    else:
        pa = pl.copy()
    r = {}
    for k in ['H', 'D', 'A']:
        r[k] = 0.4 * ph[k] + 0.4 * pa[k] + 0.2 * pl[k]
    s = sum(r.values())
    if s > 0:
        for k in r: r[k] /= s
    return {**r, 'ph': ph, 'pa': pa, 'pl': pl, 'nh': len(dh), 'na': len(da), 'nl': t}

def kelly(prob, odds):
    b = odds - 1
    return (b * prob - (1 - prob)) / b * 100 if b > 0 else 0


# ======================= APP =======================

df_proximos = cargar_fixtures(URL_FIXTURES)

if df_proximos is not None:
    st.title("⚽ Análisis Deportivo Avanzado")
    df_proximos['Date'] = pd.to_datetime(df_proximos['Date'], dayfirst=True, errors='coerce')
    df_proximos = df_proximos.dropna(subset=['Date'])
    df_proximos['Match'] = df_proximos['HomeTeam'] + " vs " + df_proximos['AwayTeam']

    # 1. FECHA
    st.subheader("1. Selecciona una fecha")
    fechas = sorted(df_proximos['Date'].dt.date.unique())
    fecha_sel = st.selectbox("Fecha:", fechas, format_func=lambda x: x.strftime("%d/%m/%Y"))
    df_fecha = df_proximos[df_proximos['Date'].dt.date == fecha_sel]

    if df_fecha.empty:
        st.warning("No hay partidos para esta fecha.")
    else:
        st.success(f"**{len(df_fecha)}** partidos para el {fecha_sel.strftime('%d/%m/%Y')}")
        st.dataframe(df_fecha[['Div', 'HomeTeam', 'AwayTeam']].rename(columns=RENAME_PARTIDOS)
                     .reset_index(drop=True), use_container_width=True)

        # 2. PARTIDO
        st.subheader("2. Selecciona un partido")
        sel = st.selectbox("Encuentro:", df_fecha['Match'].unique())
        pi = df_fecha[df_fecha['Match'] == sel].iloc[0]
        liga, eq_l, eq_v = pi['Div'], pi['HomeTeam'], pi['AwayTeam']
        st.info(f"Liga: **{liga}** — {eq_l} (Local) vs {eq_v} (Visitante)")

        # 3. HISTÓRICOS
        st.subheader("3. Análisis de Equipos")
        df_hist = cargar_historico(liga)

        if df_hist is not None and not df_hist.empty:
            st.markdown("---")
            st.markdown("#### ⚙️ Partidos para el análisis")
            dl_all = df_hist[df_hist['HomeTeam'] == eq_l]
            dv_all = df_hist[df_hist['AwayTeam'] == eq_v]

            c1, c2 = st.columns(2)
            with c1:
                ol = [0] + list(range(3, min(len(dl_all), 20) + 1))
                nl = st.selectbox(f"🏠 {eq_l} local ({len(dl_all)} disp.)", ol,
                                   index=ol.index(5) if 5 in ol else 0,
                                   format_func=lambda x: "Todos" if x == 0 else f"Últimos {x}", key="nl")
            with c2:
                ov = [0] + list(range(3, min(len(dv_all), 20) + 1))
                nv = st.selectbox(f"✈️ {eq_v} visitante ({len(dv_all)} disp.)", ov,
                                   index=ov.index(5) if 5 in ov else 0,
                                   format_func=lambda x: "Todos" if x == 0 else f"Últimos {x}", key="nv")

            st.caption("🟢 CV < 10% = dato estable y predecible.")
            st.markdown("---")

            dl = ultimos_n(dl_all, nl)
            dv = ultimos_n(dv_all, nv)

            # === 3a. LOCAL ===
            el = "Todos" if nl == 0 else f"Últimos {nl}"
            st.markdown(f"#### 🏠 {eq_l} como Local ({el} partidos)")
            if not dl.empty:
                mostrar_estadisticas_coloreadas(
                    calcular_estadisticas(dl, {**COLS_LOCAL, 'FTAG': 'Goles Recibidos (FT)', **COLS_CUOTAS}))
                g1, g2 = st.columns(2)
                with g1:
                    f1 = grafico_tendencia_goles(dl, 'FTHG', 'FTAG', f'{eq_l} — Goles por Jornada')
                    if f1: st.plotly_chart(f1, use_container_width=True)
                with g2:
                    f2 = grafico_dist_goles(dl, 'FTHG', f'{eq_l} — Dist. Goles Anotados', '#1E88E5')
                    if f2: st.plotly_chart(f2, use_container_width=True)
                    f3 = grafico_dist_goles(dl, 'FTAG', f'{eq_l} — Dist. Goles Recibidos', '#E53935')
                    if f3: st.plotly_chart(f3, use_container_width=True)
                with st.expander(f"Ver partidos de {eq_l} como local"):
                    mostrar_tabla_partidos(dl, cols_extra=['FTHG', 'FTAG', 'FTR', 'HS', 'HST', 'HC',
                                                           'HF', 'HY', 'HR', 'B365H', 'B365D', 'B365A'])
            else:
                st.warning(f"No hay datos de {eq_l} como local.")

            st.markdown("---")

            # === 3b. VISITANTE ===
            ev = "Todos" if nv == 0 else f"Últimos {nv}"
            st.markdown(f"#### ✈️ {eq_v} como Visitante ({ev} partidos)")
            if not dv.empty:
                mostrar_estadisticas_coloreadas(
                    calcular_estadisticas(dv, {**COLS_VISITANTE, 'FTHG': 'Goles Recibidos (FT)', **COLS_CUOTAS}))
                g3, g4 = st.columns(2)
                with g3:
                    f4 = grafico_tendencia_goles(dv, 'FTAG', 'FTHG', f'{eq_v} — Goles por Jornada')
                    if f4: st.plotly_chart(f4, use_container_width=True)
                with g4:
                    f5 = grafico_dist_goles(dv, 'FTAG', f'{eq_v} — Dist. Goles Anotados', '#E53935')
                    if f5: st.plotly_chart(f5, use_container_width=True)
                    f6 = grafico_dist_goles(dv, 'FTHG', f'{eq_v} — Dist. Goles Recibidos', '#1E88E5')
                    if f6: st.plotly_chart(f6, use_container_width=True)
                with st.expander(f"Ver partidos de {eq_v} como visitante"):
                    mostrar_tabla_partidos(dv, cols_extra=['FTHG', 'FTAG', 'FTR', 'AS', 'AST', 'AC',
                                                           'AF', 'AY', 'AR', 'B365H', 'B365D', 'B365A'])
            else:
                st.warning(f"No hay datos de {eq_v} como visitante.")

            # === 4. COMPARACIÓN ===
            st.markdown("---")
            st.subheader("4. ⚔️ Comparación Directa")
            if not dl.empty and not dv.empty:
                fr = grafico_radar(dl, dv, eq_l, eq_v)
                if fr: st.plotly_chart(fr, use_container_width=True)
                st.caption("🟢 Diferencia + = ventaja atacante · 🔴 − = ventaja defensor.")

                st.markdown(f"##### 🏠🗡️ Ataque **{eq_l}** vs 🛡️✈️ Defensa **{eq_v}**")
                fb1 = grafico_barras_comp(dl, dv, PARES_ATAQUE_LOCAL,
                                           f"Ataque {eq_l} vs Defensa {eq_v}")
                if fb1: st.plotly_chart(fb1, use_container_width=True)
                mostrar_comparacion(construir_comparacion(eq_l, eq_v, dl, dv, PARES_ATAQUE_LOCAL, 'ataque_local'))

                st.markdown("")
                st.markdown(f"##### ✈️🗡️ Ataque **{eq_v}** vs 🛡️🏠 Defensa **{eq_l}**")
                fb2 = grafico_barras_comp(dv, dl, PARES_ATAQUE_VISITANTE,
                                           f"Ataque {eq_v} vs Defensa {eq_l}")
                if fb2: st.plotly_chart(fb2, use_container_width=True)
                mostrar_comparacion(construir_comparacion(eq_l, eq_v, dl, dv, PARES_ATAQUE_VISITANTE, 'ataque_visitante'))
            else:
                st.warning("Datos insuficientes para comparación.")

            # === 5. RANDOM FOREST POR EQUIPO ===
            st.markdown("---")
            st.subheader("5. 🤖 Predicción Random Forest")
            st.caption("Modelo independiente por equipo. Features = promedios rodantes.")
            n_rf = st.slider("Partidos recientes para features:", 3, 15, 5, 1, key="nrf")
            st.caption("**R²:** 🟢 ≥ 0.5 · 🟡 ≥ 0.3 · 🔴 < 0.3")

            with st.spinner("Entrenando modelos..."):
                rf_l = entrenar_rf_equipo(df_hist, eq_l, eq_v, n_rf, RF_TARGETS_LOCAL)
                rf_v = entrenar_rf_equipo(df_hist, eq_l, eq_v, n_rf, RF_TARGETS_VISIT)

            st.markdown(f"#### 🏠 {eq_l} (Local)")
            if rf_l is not None and not rf_l.empty:
                mostrar_rf_equipo(rf_l, eq_l, '#1E88E5')
            else:
                st.warning(f"Datos insuficientes para {eq_l}.")

            st.markdown("---")
            st.markdown(f"#### ✈️ {eq_v} (Visitante)")
            if rf_v is not None and not rf_v.empty:
                mostrar_rf_equipo(rf_v, eq_v, '#E53935')
            else:
                st.warning(f"Datos insuficientes para {eq_v}.")

            # === ESTIMACIÓN DE GOLES ===
            if rf_l is not None and rf_v is not None:
                st.markdown("---")
                st.markdown("#### 📋 Estimación Final de Goles")

                def get_pred(df, stat):
                    r = df[df['Estadística'] == stat]['Predicción RF'].values
                    return r[0] if len(r) > 0 else 0

                gl_anota = get_pred(rf_l, 'Goles Anotados')
                gl_recibe = get_pred(rf_l, 'Goles Recibidos')
                gv_anota = get_pred(rf_v, 'Goles Anotados')
                gv_recibe = get_pred(rf_v, 'Goles Recibidos')

                est_local = (gl_anota + gv_recibe) / 2
                est_visit = (gv_anota + gl_recibe) / 2
                est_total = est_local + est_visit

                ce1, ce2, ce3 = st.columns(3)
                with ce1:
                    st.metric(f"🏠 {eq_l}", f"{est_local:.2f} goles")
                    st.caption(f"Anota: {gl_anota:.2f} → Rival recibe: {gv_recibe:.2f}")
                with ce2:
                    st.metric(f"✈️ {eq_v}", f"{est_visit:.2f} goles")
                    st.caption(f"Anota: {gv_anota:.2f} → Rival recibe: {gl_recibe:.2f}")
                with ce3:
                    st.metric("⚽ Total Estimado", f"{est_total:.2f} goles")
                    linea = "Más de 2.5" if est_total > 2.5 else "Menos de 2.5"
                    st.caption(f"Tendencia: **{linea}**")

                # HT
                gl_anota_ht = get_pred(rf_l, 'Goles Anotados (HT)')
                gl_recibe_ht = get_pred(rf_l, 'Goles Recibidos (HT)')
                gv_anota_ht = get_pred(rf_v, 'Goles Anotados (HT)')
                gv_recibe_ht = get_pred(rf_v, 'Goles Recibidos (HT)')

                est_local_ht = (gl_anota_ht + gv_recibe_ht) / 2
                est_visit_ht = (gv_anota_ht + gl_recibe_ht) / 2
                est_total_ht = est_local_ht + est_visit_ht

                ch1, ch2, ch3 = st.columns(3)
                with ch1:
                    st.metric(f"🏠 {eq_l} (HT)", f"{est_local_ht:.2f} goles")
                with ch2:
                    st.metric(f"✈️ {eq_v} (HT)", f"{est_visit_ht:.2f} goles")
                with ch3:
                    st.metric("⚽ Total HT", f"{est_total_ht:.2f} goles")
                    linea_ht = "Más de 0.5" if est_total_ht > 0.5 else "Menos de 0.5"
                    st.caption(f"Tendencia HT: **{linea_ht}**")

                # Gráfico estimación
                fig_est = go.Figure()
                fig_est.add_trace(go.Bar(x=[f'{eq_l} (FT)', f'{eq_l} (HT)', f'{eq_v} (FT)', f'{eq_v} (HT)'],
                                          y=[est_local, est_local_ht, est_visit, est_visit_ht],
                                          marker_color=['#1E88E5', '#64B5F6', '#E53935', '#EF9A9A'],
                                          text=[f'{est_local:.2f}', f'{est_local_ht:.2f}',
                                                f'{est_visit:.2f}', f'{est_visit_ht:.2f}'],
                                          textposition='outside', textfont=dict(size=16)))
                fig_est.add_hline(y=est_total / 2, line_dash="dash", line_color="#FFD600",
                                  annotation_text=f"Total FT: {est_total:.2f}")
                fig_est.update_layout(height=380, title=dict(text='Estimación de Goles (FT y HT)', x=0.5),
                                      yaxis_title='Goles', yaxis=dict(range=[0, max(est_local, est_visit) * 1.6]),
                                      margin=dict(l=20, r=20, t=60, b=40), showlegend=False)
                st.plotly_chart(fig_est, use_container_width=True)

            # === 6. KELLY ===
            st.markdown("---")
            st.subheader("6. 💰 Kelly Criterion")
            st.caption("Kelly % = (b × p − q) / b · b = cuota − 1 · p = prob. estimada · q = 1 − p")

            cH = pd.to_numeric(pi.get('B365H', np.nan), errors='coerce')
            cD = pd.to_numeric(pi.get('B365D', np.nan), errors='coerce')
            cA = pd.to_numeric(pi.get('B365A', np.nan), errors='coerce')
            if np.isnan(cH) and 'B365H' in dl.columns:
                cH = pd.to_numeric(dl['B365H'], errors='coerce').mean()
            if np.isnan(cD) and 'B365D' in dl.columns:
                cD = pd.to_numeric(dl['B365D'], errors='coerce').mean()
            if np.isnan(cA) and 'B365A' in dl.columns:
                cA = pd.to_numeric(dl['B365A'], errors='coerce').mean()

            probs = calc_probs(df_hist, eq_l, eq_v)

            if probs is not None and not any(np.isnan([cH, cD, cA])):
                st.markdown("##### 📊 Probabilidades Estimadas")
                cp1, cp2, cp3 = st.columns(3)
                with cp1:
                    st.markdown("**Fuente**")
                    st.markdown(f"🏠 {eq_l} en casa ({probs['nh']} p.)")
                    st.markdown(f"✈️ {eq_v} fuera ({probs['na']} p.)")
                    st.markdown(f"📊 Liga ({probs['nl']} p.)")
                    st.markdown("**🎯 Final**")
                with cp2:
                    st.markdown("**L / E / V**")
                    st.markdown(f"{probs['ph']['H']:.1%} / {probs['ph']['D']:.1%} / {probs['ph']['A']:.1%}")
                    st.markdown(f"{probs['pa']['H']:.1%} / {probs['pa']['D']:.1%} / {probs['pa']['A']:.1%}")
                    st.markdown(f"{probs['pl']['H']:.1%} / {probs['pl']['D']:.1%} / {probs['pl']['A']:.1%}")
                    st.markdown(f"**{probs['H']:.1%} / {probs['D']:.1%} / {probs['A']:.1%}**")
                with cp3:
                    st.markdown("**Peso**")
                    st.markdown("40%"); st.markdown("40%"); st.markdown("20%"); st.markdown("**100%**")

                piH, piD, piA = 1 / cH * 100, 1 / cD * 100, 1 / cA * 100
                fig_p = go.Figure()
                fig_p.add_trace(go.Bar(x=['Local', 'Empate', 'Visitante'],
                                        y=[probs['H'] * 100, probs['D'] * 100, probs['A'] * 100],
                                        marker_color=['#1E88E5', '#78909C', '#E53935'],
                                        text=[f"{probs['H']:.1%}", f"{probs['D']:.1%}", f"{probs['A']:.1%}"],
                                        textposition='outside', textfont=dict(size=16), name='Estimada'))
                fig_p.add_trace(go.Scatter(x=['Local', 'Empate', 'Visitante'], y=[piH, piD, piA],
                                            mode='markers+text', name='Implícita (Cuota)',
                                            marker=dict(size=14, color='#FFD600', symbol='diamond'),
                                            text=[f"{piH:.1f}%", f"{piD:.1f}%", f"{piA:.1f}%"],
                                            textposition='top center'))
                fig_p.update_layout(height=380, title=dict(text='Prob. Estimada vs Implícita', x=0.5),
                                    yaxis_title='%', yaxis=dict(range=[0, max(probs['H'], probs['D'], probs['A']) * 140]),
                                    margin=dict(l=20, r=20, t=60, b=40),
                                    legend=dict(orientation="h", yanchor="bottom", y=-0.2, xanchor="center", x=0.5))
                st.plotly_chart(fig_p, use_container_width=True)

                kH, kD, kA = kelly(probs['H'], cH), kelly(probs['D'], cD), kelly(probs['A'], cA)
                df_k = pd.DataFrame([
                    {'Resultado': 'Local', 'Prob. Estimada': f"{probs['H']:.1%}", 'Prob. Implícita': f"{1/cH:.1%}",
                     'Cuota B365': f"{cH:.2f}", 'Kelly (%)': round(kH, 2),
                     'Valor Esperado': round((probs['H'] * cH - 1) * 100, 2)},
                    {'Resultado': 'Empate', 'Prob. Estimada': f"{probs['D']:.1%}", 'Prob. Implícita': f"{1/cD:.1%}",
                     'Cuota B365': f"{cD:.2f}", 'Kelly (%)': round(kD, 2),
                     'Valor Esperado': round((probs['D'] * cD - 1) * 100, 2)},
                    {'Resultado': 'Visitante', 'Prob. Estimada': f"{probs['A']:.1%}", 'Prob. Implícita': f"{1/cA:.1%}",
                     'Cuota B365': f"{cA:.2f}", 'Kelly (%)': round(kA, 2),
                     'Valor Esperado': round((probs['A'] * cA - 1) * 100, 2)},
                ])

                st.markdown("##### 🎯 Kelly % por Resultado")
                cg1, cg2, cg3 = st.columns(3)
                with cg1: st.plotly_chart(grafico_gauge_kelly(kH, f"🏠 {eq_l}", '#1E88E5'), use_container_width=True)
                with cg2: st.plotly_chart(grafico_gauge_kelly(kD, "🤝 Empate", '#78909C'), use_container_width=True)
                with cg3: st.plotly_chart(grafico_gauge_kelly(kA, f"✈️ {eq_v}", '#E53935'), use_container_width=True)

                st.plotly_chart(grafico_kelly_barras(df_k), use_container_width=True)

                st.markdown("##### 📋 Tabla Detallada")
                def ck(v):
                    try:
                        n = float(v)
                        if n > 5: return 'background-color: #2e7d32; color: white; font-weight: bold'
                        elif n > 0: return 'background-color: #43A047; color: white'
                        else: return 'background-color: #c62828; color: white'
                    except: return ''
                def cev(v):
                    try:
                        return ('background-color: #1B5E20; color: white; font-weight: bold' if float(v) > 0
                                else 'background-color: #B71C1C; color: white')
                    except: return ''

                st.dataframe(df_k.style.applymap(ck, subset=['Kelly (%)']).applymap(cev, subset=['Valor Esperado'])
                             .format({'Kelly (%)': '{:.2f}%', 'Valor Esperado': '{:+.2f}%'}),
                             use_container_width=True, hide_index=True)

                mejor = df_k.loc[df_k['Kelly (%)'].idxmax()]
                if mejor['Kelly (%)'] > 0:
                    st.success(f"**Mejor apuesta:** {mejor['Resultado']} — **{mejor['Kelly (%)']:.2f}%** del bankroll "
                               f"a cuota **{mejor['Cuota B365']}** (VE: {mejor['Valor Esperado']:+.2f}%).")
                else:
                    st.error("**Kelly no recomienda apostar** en ningún resultado.")

                st.markdown("##### 🏦 Simulador")
                bank = st.number_input("Bankroll ($):", min_value=100, value=1000, step=100)
                sim = []
                for _, r in df_k.iterrows():
                    k = max(r['Kelly (%)'], 0)
                    ap = bank * k / 100
                    sim.append({'Resultado': r['Resultado'], 'Kelly %': f"{k:.2f}%",
                                'Apuesta ($)': f"${ap:.2f}",
                                'Ganancia ($)': f"${ap * (float(r['Cuota B365']) - 1):.2f}",
                                'Cuota': r['Cuota B365']})
                st.dataframe(pd.DataFrame(sim), use_container_width=True, hide_index=True)
                st.caption("⚠️ Herramienta matemática. No garantiza ganancias. Apuesta responsablemente.")
            else:
                st.warning("Datos insuficientes para Kelly.")

            with st.expander("Ver todos los partidos históricos"):
                mostrar_tabla_partidos(df_hist, cols_extra=['FTHG', 'FTAG', 'FTR', 'HS', 'AS', 'HST', 'AST',
                                                            'HC', 'AC', 'HF', 'AF', 'HY', 'AY', 'HR', 'AR',
                                                            'B365H', 'B365D', 'B365A'])
        else:
            st.error(f"No se pudieron obtener datos históricos para **{liga}**.")
else:
    st.error("No se pudo cargar la información de fixtures.")