-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidebar.py
More file actions
387 lines (338 loc) Β· 16.7 KB
/
Copy pathsidebar.py
File metadata and controls
387 lines (338 loc) Β· 16.7 KB
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
"""
sidebar.py β Sidebar filters, filter application, lineup status panel
V2: Added "Confirmed lineups only" toggle.
When ON, app.py filters the df to only show batters present in
today's confirmed batting orders. Prevents betting on sitting players.
"""
import streamlit as st
import pandas as pd
from config import CONFIG
def build_filters(df: pd.DataFrame, container=None, key_prefix: str = "sidebar", show_title: bool = True,
allow_clear_button: bool = True) -> dict:
"""
Build the predictor filter controls in any Streamlit container.
This used to be sidebar-only. The app now renders these controls in the
main page so mobile users are not forced to open Streamlit's sidebar.
The same function still supports st.sidebar for future desktop-only uses.
"""
ui = container or st.sidebar
if show_title:
ui.markdown("### ποΈ A1PICKS Filters")
ui.markdown("---")
filters = {}
# ββ Target ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ui.markdown("#### π― Betting Target")
target_map = {
"π― Hit Score β Any Base Hit": "hit",
"1οΈβ£ Single Score β Single Only": "single",
"π₯ XB Score β Double / Triple": "xb",
"π£ HR Score β Home Run": "hr",
"π΄ H+R+RBI Score β Hits+Runs+RBIs": "hrr",
}
label = ui.selectbox(
"Choose Your Betting Target",
list(target_map.keys()),
key=f"{key_prefix}_target",
)
filters['target'] = target_map[label]
score_col_map = {'hit':'Hit_Score','single':'Single_Score',
'xb':'XB_Score','hr':'HR_Score','hrr':'HRR_Score'}
filters['score_col'] = score_col_map[filters['target']]
filters['score_col_base'] = filters['score_col']
# ββ Park / GC toggles βββββββββββββββββββββββββββββββββββββββββββββββββββββ
c1, c2 = ui.columns(2)
with c1:
st.markdown("#### ποΈ Park")
filters['use_park'] = st.toggle(
"Include Park Factors", value=True,
key=f"{key_prefix}_use_park",
help="ON = blends park-adjusted + base probabilities.\nOFF = pure player vs pitcher."
)
with c2:
st.markdown("#### π¦οΈ Conditions")
filters['use_gc'] = st.toggle(
"Game Conditions", value=True,
key=f"{key_prefix}_use_gc",
help="ON β Full game-environment ceiling (Β±40% Hit/XB, Β±35% HR).\nOFF β 30% of full weight."
)
if filters['use_gc']:
ui.markdown(
'<small style="color:#64748b">Cond Ξ column shows per-player impact</small>',
unsafe_allow_html=True
)
# ββ Lineup filters ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ui.markdown("#### π Lineup")
l1, l2 = ui.columns(2)
with l1:
filters['starters_only'] = st.checkbox(
"Starters only", value=False, key=f"{key_prefix}_starters_only"
)
with l2:
filters['confirmed_only'] = st.toggle(
"β
Confirmed lineups only",
value=False,
key=f"{key_prefix}_confirmed_only",
help="ON = hide players not yet in a confirmed batting order.\n"
"Lineups typically confirm 60-90 min before first pitch."
)
# ββ Stat filters ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ui.markdown("#### π Stat Filters")
s1, s2 = ui.columns(2)
with s1:
filters['max_k'] = st.slider(
"Max K Prob %", 10.0, 50.0, 35.0, 0.5, key=f"{key_prefix}_max_k"
)
with s2:
filters['max_bb'] = st.slider(
"Max BB Prob %", 2.0, 20.0, 15.0, 0.5, key=f"{key_prefix}_max_bb"
)
min_cfg = {
'hit': ("Min Hit Prob % (1B+XB+HR)", "total_hit_prob", 0.0, 50.0, 20.0),
'single':("Min 1B Prob %", "p_1b", 0.0, 30.0, 10.0),
'xb': ("Min XB Prob %", "p_xb", 0.0, 12.0, 4.0),
'hr': ("Min HR Prob %", "p_hr", 0.0, 8.0, 2.0),
'hrr': ("Min Hit Prob % (H+R+RBI)", "total_hit_prob", 0.0, 50.0, 15.0),
}
pl, pc, mn, mx, dv = min_cfg[filters['target']]
s3, s4 = ui.columns(2)
with s3:
filters['min_prob'] = st.slider(pl, mn, mx, dv, 0.5, key=f"{key_prefix}_min_prob")
filters['min_prob_col'] = pc
with s4:
filters['min_vs'] = st.slider("Min vs Grade", -10, 10, -10, 1, key=f"{key_prefix}_min_vs")
# ββ Team filters ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ui.markdown("#### ποΈ Team Filters")
all_teams = sorted(df['Team'].dropna().unique().tolist()) if df is not None and 'Team' in df.columns else []
t1, t2 = ui.columns(2)
with t1:
filters['include_teams'] = st.multiselect(
"Include Only Teams", options=all_teams, key=f"{key_prefix}_include_teams"
)
with t2:
filters['exclude_teams'] = st.multiselect(
"Exclude Teams", options=all_teams, key=f"{key_prefix}_exclude_teams"
)
# ββ Player exclusions βββββββββββββββββββββββββββββββββββββββββββββββββββββ
ui.markdown("#### π« Player Exclusions")
if 'excluded_players' not in st.session_state:
st.session_state.excluded_players = []
# Streamlit does not allow assigning to a widget's session_state key after
# that widget has been instantiated in the same rerun. Use a reset nonce so
# the clear button can force a fresh multiselect instead of mutating the
# existing widget key directly.
nonce_key = f"{key_prefix}_lineup_exclusions_nonce"
if nonce_key not in st.session_state:
st.session_state[nonce_key] = 0
all_players = sorted(df['Batter'].dropna().unique().tolist()) if df is not None and 'Batter' in df.columns else []
default_exclusions = [p for p in st.session_state.excluded_players if p in all_players]
exclusion_widget_key = f"{key_prefix}_lineup_exclusions_{st.session_state[nonce_key]}"
excl = ui.multiselect(
"Players NOT Playing Today",
options=all_players,
default=default_exclusions,
key=exclusion_widget_key,
)
st.session_state.excluded_players = excl
filters['excluded_players'] = excl
def _clear_exclusions(prefix: str):
st.session_state.excluded_players = []
st.session_state[f"{prefix}_lineup_exclusions_nonce"] = (
st.session_state.get(f"{prefix}_lineup_exclusions_nonce", 0) + 1
)
if allow_clear_button:
ui.button(
"π Clear All Exclusions",
key=f"{key_prefix}_clear_exclusions",
on_click=_clear_exclusions,
args=(key_prefix,),
)
else:
ui.caption("Use the Clear exclusions button below to reset this list.")
# ββ Display βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ui.markdown("#### π’ Display")
sort_options = {
"Score (HighβLow)": (filters['score_col'], False),
"Hit Prob % (HighβLow)": ("total_hit_prob", False),
"1B Prob % (HighβLow)": ("p_1b", False),
"XB Prob % (HighβLow)": ("p_xb", False),
"HR Prob % (HighβLow)": ("p_hr", False),
"K Prob % (LowβHigh)": ("p_k", True),
"BB Prob % (LowβHigh)": ("p_bb", True),
"vs Grade (HighβLow)": ("vs Grade", False),
"Pitcher Grade (A+βD)": ("pitch_grade", True),
}
d1, d2, d3 = ui.columns(3)
with d1:
filters['sort_label'] = st.selectbox(
"Sort By", list(sort_options.keys()), key=f"{key_prefix}_sort_label"
)
filters['sort_col'], filters['sort_asc'] = sort_options[filters['sort_label']]
with d2:
filters['result_count'] = st.selectbox(
"Show Top N", [5,10,15,20,25,30,"All"], index=2, key=f"{key_prefix}_result_count"
)
with d3:
filters['best_per_team'] = st.checkbox(
"ποΈ Best per team", value=False, key=f"{key_prefix}_best_per_team"
)
return filters
def build_predictor_control_panel(df: pd.DataFrame) -> dict:
"""Primary predictor controls shown in the main page for mobile usability.
Earlier performance builds wrapped these controls in a form. That reduced
reruns, but it also made the app feel broken because filter widgets did not
visibly change results until the form submit was clicked. The expensive
slate/API work is already cached in app.py, so the better UX is immediate
filter updates while keeping Refresh Live Data as the explicit cache-bust.
"""
st.markdown(
'<div class="mobile-control-intro">π± <b>Controls & Filters</b> β primary controls are here so the app is usable on phones without opening the Streamlit sidebar.</div>',
unsafe_allow_html=True,
)
with st.expander("βοΈ Open / close predictor controls", expanded=True):
st.caption("Filters update immediately. The expensive data/API build stays cached; use Refresh Live Data when you want a fresh pull.")
filters = build_filters(
df,
container=st,
key_prefix="main_filters",
show_title=False,
allow_clear_button=False,
)
c1, c2 = st.columns([1, 3])
with c1:
if st.button("π Clear exclusions", key="main_filters_clear_exclusions_outside", width="stretch"):
st.session_state.excluded_players = []
st.session_state["main_filters_lineup_exclusions_nonce"] = (
st.session_state.get("main_filters_lineup_exclusions_nonce", 0) + 1
)
st.rerun()
with c2:
st.caption("Because the enriched slate is cached, normal filter changes should only re-filter and re-render instead of repulling every API.")
return filters
def render_lineup_status_sidebar():
try:
from mlb_api import get_lineup_status_map
status_map = get_lineup_status_map()
if not status_map:
return
confirmed = sum(1 for v in status_map.values() if 'β
' in v['status'])
total = len(status_map)
st.sidebar.markdown("### π Lineup Status")
st.sidebar.markdown(
f'<div style="font-size:.75rem;color:#64748b;margin-bottom:.3rem">'
f'{confirmed}/{total} games confirmed</div>',
unsafe_allow_html=True
)
for matchup, info in status_map.items():
icon = 'β
' if 'β
' in info['status'] else 'β³'
st.sidebar.markdown(
f'<div style="font-size:.72rem;padding:.2rem 0;'
f'border-bottom:1px solid #1e2d3d;color:#e2e8f0">'
f'{icon} <b>{matchup}</b><br>'
f'<span style="color:#64748b;font-size:.65rem">'
f'SP: {info["away_sp"]} / {info["home_sp"]}</span>'
f'</div>',
unsafe_allow_html=True
)
except Exception:
pass
def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
if df is None or df.empty:
return pd.DataFrame()
out = df.copy()
if filters.get('starters_only'):
out = out[out['Starter'] == 1]
excl = filters.get('excluded_players', [])
if excl:
n = len(out)
out = out[~out['Batter'].isin(excl)]
if n - len(out):
st.info(f"π« Excluded {n - len(out)} player(s) from lineups")
if filters.get('include_teams'):
out = out[out['Team'].isin(filters['include_teams'])]
if filters.get('exclude_teams'):
n = len(out)
out = out[~out['Team'].isin(filters['exclude_teams'])]
if n - len(out):
st.info(f"π« Excluded players from {', '.join(filters['exclude_teams'])}")
out = out[out['p_k'] <= filters['max_k']]
out = out[out['p_bb'] <= filters['max_bb']]
mc = filters.get('min_prob_col', 'total_hit_prob')
if mc in out.columns:
out = out[out[mc] >= filters['min_prob']]
if filters['min_vs'] > -10:
out = out[pd.to_numeric(out['vs Grade'],errors='coerce').fillna(-10) >= filters['min_vs']]
sc = filters['score_col']
sc_eff = sc if sc in out.columns else filters.get('score_col_base', sc)
if filters.get('best_per_team') and not out.empty:
out = out.loc[out.groupby('Team')[sc_eff].idxmax()].copy()
st.info(f"ποΈ Best player from each of {len(out)} teams")
sc_s = filters['sort_col']
if sc_s not in out.columns:
sc_s = sc_s.replace('_gc','') if sc_s.endswith('_gc') else sc_s
if sc_s in out.columns:
out[sc_s] = pd.to_numeric(out[sc_s], errors='coerce')
# ββ Profile-prioritized sort βββββββββββββββββββββββββββββββββββββββββββ
# For Single and XB targets: profile-eligible players always rank above
# profile-mismatched ones, even if their raw score is lower.
# Mismatched players are still shown (visible but ranked below eligibles).
#
# Single: mismatched = XB_Score > Single_Score OR HR_Score > Single_Score
# XB: mismatched = HR_Score > XB_Score
# Hit/HR: no profile ranking β sort purely by score
sc_base_for_sort = filters.get('score_col_base', sc_s.replace('_gc',''))
is_profile_target = sc_base_for_sort in ('Single_Score', 'XB_Score')
if is_profile_target and not out.empty:
if sc_base_for_sort == 'Single_Score':
mismatch = pd.Series(False, index=out.index)
if 'XB_Score' in out.columns:
mismatch |= (out['XB_Score'] > out['Single_Score'])
if 'HR_Score' in out.columns:
mismatch |= (out['HR_Score'] > out['Single_Score'])
else: # XB_Score
mismatch = pd.Series(False, index=out.index)
if 'HR_Score' in out.columns:
mismatch |= (out['HR_Score'] > out['XB_Score'])
out['_profile_rank'] = mismatch.astype(int) # 0=eligible, 1=mismatch
out = out.sort_values(
['_profile_rank', sc_s],
ascending=[True, filters['sort_asc']],
na_position='last'
).drop(columns=['_profile_rank'])
else:
out = out.sort_values(sc_s, ascending=filters['sort_asc'], na_position='last')
n = filters['result_count']
if n != "All":
out = out.head(int(n))
return out
def get_slate_df(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
"""
Slate df used by Today's Best and Best Per Target sections.
Applies ALL global filters so these sections always reflect the user's
active filter state β not just exclusions.
Global filters (applied here AND in apply_filters):
excluded_players β manually excluded players
starters_only β only lineup starters (Starter == 1)
include_teams β only show selected teams
exclude_teams β hide selected teams
Stat filters (only in apply_filters, NOT here):
max_k, max_bb, min_prob, min_vs, result_count, best_per_team
These are "narrow" filters for the results table, not for the best-player cards.
Note: confirmed_only is applied to df in app.py BEFORE this is called,
so slate_df automatically inherits it.
"""
if df is None or df.empty:
return df
out = df.copy()
# Exclusions
excl = filters.get('excluded_players', [])
if excl:
out = out[~out['Batter'].isin(excl)]
# Starters only β most important: Today's Best should only show starting players
if filters.get('starters_only') and 'Starter' in out.columns:
out = out[out['Starter'] == 1]
# Team filters
if filters.get('include_teams'):
out = out[out['Team'].isin(filters['include_teams'])]
if filters.get('exclude_teams'):
out = out[~out['Team'].isin(filters['exclude_teams'])]
return out