Spaces:
Sleeping
Sleeping
File size: 13,689 Bytes
24e1519 | 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 | import pandas as pd
import numpy as np
import plotly.express as px
import plotly
from IPython.display import display
import ipywidgets as widgets
import gradio as gr
import plotly.graph_objects as go
df = pd.DataFrame()
bettype_list = []
# Define a function to prepare default UI values after file upload
def prepare_ui(file):
global df
df = pd.read_csv(file.name)
df.columns = df.columns.str.lower()
min_date = df['placeddatetime'].min()
max_date = df['placeddatetime'].max()
bet_types = ["All"] + sorted(df["bet_type"].dropna().unique())
return min_date, max_date, gr.update(choices=bet_types, value="All")
def load_csv(file):
global df, bettype_list
if file is None:
return (
gr.update(choices=[], interactive=False),
gr.update(choices=[], interactive=False),
gr.update(choices=[], value=[], interactive=False),
gr.update(choices=[], value=[], interactive=False)
)
df = pd.read_csv(file.name)
df.columns = df.columns.str.lower()
market_options = sorted(df['sourcemarkettypename2'].dropna().unique())
bettype_list = sorted(df['bet_type'].dropna().unique())
return (
gr.update(choices=market_options, value=None, interactive=True),
gr.update(choices=[], value=None, interactive=False),
gr.update(choices=["All"] + bettype_list, value="All", interactive=True),
)
def filter_table(start_date, end_date, selected_bet_type):
try:
start = start_date
end = end_date
except Exception:
return pd.DataFrame(columns=[
"eventname", "selectionname2", "pot_risk", "bet_count",
"handle", "Sharp Handle"
])
mask = (df["placeddatetime"] >= start) & (df["placeddatetime"] <= end)
filtered_df = df[mask]
if selected_bet_type != "All":
filtered_df = filtered_df[filtered_df["bet_type"] == selected_bet_type]
# Main aggregation using lineid
agg_df = (
filtered_df.groupby("lineid", as_index=False)
.agg(
LineID=("lineid", "first"),
Event_Name=("eventname", "first"),
Name=("player_name", "first"),
Line=("selectionname2", "first"),
Risk=("pot_risk", "sum"),
Handle=("handle", "sum"),
Bets=("geallbetid", "nunique")
)
)
#Sharp Handle (no value cohort)
no_value_df = filtered_df[filtered_df["customerbracket"] == "Sharp"]
handle_no_value_df = (
no_value_df.groupby("lineid", as_index=False)
.agg(
line_id=("lineid", "first"),
handle_no_value=("handle", "sum"))
)
agg_df = agg_df.merge(handle_no_value_df, on="lineid", how="left")
agg_df["handle_no_value"] = agg_df["handle_no_value"].fillna(0)
# Select top 10 by most negative pot risk
top_10 = agg_df.sort_values("Risk").head(100)
top_10["Sharp Handle"] = top_10.apply(
lambda row: f"${int(row['handle_no_value']):,} ({round((row['handle_no_value'] / row['Handle']) * 100)}%)"
if row["handle_no_value"] > 0 else "$0 (0%)",
axis = 1
)
top_10["Risk"] = top_10["Risk"].round(0).apply(lambda x: f"${int(x):,}" if x >= 0 else f"-${abs(int(x)):,}")
top_10["Handle"] = top_10["Handle"].round(0).apply(lambda x: f"${int(x):,}" if x >= 0 else f"-${abs(int(x)):,}")
top_10["handle_no_value"] = top_10["handle_no_value"].round(0)
return top_10[[
"Event_Name", "Name", "Line", "Risk", "Bets", "Handle", "Sharp Handle"
]]
def get_players(market_type):
if market_type is None or df.empty:
return []
players = df[df['sourcemarkettypename2'] == market_type]['player_name'].dropna().unique()
return sorted(players)
def update_players(market_type):
players = get_players(market_type)
return gr.update(choices=players, value=None, interactive=True)
def generate_stacked_bar(data, x, y, category, title, y_label, normalize=False):
segment_colors = {
'New': 'white',
'Normal': 'gray',
'Retail': 'black',
'Outstanding': 'green',
'VIP': 'purple',
'Monitored': 'yellow',
'Live Advantage': 'orange',
'Sharp': 'red',
'No Value': '#8B0000',
'Marker': 'blue',
'Concerning': 'pink',
'Other': 'brown'
}
fig = go.Figure()
if normalize:
totals = data.groupby([x, 'direction'])[y].transform('sum').replace(0, 1)
data[y] = data[y] / totals * 100
data[y] = data.apply(lambda row: -abs(row[y]) if row['direction'] == 'Under' else abs(row[y]), axis=1)
for cat in sorted(data[category].unique()):
sub_df = data[data[category] == cat]
fig.add_trace(go.Bar(
x=sub_df[x],
y=sub_df[y],
name=cat,
marker_color=segment_colors.get(cat, 'gray')
))
fig.add_hline(y=0, line_dash="dash", line_color="gray", opacity=0.6)
fig.add_annotation(
xref="paper", yref="paper",
x=-0.1, y=1.05,
text="Over",
showarrow=False,
font=dict(size=12, color="green"),
align="left"
)
fig.add_annotation(
xref="paper", yref="paper",
x=-0.1, y=-0.05,
text="Under",
showarrow=False,
font=dict(size=12, color="red"),
align="left"
)
line_levels = sorted(data[x].unique(), key=lambda v: float(v))
fig.update_layout(
barmode='relative',
title=title,
xaxis_title=x,
yaxis_title=y_label + (" (%)" if normalize else ""),
yaxis_tickprefix= ("%" if normalize else ""),
xaxis_tickangle=-45,
bargap=0.25,
autosize=True,
margin=dict(l=40, r=20, t=60, b=60),
xaxis=dict(
categoryorder='array',
categoryarray=line_levels,
automargin=True
),
yaxis=dict(automargin=True),
dragmode=False,
modebar_remove=['zoom', 'zoomIn', 'zoomOut', 'pan', 'select', 'lasso2d', 'autoScale2d']
)
return fig
def generate_charts(market_type, player_name, bettype_filters, normalize):
if not market_type or not player_name or df.empty:
return None, None
filtered = df[
(df['sourcemarkettypename2'] == market_type) &
(df['player_name'] == player_name)
].copy()
if bettype_filters and bettype_filters != "All":
filtered = filtered[filtered['bet_type'] == bettype_filters]
selection_parts = filtered['selectionname2'].str.extract(r'(?P<direction>Over|Under)\s+(?P<line>[\d\.]+)')
filtered['direction'] = selection_parts['direction']
filtered['line'] = selection_parts['line']
filtered.dropna(subset=['direction', 'line'], inplace=True)
filtered['line'] = filtered['line'].astype(str)
summary = (
filtered
.groupby(['line', 'direction', 'customerbracket'], as_index=False)
.agg(
pot_risk=('pot_risk', 'sum'),
bet_count=('geallbetid', 'nunique')
)
)
summary['pot_risk'] = summary.apply(
lambda row: -row['pot_risk'] if row['direction'] == 'Over' else row['pot_risk'], axis=1
)
summary['bet_count'] = summary.apply(
lambda row: -row['bet_count'] if row['direction'] == 'Under' else row['bet_count'], axis=1
)
fig_risk = generate_stacked_bar(summary, 'line', 'pot_risk', 'customerbracket', f"Liability for {player_name} - {market_type}", f"Potential Risk", normalize)
fig_bets = generate_stacked_bar(summary, 'line', 'bet_count', 'customerbracket', f"Bet Count for {player_name} - {market_type}", f"Bet Count", normalize)
table_df = (
filtered
.assign(direction=filtered['direction'].fillna(''))
.groupby(['line', 'direction'], as_index=False)
.agg(
handle=('handle', 'sum'),
potential_risk=('pot_risk', 'sum'),
average_odds=('odds', 'mean'),
bet_count=('geallbetid', 'nunique')
)
)
table_df['average_odds'] = table_df['average_odds'].apply(lambda x: f"{x:.2f}")
table_df['bet_count'] = table_df['bet_count'].round(0).astype(int)
table_df['handle'] = table_df['handle'].round(0).astype(int).apply(lambda x: f"${x:,}")
table_df['potential_risk'] = table_df['potential_risk'].round(0).astype(int).apply(lambda x: f"${x:,}" if x >= 0 else f"-${abs(int(round(x))):,}")
table_df.columns = ["Line", "Selection", "Handle", "Risk", "Avg. Odds", "Bet Count"]
net_lines = sorted(filtered['selection_num'].dropna().unique())
net_rows = []
for idx, line in enumerate(net_lines):
under_risk = filtered[(filtered['selection_direction'] == 'Under') & (filtered['selection_num'] >= line)]['pot_risk'].sum()
over_recoup = filtered[(filtered['selection_direction'] == 'Over') & (filtered['selection_num'] >= line)]['handle'].sum()
under_net = under_risk + over_recoup
over_risk = filtered[(filtered['selection_direction'] == 'Over') & (filtered['selection_num'] <= line)]['pot_risk'].sum()
under_recoup = filtered[(filtered['selection_direction'] == 'Under') & (filtered['selection_num'] <= line)]['handle'].sum()
over_net = over_risk + under_recoup
# Interval exposure: liability if player finishes between this line and the next
if idx < len(net_lines) - 1:
next_line = net_lines[idx + 1]
interval_range = f"{line}–{next_line}"
over_win = filtered[(filtered['selection_direction'] == 'Over') & (filtered['selection_num'] <= line)]['pot_risk'].sum()
under_win = filtered[(filtered['selection_direction'] == 'Under') & (filtered['selection_num'] >= next_line)]['pot_risk'].sum()
over_handle_loss = filtered[(filtered['selection_direction'] == 'Over') & (filtered['selection_num'] > line)]['handle'].sum()
under_handle_loss = filtered[(filtered['selection_direction'] == 'Under') & (filtered['selection_num'] < next_line)]['handle'].sum()
interval_net = over_win + under_win + over_handle_loss + under_handle_loss
interval_exposure = f"${int(round(interval_net)):,}" if interval_net >= 0 else f"-${abs(int(round(interval_net))):,}"
else:
interval_range = None
interval_exposure = None
net_rows.append({
'line': line,
'under_net_liability': f"${int(round(under_net)):,}" if under_net >= 0 else f"-${abs(int(round(under_net))):,}",
'over_net_liability': f"${int(round(over_net)):,}" if over_net >= 0 else f"-${abs(int(round(over_net))):,}",
'interval_range': interval_range,
'interval_exposure': interval_exposure
})
net_liability_df = pd.DataFrame(net_rows)
net_liability_df.columns = ["Line", "Under Net Risk", "Over Net Risk", "Interval Range", "Interval Exposure"]
return fig_risk, fig_bets, table_df, net_liability_df
with gr.Blocks(title="Top NFL Outright Markets by Liability") as demo:
file_input = gr.File(label="Upload CSV File", file_types=[".csv"])
gr.Markdown("Upload a CSV file, then use the controls below to filter bets by date and bet type.")
gr.Markdown("### Top NFL Outright Markets by Line Liability")
with gr.Row():
start_input = gr.Textbox(label="Start Date (YYYY-MM-DD)")
end_input = gr.Textbox(label="End Date (YYYY-MM-DD)")
bet_type_input = gr.Dropdown(label="Bet Type", choices=["All"], value="All")
table = gr.Dataframe(label="Top 10 Liability Summary", interactive=False)
file_input.change(fn=prepare_ui, inputs=file_input, outputs=[start_input, end_input, bet_type_input])
start_input.change(fn=filter_table, inputs=[start_input, end_input, bet_type_input], outputs=[table])
end_input.change(fn=filter_table, inputs=[start_input, end_input, bet_type_input], outputs=[table])
bet_type_input.change(fn=filter_table, inputs=[start_input, end_input, bet_type_input], outputs=[table])
gr.Markdown("### \U0001F3C8 NFL Outright Liability Dashboard")
with gr.Row():
market_dropdown = gr.Dropdown(choices=[], label="Market Type", interactive=False)
player_dropdown = gr.Dropdown(choices=[], label="Player Name", interactive=False)
bettype_dropdown = gr.Dropdown(choices=["All"], value="All", label="Bet Types", interactive=False)
submit_button = gr.Button("Submit", variant="primary")
with gr.Row():
chart_risk = gr.Plot(label="Liability (pot_risk)")
chart_bets = gr.Plot(label="Bet Count")
normalize_toggle = gr.Checkbox(label="Normalize bar height (percent scale)", value=False)
with gr.Row():
data_table = gr.DataFrame(
label="Liability Summary",
interactive=False
)
with gr.Row():
net_liability_table = gr.DataFrame(
label="Net Liability by Line",
interactive=False
)
file_input.change(
fn=load_csv,
inputs=file_input,
outputs=[market_dropdown, player_dropdown, bettype_dropdown]
)
market_dropdown.change(fn=update_players, inputs=market_dropdown, outputs=player_dropdown)
submit_button.click(
fn=generate_charts,
inputs=[market_dropdown, player_dropdown, bettype_dropdown, normalize_toggle],
outputs=[chart_risk, chart_bets, data_table, net_liability_table]
)
normalize_toggle.change(
fn=generate_charts,
inputs=[market_dropdown, player_dropdown, bettype_dropdown, normalize_toggle],
outputs=[chart_risk, chart_bets, data_table, net_liability_table]
)
# Launch app
demo.launch() |