-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathafl_functions.py
1502 lines (1313 loc) · 70.4 KB
/
afl_functions.py
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
def get_drive():
'''
this is to automate switching between home PC and laptop
it returns J:\\AFL\\ or D:\\AFL\\ depending if D:\ is available
No parameters required
'''
import win32api
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
if 'J:\\' in drives:
drive = 'J:\\AFL\\'
else:
drive = 'C:\\Users\\shumi\\Git\\AFL\\'
return drive
def get_proxy(proxy):
if proxy:
from os import environ
#pwd = input('Please enter your LAN Pwd')
environ["http_proxy"]="http://vshumilov:lAptop78-@http://kpmgproxy.com/kpmgproxy.pac:8080"
environ["https_proxy"]=environ.get("http_proxy")
return None
def fix_round(round_in):
'''
this function convert Round values into sequential integers
'''
if round_in=='QF':
rnd='25'
elif round_in=='EF':
rnd='26'
elif round_in=='SF':
rnd='27'
elif round_in=='PF':
rnd='28'
elif round_in=='GF':
rnd='29'
elif round_in[0]=='R':
rnd=round_in[1:]
else:
rnd=round_in
return int(rnd)
def fix_team_name(name):
'''
this function converts any team name to a consistent
set of names which are usable for joins
'''
if 'Crows' in name:
team_name='Adelaide'
elif name.strip()=='Adelaide Crows':
team_name='Adelaide'
elif name=='AD':
team_name='Adelaide'
elif name=='Crows':
team_name='Adelaide'
elif name=='BL':
team_name='Brisbane Lions'
elif name=='Lions':
team_name='Brisbane Lions'
elif name=='CA':
team_name='Carlton'
elif name=='Blues':
team_name='Carlton'
elif name=='CW':
team_name='Collingwood'
elif name=='Magpies':
team_name='Collingwood'
elif name=='ES':
team_name='Essendon'
elif name=='Bombers':
team_name='Essendon'
elif name=='FR':
team_name='Fremantle'
elif name=='Dockers':
team_name='Fremantle'
elif name=='GE':
team_name='Geelong'
elif name=='Cats':
team_name='Geelong'
elif name=='Geelong Cats':
team_name='Geelong'
elif name=='GC':
team_name='Gold Coast'
elif name=='Suns':
team_name='Gold Coast'
elif name=='Gold Coast Suns':
team_name='Gold Coast'
elif name=='GWS Giants':
team_name='Greater Western Sydney'
elif name=='GWS':
team_name='Greater Western Sydney'
elif name=='GW':
team_name='Greater Western Sydney'
elif name=='Giants':
team_name='Greater Western Sydney'
elif name=='GW Sydney':
team_name='Greater Western Sydney'
elif name=='HW':
team_name='Hawthorn'
elif name=='Hawks':
team_name='Hawthorn'
elif name=='ME':
team_name='Melbourne'
elif name=='Demons':
team_name='Melbourne'
elif name=='Deamons':
team_name='Melbourne'
elif name=='KA':
team_name='North Melbourne'
elif name=='NM':
team_name='North Melbourne'
elif name=='Kangaroos':
team_name='North Melbourne'
elif name=='PA':
team_name='Port Adelaide'
elif name=='Power':
team_name='Port Adelaide'
elif name=='RI':
team_name='Richmond'
elif name=='Tigers':
team_name='Richmond'
elif name=='SK':
team_name='St Kilda'
elif name=='Saints':
team_name='St Kilda'
elif name=='SY':
team_name='Sydney'
elif 'Swans' in name:
team_name='Sydney'
elif name=='WC':
team_name='West Coast'
elif name=='West Coast Eagles':
team_name='West Coast'
elif name=='Eagles':
team_name='West Coast'
elif name=='WB':
team_name='Western Bulldogs'
elif name=='Bulldogs':
team_name='Western Bulldogs'
else:
team_name=name
return team_name
def fix_venue(name):
if name=='AAMI':
ground = 'Olympic Park'
elif name=='ANZ':
ground = 'Stadium Australia'
elif name=='Football Park':
ground='Adelaide Oval'
elif name=='Adelaide':
ground='Adelaide Oval'
elif name=='AO':
ground='Adelaide Oval'
elif name=='Aurora':
ground = 'York Park'
elif name=='Blacktown':
ground='Blacktown'
elif name=='Blundstone Arena':
ground = 'Bellerive Oval'
elif name=='BA':
ground = 'Bellerive Oval'
elif name=='Blundstone':
ground = 'Bellerive Oval'
elif name=="Cazaly's":
ground= "Cazaly's Stadium"
elif name=='Domain':
ground='Subiaco'
elif name=='Etihad Stadium':
ground = 'Docklands'
elif name=='MS':
ground = 'Docklands'
elif name=='MRVL':
ground = 'Docklands'
elif name=='Etihad':
ground = 'Docklands'
elif name=='GMHBA Stadium':
ground='Kardinia Park'
elif name=='GMHBA':
ground='Kardinia Park'
elif name=='Gabba':
ground = 'Gabba'
elif name=='G':
ground = 'Gabba'
elif name=='AAJS':
ground = 'Jiangwan Stadium'
elif name=='Jiangwan':
ground = 'Jiangwan Stadium'
elif name=='Jiangwan Stadium, China':
ground = 'Jiangwan Stadium'
elif name=='M.C.G':
ground = 'M.C.G.'
elif name=='MCG':
ground = 'M.C.G.'
elif name=='MARS':
ground = 'Eureka Stadium'
elif name=='Mars Stadium, Ballarat':
ground = 'Eureka Stadium'
elif name=='Mars':
ground = 'Eureka Stadium'
elif name=='Metricon Stadium':
ground = 'Carrara'
elif name=='Metricon':
ground = 'Carrara'
elif name=='Perth':
ground='Perth Stadium'
elif name=='Subiaco':
ground='Perth Stadium'
elif name=='OS':
ground='Perth Stadium'
elif name=='SCG':
ground='S.C.G.'
elif name=='GIA':
ground='Sydney Showground'
elif name=='Spotless Stadium':
ground='Sydney Showground'
elif name=='SSGS':
ground='Sydney Showground'
elif name=='Spotless':
ground='Sydney Showground'
elif name=='UNSW Canberra Oval':
ground='Manuka Oval'
elif name=='MO':
ground='Manuka Oval'
elif name=='StarTrack':
ground='Manuka Oval'
elif name=='Treager Park, Alice Springs':
ground='Traeger Park'
elif name=='TIO Stadium, Darwin':
ground='Marrara Oval'
elif name=='TIO':
ground='Marrara Oval'
elif name=='University of Tasmania Stadium':
ground='York Park'
elif name=='UTAS':
ground='York Park'
elif name=='Westpac':
ground='Wellington'
else:
ground=name
return ground
def get_ladder(seas_from,seas_to,proxy=False):
'''
this is just to get the ladder history
Input required - update season from and to in the function call at the bottom
this function returns a dataframe for AFL ladder position history
seas_from - season to start from
seas_to - season end - inclusive
'''
import bs4 as bs
import urllib.request
import pandas as pd
from dateutil import parser
a =get_proxy(proxy)
ladder = pd.DataFrame(columns=['Team','Games','Points','Percentage','Round','Position','Season'])
for season in range(seas_from-1,seas_to+1):
cur_url = 'http://afltables.com/afl/seas/'+str(season)+'.html'
dfs = pd.read_html(cur_url)
for df in dfs:
if df.columns.nlevels>1:
break
if len(df)>1 and 'Ladder' in df[0][0] and 'Rd' in df[0][0] and len(df.columns)>2:
rnd = df[0][0][3:5]
ldr = df.copy()
ldr = ldr.drop(0,0)
ldr.columns = ['Team','Games','Points','Percentage']
ldr['Round']=rnd
ldr['Position']=ldr.index
ldr['Season']=season
ladder = pd.concat([ladder,ldr])
ladder['Team'] = [fix_team_name(x) for x in ladder['Team']]
# repeat last round for last and until 29
ladder_f = ladder.copy()
ladder_f.drop_duplicates(subset=['Team','Season'], keep='last', inplace=True)
# get last round for each season
ladder_y = ladder_f.copy()
ladder_y.drop_duplicates(subset=['Season'], keep='last', inplace=True)
ladder_y=ladder_y.drop(['Team','Games','Points','Percentage','Position'],1)
rnd=[]
seas=[]
for index, row in ladder_y.iterrows():
st = int(row.Round)
#print(type(st))
for i in range(st+1,30):
rnd.append(i)
seas.append(row.Season)
ldr = pd.DataFrame()
ldr['Season'] = seas
ldr['Round'] = rnd
#ldr = pd.merge(ladder_f.drop(['Round'],1),ldr,how='inner',on=['Season'])
ladder = pd.concat([ladder,ldr],sort=False)
ladder = ladder.sort_values(by=['Team','Season'],axis=0)
ladder['PosOld']=ladder.Position.shift(1) #previous ladder position taken
ladder = ladder.drop(['Position'],1)
ladder['Round']= [int(x) for x in ladder['Round']]
ladder=ladder.dropna(axis=0)
ladder['PosOld']= [int(x) for x in ladder['PosOld']]
return ladder
def get_games(proxy=False):
'''
this function gets past games history
and gets attendance where it is available
'''
import pandas as pd
a =get_proxy(proxy)
col_specification =[(7, 15), (16, 33), (51, 68), (87, 116),(117,128)]
attend = pd.read_fwf('https://afltables.com/afl/stats/biglists/bg7.txt',
colspecs=col_specification, skiprows=[0],parse_dates=[1])
attend.columns = ['Attendance', 'HomeTeam', 'AwayTeam', 'Venue','Date']
attend['Date'] = pd.to_datetime(attend['Date'],dayfirst=True)
attend['Attendance'] = attend.Attendance.str.replace(r"[\*]",'')
col_specification =[(0, 5), (7, 18), (24, 27), (29, 46),(47,63), (64,81),(82,99),(100,117)]
games= pd.read_fwf('http://afltables.com/afl/stats/biglists/bg3.txt',
colspecs=col_specification, skiprows=[0],parse_dates=[1])
games.columns = ['GameID', 'Date', 'Round', 'HomeTeam', 'ScoreHm','AwayTeam','ScoreAw','Venue']
games = pd.merge(games,attend,how='left',on=['Venue','Date','HomeTeam','AwayTeam'])
#fix rounds in games
games['Round'] = [fix_round(x) for x in games['Round']]
games['Year']=games['Date'].map(lambda x: x.year)
#fix North Melb in games
games['HomeTeam'] = [fix_team_name(x) for x in games['HomeTeam']]
games['AwayTeam'] = [fix_team_name(x) for x in games['AwayTeam']]
# get result
games['H'] = [int(x.split('.')[2]) for x in games['ScoreHm']]
games['A'] = [int(x.split('.')[2]) for x in games['ScoreAw']]
games = games.drop(['ScoreHm','ScoreAw'],1)
games['Result'] = [round((x[0] /(x[0] +x[1])),3) for x in zip(games['H'],games['A'])]
#games = games.drop(['H','A'],1)
games['ResultWL'] = [1 if x>=0.5 else 0 for x in games.Result]
games['Venue']=[fix_venue(x) for x in games['Venue']]
return games
def get_team_performance_hist(season_from,season_to,proxy=False):
'''
this is to get the team performance history
'''
import pandas as pd
import numpy as np
from datetime import datetime
from dateutil import parser
import bs4 as bs
import urllib.request
a =get_proxy(proxy)
games = get_games()
games_H = games.copy()
games_H['Team']=games_H['HomeTeam']
games_H['HomeFlag']=1
games_H = games_H.drop(['HomeTeam','AwayTeam'], 1)
games_A = games.copy()
games_A['Team']=games_A['AwayTeam']
games_A['HomeFlag']=0
games_A = games_A.drop(['HomeTeam','AwayTeam'], 1)
games_for_join = pd.concat([games_H,games_A])
team_performace = pd.DataFrame()
for season in range(season_from-4,season_to+1):
sauce = urllib.request.urlopen('https://afltables.com/afl/stats/'+str(season)+'t.html')
soup = bs.BeautifulSoup(sauce,'lxml')
tms=[]
i=0
for x in soup.find_all('th'):
if 'Team Statistics [Players]' in x.text:
tms.append(x.text[0:-26])
i+=1
cur_url = 'https://afltables.com/afl/stats/'+str(season)+'t.html'
dfs = pd.read_html(cur_url,header=1)
all_dfs = pd.DataFrame()
for i in range(len(dfs)):
if i % 2==0:
x= pd.concat([dfs[i],dfs[i+1].drop(['#','Opponent'],1)],1)
x['Team']=tms[i]
cols = [c for c in x.columns if c.lower()[:4] != 'unna']
x=x[cols]
all_dfs = pd.concat([all_dfs, x])
all_dfs=all_dfs[all_dfs['#'] != 'W-D-L']
all_dfs['Year']=season
team_performace = pd.concat([team_performace,all_dfs])
team_performace = team_performace.rename(columns={'#': 'Round'})
team_performace['Round'] = [fix_round(x) for x in team_performace['Round']]
team_performace['Team'] = [fix_team_name(x) for x in team_performace['Team']]
team_performace['Opponent'] = [fix_team_name(x) for x in team_performace['Opponent']]
team_performace = pd.merge(team_performace,games_for_join.drop(['GameID','Attendance','Result'],1),how='left',on=
['Year','Round','Team'])
team_performace['KIt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['KI']]
team_performace['MKt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['MK']]
team_performace['HBt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['HB']]
team_performace['DIt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['DI']]
team_performace['GLt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['GL']]
team_performace['BHt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['BH']]
team_performace['HOt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['HO']]
team_performace['TKt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['TK']]
team_performace['RBt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['RB']]
team_performace['IFt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['IF']]
team_performace['CLt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CL']]
team_performace['CGt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CG']]
team_performace['FFt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['FF']]
team_performace['FAt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['FA']]
team_performace['BRt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['BR']]
team_performace['CPt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CP']]
team_performace['UPt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['UP']]
team_performace['CMt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CM']]
team_performace['MIt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['MI']]
team_performace['1%t'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['1%']]
team_performace['BOt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['BO']]
team_performace['GAt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['GA']]
#added Score metric SC
team_performace['SCt'] = [g*6+b for g,b in zip(team_performace['GLt'],team_performace['BHt'])]
# this version change - getting opponent's stats "o" in column name is for "opposition"
team_performace['KIo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['KI']]
team_performace['MKo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['MK']]
team_performace['HBo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['HB']]
team_performace['DIo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['DI']]
team_performace['GLo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['GL']]
team_performace['BHo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['BH']]
team_performace['HOo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['HO']]
team_performace['TKo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['TK']]
team_performace['RBo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['RB']]
team_performace['IFo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['IF']]
team_performace['CLo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CL']]
team_performace['CGo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CG']]
team_performace['FFo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['FF']]
team_performace['FAo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['FA']]
team_performace['BRo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['BR']]
team_performace['CPo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CP']]
team_performace['UPo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['UP']]
team_performace['CMo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CM']]
team_performace['MIo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['MI']]
team_performace['1%o'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['1%']]
team_performace['BOo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['BO']]
team_performace['GAo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['GA']]
team_performace['SCo'] = [g*6+b for g,b in zip(team_performace['GLo'],team_performace['BHo'])]
#added Score metric SC
#difference metric
team_performace['KI'] = [t-o for t,o in zip(team_performace['KIt'],team_performace['KIo'])]
team_performace['MK'] = [t-o for t,o in zip(team_performace['MKt'],team_performace['MKo'])]
team_performace['HB'] = [t-o for t,o in zip(team_performace['HBt'],team_performace['HBo'])]
team_performace['DI'] = [t-o for t,o in zip(team_performace['DIt'],team_performace['DIo'])]
team_performace['GL'] = [t-o for t,o in zip(team_performace['GLt'],team_performace['GLo'])]
team_performace['BH'] = [t-o for t,o in zip(team_performace['BHt'],team_performace['BHo'])]
team_performace['HO'] = [t-o for t,o in zip(team_performace['HOt'],team_performace['HOo'])]
team_performace['TK'] = [t-o for t,o in zip(team_performace['TKt'],team_performace['TKo'])]
team_performace['RB'] = [t-o for t,o in zip(team_performace['RBt'],team_performace['RBo'])]
team_performace['IF'] = [t-o for t,o in zip(team_performace['IFt'],team_performace['IFo'])]
team_performace['CL'] = [t-o for t,o in zip(team_performace['CLt'],team_performace['CLo'])]
team_performace['CG'] = [t-o for t,o in zip(team_performace['CGt'],team_performace['CGo'])]
team_performace['FF'] = [t-o for t,o in zip(team_performace['FFt'],team_performace['FFo'])]
team_performace['FA'] = [t-o for t,o in zip(team_performace['FAt'],team_performace['FAo'])]
team_performace['BR'] = [t-o for t,o in zip(team_performace['BRt'],team_performace['BRo'])]
team_performace['CP'] = [t-o for t,o in zip(team_performace['CPt'],team_performace['CPo'])]
team_performace['UP'] = [t-o for t,o in zip(team_performace['UPt'],team_performace['UPo'])]
team_performace['CM'] = [t-o for t,o in zip(team_performace['CMt'],team_performace['CMo'])]
team_performace['MI'] = [t-o for t,o in zip(team_performace['MIt'],team_performace['MIo'])]
team_performace['1%'] = [t-o for t,o in zip(team_performace['1%t'],team_performace['1%o'])]
team_performace['BO'] = [t-o for t,o in zip(team_performace['BOt'],team_performace['BOo'])]
team_performace['GA'] = [t-o for t,o in zip(team_performace['GAt'],team_performace['GAo'])]
team_performace['SC'] = [t-o for t,o in zip(team_performace['SCt'],team_performace['SCo'])]
return team_performace
def get_team_performance_hist_rel(season_from,season_to,proxy=False):
'''
this relative version of team performance history
main metric is expressed as team's relative advantage over the opponent
e.g. if team goals is 12 and opponent goals is 6
the main GL metric shows (12-6)/(12+6) = 0.333
if both team and opponent metrics are zero then combined one =0
so values range from -1 to +1
'''
import pandas as pd
import numpy as np
from datetime import datetime
from dateutil import parser
import bs4 as bs
import urllib.request
a =get_proxy(proxy)
games = get_games()
games_H = games.copy()
games_H['Team']=games_H['HomeTeam']
games_H['HomeFlag']=1
games_H = games_H.drop(['HomeTeam','AwayTeam'], 1)
games_A = games.copy()
games_A['Team']=games_A['AwayTeam']
games_A['HomeFlag']=0
games_A = games_A.drop(['HomeTeam','AwayTeam'], 1)
games_for_join = pd.concat([games_H,games_A])
team_performace = pd.DataFrame()
for season in range(season_from-4,season_to+1):
sauce = urllib.request.urlopen('https://afltables.com/afl/stats/'+str(season)+'t.html')
soup = bs.BeautifulSoup(sauce,'lxml')
tms=[]
i=0
for x in soup.find_all('th'):
if 'Team Statistics [Players]' in x.text:
tms.append(x.text[0:-26])
i+=1
cur_url = 'https://afltables.com/afl/stats/'+str(season)+'t.html'
dfs = pd.read_html(cur_url,header=1)
all_dfs = pd.DataFrame()
for i in range(len(dfs)):
if i % 2==0:
x= pd.concat([dfs[i],dfs[i+1].drop(['#','Opponent'],1)],1)
x['Team']=tms[i]
cols = [c for c in x.columns if c.lower()[:4] != 'unna']
x=x[cols]
all_dfs = pd.concat([all_dfs, x])
all_dfs=all_dfs[all_dfs['#'] != 'W-D-L']
all_dfs['Year']=season
team_performace = pd.concat([team_performace,all_dfs])
team_performace = team_performace.rename(columns={'#': 'Round'})
team_performace['Round'] = [fix_round(x) for x in team_performace['Round']]
team_performace['Team'] = [fix_team_name(x) for x in team_performace['Team']]
team_performace['Opponent'] = [fix_team_name(x) for x in team_performace['Opponent']]
team_performace = pd.merge(team_performace,games_for_join.drop(['GameID','Attendance','Result'],1),how='left',on=
['Year','Round','Team'])
team_performace['KIt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['KI']]
team_performace['MKt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['MK']]
team_performace['HBt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['HB']]
team_performace['DIt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['DI']]
team_performace['GLt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['GL']]
team_performace['BHt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['BH']]
team_performace['HOt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['HO']]
team_performace['TKt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['TK']]
team_performace['RBt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['RB']]
team_performace['IFt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['IF']]
team_performace['CLt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CL']]
team_performace['CGt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CG']]
team_performace['FFt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['FF']]
team_performace['FAt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['FA']]
team_performace['BRt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['BR']]
team_performace['CPt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CP']]
team_performace['UPt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['UP']]
team_performace['CMt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['CM']]
team_performace['MIt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['MI']]
team_performace['1%t'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['1%']]
team_performace['BOt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['BO']]
team_performace['GAt'] = [0 if len(x.split('-')[0])==0 else int(x.split('-')[0]) for x in team_performace['GA']]
#added Score metric SC
team_performace['SCt'] = [g*6+b for g,b in zip(team_performace['GLt'],team_performace['BHt'])]
# this version change - getting opponent's stats "o" in column name is for "opposition"
team_performace['KIo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['KI']]
team_performace['MKo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['MK']]
team_performace['HBo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['HB']]
team_performace['DIo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['DI']]
team_performace['GLo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['GL']]
team_performace['BHo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['BH']]
team_performace['HOo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['HO']]
team_performace['TKo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['TK']]
team_performace['RBo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['RB']]
team_performace['IFo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['IF']]
team_performace['CLo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CL']]
team_performace['CGo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CG']]
team_performace['FFo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['FF']]
team_performace['FAo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['FA']]
team_performace['BRo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['BR']]
team_performace['CPo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CP']]
team_performace['UPo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['UP']]
team_performace['CMo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['CM']]
team_performace['MIo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['MI']]
team_performace['1%o'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['1%']]
team_performace['BOo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['BO']]
team_performace['GAo'] = [0 if len(x.split('-')[1])==0 else int(x.split('-')[1]) for x in team_performace['GA']]
team_performace['SCo'] = [g*6+b for g,b in zip(team_performace['GLo'],team_performace['BHo'])]
#added Score metric SC
#difference metric - now relative version ranging from -1 to +1 where 0 is even performance
team_performace['KI'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['KIt'],team_performace['KIo'])]
team_performace['MK'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['MKt'],team_performace['MKo'])]
team_performace['HB'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['HBt'],team_performace['HBo'])]
team_performace['DI'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['DIt'],team_performace['DIo'])]
team_performace['GL'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['GLt'],team_performace['GLo'])]
team_performace['BH'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['BHt'],team_performace['BHo'])]
team_performace['HO'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['HOt'],team_performace['HOo'])]
team_performace['TK'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['TKt'],team_performace['TKo'])]
team_performace['RB'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['RBt'],team_performace['RBo'])]
team_performace['IF'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['IFt'],team_performace['IFo'])]
team_performace['CL'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['CLt'],team_performace['CLo'])]
team_performace['CG'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['CGt'],team_performace['CGo'])]
team_performace['FF'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['FFt'],team_performace['FFo'])]
team_performace['FA'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['FAt'],team_performace['FAo'])]
team_performace['BR'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['BRt'],team_performace['BRo'])]
team_performace['CP'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['CPt'],team_performace['CPo'])]
team_performace['UP'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['UPt'],team_performace['UPo'])]
team_performace['CM'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['CMt'],team_performace['CMo'])]
team_performace['MI'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['MIt'],team_performace['MIo'])]
team_performace['1%'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['1%t'],team_performace['1%o'])]
team_performace['BO'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['BOt'],team_performace['BOo'])]
team_performace['GA'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['GAt'],team_performace['GAo'])]
team_performace['SC'] = [(t-o)/(t+o) if (t+o)>0 else 0 for t,o in zip(team_performace['SCt'],team_performace['SCo'])]
return team_performace
def get_lineup(year,rnd,proxy=False):
'''
returns all available line-up for given year
year - current year you need to specify
rnd - current round where line-up has been released (could be improved into auto later)
proxy = True if on LAN
Pre-requisites:
1.TeamRef.csv - file which maps team names to AFL line-up abbreviated names
2.Fixture function is used
'''
import bs4 as bs
import urllib.request
import pandas as pd
from dateutil import parser
from string import ascii_uppercase
from dateutil import parser
import datetime
fixture = get_fixture(proxy)
fixture = fixture[fixture.Round==rnd] #this limits to current round only
teams = pd.read_csv(get_drive()+'TeamRef.csv')
this_1 = pd.merge(fixture,teams,how="inner",left_on=['HomeTeam'],right_on=['Team'])
this_2 = pd.merge(this_1,teams,how="inner",left_on=['AwayTeam'],right_on=['Team'])
rounds = this_2.drop(['Team_x','Team_y'],1)
rounds['Game'] = [x + '-v-' +y for x,y in zip(rounds.AFL_Team_Nm_x,rounds.AFL_Team_Nm_y)]
rounds = rounds.drop(['AFL_Team_Nm_x','AFL_Team_Nm_y'],1)
# now get available line-up for player ref working
#rounds = rounds[rounds.Round<=max_round] # needs updating, just available
lineup=pd.DataFrame()
for gm,rnd in zip(rounds['Game'],rounds['Round']):
url='http://www.afl.com.au/match-centre/'+str(year)+'/'+str(rnd)+'/'+gm
sauce = urllib.request.urlopen(url)
soup = bs.BeautifulSoup(sauce,'lxml')
tms=[]
plrs=[]
for x in soup.find_all('div',class_ ='lineup'):
for t in x.find_all('div',class_ ='text-inouts'):
team=''
for tm in t.find_all('h4'):
team=tm.text
for p in t.find_all('div',class_ ='posGroup'):
position=''
for pos in p.find_all('p',class_ ='pos'):
position =pos.text.strip()
for player in p.find_all('li'):
if position in ['B','HB','C','HF','F','Fol','I/C']:
tms.append(team)
plrs.append(player.text.strip().strip(','))
d = pd.DataFrame()
d['Team'] = tms
d['Player'] = plrs
lineup=pd.concat([lineup,d])
lineup['Team']=[fix_team_name(x) for x in lineup['Team']]
return lineup
def get_player_base(proxy):
'''
!!! run only when need to update for new players !!!
returns a dataframe of player base table to enable to skip older players
e.g. players[players.DoB>'1975-01-01'] this gives 2.5k player subset
typical use - to create Players.csv file in AFL directory - !!! pre-requisite for getting player performance
'''
import bs4 as bs
import urllib.request
import pandas as pd
from string import ascii_uppercase
from dateutil import parser
import datetime
a =get_proxy(proxy)
players = pd.DataFrame(columns=['Name','DoB','Url','Debut_Age','Age_Last_Played_Days'])
# get player urls
links = []
for c in ascii_uppercase :
sauce = urllib.request.urlopen('https://afltables.com/afl/stats/players'+c+'_idx.html')
soup = bs.BeautifulSoup(sauce,'lxml')
for url in soup.find_all('a',href=True):
links.append('https://afltables.com/afl/stats/'+url['href'])
# now remove non-player links - ones that contain 'idx'
links = [item for item in links if 'players' in item and 'idx' not in item and 'afl_index' not in item]
for cur_url in links:
sauce = urllib.request.urlopen(cur_url)
soup = bs.BeautifulSoup(sauce,'lxml')
#Name
x = soup.find_all('h1')
name = x[0].text
#DoB
found_dob=False
for x in soup.find_all('b'):
if x.text == 'Born:':
dob = x.next_sibling
found_dob=True
break
if found_dob:
dob=parser.parse(dob[0:11],dayfirst=True)
else:
dob = datetime.datetime(1900, 1, 1, 0, 0)
#Debut
found_debut = False
for x in soup.find_all('b'):
if x.text == 'Debut:':
debut = x.next_sibling
found_debut=True
break
if found_debut:
debut =debut.split()
debut1 = ''.join(c for c in debut[0] if c.isdigit())
if len(debut)>1:
debut2 = ''.join(c for c in debut[1] if c.isdigit())
debut = int(debut1)+int(debut2)/365
else:
debut = int(debut1)
else:
debut = 100
#age last played
found_last = False
for x in soup.find_all('b'):
if x.text == 'Last:':
age_last = x.next_sibling
found_last=True
break
if found_last:
age_last =age_last.split()
a1 = ''.join(c for c in age_last[0] if c.isdigit())
if len(age_last)>1:
a2 = ''.join(c for c in age_last[1] if c.isdigit())
age_last = int(a1)*365.25+int(a2) #in days
else:
age_last = int(a1)*365.25
else:
age_last = 40*365.25
today = datetime.datetime.today()
last_played_date = dob + datetime.timedelta(days=age_last)
since_last_game=today-last_played_date
df = pd.DataFrame(columns=['Name','DoB','Url','Debut_Age','Age_Last_Played_Days','Last_Played_Date'])
df.loc[0]=[name,dob,cur_url,debut,age_last,last_played_date]
players = pd.concat([players,df])
print(name)
return players
def get_player_perf(DoB_min='1975-01-01',proxy=False):
'''
Use this only once per complete round and save into CSV as it takes a while to run
this function returns a dataframe of player performance history
Entire player history is returned
DoB_min is limiting factor to get only player born after the date - for performance reasons
change the default if you need to go more back into older players or in reverse
Pre-requisite: Players.csv file exists in the AFL directory
set proxy=True when on office LAN
'''
import bs4 as bs
import urllib.request
import pandas as pd
a =get_proxy(proxy)
players = pd.read_csv(get_drive()+'Players.csv')
players =players[players['DoB']>DoB_min]
player_stats = pd.DataFrame(columns=['Url','Team','Year'])
for cur_url in players.Url:
print(cur_url)
sauce = urllib.request.urlopen(cur_url)
soup = bs.BeautifulSoup(sauce,'lxml')
found=False
dfs=[]
for table in soup.find_all('table'):
#t1=tables[7]
t=table.find('tbody')
res = []
row = []
rows = t.find_all('tr')
for tr in rows:
for td in tr.find_all('td'):
row.append(td.text)
res.append(row)
row = []
df=pd.DataFrame(data=res)
if len(df.columns)==28: # found first game
found = True
if found:
h=table.find('thead')
h1 = h.find('tr')
h2 = h1.find('th')
header =h2.text
team_year = header.split('-')
team = team_year[0].strip()
year = team_year[1].strip()
df['Url']=cur_url
df['Team']=team
df['Year']=year
player_stats = pd.concat([player_stats,df])
player_stats = player_stats.rename(columns={0:'GameNo',1:'Opponent',2:'Round',3:'Result',4:'Jersey',5:'KI',6:'MK',7:'HB',8:'DI',9:'GL',10:'BH',11:'HO',12:'TK',13:'RB',14:'IF',15:'CL',16:'CG',17:'FF',18:'FA',19:'BR',20:'CP',21:'UP',22:'CM',23:'MI',24:'1%',25:'BO',26:'GA',27:'%P'})
player_stats['Round']=[fix_round(x) for x in player_stats['Round']]
games_set = get_games(proxy=False)
#create one game row for each team
gamesH = games_set.drop(['AwayTeam','Venue','Attendance','Result','ResultWL'],1)
gamesA = games_set.drop(['HomeTeam','Venue','Attendance','Result','ResultWL'],1)
gamesH=gamesH.rename(columns={'HomeTeam':'Team'})
gamesA=gamesA.rename(columns={'AwayTeam':'Team'})
gamesAH=pd.concat([gamesH,gamesA])
gamesAH['Year'] = [str(x) for x in gamesAH['Year']]
# get date and game id for each player record
player_stats=pd.merge(player_stats,gamesAH,how='inner',on=['Team','Year','Round'])
player_stats=player_stats.drop_duplicates(subset=['Url','Year','Round'],keep='first')
return player_stats
def get_pastXthis_opponent(x,team,opponent,dt,team_performaceDF):
'''
this function gets previous team performance coming to this game
takes x(how many games of history), team, opponent, date of current game, team stats dataframe to get games prior to this
'''
#last 3 against this team
tp = team_performaceDF[(team_performaceDF['Team']==team) & (team_performaceDF['Date'] <dt) & (team_performaceDF['Opponent']==opponent) ] # later row.Team
tp = tp.sort_values(by=['Date'],ascending=False)
tp = tp.head(x)
tp = tp.drop(['Round','Date', 'HomeFlag','Year'],1)
tp_avg = tp.groupby(by='Team').aggregate('mean')
tp_avg.columns = [str(col) + '_lstXopp' for col in tp_avg.columns]
if tp_avg.shape[0]==0:
print('empty row generated for ', dt,' team:',team, ' vs.', opponent)
return tp_avg
def get_pastXground(x,team,dt,venue,team_performaceDF):
'''
this function gets previous team performance coming to this game
takes x(how many games of history), team, date and venue of current game, team stats dataframe to get games prior to this
'''
tp2 = team_performaceDF[(team_performaceDF['Team']==team) & (team_performaceDF['Date'] <dt) & (team_performaceDF['Venue'] == venue)]
tp2 = tp2.sort_values(by=['Date'],ascending=False)
tp2 = tp2.head(x)
tp2 = tp2.drop(['Round','Date', 'HomeFlag','Year'],1)
tp2_avg = tp2.groupby(by='Team').aggregate('mean')
tp2_avg.columns = [str(col) + '_lstXgrd' for col in tp2_avg.columns]
if tp2_avg.shape[0]==0:
print('empty row generated for ',dt,' at ', venue,' team:',team)
return tp2_avg
def get_pastX(x,team,dt,team_performaceDF,print_missing=False):
'''
this function gets previous team performance coming to this game
takes x(how many games of history), team, date of current game, team stats dataframe to get games prior to this
'''
tp1 = team_performaceDF[(team_performaceDF['Team']==team) & (team_performaceDF['Date'] <dt)]
tp1 = tp1.sort_values(by=['Date'],ascending=False)
tp1 = tp1.head(x)
tp1 = tp1.drop(['Round','Date', 'HomeFlag','Year'],1)
tp1_avg = tp1.groupby(by='Team').aggregate('mean')
tp1_avg.columns = [str(col) + '_lstX' for col in tp1_avg.columns]
if tp1_avg.shape[0]==0 and print_missing:
print('empty row generated for ', dt,' team:',team)
return tp1_avg
#create functions to calculate adj.ladder points
def adj_points_home(lst):
w1=5.0 # for winning against top4 team as of end of last season
w2=4.0 # for winning against top5-8 team as of end of last season
w3=3.0 # for winning against 9-13 team as of end of last season
w4=2.5 # for winning against 14-18 team as of end of last season
l1=0.5 # for a bottom team (>=12) losing against to top 4 team as of end of last season with close margin
l2=0.5 # for a bottom team (>=12) losing against to top 5-8 team as of end of last season with close margin
if lst['ResultWL'] >0.5:
if lst['PreseasonRankA']<=4:
return w1
elif lst['PreseasonRankA']<=8:
return w2
elif lst['PreseasonRankA']<=13:
return w3
else:
return w4
else:
if lst['PreseasonRankH']>=12 and lst['PreseasonRankA']<=4 and lst['Result']>=0.42:
return l1
elif lst['PreseasonRankH']>=12 and lst['PreseasonRankA']<=8 and lst['Result']>=0.42:
return l2
else:
return 0
def adj_points_away(lst):
w1=5.0 # for winning against top4 team as of end of last season
w2=4.0 # for winning against top5-8 team as of end of last season
w3=3.0 # for winning against 9-13 team as of end of last season
w4=2.5 # for winning against 14-18 team as of end of last season
l1=0.5 # for a bottom team (>=12) losing against to top 4 team as of end of last season with close margin
l2=0.5 # for a bottom team (>=12) losing against to top 5-8 team as of end of last season with close margin
if lst['ResultWL'] <0.5:
if lst['PreseasonRankH']<=4:
return w1
elif lst['PreseasonRankH']<=8:
return w2
elif lst['PreseasonRankH']<=13:
return w3
else:
return w4
else:
if lst['PreseasonRankA']>=12 and lst['PreseasonRankH']<=4 and lst['Result']<=0.58:
return l1
elif lst['PreseasonRankA']>=12 and lst['PreseasonRankH']<=8 and lst['Result']<=0.58:
return l2
else:
return 0
# function to create a column with points for this team from either home or away column
def adj_points_combo(lst):
if lst['HomeFlag'] ==1:
return lst['PointsHome']
else:
return lst['PointsAway']
def get_pastXgames(x,team,dt,DF):
'''
this function gets previous team performance coming to this game
takes x(how many games of history), team, date of current game, team stats dataframe to get games prior to this
'''
newDF = DF[(DF['Team']==team) & (DF['Date'] <dt)]
newDF = newDF.sort_values(by=['Date'],ascending=False)
newDF = newDF.head(x)
newDF = newDF.drop(['Round','GameID','Result','Date','Venue','H','A','ResultWL','PointsHome','PointsAway','PreseasonRankA','PreseasonRankH', 'HomeFlag','Year'],1)
newDF = newDF.groupby(by='Team',as_index=False).aggregate('sum')
if len(newDF)>0:
return newDF.iloc[0]['TeamPoints']
else:
return 0
def get_game_base(season_from,season_to,proxy=False):
'''