# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: StatsBomb open data, Premier League 2015/16 (competition 2, season 27): github.com/statsbomb/open-data
# Order: download events to /tmp/sb/events, run flatten.py, base.py, then a1 (needed by a8), a2, a3, a5, a6, a8

import pandas as pd, numpy as np
ev=pd.read_parquet('/tmp/sb/epl1516.parquet'); mt=pd.read_parquet('/tmp/sb/matches.parquet').sort_values('date')
CUT='2015-12-26'
xg=ev[ev.type=='Shot'].groupby(['match_id','team']).xg.sum()
mt['hxg']=[xg.get((m,h),0) for m,h in zip(mt.match_id,mt.home)]; mt['axg']=[xg.get((m,a),0) for m,a in zip(mt.match_id,mt.away)]
played=mt[mt.date<CUT]; rest=mt[mt.date>=CUT]
teams=sorted(set(mt.home))
def ratings(df,hcol,acol):
    # simple multiplicative attack/defence with home factor, fitted by iterative proportional updates
    att={t:1.0 for t in teams}; de={t:1.0 for t in teams}
    avg=(df[hcol].sum()+df[acol].sum())/(2*len(df)); home=df[hcol].mean()/df[acol].mean()
    for _ in range(50):
        for t in teams:
            h=df[df.home==t]; a=df[df.away==t]
            sf=h[hcol].sum()+a[acol].sum(); ef=sum(avg*np.sqrt(home)*de[o] for o in h.away)+sum(avg/np.sqrt(home)*de[o] for o in a.home)
            att[t]=sf/ef*att[t] if False else sf/(ef) 
        for t in teams:
            h=df[df.home==t]; a=df[df.away==t]
            sa=h[acol].sum()+a[hcol].sum(); ea=sum(avg/np.sqrt(home)*att[o] for o in h.away)+sum(avg*np.sqrt(home)*att[o] for o in a.home)
            de[t]=sa/ea
    return att,de,avg,home
def table(df):
    pts={t:0 for t in teams}; gd={t:0 for t in teams}
    for _,m in df.iterrows():
        if m.hs>m.as_: pts[m.home]+=3
        elif m.hs<m.as_: pts[m.away]+=3
        else: pts[m.home]+=1; pts[m.away]+=1
        gd[m.home]+=m.hs-m.as_; gd[m.away]+=m.as_-m.hs
    return pts,gd
pts0,gd0=table(played)
rng=np.random.default_rng(7); N=20000
res={}
for label,(hc,ac) in {'goals':('hs','as_'),'xG':('hxg','axg')}.items():
    att,de,avg,home=ratings(played,hc,ac)
    lh=np.array([avg*np.sqrt(home)*att[h]*de[a] for h,a in zip(rest.home,rest.away)])
    la=np.array([avg/np.sqrt(home)*att[a]*de[h] for h,a in zip(rest.home,rest.away)])
    HG=rng.poisson(lh,(N,len(rest))); AG=rng.poisson(la,(N,len(rest)))
    idx={t:i for i,t in enumerate(teams)}
    P=np.tile(np.array([pts0[t] for t in teams],float),(N,1)); G=np.tile(np.array([gd0[t] for t in teams],float),(N,1))
    hi=np.array([idx[h] for h in rest.home]); ai=np.array([idx[a] for a in rest.away])
    hw=(HG>AG)*3+(HG==AG); aw=(AG>HG)*3+(HG==AG)
    for j in range(len(rest)):
        P[:,hi[j]]+=hw[:,j]; P[:,ai[j]]+=aw[:,j]; G[:,hi[j]]+=HG[:,j]-AG[:,j]; G[:,ai[j]]+=AG[:,j]-HG[:,j]
    score=P+G*1e-3+rng.random(P.shape)*1e-6
    rank=(-score).argsort(1).argsort(1)+1
    out=pd.DataFrame({'team':teams,'pts_now':[pts0[t] for t in teams],'title':(rank==1).mean(0),'top4':(rank<=4).mean(0),'rel':(rank>=18).mean(0),'exp_pts':P.mean(0)})
    res[label]=out.set_index('team')
final,_=table(mt)
o=res['goals'].join(res['xG'],rsuffix='_xg'); o['final']=pd.Series(final)
print(len(played),'played before',CUT)
print(o.sort_values('pts_now',ascending=False)[['pts_now','title','title_xg','top4','top4_xg','rel','rel_xg','exp_pts','exp_pts_xg','final']].round(3).to_string())
o.to_csv('/tmp/sb/sim.csv')
