# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: Premier League results 2000/01-2024/25: github.com/datasets/football-datasets (premier-league/season-XXXX.csv) -> /tmp/res

# Elo season forecasts (#68 James Young) and Gerrard-style win-contribution regression (#71) on 25 Premier League seasons
import pandas as pd, numpy as np, glob
fs=sorted(glob.glob('/tmp/res/pl_*.csv'))
D=[]
for f in fs:
    s=f[-8:-4]; d=pd.read_csv(f); d['season']=s; D.append(d)
D=pd.concat(D,ignore_index=True)
D['Date']=pd.to_datetime(D.Date,dayfirst=True,errors='coerce',format='mixed')
seasons=sorted(D.season.unique())
HFA,K=60,20
R={}
def exp(a,b): return 1/(1+10**((b-a)/400))
# empirical outcome probabilities by expected score bin (learned on first 5 seasons, then fixed)
def pts_from_E(E,tab):
    i=min(int(E*20),19); ph,pd_,pa=tab[i]; return 3*ph+pd_, 3*pa+pd_
recs=[];bins=[[] for _ in range(20)];tab=None
for s in seasons:
    d=D[D.season==s].sort_values('Date')
    teams=sorted(set(d.HomeTeam)|set(d.AwayTeam))
    if R:
        old=[t for t in R if t not in teams]; new=[t for t in teams if t not in R]
        base=np.mean(sorted(R[t] for t in R)[:3]) if R else 1500  # promoted ~ level of the bottom 3
        for t in new: R[t]=base
    else:
        for t in teams: R[t]=1500
    # pre-season forecast
    if tab is not None:
        fc={t:0.0 for t in teams}
        for _,m in d.iterrows():
            E=exp(R[m.HomeTeam]+HFA,R[m.AwayTeam]); h,a=pts_from_E(E,tab); fc[m.HomeTeam]+=h; fc[m.AwayTeam]+=a
    act={t:0 for t in teams}
    for _,m in d.iterrows():
        E=exp(R[m.HomeTeam]+HFA,R[m.AwayTeam]); res=1 if m.FTHG>m.FTAG else (0.5 if m.FTHG==m.FTAG else 0)
        bins[min(int(E*20),19)].append(res)
        gd=abs(m.FTHG-m.FTAG); mult=1 if gd<=1 else (1.5 if gd==2 else (11+gd)/8)
        R[m.HomeTeam]+=K*mult*(res-E); R[m.AwayTeam]-=K*mult*(res-E)
        if res==1: act[m.HomeTeam]+=3
        elif res==0: act[m.AwayTeam]+=3
        else: act[m.HomeTeam]+=1; act[m.AwayTeam]+=1
    if tab is not None:
        prev=globals().get('lastpts',{})
        for t in teams: recs.append((s,t,fc[t],act[t],prev.get(t,np.nan)))
    globals()['lastpts']=act
    if s=='0405':
        tab=[]
        for b in bins:
            b=np.array(b) if b else np.array([1,0.5,0])
            tab.append(((b==1).mean(),(b==0.5).mean(),(b==0).mean()))
r=pd.DataFrame(recs,columns=['season','team','elo_fc','actual','last'])
r['err']=r.elo_fc-r.actual
print('seasons forecast',r.season.nunique(),'team-seasons',len(r))
print('Elo pre-season MAE',r.err.abs().mean().round(2),' median',r.err.abs().median().round(2),' within 5 pts',(r.err.abs()<=5).mean().round(3))
nv=r.dropna(subset=['last']); print('Naive last-season MAE (non-promoted)',(nv['last']-nv.actual).abs().mean().round(2),' Elo on same teams',(nv.elo_fc-nv.actual).abs().mean().round(2))
print('Sunderland:'); print(r[r.team=='Sunderland'].round(1).to_string())
r.to_csv('/tmp/res/elo_fc.csv',index=False)
# ---- Gerrard regression
rows=[]
for s in seasons:
    d=D[D.season==s]
    for t in sorted(set(d.HomeTeam)):
        h=d[d.HomeTeam==t]; a=d[d.AwayTeam==t]
        gf=h.FTHG.sum()+a.FTAG.sum(); ga=h.FTAG.sum()+a.FTHG.sum()
        sf=h.HS.sum()+a.AS.sum(); sa=h.AS.sum()+a.HS.sum(); stf=h.HST.sum()+a.AST.sum(); sta=h.AST.sum()+a.HST.sum()
        pts=3*((h.FTHG>h.FTAG).sum()+(a.FTAG>a.FTHG).sum())+(h.FTHG==h.FTAG).sum()+(a.FTAG==a.FTHG).sum()
        rows.append((s,t,pts,gf,ga,sf,sa,stf/sf,sta/sa,gf/stf,1-ga/sta))
T=pd.DataFrame(rows,columns=['season','team','pts','gf','ga','shots_for','shots_against','acc_for','acc_against','conversion','save_pct'])
T=T.dropna()
X=T[['shots_for','acc_for','conversion','shots_against','acc_against','save_pct']]
Z=(X-X.mean())/X.std(); y=T.pts
A=np.c_[np.ones(len(Z)),Z.values]; b,*_=np.linalg.lstsq(A,y.values,rcond=None)
pred=A@b; r2=1-((y-pred)**2).sum()/((y-y.mean())**2).sum()
coef=pd.Series(b[1:],index=X.columns)
print('team-seasons',len(T),' R2',round(r2,3)); print('points per 1 SD:'); print(coef.round(2))
print(T[['shots_for','shots_against','acc_for','conversion','save_pct']].describe().round(3))
coef.to_csv('/tmp/res/gerrard_coef.csv'); T.to_csv('/tmp/res/team_seasons.csv',index=False)
