Skip to content

Football #409

@lucdahlmann94-art

Description

@lucdahlmann94-art

import streamlit as st
import pandas as pd
from scipy.stats import poisson
import requests
import time

SIMULATIONS = 10000
MAX_GOALS = 6
API_KEY = "DEIN_API_KEY"
HEADERS = {"X-Auth-Token": API_KEY}
LIVE_API_URL = "https://api.football-data.org/v4/matches/live"

--- Daten laden ---

top_picks = pd.read_csv("data/top_picks.csv")
score_table = pd.read_csv("data/score_probs.csv")
players_df = pd.read_csv("data/players.csv")
teams_df = pd.read_csv("data/teams.csv")

--- Funktionen ---

def calculate_team_strength(team_name):
team = teams_df[teams_df["team"]==team_name].iloc[0]
lineup = players_df[players_df["team"]==team_name]
base_attack = team["goals_per_game"] + team["xG"]
base_defense = team["conceded_per_game"] + team["xGA"]
fitness = lineup["fitness"].mean()
chemistry = lineup.get("games_with", pd.Series([0])).mean()
attack = base_attack * (1 + 0.05fitness + 0.02chemistry)
defense = base_defense * (1 - 0.02*chemistry)
return attack, defense

def score_probabilities(home_lambda, away_lambda):
scores=[]
for h in range(MAX_GOALS+1):
for a in range(MAX_GOALS+1):
prob = poisson.pmf(h, home_lambda)*poisson.pmf(a, away_lambda)
scores.append({"home_goals":h,"away_goals":a,"probability":prob})
return pd.DataFrame(scores).sort_values("probability",ascending=False)

def live_simulation(live_data):
home_attack, home_defense = calculate_team_strength(live_data["home_team"])
away_attack, away_defense = calculate_team_strength(live_data["away_team"])
home_lambda = max(home_attack/away_defense - live_data["home_goals"],0.1)
away_lambda = max(away_attack/home_defense - live_data["away_goals"],0.1)
for sub in live_data.get("substitutions", []):
player_out = players_df[players_df["name"]==sub["player_out"]]["rating"].values[0]
player_in = players_df[players_df["name"]==sub["player_in"]]["rating"].values[0]
home_lambda += (player_in-player_out)*0.05
results={"Heimsieg":0,"Unentschieden":0,"Auswärtssieg":0}
for _ in range(SIMULATIONS):
h_goals=poisson.rvs(home_lambda)
a_goals=poisson.rvs(away_lambda)
if h_goals>a_goals: results["Heimsieg"]+=1
elif h_goals==a_goals: results["Unentschieden"]+=1
else: results["Auswärtssieg"]+=1
total=sum(results.values())
for k in results: results[k]/=total
return results

def fetch_live_matches():
response = requests.get(LIVE_API_URL, headers=HEADERS)
data = response.json()
live_matches = []
for m in data["matches"]:
live_matches.append({
"home_team": m["homeTeam"]["name"],
"away_team": m["awayTeam"]["name"],
"home_goals": m["score"]["fullTime"]["home"],
"away_goals": m["score"]["fullTime"]["away"],
"time": m["minute"],
"substitutions": m.get("substitutions",[]),
"cards": m.get("cards",[])
})
return live_matches

--- Dashboard ---

st.title("⚽ Fußball KI – Komplettes Dashboard")

1️⃣ Top-Picks Übersicht

st.header("🏆 Top Vorhersagen des Tages")
for i, match in top_picks.head(10).iterrows():
st.subheader(f"{i+1}. {match['home']} vs {match['away']} ({match['league']})")
sim_dict = eval(match['simulation']) if isinstance(match['simulation'], str) else match['simulation']
st.write(f"Vorhersage: {match['prediction']} | Wahrscheinlichkeit: {max(sim_dict.values())*100:.1f}% | Confidence: {match['confidence']:.2f}")

2️⃣ Exakte Ergebnisse

st.header("📊 Exakte Ergebniswahrscheinlichkeiten")
selected_match = st.selectbox("Spiel auswählen", top_picks["home"] + " vs " + top_picks["away"])
home_team, away_team = selected_match.split(" vs ")
match_scores = score_table[(score_table["home"]==home_team) & (score_table["away"]==away_team)]
st.table(match_scores.head(5))

3️⃣ Live-Spiele Simulation

st.header("⚡ Live-Spiel Vorhersagen")
if st.button("Live aktualisieren"):
live_matches = fetch_live_matches()
for match in live_matches:
result = live_simulation(match)
st.write(f"{match['home_team']} vs {match['away_team']} – Live-Vorhersage: {result}")

Optional automatische Aktualisierung alle 2 Minuten

from streamlit_autorefresh import st_autorefresh
count = st_autorefresh(interval=120000, limit=None, key="live_refresh")
if count:
live_matches = fetch_live_matches()
for match in live_matches:
result = live_simulation(match)
st.write(f"{match['home_team']} vs {match['away_team']} – Live-Vorhersage: {result}")

4️⃣ Legende

st.markdown("""
Legende:

  • Heimsieg / Unentschieden / Auswärtssieg = Wahrscheinlichkeit aus Simulationen
  • Confidence = Modellvertrauen in die Vorhersage
  • Exakte Ergebnisse = wahrscheinlichste Scorelines
    """)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions