Trebor1009 commited on
Commit
7213a0d
·
verified ·
1 Parent(s): 976edb8

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +51 -29
src/streamlit_app.py CHANGED
@@ -130,13 +130,14 @@ def get_avg_daily_volumes(tickers_tuple):
130
  """Bulk-fetch ~1 month of daily bars to compute each ticker's typical daily volume."""
131
  avg_vols = {}
132
  batch_size = 150
133
- total_batches = max(1, (len(tickers_tuple) + batch_size - 1) // batch_size)
 
134
  progress = st.progress(0, text="Fetching volume baselines...")
135
 
136
- for b, i in enumerate(range(0, len(tickers_tuple), batch_size)):
137
- batch = tickers_tuple[i:i + batch_size]
138
  try:
139
- data = yf.download(list(batch), period="1mo", interval="1d", group_by="ticker",
140
  progress=False, threads=True)
141
  except Exception:
142
  progress.progress((b + 1) / total_batches)
@@ -144,11 +145,18 @@ def get_avg_daily_volumes(tickers_tuple):
144
 
145
  for ticker in batch:
146
  try:
147
- try:
148
- raw = data[ticker]
149
- except Exception:
150
- raw = data
151
- vol = raw["Volume"].dropna()
 
 
 
 
 
 
 
152
  if len(vol) >= 5:
153
  avg_vols[ticker] = float(vol.mean())
154
  except Exception:
@@ -166,13 +174,14 @@ def run_premarket_scan(universe_label, tickers_tuple, min_pct_avg_vol, min_abs_v
166
 
167
  results = []
168
  batch_size = 150
169
- total_batches = max(1, (len(tickers_tuple) + batch_size - 1) // batch_size)
 
170
  progress = st.progress(0, text="Scanning premarket activity...")
171
 
172
- for b, i in enumerate(range(0, len(tickers_tuple), batch_size)):
173
- batch = tickers_tuple[i:i + batch_size]
174
  try:
175
- data = yf.download(list(batch), period="1d", interval="1m", prepost=True,
176
  group_by="ticker", progress=False, threads=True)
177
  except Exception:
178
  progress.progress((b + 1) / total_batches, text=f"Batch {b + 1}/{total_batches} failed, continuing...")
@@ -180,11 +189,18 @@ def run_premarket_scan(universe_label, tickers_tuple, min_pct_avg_vol, min_abs_v
180
 
181
  for ticker in batch:
182
  try:
183
- try:
184
- raw = data[ticker]
185
- except Exception:
186
- raw = data
187
- df = raw.dropna(subset=["Close"])
 
 
 
 
 
 
 
188
  if df.empty:
189
  continue
190
 
@@ -193,7 +209,7 @@ def run_premarket_scan(universe_label, tickers_tuple, min_pct_avg_vol, min_abs_v
193
  df.index = df.index.tz_convert("America/New_York")
194
  else:
195
  df = df.copy()
196
- df.index = df.index.tz_localize("America/New_York")
197
 
198
  premarket = df[df.index.time < dt_time(9, 30)]
199
  if premarket.empty:
@@ -208,7 +224,7 @@ def run_premarket_scan(universe_label, tickers_tuple, min_pct_avg_vol, min_abs_v
208
  if pm_volume < min_abs_volume or pct_of_avg < min_pct_avg_vol:
209
  continue
210
 
211
- open_price = premarket["Close"].iloc[0]
212
  last_price = premarket["Close"].iloc[-1]
213
  pct_change = ((last_price - open_price) / open_price * 100) if open_price else np.nan
214
 
@@ -553,7 +569,7 @@ def render_peak_detector():
553
 
554
 
555
  # =========================================================
556
- # TAB 3: SNIPER SCANNER (historical analog / triple-positive setup scanner)
557
  # =========================================================
558
 
559
  def sniper_rsi(series, period=14):
@@ -693,11 +709,17 @@ def run_full_scan(universe_label, extra_tickers_tuple, rsi_threshold, stretch_th
693
 
694
  for ticker in batch:
695
  try:
696
- try:
697
- raw = data[ticker]
698
- except Exception:
699
- raw = data
700
- df = raw.dropna()
 
 
 
 
 
 
701
  if len(df) < 200:
702
  continue
703
  result = analyze_ticker(df, rsi_threshold, stretch_threshold, strict_window, lookback, win_rate_min)
@@ -906,7 +928,7 @@ def render_sniper_tab():
906
 
907
 
908
  # =========================================================
909
- # ANALOG PATH PROJECTION (used by the Signal Tracker chart)
910
  # =========================================================
911
 
912
  ANALOG_LOOKBACK = 60
@@ -945,7 +967,7 @@ def compute_analog_projection(ticker: str, flag_date_str: str, lookback=ANALOG_L
945
  end_idx = min(end_idx, len(close) - 1)
946
 
947
  if end_idx - lookback - forward < 5:
948
- return None # not enough pre-flag history for this method
949
 
950
  matches = _similarity_matches(close, end_idx, lookback, forward)
951
  if not matches:
@@ -991,7 +1013,7 @@ def compute_analog_projection(ticker: str, flag_date_str: str, lookback=ANALOG_L
991
 
992
 
993
  # =========================================================
994
- # TAB 4: SIGNAL TRACKER (predicted vs. actual, out-of-sample)
995
  # =========================================================
996
 
997
  def render_signal_tracker():
 
130
  """Bulk-fetch ~1 month of daily bars to compute each ticker's typical daily volume."""
131
  avg_vols = {}
132
  batch_size = 150
133
+ tickers_list = list(tickers_tuple)
134
+ total_batches = max(1, (len(tickers_list) + batch_size - 1) // batch_size)
135
  progress = st.progress(0, text="Fetching volume baselines...")
136
 
137
+ for b, i in enumerate(range(0, len(tickers_list), batch_size)):
138
+ batch = tickers_list[i:i + batch_size]
139
  try:
140
+ data = yf.download(batch, period="1mo", interval="1d", group_by="ticker",
141
  progress=False, threads=True)
142
  except Exception:
143
  progress.progress((b + 1) / total_batches)
 
145
 
146
  for ticker in batch:
147
  try:
148
+ # Safe MultiIndex column extraction checking
149
+ if isinstance(data.columns, pd.MultiIndex):
150
+ if ticker in data.columns.levels[0]:
151
+ vol = data[ticker]["Volume"].dropna()
152
+ else:
153
+ continue
154
+ else:
155
+ if len(batch) == 1:
156
+ vol = data["Volume"].dropna()
157
+ else:
158
+ continue
159
+
160
  if len(vol) >= 5:
161
  avg_vols[ticker] = float(vol.mean())
162
  except Exception:
 
174
 
175
  results = []
176
  batch_size = 150
177
+ tickers_list = list(tickers_tuple)
178
+ total_batches = max(1, (len(tickers_list) + batch_size - 1) // batch_size)
179
  progress = st.progress(0, text="Scanning premarket activity...")
180
 
181
+ for b, i in enumerate(range(0, len(tickers_list), batch_size)):
182
+ batch = tickers_list[i:i + batch_size]
183
  try:
184
+ data = yf.download(batch, period="1d", interval="1m", prepost=True,
185
  group_by="ticker", progress=False, threads=True)
186
  except Exception:
187
  progress.progress((b + 1) / total_batches, text=f"Batch {b + 1}/{total_batches} failed, continuing...")
 
189
 
190
  for ticker in batch:
191
  try:
192
+ # Bulletproof structural check for MultiIndex extraction layers
193
+ if isinstance(data.columns, pd.MultiIndex):
194
+ if ticker in data.columns.levels[0]:
195
+ df = data[ticker].dropna(subset=["Close"])
196
+ else:
197
+ continue
198
+ else:
199
+ if len(batch) == 1:
200
+ df = data.dropna(subset=["Close"])
201
+ else:
202
+ continue
203
+
204
  if df.empty:
205
  continue
206
 
 
209
  df.index = df.index.tz_convert("America/New_York")
210
  else:
211
  df = df.copy()
212
+ df.index = df.index.tz_localize("UTC").tz_convert("America/New_York")
213
 
214
  premarket = df[df.index.time < dt_time(9, 30)]
215
  if premarket.empty:
 
224
  if pm_volume < min_abs_volume or pct_of_avg < min_pct_avg_vol:
225
  continue
226
 
227
+ open_price = premarket["Open"].iloc[0]
228
  last_price = premarket["Close"].iloc[-1]
229
  pct_change = ((last_price - open_price) / open_price * 100) if open_price else np.nan
230
 
 
569
 
570
 
571
  # =========================================================
572
+ # TAB 3: SNIPER SCANNER
573
  # =========================================================
574
 
575
  def sniper_rsi(series, period=14):
 
709
 
710
  for ticker in batch:
711
  try:
712
+ if isinstance(data.columns, pd.MultiIndex):
713
+ if ticker in data.columns.levels[0]:
714
+ df = data[ticker].dropna()
715
+ else:
716
+ continue
717
+ else:
718
+ if len(batch) == 1:
719
+ df = data.dropna()
720
+ else:
721
+ continue
722
+
723
  if len(df) < 200:
724
  continue
725
  result = analyze_ticker(df, rsi_threshold, stretch_threshold, strict_window, lookback, win_rate_min)
 
928
 
929
 
930
  # =========================================================
931
+ # ANALOG PATH PROJECTION
932
  # =========================================================
933
 
934
  ANALOG_LOOKBACK = 60
 
967
  end_idx = min(end_idx, len(close) - 1)
968
 
969
  if end_idx - lookback - forward < 5:
970
+ return None
971
 
972
  matches = _similarity_matches(close, end_idx, lookback, forward)
973
  if not matches:
 
1013
 
1014
 
1015
  # =========================================================
1016
+ # TAB 4: SIGNAL TRACKER
1017
  # =========================================================
1018
 
1019
  def render_signal_tracker():