Spaces:
Sleeping
Sleeping
File size: 19,390 Bytes
9c8b563 f38e3d2 3ff20a2 db9b5ba 79118f9 04b3e39 79118f9 04b3e39 79118f9 04b3e39 79118f9 04b3e39 79118f9 04b3e39 79118f9 f38e3d2 17fdde8 79118f9 f38e3d2 3ff20a2 d170eff 3ff20a2 f38e3d2 79118f9 f38e3d2 79118f9 3ff20a2 17fdde8 3ff20a2 db9b5ba 79118f9 04b3e39 3e07060 04b3e39 79118f9 04b3e39 79118f9 04b3e39 79118f9 04b3e39 3e481b2 04b3e39 79118f9 04b3e39 3e481b2 79118f9 3e481b2 54951c3 04b3e39 79118f9 f7e259c 04b3e39 79118f9 3e481b2 79118f9 04b3e39 79118f9 04b3e39 79118f9 8d35029 3e481b2 17fdde8 3e481b2 79118f9 17fdde8 04b3e39 3e481b2 79118f9 3e481b2 04b3e39 db9b5ba f38e3d2 db9b5ba 79118f9 db9b5ba 79118f9 f38e3d2 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 17fdde8 70a3d14 17fdde8 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 70a3d14 79118f9 17fdde8 f38e3d2 79118f9 db9b5ba 79118f9 3ff20a2 17fdde8 79118f9 3ff20a2 79118f9 db9b5ba 79118f9 db9b5ba 79118f9 db9b5ba 79118f9 3ff20a2 79118f9 3ff20a2 79118f9 db9b5ba d170eff 79118f9 d170eff 79118f9 d170eff 79118f9 3e07060 17fdde8 79118f9 3e07060 79118f9 3e07060 79118f9 3e07060 79118f9 3e07060 79118f9 3e07060 79118f9 3e07060 9a0642b 3e07060 79118f9 3e07060 79118f9 17fdde8 3e07060 db9b5ba 0c4f863 8f5c870 0c4f863 79118f9 04b3e39 79118f9 04b3e39 8d35029 3e07060 db9b5ba 04b3e39 0c4f863 04b3e39 79118f9 04b3e39 79118f9 f38e3d2 17fdde8 79118f9 17fdde8 db9b5ba 17fdde8 79118f9 d170eff 17fdde8 d170eff 3e07060 3ff20a2 17fdde8 3ff20a2 3e07060 79118f9 3ff20a2 17fdde8 79118f9 17fdde8 3e07060 3ff20a2 db9b5ba 79118f9 0c4f863 79118f9 | 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 | 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 = []
def format_selection_num(value):
"""
Format selection_num for display:
- 500.0 -> "500"
- 499.5 -> "499.5"
"""
if pd.isna(value):
return ""
try:
numeric_value = float(value)
if numeric_value.is_integer():
return str(int(numeric_value))
return str(numeric_value).rstrip("0").rstrip(".")
except Exception:
return str(value)
def clean_uploaded_df(raw_df):
"""
Standardize column names and normalize selection_direction for consistent logic.
"""
raw_df.columns = raw_df.columns.str.lower()
if "selection_direction" in raw_df.columns:
raw_df["selection_direction"] = raw_df["selection_direction"].astype(str).str.strip().str.title()
return raw_df
def prepare_ui(file):
global df
df = pd.read_csv(file.name)
df = clean_uploaded_df(df)
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)
)
df = pd.read_csv(file.name)
df = clean_uploaded_df(df)
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=[
"Event_Name", "Name", "Line", "Risk", "Bets", "Handle", "Sharp Handle"
])
mask = (df["placeddatetime"] >= start) & (df["placeddatetime"] <= end)
filtered_df = df[mask].copy()
if selected_bet_type != "All":
filtered_df = filtered_df[filtered_df["bet_type"] == selected_bet_type].copy()
if filtered_df.empty:
return pd.DataFrame(columns=[
"Event_Name", "Name", "Line", "Risk", "Bets", "Handle", "Sharp Handle"
])
# Build display line from selection_direction + selection_num
filtered_df["line_display"] = (
filtered_df["selection_direction"].astype(str).str.strip().str.title()
+ " "
+ filtered_df["selection_num"].apply(format_selection_num)
)
# 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=("line_display", "first"),
Risk=("pot_risk", "sum"),
Handle=("handle", "sum"),
Bets=("geallbetid", "nunique")
)
)
# Sharp Handle
target_brackets = ["Marker", "No Value", "Concerning"]
no_value_df = filtered_df[
filtered_df["customerbracket"].isin(target_brackets)
]
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 100 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 and row["Handle"] != 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:
data = data.copy()
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].dropna().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].dropna().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, pd.DataFrame(), pd.DataFrame()
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].copy()
if filtered.empty:
return None, None, pd.DataFrame(), pd.DataFrame()
# Use selection_num directly as line.
# Use selection_direction directly as direction.
filtered["line"] = filtered["selection_num"]
filtered["direction"] = filtered["selection_direction"].astype(str).str.strip().str.title()
filtered.dropna(subset=["direction", "line"], inplace=True)
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}",
"Potential Risk",
normalize
)
fig_bets = generate_stacked_bar(
summary,
"line",
"bet_count",
"customerbracket",
f"Bet Count for {player_name} - {market_type}",
"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"]
# No change requested here.
# Net liability table continues to use selection_num directly.
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"{format_selection_num(line)}–{format_selection_num(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",
css="""
#top-table-container {
height: 400px; /* adjust to taste */
overflow-y: auto;
}
"""
) 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")
# ✅ Wrapped in scrollable container
with gr.Group(elem_id="top-table-container"):
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("### 🏈 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]
)
# 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, height=150 )
# with gr.Group(elem_id="top-table-container"):
# 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("### 🏈 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]
# )
demo.launch() |