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()