-
Notifications
You must be signed in to change notification settings - Fork 10
/
vpc.py
186 lines (159 loc) · 6.07 KB
/
vpc.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
from functions import get_raw_data
from functions import get_gameweek_data
from functions import map_id_to_str
from decouple import config
import numpy
import os
import requests
import pandas
import plotly.graph_objs as go
import chart_studio
import chart_studio.plotly as py
def plot_vpc(vpc):
goalkeepers = vpc[(vpc['position']=='Goalkeeper') & (vpc['total_points']>0.1)]
defenders = vpc[(vpc['position']=='Defender') & (vpc['total_points']>0.1)]
midfielders = vpc[(vpc['position']=='Midfielder') & (vpc['total_points']>0.1)]
forwards = vpc[(vpc['position']=='Forward') & (vpc['total_points']>0.1)]
trace_gkp = get_trace(goalkeepers,'Goalkeeper')
trace_def = get_trace(defenders,'Defender')
trace_mid = get_trace(midfielders,'Midfielder')
trace_fwd = get_trace(forwards,'Forward')
data = [trace_gkp,trace_def,trace_mid,trace_fwd]
updatemenus = list([
dict(active=0,
pad = {'r': 0, 't': 10},
x = 0,
y = 1.18,
type = 'buttons',
font=dict(color='#404040'),
bgcolor = 'rgba(255,255,255,100)',
direction = 'right',
xanchor = 'left',
buttons=list([
dict(label = 'All',
method = 'update',
args = [{'visible': [True, True, True, True]}]),
dict(label = 'Goalkeepers',
method = 'update',
args = [{'visible': [True, False, False, False]}]),
dict(label = 'Defenders',
method = 'update',
args = [{'visible': [False, True, False, False]}]),
dict(label = 'Midfielders',
method = 'update',
args = [{'visible': [False, False, True, False]}]),
dict(label = 'Forwards',
method = 'update',
args = [{'visible': [False, False, False, True]}])
]),
)
])
layout = go.Layout(
modebar={'bgcolor': 'rgba(0,0,0,0)'},
hovermode = 'closest',
showlegend=False,
updatemenus=updatemenus,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
xaxis=go.layout.XAxis(
showgrid=True,
zeroline=False,
color='rgba(255,255,255,1)',
showticklabels=False,
title=go.layout.xaxis.Title(
text='Cost',
font=dict(
size=18,
color='white'
)
)
),
yaxis=go.layout.YAxis(
showgrid=True,
zeroline=False,
color='rgba(255,255,255,10)',
showticklabels=False,
title=go.layout.yaxis.Title(
text='Value',
font=dict(
size=18,
color='white'
)
)
)
)
fig = go.Figure(data=data, layout=layout)
return fig
def calc_vpc(base_path, season, currgw):
# cleaned data - df1
df1 = get_raw_data(base_path, season)
df1['value'] = df1['now_cost']/10
df1['id_str'] = df1.apply(map_id_to_str, axis=1)
df1['display_name'] = df1['name']
# df1['name'] = df1['name'] + ' ' + df1['id_str']
df1 = df1[['value', 'name', 'position', 'display_name']]
# data by gws for each player
df2 = get_gameweek_data(base_path, season, currgw)
df2 = df2[['value', 'name', 'bonus', 'bonus_weighted', 'bps', 'bps_weighted', 'total_points', 'total_points_weighted']]
# df2.to_csv('in.csv', sep='\t')
# group by player and calculate ratio
df2['total_points'] = df2['total_points'].apply(pandas.to_numeric, downcast='float', errors='coerce')
df2['total_points'] = df2['total_points'].astype(float)
df2['bps'] = df2['bps'].apply(pandas.to_numeric, downcast='float', errors='coerce')
df2['bonus'] = df2['bonus'].apply(pandas.to_numeric, downcast='float', errors='coerce')
df2 = df2.groupby(['name']).mean()
# merge
df = pandas.merge(df1, df2, on='name', how='outer')
df['vpc_ratio'] = df['total_points'] / df['value']
df['vpc_ratio_weighted'] = df['total_points_weighted'] * 100 / df['value']
df.replace([numpy.inf, -numpy.inf], numpy.nan, inplace=True)
df = df.fillna(0)
return df[df.vpc_ratio > 0]
def map_position_to_color(position):
if position == 'Goalkeeper':
return 'rgba(0,53,166, 0.8)'
elif position == 'Defender':
return 'rgba(101,255,71, 0.8)'
elif position == 'Midfielder':
return 'rgba(254,213,0, 0.8)'
else:
return 'rgba(236,0,0, 0.8)'
def get_trace(df, position):
return go.Scatter(
x = df['value'],
y = df['total_points'],
name= (position+'s'),
text = df['display_name'],
mode = 'markers',
marker=dict(color = map_position_to_color(position),
size = df['vpc_ratio'],
sizeref = 0.001,
sizemode = 'area'),
hoverlabel= dict(
font=dict(color='#404040'),
bordercolor='#404040',
bgcolor='white'
),
hovertemplate = "<b>%{text}</b><br><br>" +
"Value: %{y:.2f}</br>"+
"Cost: %{x:.2f}£</br>"+
"<extra></extra>")
def main():
print('Fetching curr gameweek...')
URL = "https://fantasy.premierleague.com/api/bootstrap-static/"
DATA = requests.get(URL).json()
CURR_GW_OBJS = [x for x in DATA['events'] if x['is_current'] == True]
if len(CURR_GW_OBJS) == 0:
CURR_GW_OBJS = DATA['events']
CURR_GW = CURR_GW_OBJS[-1]['id']
BASE_PATH = './scraper/'
SEASON = '2022-23'
CHARTS_USER = config('CHARTS_USER')
CHARTS_API_KEY = config('CHARTS_API_KEY')
chart_studio.tools.set_credentials_file(username=CHARTS_USER, api_key=CHARTS_API_KEY)
print('Generating VPC plot...')
vpc = calc_vpc(BASE_PATH, SEASON, CURR_GW)
fig = plot_vpc(vpc)
chart_studio.plotly.plot(fig, filename="vpc", auto_open=False)
if __name__ == '__main__':
main()