Trebor1009 commited on
Commit
a8e83c3
Β·
verified Β·
1 Parent(s): 82696f6

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +182 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,184 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import yfinance as yf
3
+ import pandas as pd
4
+
5
+ st.set_page_config(page_title="Whale Monitor", page_icon="πŸ‹", layout="wide")
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 fetch_data(sym: str) -> pd.DataFrame:
28
+ try:
29
+ ticker = yf.Ticker(sym)
30
+ return ticker.history(period="5d", interval="1m")
31
+ except Exception:
32
+ return pd.DataFrame()
33
+
34
+
35
+ if not symbol:
36
+ st.info("Enter a ticker symbol in the sidebar to begin.")
37
+ st.stop()
38
+
39
+ df = fetch_data(symbol)
40
+
41
+ if df.empty:
42
+ st.error(f"No data available for '{symbol}'. Check the ticker symbol and try again.")
43
+ st.stop()
44
+
45
+ # Keep only the most recent trading session present in the data
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):
72
+ if row["Price_Change"] > 0:
73
+ return row["Volume"], "BUY"
74
+ elif row["Price_Change"] < 0:
75
+ return -row["Volume"], "SELL"
76
+ return 0, "NEUTRAL"
77
+
78
+
79
+ df[["Delta", "Sentiment"]] = df.apply(lambda r: pd.Series(get_sentiment(r)), axis=1)
80
+ df["Cum_Delta"] = df["Delta"].cumsum()
81
+
82
+
83
+ def classify(vol, median):
84
+ ratio = vol / median if median > 0 else 0
85
+ if ratio >= 10:
86
+ return "WHALE"
87
+ elif ratio >= 5:
88
+ return "INSTITUTIONAL"
89
+ elif ratio >= 2:
90
+ return "LARGE"
91
+ elif ratio >= 1:
92
+ return "MEDIUM"
93
+ return "RETAIL"
94
+
95
+
96
+ df["Size"] = df["Volume"].apply(lambda v: classify(v, median_vol))
97
+
98
+ # ---------- Header metrics ----------
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
+ # ---------- Notable activity table ----------
111
+ st.markdown("### Notable Activity")
112
+ notable = df[df["is_notable"]].copy()
113
+
114
+ if notable.empty:
115
+ st.info("No candles crossed the sensitivity threshold for this session.")
116
+ else:
117
+ notable["Whale Alert"] = notable["Volume"] >= whale_threshold
118
+ table = notable[["Volume", "Vol_Ratio", "Size", "Sentiment", "Close", "Pct_Change", "Whale Alert"]]
119
+ table.index.name = "Datetime"
120
+ st.dataframe(
121
+ table.style.format(
122
+ {
123
+ "Volume": "{:,.0f}",
124
+ "Vol_Ratio": "{:.1f}x",
125
+ "Close": "${:.2f}",
126
+ "Pct_Change": "{:+.2f}%",
127
+ }
128
+ ),
129
+ use_container_width=True,
130
+ height=400,
131
+ )
132
+
133
+ # ---------- Cumulative delta chart ----------
134
+ st.markdown("### Cumulative Buy/Sell Delta")
135
+ st.line_chart(df["Cum_Delta"])
136
+
137
+ # ---------- Session analysis ----------
138
+ total_buy = df[df["Delta"] > 0]["Delta"].sum()
139
+ total_sell = abs(df[df["Delta"] < 0]["Delta"].sum())
140
+ net = total_buy - total_sell
141
+
142
+ whale_buys = df[(df["Size"] == "WHALE") & (df["Sentiment"] == "BUY")]["Volume"].sum()
143
+ whale_sells = df[(df["Size"] == "WHALE") & (df["Sentiment"] == "SELL")]["Volume"].sum()
144
+ inst_buys = df[(df["Size"].isin(["INSTITUTIONAL", "WHALE"])) & (df["Sentiment"] == "BUY")]["Volume"].sum()
145
+ inst_sells = df[(df["Size"].isin(["INSTITUTIONAL", "WHALE"])) & (df["Sentiment"] == "SELL")]["Volume"].sum()
146
+
147
+ st.markdown("### Session Analysis")
148
+ colA, colB, colC = st.columns(3)
149
+ with colA:
150
+ st.markdown("**Overall**")
151
+ st.write(f"Buy volume: {total_buy:,.0f}")
152
+ st.write(f"Sell volume: {total_sell:,.0f}")
153
+ st.write(f"Net delta: {net:,.0f}")
154
+ st.write(f"Buy/Sell ratio: {(total_buy / total_sell) if total_sell > 0 else 0:.2f}x")
155
+ with colB:
156
+ st.markdown("**Whale tier**")
157
+ st.write(f"Buy: {whale_buys:,.0f}")
158
+ st.write(f"Sell: {whale_sells:,.0f}")
159
+ st.write(f"Net: {whale_buys - whale_sells:,.0f}")
160
+ with colC:
161
+ st.markdown("**Institutional+**")
162
+ st.write(f"Buy: {inst_buys:,.0f}")
163
+ st.write(f"Sell: {inst_sells:,.0f}")
164
+ st.write(f"Net: {inst_buys - inst_sells:,.0f}")
165
+
166
+ status = "🟒 ACCUMULATION (Bullish)" if net > 0 else "πŸ”΄ DISTRIBUTION (Bearish)"
167
+ st.markdown(f"## Market Sentiment: {status}")
168
+
169
+ # ---------- Volume by size category ----------
170
+ st.markdown("### Volume by Size Category")
171
+ rows = []
172
+ total_vol = df["Volume"].sum()
173
+ for size in ["WHALE", "INSTITUTIONAL", "LARGE", "MEDIUM", "RETAIL"]:
174
+ vol = df[df["Size"] == size]["Volume"].sum()
175
+ count = len(df[df["Size"] == size])
176
+ pct = (vol / total_vol * 100) if total_vol > 0 else 0
177
+ rows.append({"Size": size, "Volume": vol, "% of Total": round(pct, 1), "Candles": count})
178
+
179
+ st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
180
 
181
+ st.caption(
182
+ "Data source: yfinance (Yahoo Finance), unofficial and delayed. "
183
+ "Cached for 2 minutes β€” use the Refresh button in the sidebar for the latest data."
184
+ )