Spaces:
Running
Running
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +288 -156
src/streamlit_app.py
CHANGED
|
@@ -1,30 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import yfinance as yf
|
| 3 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
st.set_page_config(page_title="
|
| 6 |
-
|
| 7 |
-
st.title("π Whale Monitor")
|
| 8 |
-
st.caption(
|
| 9 |
-
"Flags unusual 1-minute volume on the public exchange tape. "
|
| 10 |
-
"This is a lit-market 'unusual volume' heuristic, not off-exchange dark pool print data."
|
| 11 |
-
)
|
| 12 |
-
|
| 13 |
-
# ---------- Sidebar controls ----------
|
| 14 |
-
with st.sidebar:
|
| 15 |
-
st.header("Settings")
|
| 16 |
-
symbol = st.text_input("Ticker", value="AIIO").strip().upper()
|
| 17 |
-
multiplier = st.slider("Sensitivity (x median volume)", 1.0, 10.0, 2.0, 0.5)
|
| 18 |
-
whale_threshold = st.number_input("Whale alert threshold (volume)", value=50000, step=5000)
|
| 19 |
-
show_all = st.checkbox("Show all candles (ignore threshold)", value=False)
|
| 20 |
-
exclude_open = st.checkbox("Exclude opening auction print (09:30 bar)", value=True)
|
| 21 |
-
if st.button("π Refresh data"):
|
| 22 |
-
st.cache_data.clear()
|
| 23 |
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
# ---------- Data fetch (cached so it doesn't hit Yahoo on every interaction) ----------
|
| 26 |
@st.cache_data(ttl=120, show_spinner="Fetching data...")
|
| 27 |
-
def
|
| 28 |
try:
|
| 29 |
ticker = yf.Ticker(sym)
|
| 30 |
return ticker.history(period="5d", interval="1m")
|
|
@@ -32,40 +23,17 @@ def fetch_data(sym: str) -> pd.DataFrame:
|
|
| 32 |
return pd.DataFrame()
|
| 33 |
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
last_session = df.index.normalize().max()
|
| 47 |
-
df = df[df.index.normalize() == last_session].copy()
|
| 48 |
-
|
| 49 |
-
if df.empty:
|
| 50 |
-
st.error("No data for the most recent session.")
|
| 51 |
-
st.stop()
|
| 52 |
-
|
| 53 |
-
if exclude_open and len(df) > 1:
|
| 54 |
-
df = df.iloc[1:] # drop the opening auction print, not a true intraday trade
|
| 55 |
-
|
| 56 |
-
df = df[df["Volume"] >= 0]
|
| 57 |
-
if (df["Volume"] > 0).sum() == 0:
|
| 58 |
-
st.error("Not enough volume data after filtering.")
|
| 59 |
-
st.stop()
|
| 60 |
-
|
| 61 |
-
# ---------- Calculations ----------
|
| 62 |
-
median_vol = df[df["Volume"] > 0]["Volume"].median()
|
| 63 |
-
mean_vol = df[df["Volume"] > 0]["Volume"].mean()
|
| 64 |
-
|
| 65 |
-
df["Price_Change"] = df["Close"].diff()
|
| 66 |
-
df["Pct_Change"] = df["Close"].pct_change() * 100
|
| 67 |
-
df["Vol_Ratio"] = df["Volume"] / median_vol
|
| 68 |
-
df["is_notable"] = df["Volume"] > (median_vol * multiplier) if not show_all else True
|
| 69 |
|
| 70 |
|
| 71 |
def get_sentiment(row):
|
|
@@ -76,111 +44,275 @@ def get_sentiment(row):
|
|
| 76 |
return 0, "NEUTRAL"
|
| 77 |
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
if
|
| 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 |
-
whale_sells = df[(df["Size"] == "WHALE") & (df["Sentiment"] == "SELL")]["Volume"].sum()
|
| 146 |
-
inst_buys = df[(df["Size"].isin(["INSTITUTIONAL", "WHALE"])) & (df["Sentiment"] == "BUY")]["Volume"].sum()
|
| 147 |
-
inst_sells = df[(df["Size"].isin(["INSTITUTIONAL", "WHALE"])) & (df["Sentiment"] == "SELL")]["Volume"].sum()
|
| 148 |
-
|
| 149 |
-
st.markdown("### Session Analysis")
|
| 150 |
-
colA, colB, colC = st.columns(3)
|
| 151 |
-
with colA:
|
| 152 |
-
st.markdown("**Overall**")
|
| 153 |
-
st.write(f"Buy volume: {total_buy:,.0f}")
|
| 154 |
-
st.write(f"Sell volume: {total_sell:,.0f}")
|
| 155 |
-
st.write(f"Net delta: {net:,.0f}")
|
| 156 |
-
st.write(f"Buy/Sell ratio: {(total_buy / total_sell) if total_sell > 0 else 0:.2f}x")
|
| 157 |
-
with colB:
|
| 158 |
-
st.markdown("**Whale tier**")
|
| 159 |
-
st.write(f"Buy: {whale_buys:,.0f}")
|
| 160 |
-
st.write(f"Sell: {whale_sells:,.0f}")
|
| 161 |
-
st.write(f"Net: {whale_buys - whale_sells:,.0f}")
|
| 162 |
-
with colC:
|
| 163 |
-
st.markdown("**Institutional+**")
|
| 164 |
-
st.write(f"Buy: {inst_buys:,.0f}")
|
| 165 |
-
st.write(f"Sell: {inst_sells:,.0f}")
|
| 166 |
-
st.write(f"Net: {inst_buys - inst_sells:,.0f}")
|
| 167 |
-
|
| 168 |
-
status = "π’ ACCUMULATION (Bullish)" if net > 0 else "π΄ DISTRIBUTION (Bearish)"
|
| 169 |
-
st.markdown(f"## Market Sentiment: {status}")
|
| 170 |
-
|
| 171 |
-
# ---------- Volume by size category ----------
|
| 172 |
-
st.markdown("### Volume by Size Category")
|
| 173 |
-
rows = []
|
| 174 |
-
total_vol = df["Volume"].sum()
|
| 175 |
-
for size in ["WHALE", "INSTITUTIONAL", "LARGE", "MEDIUM", "RETAIL"]:
|
| 176 |
-
vol = df[df["Size"] == size]["Volume"].sum()
|
| 177 |
-
count = len(df[df["Size"] == size])
|
| 178 |
-
pct = (vol / total_vol * 100) if total_vol > 0 else 0
|
| 179 |
-
rows.append({"Size": size, "Volume": vol, "% of Total": round(pct, 1), "Candles": count})
|
| 180 |
-
|
| 181 |
-
st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
|
| 182 |
-
|
| 183 |
-
st.caption(
|
| 184 |
-
"Data source: yfinance (Yahoo Finance), unofficial and delayed. "
|
| 185 |
-
"Cached for 2 minutes β use the Refresh button in the sidebar for the latest data."
|
| 186 |
-
)
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
warnings.filterwarnings("ignore")
|
| 3 |
+
|
| 4 |
import streamlit as st
|
| 5 |
import yfinance as yf
|
| 6 |
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
from sklearn.ensemble import GradientBoostingClassifier
|
| 10 |
|
| 11 |
+
st.set_page_config(page_title="Market Dashboard", page_icon="π", layout="wide")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# =========================================================
|
| 14 |
+
# TAB 1: WHALE MONITOR
|
| 15 |
+
# =========================================================
|
| 16 |
|
|
|
|
| 17 |
@st.cache_data(ttl=120, show_spinner="Fetching data...")
|
| 18 |
+
def fetch_whale_data(sym: str) -> pd.DataFrame:
|
| 19 |
try:
|
| 20 |
ticker = yf.Ticker(sym)
|
| 21 |
return ticker.history(period="5d", interval="1m")
|
|
|
|
| 23 |
return pd.DataFrame()
|
| 24 |
|
| 25 |
|
| 26 |
+
def classify_size(vol, median):
|
| 27 |
+
ratio = vol / median if median > 0 else 0
|
| 28 |
+
if ratio >= 10:
|
| 29 |
+
return "WHALE"
|
| 30 |
+
elif ratio >= 5:
|
| 31 |
+
return "INSTITUTIONAL"
|
| 32 |
+
elif ratio >= 2:
|
| 33 |
+
return "LARGE"
|
| 34 |
+
elif ratio >= 1:
|
| 35 |
+
return "MEDIUM"
|
| 36 |
+
return "RETAIL"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def get_sentiment(row):
|
|
|
|
| 44 |
return 0, "NEUTRAL"
|
| 45 |
|
| 46 |
|
| 47 |
+
def render_whale_monitor():
|
| 48 |
+
st.title("π Whale Monitor")
|
| 49 |
+
st.caption(
|
| 50 |
+
"Flags unusual 1-minute volume on the public exchange tape. "
|
| 51 |
+
"This is a lit-market 'unusual volume' heuristic, not off-exchange dark pool print data."
|
| 52 |
+
)
|
| 53 |
|
| 54 |
+
with st.sidebar:
|
| 55 |
+
st.header("Whale Monitor Settings")
|
| 56 |
+
symbol = st.text_input("Ticker", value="AIIO", key="wm_ticker").strip().upper()
|
| 57 |
+
multiplier = st.slider("Sensitivity (x median volume)", 1.0, 10.0, 2.0, 0.5, key="wm_mult")
|
| 58 |
+
whale_threshold = st.number_input("Whale alert threshold (volume)", value=50000, step=5000, key="wm_thresh")
|
| 59 |
+
show_all = st.checkbox("Show all candles (ignore threshold)", value=False, key="wm_all")
|
| 60 |
+
exclude_open = st.checkbox("Exclude opening auction print (09:30 bar)", value=True, key="wm_exopen")
|
| 61 |
+
if st.button("π Refresh data", key="wm_refresh"):
|
| 62 |
+
fetch_whale_data.clear()
|
| 63 |
+
|
| 64 |
+
if not symbol:
|
| 65 |
+
st.info("Enter a ticker symbol in the sidebar to begin.")
|
| 66 |
+
return
|
| 67 |
+
|
| 68 |
+
df = fetch_whale_data(symbol)
|
| 69 |
+
if df.empty:
|
| 70 |
+
st.error(f"No data available for '{symbol}'. Check the ticker symbol and try again.")
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
last_session = df.index.normalize().max()
|
| 74 |
+
df = df[df.index.normalize() == last_session].copy()
|
| 75 |
+
if df.empty:
|
| 76 |
+
st.error("No data for the most recent session.")
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
if exclude_open and len(df) > 1:
|
| 80 |
+
df = df.iloc[1:]
|
| 81 |
+
|
| 82 |
+
df = df[df["Volume"] >= 0]
|
| 83 |
+
if (df["Volume"] > 0).sum() == 0:
|
| 84 |
+
st.error("Not enough volume data after filtering.")
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
median_vol = df[df["Volume"] > 0]["Volume"].median()
|
| 88 |
+
mean_vol = df[df["Volume"] > 0]["Volume"].mean()
|
| 89 |
+
|
| 90 |
+
df["Price_Change"] = df["Close"].diff()
|
| 91 |
+
df["Pct_Change"] = df["Close"].pct_change() * 100
|
| 92 |
+
df["Vol_Ratio"] = df["Volume"] / median_vol
|
| 93 |
+
df["is_notable"] = df["Volume"] > (median_vol * multiplier) if not show_all else True
|
| 94 |
+
|
| 95 |
+
df[["Delta", "Sentiment"]] = df.apply(lambda r: pd.Series(get_sentiment(r)), axis=1)
|
| 96 |
+
df["Cum_Delta"] = df["Delta"].cumsum()
|
| 97 |
+
df["Size"] = df["Volume"].apply(lambda v: classify_size(v, median_vol))
|
| 98 |
+
|
| 99 |
+
st.subheader(f"{symbol} β Session: {last_session.date()}")
|
| 100 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 101 |
+
c1.metric("Median 1-min Volume", f"{median_vol:,.0f}")
|
| 102 |
+
c2.metric("Mean 1-min Volume", f"{mean_vol:,.0f}")
|
| 103 |
+
c3.metric("Flag Threshold", f"{median_vol * multiplier:,.0f}")
|
| 104 |
+
c4.metric(
|
| 105 |
+
"Last Price",
|
| 106 |
+
f"${df['Close'].iloc[-1]:.2f}",
|
| 107 |
+
f"{df['Pct_Change'].iloc[-1]:+.2f}%" if pd.notna(df["Pct_Change"].iloc[-1]) else None,
|
| 108 |
+
)
|
| 109 |
|
| 110 |
+
st.markdown("### Notable Activity")
|
| 111 |
+
notable = df[df["is_notable"]].copy()
|
| 112 |
+
if notable.empty:
|
| 113 |
+
st.info("No candles crossed the sensitivity threshold for this session.")
|
| 114 |
+
else:
|
| 115 |
+
notable["Whale Alert"] = notable["Volume"] >= whale_threshold
|
| 116 |
+
table = notable[["Volume", "Vol_Ratio", "Size", "Sentiment", "Close", "Pct_Change", "Whale Alert"]]
|
| 117 |
+
table.index.name = "Datetime"
|
| 118 |
+
st.dataframe(
|
| 119 |
+
table.style.format(
|
| 120 |
+
{"Volume": "{:,.0f}", "Vol_Ratio": "{:.1f}x", "Close": "${:.2f}", "Pct_Change": "{:+.2f}%"}
|
| 121 |
+
),
|
| 122 |
+
use_container_width=True,
|
| 123 |
+
height=400,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
st.markdown("### Cumulative Buy/Sell Delta")
|
| 127 |
+
chart_df = df[["Cum_Delta"]].copy()
|
| 128 |
+
chart_df.index = chart_df.index.strftime("%H:%M")
|
| 129 |
+
st.line_chart(chart_df)
|
| 130 |
+
|
| 131 |
+
total_buy = df[df["Delta"] > 0]["Delta"].sum()
|
| 132 |
+
total_sell = abs(df[df["Delta"] < 0]["Delta"].sum())
|
| 133 |
+
net = total_buy - total_sell
|
| 134 |
+
|
| 135 |
+
whale_buys = df[(df["Size"] == "WHALE") & (df["Sentiment"] == "BUY")]["Volume"].sum()
|
| 136 |
+
whale_sells = df[(df["Size"] == "WHALE") & (df["Sentiment"] == "SELL")]["Volume"].sum()
|
| 137 |
+
inst_buys = df[(df["Size"].isin(["INSTITUTIONAL", "WHALE"])) & (df["Sentiment"] == "BUY")]["Volume"].sum()
|
| 138 |
+
inst_sells = df[(df["Size"].isin(["INSTITUTIONAL", "WHALE"])) & (df["Sentiment"] == "SELL")]["Volume"].sum()
|
| 139 |
+
|
| 140 |
+
st.markdown("### Session Analysis")
|
| 141 |
+
colA, colB, colC = st.columns(3)
|
| 142 |
+
with colA:
|
| 143 |
+
st.markdown("**Overall**")
|
| 144 |
+
st.write(f"Buy volume: {total_buy:,.0f}")
|
| 145 |
+
st.write(f"Sell volume: {total_sell:,.0f}")
|
| 146 |
+
st.write(f"Net delta: {net:,.0f}")
|
| 147 |
+
st.write(f"Buy/Sell ratio: {(total_buy / total_sell) if total_sell > 0 else 0:.2f}x")
|
| 148 |
+
with colB:
|
| 149 |
+
st.markdown("**Whale tier**")
|
| 150 |
+
st.write(f"Buy: {whale_buys:,.0f}")
|
| 151 |
+
st.write(f"Sell: {whale_sells:,.0f}")
|
| 152 |
+
st.write(f"Net: {whale_buys - whale_sells:,.0f}")
|
| 153 |
+
with colC:
|
| 154 |
+
st.markdown("**Institutional+**")
|
| 155 |
+
st.write(f"Buy: {inst_buys:,.0f}")
|
| 156 |
+
st.write(f"Sell: {inst_sells:,.0f}")
|
| 157 |
+
st.write(f"Net: {inst_buys - inst_sells:,.0f}")
|
| 158 |
+
|
| 159 |
+
status = "π’ ACCUMULATION (Bullish)" if net > 0 else "π΄ DISTRIBUTION (Bearish)"
|
| 160 |
+
st.markdown(f"## Market Sentiment: {status}")
|
| 161 |
+
|
| 162 |
+
st.markdown("### Volume by Size Category")
|
| 163 |
+
rows = []
|
| 164 |
+
total_vol = df["Volume"].sum()
|
| 165 |
+
for size in ["WHALE", "INSTITUTIONAL", "LARGE", "MEDIUM", "RETAIL"]:
|
| 166 |
+
vol = df[df["Size"] == size]["Volume"].sum()
|
| 167 |
+
count = len(df[df["Size"] == size])
|
| 168 |
+
pct = (vol / total_vol * 100) if total_vol > 0 else 0
|
| 169 |
+
rows.append({"Size": size, "Volume": vol, "% of Total": round(pct, 1), "Candles": count})
|
| 170 |
+
st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
|
| 171 |
+
|
| 172 |
+
st.caption(
|
| 173 |
+
"Data source: yfinance (Yahoo Finance), unofficial and delayed. "
|
| 174 |
+
"Cached for 2 minutes β use the Refresh button in the sidebar for the latest data."
|
| 175 |
+
)
|
| 176 |
|
| 177 |
|
| 178 |
+
# =========================================================
|
| 179 |
+
# TAB 2: PEAK EXHAUSTION DETECTOR
|
| 180 |
+
# =========================================================
|
| 181 |
+
|
| 182 |
+
DEFAULT_PEAK_TICKERS = [
|
| 183 |
+
"SOL-USD", "SLMT", "BTC-USD", "GC=F", "GPUS", "LLY", "MSFT", "NVDA",
|
| 184 |
+
"AIIO", "^IXIC", "IAUP.L", "PLTR", "MSTR", "CVX", "BZ=F", "CRML", "ABTC", "^FTSE",
|
| 185 |
+
]
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_clean_peak_data(ticker: str) -> pd.DataFrame:
|
| 189 |
+
df = yf.download(ticker, start="2018-01-01", progress=False)
|
| 190 |
+
if df.empty:
|
| 191 |
+
return df
|
| 192 |
+
if isinstance(df.columns, pd.MultiIndex):
|
| 193 |
+
df.columns = df.columns.get_level_values(0)
|
| 194 |
+
return df.reset_index()
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def label_peaks(df: pd.DataFrame, target_drop: float, window: int) -> pd.DataFrame:
|
| 198 |
+
d = df.copy()
|
| 199 |
+
d["Peak"] = 0
|
| 200 |
+
w = 10
|
| 201 |
+
for i in range(w, len(d) - w):
|
| 202 |
+
if d["High"].iloc[i] == d["High"].iloc[i - w : i + w].max():
|
| 203 |
+
if d["Low"].iloc[i + 1 : i + 15].min() <= (1 - target_drop) * d["High"].iloc[i]:
|
| 204 |
+
d.at[i, "Peak"] = 1
|
| 205 |
+
d["Target"] = d["Peak"].rolling(window=window).max().shift(-window).fillna(0)
|
| 206 |
+
return d
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def add_peak_features(df: pd.DataFrame, vol_sensitivity: float) -> pd.DataFrame:
|
| 210 |
+
d = df.copy()
|
| 211 |
+
delta = d["Close"].diff()
|
| 212 |
+
gain = (delta.where(delta > 0, 0)).rolling(14).mean()
|
| 213 |
+
loss = (-delta.where(delta < 0, 0)).rolling(14).mean()
|
| 214 |
+
d["RSI"] = 100 - (100 / (1 + (gain / (loss + 1e-9))))
|
| 215 |
+
d["Div_Warning"] = ((d["High"] >= d["High"].shift(1)) & (d["RSI"] < d["RSI"].shift(1))).astype(int)
|
| 216 |
+
d["Vol_Rel"] = d["Volume"] / d["Volume"].rolling(20).mean()
|
| 217 |
+
d["Vol_Price_Inertia"] = (d["Vol_Rel"] * vol_sensitivity) / (abs(d["Close"].pct_change()) + 0.001)
|
| 218 |
+
d["EMA_20"] = d["Close"].ewm(span=20).mean()
|
| 219 |
+
d["Dist_EMA"] = (d["Close"] - d["EMA_20"]) / d["EMA_20"]
|
| 220 |
+
d["RSI_Blowoff_Band"] = d["Close"] * (1 + (80 - d["RSI"]) / 100)
|
| 221 |
+
return d.dropna()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@st.cache_data(ttl=6 * 3600, show_spinner="Training peak detection model...")
|
| 225 |
+
def run_peak_model(ticker: str, target_drop: float, window: int, vol_sensitivity: float):
|
| 226 |
+
df = get_clean_peak_data(ticker)
|
| 227 |
+
if df.empty:
|
| 228 |
+
return None
|
| 229 |
+
df = label_peaks(df, target_drop, window)
|
| 230 |
+
data = add_peak_features(df, vol_sensitivity)
|
| 231 |
+
if data.empty:
|
| 232 |
+
return None
|
| 233 |
+
features = ["RSI", "Dist_EMA", "Div_Warning", "Vol_Price_Inertia"]
|
| 234 |
+
X, y = data[features], data["Target"]
|
| 235 |
+
model = GradientBoostingClassifier(n_estimators=100, random_state=42)
|
| 236 |
+
model.fit(X, y)
|
| 237 |
+
data["Risk_Pct"] = model.predict_proba(X)[:, 1] * 100
|
| 238 |
+
return data
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def render_peak_detector():
|
| 242 |
+
st.title("π Peak Exhaustion Detector")
|
| 243 |
+
st.caption(
|
| 244 |
+
"Scores potential local price peaks using RSI divergence, distance from EMA20, "
|
| 245 |
+
"and a volume/price-inertia signal, via a Gradient Boosting model."
|
| 246 |
+
)
|
| 247 |
+
st.warning(
|
| 248 |
+
"β οΈ This model is fit and scored on the same historical data β there's no held-out "
|
| 249 |
+
"test period. The Risk % shows how closely current conditions match past peaks in "
|
| 250 |
+
"its own training data, not a validated out-of-sample forecast. Treat it as structured "
|
| 251 |
+
"pattern-matching against history, not a calibrated probability."
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
with st.sidebar:
|
| 255 |
+
st.markdown("---")
|
| 256 |
+
st.header("Peak Detector Settings")
|
| 257 |
+
pd_ticker = st.selectbox("Ticker", DEFAULT_PEAK_TICKERS, index=0, key="pd_ticker")
|
| 258 |
+
pd_custom = st.text_input("...or enter a custom ticker", value="", key="pd_custom")
|
| 259 |
+
target_drop = st.slider("Drop % that counts as a peak", 0.03, 0.15, 0.06, 0.01, key="pd_drop")
|
| 260 |
+
window = st.slider("Forward warning window (days)", 3, 15, 5, 1, key="pd_window")
|
| 261 |
+
vol_sensitivity = st.slider("Volume sensitivity", 0.5, 3.0, 1.0, 0.1, key="pd_vol")
|
| 262 |
+
if st.button("π Retrain model", key="pd_refresh"):
|
| 263 |
+
run_peak_model.clear()
|
| 264 |
+
|
| 265 |
+
ticker = pd_custom.strip().upper() if pd_custom.strip() else pd_ticker
|
| 266 |
+
|
| 267 |
+
data = run_peak_model(ticker, target_drop, window, vol_sensitivity)
|
| 268 |
+
if data is None or data.empty:
|
| 269 |
+
st.error(f"No usable data for '{ticker}'.")
|
| 270 |
+
return
|
| 271 |
+
|
| 272 |
+
latest = data.iloc[-1]
|
| 273 |
+
status = "π΄ CRITICAL" if latest["Risk_Pct"] > 50 else "π’ STABLE"
|
| 274 |
+
|
| 275 |
+
st.subheader(f"{ticker}")
|
| 276 |
+
c1, c2, c3 = st.columns(3)
|
| 277 |
+
c1.metric("Status", status)
|
| 278 |
+
c2.metric("Risk %", f"{latest['Risk_Pct']:.1f}%")
|
| 279 |
+
c3.metric("RSI", f"{latest['RSI']:.1f}")
|
| 280 |
+
|
| 281 |
+
plot_df = data.iloc[-240:].copy()
|
| 282 |
+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), sharex=True, gridspec_kw={"height_ratios": [2.5, 1]})
|
| 283 |
+
|
| 284 |
+
ax1.plot(plot_df["Date"], plot_df["Close"], color="black", linewidth=1)
|
| 285 |
+
ax1.fill_between(plot_df["Date"], plot_df["Close"], plot_df["RSI_Blowoff_Band"], color="red", alpha=0.1)
|
| 286 |
+
|
| 287 |
+
risk_days = plot_df[plot_df["Risk_Pct"] > 50]
|
| 288 |
+
ax1.scatter(risk_days["Date"], risk_days["High"] * 1.02, color="red", marker="D", s=50)
|
| 289 |
+
for _, row in risk_days.iterrows():
|
| 290 |
+
ax1.text(row["Date"], row["High"] * 1.03, "!", color="red", fontweight="bold", ha="center")
|
| 291 |
+
|
| 292 |
+
ax1.set_title(f"{ticker} | Price vs Risk Heatmap")
|
| 293 |
+
|
| 294 |
+
ax2.fill_between(plot_df["Date"], 0, plot_df["Risk_Pct"], color="purple", alpha=0.4)
|
| 295 |
+
ax2.axhline(50, color="red", linestyle="--", alpha=0.3)
|
| 296 |
+
ax2.set_ylabel("Drop Risk %")
|
| 297 |
+
|
| 298 |
+
plt.tight_layout()
|
| 299 |
+
st.pyplot(fig)
|
| 300 |
+
plt.close(fig)
|
| 301 |
+
|
| 302 |
+
st.caption(
|
| 303 |
+
"Data source: yfinance (Yahoo Finance), daily bars since 2018. "
|
| 304 |
+
"Model retrains on parameter changes and is cached for 6 hours."
|
| 305 |
)
|
| 306 |
|
| 307 |
+
|
| 308 |
+
# =========================================================
|
| 309 |
+
# MAIN LAYOUT
|
| 310 |
+
# =========================================================
|
| 311 |
+
|
| 312 |
+
tab1, tab2 = st.tabs(["π Whale Monitor", "π Peak Detector"])
|
| 313 |
+
|
| 314 |
+
with tab1:
|
| 315 |
+
render_whale_monitor()
|
| 316 |
+
|
| 317 |
+
with tab2:
|
| 318 |
+
render_peak_detector()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|