Spaces:
Running
Running
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +210 -3
src/streamlit_app.py
CHANGED
|
@@ -2,6 +2,7 @@ import warnings
|
|
| 2 |
warnings.filterwarnings("ignore")
|
| 3 |
|
| 4 |
import os
|
|
|
|
| 5 |
from datetime import time as dt_time
|
| 6 |
import streamlit as st
|
| 7 |
import yfinance as yf
|
|
@@ -1208,12 +1209,215 @@ def render_signal_tracker():
|
|
| 1208 |
plt.close(fig)
|
| 1209 |
|
| 1210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1211 |
# =========================================================
|
| 1212 |
# MAIN LAYOUT
|
| 1213 |
# =========================================================
|
| 1214 |
|
| 1215 |
-
tab1, tab2, tab3, tab4 = st.tabs(
|
| 1216 |
-
["π Whale Monitor", "π Peak Detector", "π Bottom Scanner", "ποΈ Signal Tracker"]
|
| 1217 |
)
|
| 1218 |
|
| 1219 |
with tab1:
|
|
@@ -1226,4 +1430,7 @@ with tab3:
|
|
| 1226 |
render_sniper_tab()
|
| 1227 |
|
| 1228 |
with tab4:
|
| 1229 |
-
render_signal_tracker()
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
warnings.filterwarnings("ignore")
|
| 3 |
|
| 4 |
import os
|
| 5 |
+
import time
|
| 6 |
from datetime import time as dt_time
|
| 7 |
import streamlit as st
|
| 8 |
import yfinance as yf
|
|
|
|
| 1209 |
plt.close(fig)
|
| 1210 |
|
| 1211 |
|
| 1212 |
+
# =========================================================
|
| 1213 |
+
# TAB 5: OPTIONS SCANNER (full-universe daily options-volume database)
|
| 1214 |
+
# =========================================================
|
| 1215 |
+
|
| 1216 |
+
OPTIONS_LOG_FILENAME = "options_volume_log.csv"
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
+
def load_options_log() -> pd.DataFrame:
|
| 1220 |
+
if not _log_configured():
|
| 1221 |
+
return pd.DataFrame()
|
| 1222 |
+
try:
|
| 1223 |
+
local_path = hf_hub_download(
|
| 1224 |
+
repo_id=DATASET_REPO, repo_type="dataset", filename=OPTIONS_LOG_FILENAME, token=HF_TOKEN
|
| 1225 |
+
)
|
| 1226 |
+
df = pd.read_csv(local_path)
|
| 1227 |
+
if "Date" in df.columns:
|
| 1228 |
+
df["Date"] = pd.to_datetime(df["Date"])
|
| 1229 |
+
return df
|
| 1230 |
+
except Exception:
|
| 1231 |
+
return pd.DataFrame()
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
def save_options_log(df: pd.DataFrame) -> bool:
|
| 1235 |
+
if not _log_configured():
|
| 1236 |
+
return False
|
| 1237 |
+
try:
|
| 1238 |
+
api = HfApi(token=HF_TOKEN)
|
| 1239 |
+
csv_bytes = df.to_csv(index=False).encode("utf-8")
|
| 1240 |
+
api.upload_file(
|
| 1241 |
+
path_or_fileobj=csv_bytes,
|
| 1242 |
+
path_in_repo=OPTIONS_LOG_FILENAME,
|
| 1243 |
+
repo_id=DATASET_REPO,
|
| 1244 |
+
repo_type="dataset",
|
| 1245 |
+
commit_message=f"Update options volume log ({len(df)} rows)",
|
| 1246 |
+
)
|
| 1247 |
+
return True
|
| 1248 |
+
except Exception as e:
|
| 1249 |
+
st.warning(f"Could not save options log: {e}")
|
| 1250 |
+
return False
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
def get_ticker_options_totals(ticker: str, max_expiries: int):
|
| 1254 |
+
"""Sum call/put volume and open interest across the nearest expiries for one ticker.
|
| 1255 |
+
No bulk endpoint exists for options data, so this is one ticker at a time, deliberately
|
| 1256 |
+
unhurried to avoid the rate limiting already hit elsewhere in this project."""
|
| 1257 |
+
try:
|
| 1258 |
+
tk = yf.Ticker(ticker)
|
| 1259 |
+
expiries = tk.options
|
| 1260 |
+
if not expiries:
|
| 1261 |
+
return None
|
| 1262 |
+
call_vol = put_vol = call_oi = put_oi = 0
|
| 1263 |
+
for exp in expiries[:max_expiries]:
|
| 1264 |
+
try:
|
| 1265 |
+
chain = tk.option_chain(exp)
|
| 1266 |
+
call_vol += chain.calls["volume"].fillna(0).sum()
|
| 1267 |
+
put_vol += chain.puts["volume"].fillna(0).sum()
|
| 1268 |
+
call_oi += chain.calls["openInterest"].fillna(0).sum()
|
| 1269 |
+
put_oi += chain.puts["openInterest"].fillna(0).sum()
|
| 1270 |
+
except Exception:
|
| 1271 |
+
continue
|
| 1272 |
+
time.sleep(0.2)
|
| 1273 |
+
return {
|
| 1274 |
+
"call_volume": int(call_vol), "put_volume": int(put_vol),
|
| 1275 |
+
"call_oi": int(call_oi), "put_oi": int(put_oi),
|
| 1276 |
+
}
|
| 1277 |
+
except Exception:
|
| 1278 |
+
return None
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
@st.cache_data(ttl=3600, show_spinner=False)
|
| 1282 |
+
def run_options_scan(tickers_tuple, max_expiries):
|
| 1283 |
+
rows = []
|
| 1284 |
+
total = len(tickers_tuple)
|
| 1285 |
+
progress = st.progress(0, text="Scanning options activity (this is the slow one)...")
|
| 1286 |
+
|
| 1287 |
+
for i, ticker in enumerate(tickers_tuple):
|
| 1288 |
+
totals = get_ticker_options_totals(ticker, max_expiries)
|
| 1289 |
+
if totals:
|
| 1290 |
+
rows.append({"Ticker": ticker, **totals})
|
| 1291 |
+
if (i + 1) % 10 == 0 or (i + 1) == total:
|
| 1292 |
+
progress.progress((i + 1) / total, text=f"Scanned {i + 1}/{total} tickers...")
|
| 1293 |
+
|
| 1294 |
+
progress.empty()
|
| 1295 |
+
return pd.DataFrame(rows)
|
| 1296 |
+
|
| 1297 |
+
|
| 1298 |
+
def render_options_scan():
|
| 1299 |
+
st.title("π Options Scanner")
|
| 1300 |
+
st.caption(
|
| 1301 |
+
"Tracks total call and put volume across each ticker's nearest options expiries, building "
|
| 1302 |
+
"a day-by-day database to compare today's activity against that ticker's own normal range."
|
| 1303 |
+
)
|
| 1304 |
+
st.info(
|
| 1305 |
+
"π This needs time before it's useful. There's no historical options-volume data available "
|
| 1306 |
+
"for free, only today's snapshot β so the baseline gets built from scratch, one logged day "
|
| 1307 |
+
"at a time. Spike detection will be unreliable for the first couple of weeks and improve as "
|
| 1308 |
+
"the log fills in, same bootstrapping as the Signal Tracker."
|
| 1309 |
+
)
|
| 1310 |
+
st.warning(
|
| 1311 |
+
"β οΈ This is the slowest scan in the dashboard. Options data has no bulk multi-ticker endpoint "
|
| 1312 |
+
"the way price data does β every ticker needs its own sequential request (and another per "
|
| 1313 |
+
"expiry checked) β and Yahoo's rate limit already forced batch sizes down elsewhere in this "
|
| 1314 |
+
"project. Best run once, end-of-day, exactly as you planned, with no time pressure."
|
| 1315 |
+
)
|
| 1316 |
+
|
| 1317 |
+
with st.sidebar:
|
| 1318 |
+
st.markdown("---")
|
| 1319 |
+
st.header("Options Scanner Settings")
|
| 1320 |
+
max_expiries = st.slider("Nearest expiries to include per ticker", 1, 4, 2, 1, key="opt_expiries")
|
| 1321 |
+
baseline_days = st.slider("Baseline lookback (days)", 10, 90, 60, 5, key="opt_baseline")
|
| 1322 |
+
spike_multiplier = st.slider("Spike threshold (x median)", 1.5, 10.0, 3.0, 0.5, key="opt_mult")
|
| 1323 |
+
min_contracts = st.number_input("Min absolute contract volume", value=50, step=10, key="opt_minabs")
|
| 1324 |
+
|
| 1325 |
+
universe = get_clean_premarket_universe()
|
| 1326 |
+
st.caption(f"Universe: {len(universe)} tickers from your curated list.")
|
| 1327 |
+
|
| 1328 |
+
if st.button("π Run Options Scan & Log Today", key="opt_scan_btn"):
|
| 1329 |
+
if not universe:
|
| 1330 |
+
st.error("No tickers loaded from the curated list.")
|
| 1331 |
+
elif not _log_configured():
|
| 1332 |
+
st.error("Signal log storage isn't configured β see the Signal Tracker tab for setup.")
|
| 1333 |
+
else:
|
| 1334 |
+
today_df = run_options_scan(tuple(universe), max_expiries)
|
| 1335 |
+
if today_df.empty:
|
| 1336 |
+
st.warning("No options data returned for any ticker.")
|
| 1337 |
+
else:
|
| 1338 |
+
today_df["Date"] = pd.Timestamp.now().normalize()
|
| 1339 |
+
existing = load_options_log()
|
| 1340 |
+
combined = pd.concat([existing, today_df], ignore_index=True) if not existing.empty else today_df
|
| 1341 |
+
combined = combined.drop_duplicates(subset=["Ticker", "Date"], keep="last")
|
| 1342 |
+
if save_options_log(combined):
|
| 1343 |
+
st.success(f"Logged today's options data for {len(today_df)} tickers.")
|
| 1344 |
+
|
| 1345 |
+
log = load_options_log()
|
| 1346 |
+
if log.empty:
|
| 1347 |
+
st.info("No options data logged yet. Run a scan to start building the database.")
|
| 1348 |
+
return
|
| 1349 |
+
|
| 1350 |
+
st.caption(f"Database: {log['Date'].nunique()} day(s) logged across {log['Ticker'].nunique()} tickers.")
|
| 1351 |
+
|
| 1352 |
+
today = log["Date"].max()
|
| 1353 |
+
history = log[log["Date"] < today]
|
| 1354 |
+
today_rows = log[log["Date"] == today]
|
| 1355 |
+
|
| 1356 |
+
if history.empty:
|
| 1357 |
+
st.info(
|
| 1358 |
+
"Only one day logged so far β nothing to compare against yet. Run this again on a "
|
| 1359 |
+
"later day to start seeing real comparisons."
|
| 1360 |
+
)
|
| 1361 |
+
return
|
| 1362 |
+
|
| 1363 |
+
results = []
|
| 1364 |
+
for ticker, grp in today_rows.groupby("Ticker"):
|
| 1365 |
+
hist_grp = history[history["Ticker"] == ticker].sort_values("Date").tail(baseline_days)
|
| 1366 |
+
if len(hist_grp) < 3:
|
| 1367 |
+
continue
|
| 1368 |
+
# Median, not mean β a handful of extreme days can't drag this baseline around
|
| 1369 |
+
# the way they would an average, so the baseline stays representative as the log grows.
|
| 1370 |
+
call_baseline = hist_grp["call_volume"].median()
|
| 1371 |
+
put_baseline = hist_grp["put_volume"].median()
|
| 1372 |
+
|
| 1373 |
+
row = grp.iloc[-1]
|
| 1374 |
+
call_ratio = (row["call_volume"] / call_baseline) if call_baseline > 0 else np.nan
|
| 1375 |
+
put_ratio = (row["put_volume"] / put_baseline) if put_baseline > 0 else np.nan
|
| 1376 |
+
|
| 1377 |
+
call_hit = row["call_volume"] >= min_contracts and pd.notna(call_ratio) and call_ratio >= spike_multiplier
|
| 1378 |
+
put_hit = row["put_volume"] >= min_contracts and pd.notna(put_ratio) and put_ratio >= spike_multiplier
|
| 1379 |
+
|
| 1380 |
+
if call_hit or put_hit:
|
| 1381 |
+
if call_hit and put_hit and abs((call_ratio or 0) - (put_ratio or 0)) < 1:
|
| 1382 |
+
lean = "Both sides spiking (binary event?)"
|
| 1383 |
+
elif (call_ratio or 0) >= (put_ratio or 0):
|
| 1384 |
+
lean = "Call-skewed (bullish lean)"
|
| 1385 |
+
else:
|
| 1386 |
+
lean = "Put-skewed (bearish lean)"
|
| 1387 |
+
|
| 1388 |
+
results.append({
|
| 1389 |
+
"Ticker": ticker,
|
| 1390 |
+
"Call Volume": int(row["call_volume"]),
|
| 1391 |
+
"Call Baseline (median)": round(call_baseline, 1),
|
| 1392 |
+
"Call Ratio": round(call_ratio, 1) if pd.notna(call_ratio) else None,
|
| 1393 |
+
"Put Volume": int(row["put_volume"]),
|
| 1394 |
+
"Put Baseline (median)": round(put_baseline, 1),
|
| 1395 |
+
"Put Ratio": round(put_ratio, 1) if pd.notna(put_ratio) else None,
|
| 1396 |
+
"Read": lean,
|
| 1397 |
+
"Days in Baseline": len(hist_grp),
|
| 1398 |
+
})
|
| 1399 |
+
|
| 1400 |
+
if not results:
|
| 1401 |
+
st.info("No tickers showed an options-volume spike past your thresholds today.")
|
| 1402 |
+
else:
|
| 1403 |
+
results_df = pd.DataFrame(results).sort_values(
|
| 1404 |
+
by=["Call Ratio", "Put Ratio"], ascending=False, na_position="last"
|
| 1405 |
+
).reset_index(drop=True)
|
| 1406 |
+
st.success(f"{len(results_df)} ticker(s) with unusual options activity today.")
|
| 1407 |
+
st.dataframe(results_df, use_container_width=True, hide_index=True)
|
| 1408 |
+
st.caption(
|
| 1409 |
+
"Remember: this flags unusual volume, not confirmed direction β the call/put skew is a "
|
| 1410 |
+
"lean, not a verified trade side. Treat it the same as everything else here: a reason to "
|
| 1411 |
+
"go look closer, not a standalone signal."
|
| 1412 |
+
)
|
| 1413 |
+
|
| 1414 |
+
|
| 1415 |
# =========================================================
|
| 1416 |
# MAIN LAYOUT
|
| 1417 |
# =========================================================
|
| 1418 |
|
| 1419 |
+
tab1, tab2, tab3, tab4, tab5 = st.tabs(
|
| 1420 |
+
["π Whale Monitor", "π Peak Detector", "π Bottom Scanner", "ποΈ Signal Tracker", "π Options Scanner"]
|
| 1421 |
)
|
| 1422 |
|
| 1423 |
with tab1:
|
|
|
|
| 1430 |
render_sniper_tab()
|
| 1431 |
|
| 1432 |
with tab4:
|
| 1433 |
+
render_signal_tracker()
|
| 1434 |
+
|
| 1435 |
+
with tab5:
|
| 1436 |
+
render_options_scan()
|