Spaces:
Running

Trebor1009 commited on
Commit
2c24a77
Β·
verified Β·
1 Parent(s): 86a9915

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +541 -292
src/streamlit_app.py CHANGED
@@ -567,347 +567,596 @@ def render_peak_detector():
567
 
568
 
569
  # =========================================================
570
- # TAB 3: BOTTOM SCANNER
571
  # =========================================================
572
 
573
- def sniper_rsi(series, period=14):
574
- delta = series.diff()
575
- gain = (delta.where(delta > 0, 0)).ewm(alpha=1 / period, adjust=False).mean()
576
- loss = (-delta.where(delta < 0, 0)).ewm(alpha=1 / period, adjust=False).mean()
577
- rs = gain / (loss + 1e-9)
578
- return 100 - (100 / (1 + rs))
579
-
580
-
581
- def get_strict_stats(df, rsi, sma, current_stretch, rsi_threshold, strict_window,
582
- forward_1d=1, forward_5d=5, forward_3m=63):
583
- close = df["Close"].values
584
- stretches = ((close - sma.values) / sma.values) * 100
585
- ret_1d = (pd.Series(close).shift(-forward_1d).values - close) / close
586
- ret_5d = (pd.Series(close).shift(-forward_5d).values - close) / close
587
- ret_3m = (pd.Series(close).shift(-forward_3m).values - close) / close
588
- mask_stretch_lower = stretches >= current_stretch - strict_window
589
- mask_stretch_upper = stretches <= current_stretch + strict_window
590
- mask_rsi_threshold = (rsi < rsi_threshold).values
591
- mask = mask_stretch_lower & mask_stretch_upper & mask_rsi_threshold
592
- valid_mask = mask & (~np.isnan(ret_3m))
593
- match_indices = np.where(valid_mask)[0]
594
- if len(match_indices) < 10:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595
  return None
596
- return {
597
- "count": len(match_indices),
598
- "avg_1d": np.mean(ret_1d[valid_mask]) * 100,
599
- "avg_5d": np.mean(ret_5d[valid_mask]) * 100,
600
- "avg_3m": np.mean(ret_3m[valid_mask]) * 100,
601
- "win_3m": (ret_3m[valid_mask] > 0).mean() * 100,
602
- "match_dates": df.index[match_indices],
603
- "match_prices": close[match_indices],
604
- }
605
 
 
 
 
606
 
607
- def analyze_ticker(df, rsi_threshold, stretch_threshold, strict_window, lookback, win_rate_min=80):
608
- df = df.dropna()
609
- if len(df) < 200:
610
  return None
611
- close = df["Close"].astype(float)
612
- rsi = sniper_rsi(close)
613
- sma20 = close.rolling(20).mean()
614
- current_stretch = ((close.iloc[-1] - sma20.iloc[-1]) / sma20.iloc[-1]) * 100
615
- result = {
616
- "rsi": rsi.iloc[-1], "stretch": current_stretch, "price": close.iloc[-1],
617
- "stats": None, "fractal_target": None, "df": df,
618
- "rsi_series": rsi, "signal_met": False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619
  }
 
 
 
 
 
 
 
620
  try:
621
- hist = np.squeeze(close.values[:-90])
622
- if hist.ndim == 1 and len(hist) > lookback:
623
- curr = close.values[-lookback:]
624
- curr_n = (curr - np.mean(curr)) / (np.std(curr) + 1e-9)
625
- wins = sliding_window_view(hist, lookback)
626
- wins_n = (wins - np.mean(wins, axis=1, keepdims=True)) / (np.std(wins, axis=1, keepdims=True) + 1e-9)
627
- corrs = np.dot(wins_n, curr_n) / lookback
628
- top_idx = np.argmax(corrs)
629
- result["fractal_target"] = close.values[-1] * (
630
- close.values[top_idx + lookback] / close.values[top_idx + lookback - 1]
631
- )
632
  except Exception:
633
- pass
634
- if result["rsi"] < rsi_threshold and current_stretch < stretch_threshold:
635
- stats = get_strict_stats(df, rsi, sma20, current_stretch, rsi_threshold, strict_window)
636
- result["stats"] = stats
637
- if stats:
638
- is_triple_positive = stats["avg_1d"] > 0 and stats["avg_5d"] > 0 and stats["avg_3m"] > 0
639
- result["signal_met"] = is_triple_positive and stats["win_3m"] >= win_rate_min
640
- return result
641
-
642
-
643
- def get_sniper_ticker_data(ticker: str) -> pd.DataFrame:
644
- df = yf.download(ticker, period="max", interval="1d", progress=False)
645
- if df.empty:
646
- return df
647
- if isinstance(df.columns, pd.MultiIndex):
648
- df.columns = df.columns.get_level_values(0)
649
- return df.dropna()
650
 
651
 
652
- @st.cache_data(ttl=12 * 3600, show_spinner=False)
653
- def run_full_scan(universe_label, extra_tickers_tuple, rsi_threshold, stretch_threshold,
654
- strict_window, lookback, win_rate_min, _tickers):
655
- results = []
656
- batch_size = 10
657
- total_batches = max(1, (len(_tickers) + batch_size - 1) // batch_size)
658
- progress = st.progress(0, text="Starting scan...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
659
 
660
- for b, i in enumerate(range(0, len(_tickers), batch_size)):
661
- batch = _tickers[i:i + batch_size]
662
  try:
663
- data = yf.download(batch, period="max", interval="1d", group_by="ticker",
664
- progress=False, threads=True)
 
665
  except Exception:
666
- progress.progress((b + 1) / total_batches,
667
- text=f"Batch {b + 1}/{total_batches} failed, continuing...")
668
  continue
669
- for ticker in batch:
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  try:
671
- try:
672
- raw = data[ticker]
673
- except Exception:
674
- raw = data
675
- df = raw.dropna()
676
- if len(df) < 200:
 
 
 
677
  continue
678
- result = analyze_ticker(df, rsi_threshold, stretch_threshold,
679
- strict_window, lookback, win_rate_min)
680
- if result and result["signal_met"]:
681
- stats = result["stats"]
682
- results.append({
683
- "Ticker": ticker,
684
- "Price": round(result["price"], 2),
685
- "RSI": round(result["rsi"], 1),
686
- "Stretch %": round(result["stretch"], 2),
687
- "Matches": stats["count"],
688
- "Avg_1D": round(stats["avg_1d"], 2),
689
- "Avg_5D": round(stats["avg_5d"], 2),
690
- "Avg_3M": round(stats["avg_3m"], 2),
691
- "WinRate_3M": round(stats["win_3m"], 1),
692
- })
 
 
 
 
 
 
 
 
 
 
 
 
693
  except Exception:
 
694
  continue
695
- progress.progress((b + 1) / total_batches, text=f"Scanned batch {b + 1}/{total_batches}...")
696
 
697
- progress.empty()
698
- return pd.DataFrame(results)
699
 
 
 
 
700
 
701
- def render_sniper_dashboard(ticker, result):
702
- df = result["df"]
703
- rsi_series = result["rsi_series"]
704
- stats = result["stats"]
705
- target = result["fractal_target"]
706
-
707
- fig = plt.figure(figsize=(12, 8))
708
- gs = fig.add_gridspec(2, 2)
709
- ax1 = fig.add_subplot(gs[0, :])
710
- ax1.plot(df.index, df["Close"], color="gray", alpha=0.3, label="History")
711
- recent = df.tail(120)
712
- ax1.plot(recent.index, recent["Close"], color="black", linewidth=1.5, label="Current Trend")
713
- if stats:
714
- ax1.scatter(stats["match_dates"], stats["match_prices"],
715
- color="limegreen", s=20, zorder=5, label="Strict Matches")
716
- if target is not None:
717
- ax1.axhline(target, color="blue", ls="--", alpha=0.6,
718
- label="Single best-match analog (not a target)")
719
- ax1.set_title(f"{ticker}", fontsize=16, fontweight="bold")
720
- ax1.legend(loc="upper left", fontsize=9)
721
- ax1.grid(True, alpha=0.1)
722
- if stats:
723
- stats_text = (
724
- f"Historical Matches: {stats['count']}\n"
725
- f"Avg Change 1D: {stats['avg_1d']:+.2f}%\n"
726
- f"Avg Change 5D: {stats['avg_5d']:+.2f}%\n"
727
- f"Avg Change 3M: {stats['avg_3m']:+.2f}%\n"
728
- f"3M Win Rate: {stats['win_3m']:.1f}% (n={stats['count']})"
729
- )
730
- ax1.text(0.98, 0.05, stats_text, transform=ax1.transAxes, va="bottom", ha="right",
731
- bbox=dict(boxstyle="round", facecolor="white", alpha=0.9, edgecolor="darkgreen"),
732
- fontsize=10, family="monospace")
733
- ax2 = fig.add_subplot(gs[1, 0])
734
- ax2.plot(recent.index, rsi_series.tail(120), color="purple")
735
- ax2.axhline(result["rsi"], color="orange", ls=":")
736
- ax2.set_title(f"RSI: {result['rsi']:.1f}")
737
- ax3 = fig.add_subplot(gs[1, 1])
738
- if stats:
739
- horizons = ["1D", "5D", "3M"]
740
- values = [stats["avg_1d"], stats["avg_5d"], stats["avg_3m"]]
741
- ax3.bar(horizons, values, color="limegreen", alpha=0.8)
742
- ax3.axhline(0, color="black", linewidth=0.8)
743
- ax3.set_title("Historical Edge by Horizon")
744
- else:
745
- ax3.set_title("No matches to show")
746
- plt.tight_layout()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
  st.pyplot(fig)
748
  plt.close(fig)
749
 
750
 
751
- def render_quick_forecast(ticker: str):
752
- raw = get_sniper_ticker_data(ticker)
753
- if raw.empty:
754
- st.error(f"No data for '{ticker}'.")
755
- return
756
- anchor_date = raw.index[-1]
757
- context = raw[raw.index >= (anchor_date - pd.Timedelta(days=90))]
758
- current_price = raw["Close"].iloc[-1]
759
- projection = compute_analog_projection(ticker, str(anchor_date.date()))
760
-
761
- fig, ax = plt.subplots(figsize=(12, 5))
762
- if not context.empty:
763
- ax.plot(context.index, context["Close"], color="black", linewidth=1.5,
764
- marker="o", markersize=2, label="Price")
765
- ax.axvline(anchor_date, color="red", ls="-", alpha=0.4, label="Today")
766
- ax.axhline(current_price, color="gray", ls=":", alpha=0.6, label="Current price")
767
- if projection:
768
- ax.plot(projection["future_dates"], projection["weighted_mean"],
769
- color="green", ls="--", linewidth=2, label="Analog-weighted projection")
770
- ax.fill_between(projection["future_dates"], projection["lower"], projection["upper"],
771
- color="green", alpha=0.15, label="Projection band (1Οƒ)")
772
- st.caption(
773
- f"Projection built from the {projection['match_count']} most similar non-overlapping "
774
- f"60-day windows in {ticker}'s own history (robust similarity: "
775
- f"{projection['robust_similarity']:.1f}%)."
776
  )
 
 
 
 
 
 
 
 
 
 
 
 
777
  else:
778
- st.info("Not enough history for this ticker to build a projection.")
779
- ax.set_title(f"{ticker} β€” forecast as of {anchor_date.date()}")
780
- ax.legend(loc="best", fontsize=9)
781
- ax.grid(True, alpha=0.1)
782
- st.pyplot(fig)
783
- plt.close(fig)
 
 
784
 
785
 
786
- def render_sniper_tab():
787
- st.title("πŸ“‰ Bottom Scanner")
 
 
788
  st.caption(
789
- "Looks for 'triple-positive' historical analog setups: today's RSI/SMA-stretch combination "
790
- "compared against similar conditions earlier in a ticker's own price history, scored by average "
791
- "forward returns and win rate."
792
- )
793
- st.warning(
794
- "⚠️ Two things worth keeping in mind:\n\n"
795
- "1. **Small samples** β€” many qualifying setups have only 10-30 historical matches. An '80% win rate' "
796
- "on 10 matches has a much wider true range than the headline number suggests.\n\n"
797
- "2. **Full-universe scans test thousands of tickers at once.** With that many tests, some will "
798
- "clear an 80%+ bar by chance alone. A hit is a reason to look closer, not a standalone signal.\n\n"
799
- "The dashed blue line ('best-match analog') is one single closest-matching historical window, "
800
- "shown for context β€” not a statistical price target."
801
  )
802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
803
  with st.sidebar:
804
  st.markdown("---")
805
- st.header("Bottom Scanner Settings")
806
- rsi_threshold = st.slider("RSI threshold (oversold below this)", 20, 60, 45, 1, key="sn_rsi")
807
- stretch_threshold = st.slider("Max SMA20 stretch %", -8.0, 0.0, -2.0, 0.5, key="sn_stretch")
808
- strict_window = st.slider("Match strictness (Β± stretch %)", 0.1, 2.0, 0.5, 0.1, key="sn_window")
809
- lookback = st.slider("Fractal lookback (days)", 20, 120, 60, 5, key="sn_lookback")
810
- win_rate_min = st.slider("Min 3M win rate to flag (%)", 50, 95, 80, 5, key="sn_winrate")
811
-
812
- settings = {
813
- "rsi_threshold": rsi_threshold, "stretch_threshold": stretch_threshold,
814
- "strict_window": strict_window, "lookback": lookback, "win_rate_min": win_rate_min,
815
- }
816
 
 
817
  st.subheader("Analyze a single ticker")
818
- single_ticker = st.text_input("Ticker", value="BTC-USD", key="sn_single").strip().upper()
819
- col_analyze, col_forecast = st.columns([1, 1])
820
- analyze_clicked = col_analyze.button("Analyze", key="sn_analyze_btn")
821
- forecast_clicked = col_forecast.button("Forecast", key="sn_forecast_btn")
822
-
823
- if analyze_clicked and single_ticker:
824
- raw = get_sniper_ticker_data(single_ticker)
825
- if raw.empty:
826
- st.error(f"No data for '{single_ticker}'.")
 
 
827
  else:
828
- result = analyze_ticker(raw, rsi_threshold, stretch_threshold,
829
- strict_window, lookback, win_rate_min)
830
- if result is None:
831
- st.error("Not enough history for this ticker.")
 
 
 
 
 
 
 
 
 
 
 
832
  else:
833
- entry_met = result["rsi"] < rsi_threshold and result["stretch"] < stretch_threshold
834
- if not entry_met:
835
- st.info(
836
- f"RSI {result['rsi']:.1f} / Stretch {result['stretch']:.2f}% β€” entry conditions "
837
- f"(RSI < {rsi_threshold}, stretch < {stretch_threshold}%) not currently met."
838
- )
839
- elif result["stats"] is None:
840
- st.info(
841
- f"Entry conditions met but fewer than 10 historical analogs found."
842
- )
843
- elif result["signal_met"]:
844
- st.success(
845
- f"βœ… Full signal met β€” {result['stats']['win_3m']:.1f}% historical 3M win rate "
846
- f"over {result['stats']['count']} matches."
847
- )
848
- if _log_configured() and st.button("πŸ“Œ Log this signal", key="sn_log_single"):
849
- hit_row = pd.DataFrame([{
850
- "Ticker": single_ticker, "Price": round(result["price"], 2),
851
- "RSI": round(result["rsi"], 1), "Stretch %": round(result["stretch"], 2),
852
- "Matches": result["stats"]["count"],
853
- "Avg_1D": round(result["stats"]["avg_1d"], 2),
854
- "Avg_5D": round(result["stats"]["avg_5d"], 2),
855
- "Avg_3M": round(result["stats"]["avg_3m"], 2),
856
- "WinRate_3M": round(result["stats"]["win_3m"], 1),
857
- }])
858
- if append_hits_to_log(hit_row, settings):
859
- st.success("Logged.")
860
- else:
861
- st.info(
862
- f"Entry conditions met but didn't clear the win-rate/triple-positive bar "
863
- f"({result['stats']['win_3m']:.1f}% win rate over {result['stats']['count']} matches)."
864
- )
865
- render_sniper_dashboard(single_ticker, result)
866
 
867
- if forecast_clicked and single_ticker:
868
- render_quick_forecast(single_ticker)
869
 
 
870
  st.markdown("---")
871
- st.subheader("Full universe scan")
 
 
 
 
 
 
 
 
872
  st.caption(
873
- "Scans your curated ticker list for setups meeting the full criteria. "
874
- "First run can take several minutes β€” results are cached for 12 hours.\n\n"
875
- f"{'βœ… Hits will be auto-saved to your signal log.' if _log_configured() else '⚠️ Signal log storage not configured β€” hits will NOT be saved.'}"
876
  )
877
- if st.button("πŸ” Run Full Universe Scan", key="sn_scan_btn"):
878
- tickers = get_clean_premarket_universe()
879
- if not tickers:
880
- st.error("No tickers loaded from the curated list.")
881
  else:
882
- st.write(f"Scanning {len(tickers)} tickers...")
883
- results_df = run_full_scan(
884
- "clean_list", tuple(), rsi_threshold, stretch_threshold,
885
- strict_window, lookback, win_rate_min, tuple(tickers),
 
 
 
 
 
 
 
 
 
886
  )
887
- st.session_state["sn_results"] = results_df
888
- if not results_df.empty and _log_configured():
889
- if append_hits_to_log(results_df, settings):
890
- st.success(f"Logged {len(results_df)} hit(s) to the signal tracker.")
891
 
892
- if "sn_results" in st.session_state:
893
- results_df = st.session_state["sn_results"]
894
- if results_df.empty:
895
- st.info("No tickers met the full signal criteria with current settings.")
896
  else:
897
- st.success(f"{len(results_df)} ticker(s) met the criteria.")
898
- sorted_df = results_df.sort_values("WinRate_3M", ascending=False).reset_index(drop=True)
899
- st.dataframe(sorted_df, use_container_width=True, hide_index=True)
900
- pick = st.selectbox("View chart for:", sorted_df["Ticker"].tolist(), key="sn_pick")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901
  if pick:
902
- raw = get_sniper_ticker_data(pick)
903
- if not raw.empty:
904
- result = analyze_ticker(raw, rsi_threshold, stretch_threshold,
905
- strict_window, lookback, win_rate_min)
906
- if result:
907
- render_sniper_dashboard(pick, result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
 
909
 
910
- # =========================================================
911
  # ANALOG PATH PROJECTION
912
  # =========================================================
913
 
@@ -1913,7 +2162,7 @@ The edge is mean-reversion β€” cutting at -5% destroys it.
1913
  tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
1914
  "πŸ‹ Whale Monitor",
1915
  "πŸ“ˆ Peak Detector",
1916
- "πŸ“‰ Bottom Scanner",
1917
  "πŸ—’οΈ Signal Tracker",
1918
  "🧭 Rotation Map",
1919
  "🎯 Combined Scanner",
@@ -1926,7 +2175,7 @@ with tab2:
1926
  render_peak_detector()
1927
 
1928
  with tab3:
1929
- render_sniper_tab()
1930
 
1931
  with tab4:
1932
  render_signal_tracker()
 
567
 
568
 
569
  # =========================================================
570
+ # TAB 3: SMALL-CAP PUMP SCANNER
571
  # =========================================================
572
 
573
+ # Signal thresholds (calibrated from LEDS/AIIO/GPUS/CXAI pre-pump analysis)
574
+ MAX_PRICE = 5.0
575
+ MIN_PRICE = 0.05
576
+ MIN_BARS = 30
577
+ MIN_VOL_DAYS = 15
578
+ COIL_VOL_THRESH = 0.4
579
+ COIL_MIN_DAYS = 3
580
+ COIL_BREAK_MIN = 0.8
581
+ RSI_COIL_MAX = 47
582
+ SURGE_VOL_MIN = 3.0
583
+ SURGE_RANGE_POS = 0.35
584
+ RSI_SURGE_MAX = 52
585
+ RANGE_POS_MAX = 0.35
586
+
587
+ HF_TOKEN = os.environ.get("HF_TOKEN")
588
+
589
+ # ── Constants ─────────────────────────────────────────────────────────────────
590
+ MAX_PRICE = 5.0 # sub-$5 universe
591
+ MIN_PRICE = 0.05 # below 5 cents = data noise
592
+ MIN_BARS = 30 # need at least 30 daily bars for indicators
593
+ MIN_VOL_DAYS = 15 # must have volume on 15 of last 20 days
594
+
595
+ # Pattern A thresholds
596
+ COIL_VOL_THRESH = 0.4 # quiet = vol below this fraction of 20MA
597
+ COIL_MIN_DAYS = 3 # must be quiet for this many consecutive days
598
+ COIL_BREAK_MIN = 0.8 # breakout vol must be at least this x 20MA
599
+ RSI_COIL_MAX = 47 # RSI must be below this for coil signal
600
+
601
+ # Pattern B thresholds
602
+ SURGE_VOL_MIN = 3.0 # today's vol must be >= this x 20MA
603
+ SURGE_RANGE_POS = 0.35 # close must be in top % of today's range
604
+ RSI_SURGE_MAX = 52 # RSI must be below this for surge signal
605
+
606
+ # Range position for "near 20-day low"
607
+ RANGE_POS_MAX = 0.35 # in bottom 35% of 20-day hi-lo range
608
+
609
+
610
+ # ── Feature engineering ───────────────────────────────────────────────────────
611
+
612
+ def compute_features(df: pd.DataFrame) -> pd.DataFrame | None:
613
+ """
614
+ Returns a DataFrame with all indicator columns, or None if insufficient data.
615
+ df: OHLCV DataFrame from yfinance (daily), indexed by Date.
616
+ """
617
+ if df is None or len(df) < MIN_BARS:
618
  return None
 
 
 
 
 
 
 
 
 
619
 
620
+ # Normalise MultiIndex columns (yfinance batch download)
621
+ if isinstance(df.columns, pd.MultiIndex):
622
+ df.columns = df.columns.get_level_values(0)
623
 
624
+ df = df[['Open','High','Low','Close','Volume']].copy().dropna()
625
+ if len(df) < MIN_BARS:
 
626
  return None
627
+
628
+ close = df['Close'].astype(float)
629
+ high = df['High'].astype(float)
630
+ low = df['Low'].astype(float)
631
+ vol = df['Volume'].astype(float)
632
+
633
+ # Volume quality check
634
+ last20_vol = vol.iloc[-20:]
635
+ if (last20_vol > 0).sum() < MIN_VOL_DAYS:
636
+ return None # too many zero-volume days β€” bad OTC data
637
+
638
+ # RSI (Wilder EWM)
639
+ delta = close.diff()
640
+ gain = delta.where(delta > 0, 0).ewm(alpha=1/14, adjust=False).mean()
641
+ loss = (-delta.where(delta < 0, 0)).ewm(alpha=1/14, adjust=False).mean()
642
+ df['RSI'] = 100 - 100 / (1 + gain / (loss + 1e-9))
643
+
644
+ # Volume indicators
645
+ df['Vol_MA20'] = vol.rolling(20).mean()
646
+ df['Vol_Ratio'] = vol / (df['Vol_MA20'] + 1e-9)
647
+ df['Vol_MA5'] = vol.rolling(5).mean()
648
+ df['Vol_Contract'] = df['Vol_MA5'] / (df['Vol_MA20'] + 1e-9)
649
+
650
+ # Quiet streak (consecutive days below COIL_VOL_THRESH)
651
+ quiet = (df['Vol_Ratio'] < COIL_VOL_THRESH).astype(int)
652
+ streak = quiet * (quiet.groupby((quiet != quiet.shift()).cumsum()).cumcount() + 1)
653
+ df['Quiet_Streak'] = streak.where(quiet == 1, 0)
654
+
655
+ # Bollinger Band width (normalised)
656
+ sma20 = close.rolling(20).mean()
657
+ std20 = close.rolling(20).std()
658
+ df['SMA20'] = sma20
659
+ df['BB_Width'] = (std20 * 4) / (sma20 + 1e-9) * 100
660
+ df['Dist_SMA'] = (close - sma20) / (sma20 + 1e-9) * 100
661
+
662
+ # 20-day range position (0 = at low, 1 = at high)
663
+ low20 = low.rolling(20).min()
664
+ high20 = high.rolling(20).max()
665
+ df['Range_Pos'] = (close - low20) / (high20 - low20 + 1e-9)
666
+
667
+ # Today's intraday range position (close vs today's high-low)
668
+ df['Day_Range_Pos'] = (close - low) / (high - low + 1e-9)
669
+
670
+ return df.dropna()
671
+
672
+
673
+ def check_signals(df: pd.DataFrame) -> dict:
674
+ """
675
+ Check Pattern A (Coil) and Pattern B (Surge) on the latest bar.
676
+ Returns dict with signal details.
677
+ """
678
+ if df is None or len(df) < 2:
679
+ return {"pattern_a": False, "pattern_b": False}
680
+
681
+ latest = df.iloc[-1]
682
+ prev = df.iloc[-2]
683
+
684
+ rsi = float(latest['RSI'])
685
+ vol_ratio = float(latest['Vol_Ratio'])
686
+ quiet_streak = float(df['Quiet_Streak'].iloc[-2]) # yesterday's streak
687
+ range_pos = float(latest['Range_Pos'])
688
+ day_range = float(latest['Day_Range_Pos'])
689
+ bb_width = float(latest['BB_Width'])
690
+ dist_sma = float(latest['Dist_SMA'])
691
+ close = float(latest['Close'])
692
+
693
+ # ── Pattern A: Coil break ─────────────────────────────────────────────
694
+ # Was quiet for 3+ days, today vol returns above 0.8x avg
695
+ pattern_a = (
696
+ quiet_streak >= COIL_MIN_DAYS and
697
+ vol_ratio >= COIL_BREAK_MIN and
698
+ rsi < RSI_COIL_MAX and
699
+ range_pos < RANGE_POS_MAX
700
+ )
701
+
702
+ # ── Pattern B: First surge ─────────────────────────────────────────────
703
+ # Today explodes with 3x+ volume, closing near top of range
704
+ pattern_b = (
705
+ vol_ratio >= SURGE_VOL_MIN and
706
+ day_range >= SURGE_RANGE_POS and
707
+ rsi < RSI_SURGE_MAX and
708
+ range_pos < RANGE_POS_MAX
709
+ )
710
+
711
+ # Confidence score (0-100) β€” how many sub-conditions met
712
+ score = 0
713
+ # RSI contribution
714
+ score += max(0, (45 - rsi)) * 1.2 # deeper oversold = higher score
715
+ # Range position contribution (lower = better)
716
+ score += max(0, (0.35 - range_pos)) * 80
717
+ # BB Width compression (lower width = tighter coil)
718
+ score += max(0, (30 - bb_width)) * 0.8
719
+ # Pattern-specific vol bonus
720
+ if pattern_a:
721
+ score += min(30, quiet_streak * 5) # longer quiet streak = higher
722
+ if pattern_b:
723
+ score += min(30, (vol_ratio - 3) * 5) # bigger surge = higher
724
+
725
+ return {
726
+ "pattern_a": pattern_a,
727
+ "pattern_b": pattern_b,
728
+ "rsi": round(rsi, 1),
729
+ "vol_ratio": round(vol_ratio, 2),
730
+ "quiet_streak": int(quiet_streak),
731
+ "range_pos": round(range_pos, 3),
732
+ "day_range_pos":round(day_range, 3),
733
+ "bb_width": round(bb_width, 1),
734
+ "dist_sma": round(dist_sma, 1),
735
+ "close": round(close, 4),
736
+ "score": round(min(100, score), 1),
737
+ "vol_ma20": round(float(latest['Vol_MA20']), 0),
738
+ "vol_today": round(float(latest['Volume']), 0),
739
  }
740
+
741
+
742
+ # ── Data fetch ────────────────────────────────────────────────────────────────
743
+
744
+ @st.cache_data(ttl=3 * 3600, show_spinner=False)
745
+ def fetch_penny_data(ticker: str) -> pd.DataFrame | None:
746
+ """Fetch 3 months of daily data for a single ticker."""
747
  try:
748
+ raw = yf.download(ticker, period="3mo", interval="1d",
749
+ progress=False, auto_adjust=True)
750
+ if isinstance(raw.columns, pd.MultiIndex):
751
+ raw.columns = raw.columns.get_level_values(0)
752
+ return raw if not raw.empty else None
 
 
 
 
 
 
753
  except Exception:
754
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755
 
756
 
757
+ # ── Universe scan ─────────────────────────────────────────────────────────────
758
+
759
+ @st.cache_data(ttl=6 * 3600, show_spinner=False)
760
+ def run_penny_scan(
761
+ tickers_tuple: tuple, # tuple of (ticker, yf_ticker, name, close, exchange, otc_f)
762
+ min_price: float,
763
+ max_price: float,
764
+ require_exchange: bool,
765
+ pattern_filter: str,
766
+ ) -> pd.DataFrame:
767
+ # Reconstruct list of dicts from flat tuple-of-tuples
768
+ rows = [{'ticker': t[0], 'yf': t[1], 'name': t[2],
769
+ 'close': t[3], 'exchange': t[4], 'otc_f': t[5]}
770
+ for t in tickers_tuple]
771
+
772
+ results = []
773
+ failed = []
774
+ batch = 10
775
+ n_batch = max(1, (len(rows) + batch - 1) // batch)
776
+ prog = st.progress(0, text="Scanning…")
777
+
778
+ for b, i in enumerate(range(0, len(rows), batch)):
779
+ batch_t = rows[i:i + batch]
780
+ batch_yf = [r['yf'] for r in batch_t]
781
 
 
 
782
  try:
783
+ raw = yf.download(batch_yf, period="3mo", interval="1d",
784
+ group_by="ticker", progress=False,
785
+ threads=True, auto_adjust=True)
786
  except Exception:
787
+ prog.progress((b+1)/n_batch)
 
788
  continue
789
+
790
+ for row in batch_t:
791
+ ticker = row['ticker']
792
+ yf_tick = row['yf']
793
+ name = row['name']
794
+ price = row['close']
795
+ exchange = row['exchange']
796
+ is_otc_f = row['otc_f']
797
+
798
+ if price < min_price or price > max_price:
799
+ continue
800
+ if require_exchange and exchange == 'OTC':
801
+ continue
802
+
803
  try:
804
+ if len(batch_yf) == 1:
805
+ df_raw = raw
806
+ else:
807
+ df_raw = raw[yf_tick] if yf_tick in raw.columns.get_level_values(0) else None
808
+
809
+ features = compute_features(df_raw)
810
+ sig = check_signals(features)
811
+
812
+ if not sig.get('pattern_a') and not sig.get('pattern_b'):
813
  continue
814
+
815
+ # Apply pattern filter
816
+ if pattern_filter == "Coil only" and not sig['pattern_a']:
817
+ continue
818
+ if pattern_filter == "Surge only" and not sig['pattern_b']:
819
+ continue
820
+
821
+ pattern_label = []
822
+ if sig['pattern_a']: pattern_label.append("πŸ”΅ Coil break")
823
+ if sig['pattern_b']: pattern_label.append("πŸ”΄ First surge")
824
+
825
+ results.append({
826
+ "Score": sig['score'],
827
+ "Pattern": " + ".join(pattern_label),
828
+ "Ticker": ticker,
829
+ "Name": name[:25],
830
+ "Exchange": exchange + (" ⚠️" if is_otc_f else ""),
831
+ "Price": sig['close'],
832
+ "RSI": sig['rsi'],
833
+ "Vol x MA20": sig['vol_ratio'],
834
+ "Quiet days": sig['quiet_streak'],
835
+ "Range pos": sig['range_pos'],
836
+ "BB Width%": sig['bb_width'],
837
+ "Dist SMA%": sig['dist_sma'],
838
+ "Vol MA20": int(sig['vol_ma20']),
839
+ "Vol today": int(sig['vol_today']),
840
+ })
841
  except Exception:
842
+ failed.append(ticker)
843
  continue
 
844
 
845
+ prog.progress((b+1)/n_batch, text=f"Batch {b+1}/{n_batch}…")
 
846
 
847
+ prog.empty()
848
+ if not results:
849
+ return pd.DataFrame()
850
 
851
+ out = (pd.DataFrame(results)
852
+ .sort_values("Score", ascending=False)
853
+ .reset_index(drop=True))
854
+ return out
855
+
856
+
857
+ # ── Single-ticker chart ───────────────────────────────────────────────────────
858
+
859
+ def plot_penny_chart(ticker: str, yf_ticker: str):
860
+ with st.spinner(f"Fetching {ticker}…"):
861
+ raw = fetch_penny_data(yf_ticker)
862
+ features = compute_features(raw)
863
+ if features is None or len(features) < 20:
864
+ st.error(f"Not enough data for {ticker}.")
865
+ return
866
+
867
+ sig = check_signals(features)
868
+ recent = features.tail(60)
869
+
870
+ fig = plt.figure(figsize=(13, 10))
871
+ gs = gridspec.GridSpec(3, 1, figure=fig, hspace=0.45,
872
+ height_ratios=[2.5, 1, 1])
873
+
874
+ # Panel 1: Price + SMA20 + BB
875
+ ax1 = fig.add_subplot(gs[0])
876
+ sma = recent['SMA20']
877
+ std = recent['Close'].rolling(20).std().iloc[-len(recent):]
878
+ ax1.plot(recent.index, recent['Close'], color='black', lw=1.5, label='Price')
879
+ ax1.plot(recent.index, sma, color='blue', lw=0.8, ls='--', alpha=0.6, label='SMA20')
880
+ ax1.fill_between(recent.index, sma - 2*std, sma + 2*std,
881
+ alpha=0.08, color='purple', label='BB Β±2Οƒ')
882
+ # Highlight signal day
883
+ ax1.axvline(recent.index[-1], color='red', lw=1.5, ls='--', alpha=0.7)
884
+
885
+ pattern_str = []
886
+ if sig.get('pattern_a'): pattern_str.append("πŸ”΅ COIL BREAK")
887
+ if sig.get('pattern_b'): pattern_str.append("πŸ”΄ FIRST SURGE")
888
+ title_sig = " | " + " + ".join(pattern_str) if pattern_str else " | No signal today"
889
+ ax1.set_title(f"{ticker} ${sig['close']:.4f}{title_sig} Score:{sig['score']:.0f}",
890
+ fontweight='bold', fontsize=11)
891
+ ax1.legend(fontsize=8); ax1.grid(True, alpha=0.15)
892
+
893
+ # Panel 2: RSI
894
+ ax2 = fig.add_subplot(gs[1])
895
+ ax2.plot(recent.index, recent['RSI'], color='purple', lw=1.5)
896
+ ax2.axhline(30, color='green', ls=':', lw=1, alpha=0.7, label='RSI 30')
897
+ ax2.axhline(50, color='gray', ls=':', lw=0.8, alpha=0.5, label='RSI 50')
898
+ ax2.axvline(recent.index[-1], color='red', lw=1.5, ls='--', alpha=0.7)
899
+ ax2.set_ylim(0, 100)
900
+ ax2.set_title(f"RSI (14) β€” current: {sig['rsi']:.1f}", fontsize=10)
901
+ ax2.legend(fontsize=8); ax2.grid(True, alpha=0.15)
902
+
903
+ # Panel 3: Volume bars coloured by ratio
904
+ ax3 = fig.add_subplot(gs[2])
905
+ vol_ratio = recent['Vol_Ratio']
906
+ colors = ['#e74c3c' if v >= 3 else ('#f39c12' if v >= 1 else '#95a5a6')
907
+ for v in vol_ratio]
908
+ ax3.bar(recent.index, recent['Volume'], color=colors, alpha=0.8, width=1)
909
+ ax3.axhline(recent['Vol_MA20'].iloc[-1], color='blue', lw=1.2, ls='--',
910
+ alpha=0.7, label=f"20MA vol ({recent['Vol_MA20'].iloc[-1]:,.0f})")
911
+ ax3.set_title(f"Volume β€” today {sig['vol_ratio']:.1f}x MA20 | "
912
+ f"Quiet streak before: {sig['quiet_streak']}d | "
913
+ f"Range pos: {sig['range_pos']:.2f} BB Width: {sig['bb_width']:.1f}%",
914
+ fontsize=9)
915
+ ax3.legend(fontsize=8); ax3.grid(True, alpha=0.15, axis='y')
916
+
917
+ # Colour legend
918
+ from matplotlib.patches import Patch
919
+ legend_els = [Patch(facecolor='#e74c3c', label='Vol β‰₯3x (surge)'),
920
+ Patch(facecolor='#f39c12', label='Vol β‰₯1x (normal)'),
921
+ Patch(facecolor='#95a5a6', label='Vol <1x (quiet)')]
922
+ ax3.legend(handles=legend_els, fontsize=7, loc='upper left')
923
+
924
+ plt.suptitle("Pattern A = Coil break (quiet then first vol return) | "
925
+ "Pattern B = First surge (3x+ vol, close near high)",
926
+ fontsize=9, style='italic', y=1.005)
927
  st.pyplot(fig)
928
  plt.close(fig)
929
 
930
 
931
+ # ── Universe loader ───────────────────────────────────────────────────────────
932
+
933
+ @st.cache_data(ttl=24 * 3600, show_spinner="Loading penny stock universe…")
934
+ def load_penny_universe(max_price: float = 5.0) -> list[dict]:
935
+ """Load and clean the penny stock watchlist from HF dataset."""
936
+ try:
937
+ from huggingface_hub import hf_hub_download
938
+ path = hf_hub_download(
939
+ repo_id="Trebor1009/clean-premarket-data", repo_type="dataset",
940
+ filename="my_penny_stocks.csv", token=HF_TOKEN,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
941
  )
942
+ df = pd.read_csv(path)
943
+ except Exception:
944
+ # Fallback: try local path (for development)
945
+ try:
946
+ df = pd.read_csv("/home/claude/penny_watchlist_clean.csv")
947
+ df = df.rename(columns={'yf_ticker':'ticker','prefix':'exchange'})
948
+ except Exception:
949
+ return []
950
+
951
+ if 'ticker' in df.columns and ':' in str(df['ticker'].iloc[0]):
952
+ df['exchange'] = df['ticker'].str.split(':').str[0]
953
+ df['yf_ticker'] = df['ticker'].str.split(':').str[-1].str.replace('.', '-', regex=False)
954
  else:
955
+ df['yf_ticker'] = df.get('yf_ticker', df['ticker'])
956
+ df['exchange'] = df.get('exchange', 'UNKNOWN')
957
+
958
+ df['otc_f'] = (df['exchange'] == 'OTC') & (df['yf_ticker'].str.endswith('F'))
959
+ df['close'] = pd.to_numeric(df['close'], errors='coerce').fillna(0)
960
+ df = df[df['close'] <= max_price].copy()
961
+
962
+ return df.to_dict('records')
963
 
964
 
965
+ # ── MAIN RENDER ───────────────────────────────────────────────────────────────
966
+
967
+ def render_penny_scanner():
968
+ st.title("πŸ“‘ Small-Cap Pump Scanner")
969
  st.caption(
970
+ "Scans sub-$5 tickers for two pre-pump patterns identified from LEDS, AIIO, "
971
+ "GPUS and CXAI data. Not a guarantee of a pump β€” a structural similarity to "
972
+ "conditions that preceded pumps in those examples."
 
 
 
 
 
 
 
 
 
973
  )
974
 
975
+ with st.expander("πŸ“Š How the two signals work", expanded=False):
976
+ st.markdown("""
977
+ **Pattern A β€” πŸ”΅ Coil Break**
978
+ Stock has been quiet for 3+ consecutive days (volume <0.4x its 20-day average),
979
+ RSI below 47, in the bottom 35% of its 20-day price range, Bollinger Bands compressed.
980
+ Signal fires on the **first day volume returns above 0.8x average**.
981
+ This is the pre-pump entry β€” before the explosive day, when most traders aren't looking.
982
+ *Based on: LEDS pattern (+97% over 20 days from this signal)*
983
+
984
+ **Pattern B β€” πŸ”΄ First Surge**
985
+ Today's volume is **β‰₯3x the 20-day average**, close is in the top 35% of today's
986
+ high-low range (buyers controlling the close), RSI below 52, in the bottom 35%
987
+ of 20-day price range. This catches day 1 of an explosive move.
988
+ *Based on: AIIO (+858%), GPUS (+477%), CXAI (+86%) β€” all had this profile on day 1.*
989
+
990
+ **Score (0-100):** composite of RSI depth, range position, BB compression and vol strength.
991
+ Higher = more conditions aligned.
992
+
993
+ **⚠️ OTC-F tickers** (foreign OTC, e.g. Canadian companies) are flagged with ⚠️.
994
+ Yahoo Finance often has sparse or unreliable volume for these β€” treat any signal
995
+ from an OTC-F ticker with extra caution and verify the chart manually.
996
+ """)
997
+
998
+ # ── Sidebar ───────────────────────────────────────────────────────────────
999
  with st.sidebar:
1000
  st.markdown("---")
1001
+ st.header("Pump Scanner")
1002
+ max_price_filter = st.slider("Max price ($)", 0.10, 5.00, 5.00, 0.10, key="ps_maxprice")
1003
+ min_price_filter = st.slider("Min price ($)", 0.05, 2.00, 0.10, 0.05, key="ps_minprice")
1004
+ pattern_filter = st.radio("Pattern", ["Both","Coil only","Surge only"], key="ps_pat")
1005
+ exchange_filter = st.checkbox("Exchange-listed only (exclude OTC)", value=False, key="ps_exch")
1006
+ st.markdown("---")
1007
+ st.caption(
1008
+ "Coil break = pre-pump entry (lower risk, smaller initial move).\n\n"
1009
+ "First surge = day-1 entry on explosive volume (higher risk, bigger move)."
1010
+ )
 
1011
 
1012
+ # ── Single ticker analysis ────────────────────────────────────────────────
1013
  st.subheader("Analyze a single ticker")
1014
+ col_a, col_b = st.columns([2, 1])
1015
+ single = col_a.text_input("Ticker (as listed on Yahoo Finance)", value="AIIO", key="ps_single")
1016
+ go_btn = col_b.button("Analyze", key="ps_analyze")
1017
+
1018
+ if go_btn and single:
1019
+ raw = fetch_penny_data(single.strip().upper())
1020
+ features = compute_features(raw)
1021
+ sig = check_signals(features)
1022
+
1023
+ if features is None:
1024
+ st.error(f"No usable data for {single}. Check the ticker and try again.")
1025
  else:
1026
+ c1, c2, c3, c4, c5 = st.columns(5)
1027
+ c1.metric("Price", f"${sig['close']:.4f}")
1028
+ c2.metric("RSI", f"{sig['rsi']}")
1029
+ c3.metric("Vol ratio", f"{sig['vol_ratio']:.1f}x")
1030
+ c4.metric("Quiet streak", f"{sig['quiet_streak']}d")
1031
+ c5.metric("Range pos", f"{sig['range_pos']:.2f}")
1032
+
1033
+ if sig.get('pattern_a') or sig.get('pattern_b'):
1034
+ parts = []
1035
+ if sig['pattern_a']: parts.append("πŸ”΅ **Coil Break**")
1036
+ if sig['pattern_b']: parts.append("πŸ”΄ **First Surge**")
1037
+ st.success(f"Signal: {' + '.join(parts)} | Score: {sig['score']:.0f}/100\n\n"
1038
+ f"BB Width: {sig['bb_width']:.1f}% | "
1039
+ f"Dist SMA20: {sig['dist_sma']:.1f}% | "
1040
+ f"Day range pos: {sig['day_range_pos']:.2f}")
1041
  else:
1042
+ reasons = []
1043
+ if sig['rsi'] >= RSI_COIL_MAX: reasons.append(f"RSI {sig['rsi']:.1f} (need <{RSI_COIL_MAX} for coil, <{RSI_SURGE_MAX} for surge)")
1044
+ if sig['range_pos'] >= RANGE_POS_MAX: reasons.append(f"Range pos {sig['range_pos']:.2f} (need <{RANGE_POS_MAX})")
1045
+ if sig['quiet_streak'] < COIL_MIN_DAYS and sig['vol_ratio'] < SURGE_VOL_MIN:
1046
+ reasons.append(f"Vol {sig['vol_ratio']:.1f}x (need β‰₯{COIL_BREAK_MIN}x after {COIL_MIN_DAYS}d quiet OR β‰₯{SURGE_VOL_MIN}x surge)")
1047
+ st.info("No signal today. " + (" | ".join(reasons) if reasons else "Conditions not met."))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1048
 
1049
+ plot_penny_chart(single.strip().upper(), single.strip().upper())
 
1050
 
1051
+ # ── Full scan ─────────────────────────────────────────────────────────────
1052
  st.markdown("---")
1053
+ st.subheader("Full watchlist scan")
1054
+
1055
+ universe = load_penny_universe(max_price=max_price_filter)
1056
+ filtered = [r for r in universe
1057
+ if r.get('close', 0) >= min_price_filter
1058
+ and r.get('close', 0) <= max_price_filter]
1059
+ if exchange_filter:
1060
+ filtered = [r for r in filtered if r.get('exchange', '') != 'OTC']
1061
+
1062
  st.caption(
1063
+ f"Universe: {len(filtered):,} tickers after price filter "
1064
+ f"({'exchange-listed only' if exchange_filter else 'including OTC'}) | "
1065
+ f"Cached 6 hours β€” ~{'10-15' if len(filtered) > 1000 else '5-10'} min first run."
1066
  )
1067
+
1068
+ if st.button("πŸ” Run Pump Scan", key="ps_scan"):
1069
+ if not filtered:
1070
+ st.error("No tickers match the current filters.")
1071
  else:
1072
+ scan_tuples = tuple(
1073
+ (r.get('ticker', r.get('yf_ticker','')),
1074
+ r.get('yf_ticker', r.get('ticker','').split(':')[-1]),
1075
+ r.get('name', ''),
1076
+ float(r.get('close', 0)),
1077
+ str(r.get('exchange', r.get('prefix', 'UNK'))),
1078
+ bool(r.get('otc_f', False)))
1079
+ for r in filtered
1080
+ )
1081
+ results_df = run_penny_scan(
1082
+ scan_tuples,
1083
+ min_price_filter, max_price_filter,
1084
+ exchange_filter, pattern_filter,
1085
  )
1086
+ st.session_state["ps_results"] = results_df
 
 
 
1087
 
1088
+ if "ps_results" in st.session_state:
1089
+ df_r = st.session_state["ps_results"]
1090
+ if df_r.empty:
1091
+ st.info("No tickers matched either signal pattern today.")
1092
  else:
1093
+ coil_n = df_r['Pattern'].str.contains('Coil').sum()
1094
+ surge_n = df_r['Pattern'].str.contains('Surge').sum()
1095
+ both_n = df_r['Pattern'].str.contains('Coil').sum() & df_r['Pattern'].str.contains('Surge').sum()
1096
+ st.success(
1097
+ f"{len(df_r)} hits β€” "
1098
+ f"πŸ”΅ {coil_n} Coil breaks, πŸ”΄ {surge_n} First surges | "
1099
+ f"Sorted by Score"
1100
+ )
1101
+ st.caption(
1102
+ "⚠️ = OTC-F (foreign OTC) β€” Yahoo volume data may be unreliable. "
1103
+ "Verify chart before acting on any OTC-F signal."
1104
+ )
1105
+
1106
+ # Highlight OTC-F rows
1107
+ def row_style(row):
1108
+ if "⚠️" in str(row.get("Exchange", "")):
1109
+ return ["background-color: #fff3cd"] * len(row)
1110
+ if "πŸ”΅" in str(row.get("Pattern","")) and "πŸ”΄" in str(row.get("Pattern","")):
1111
+ return ["background-color: #d4edda"] * len(row)
1112
+ return [""] * len(row)
1113
+
1114
+ st.dataframe(
1115
+ df_r.style.apply(row_style, axis=1),
1116
+ use_container_width=True, hide_index=True,
1117
+ )
1118
+
1119
+ pick = st.selectbox(
1120
+ "View chart for:", df_r["Ticker"].tolist(), key="ps_pick"
1121
+ )
1122
  if pick:
1123
+ # Get yf ticker for the pick
1124
+ match = [r for r in filtered
1125
+ if r.get('ticker', r.get('yf_ticker','')) == pick]
1126
+ yf_t = match[0].get('yf_ticker', pick.split(':')[-1]) if match else pick.split(':')[-1]
1127
+ plot_penny_chart(pick, yf_t)
1128
+
1129
+ # ── How to use ────────────────────────────────────────────────────────────
1130
+ st.markdown("---")
1131
+ with st.expander("πŸ’‘ How to use these signals + position sizing"):
1132
+ st.markdown(f"""
1133
+ **Coil Break (Pattern A):**
1134
+ The first quiet-to-active transition is an early entry before most traders notice.
1135
+ The LEDS example showed a 5-day coil period at volume <0.2x average before a
1136
+ +97% pump. Entry on the coil-break day means buying into uncertainty β€” the pump
1137
+ may not materialise for several more days, or at all.
1138
+
1139
+ **First Surge (Pattern B):**
1140
+ Volume 3x+ on day 1 of a move, with buyers controlling the close. AIIO, GPUS
1141
+ and CXAI all showed this on day 1 of their pumps. The risk is buying into a
1142
+ single spike that fades β€” check that close is near the day's high, not the low.
1143
+
1144
+ **Position sizing for this universe:**
1145
+ Sub-$5 small caps and OTC stocks have bid-ask spreads of 2-5% and can halt
1146
+ or reverse violently. Appropriate sizing is much smaller than the large-cap
1147
+ DCA positions. These are asymmetric bets β€” small fixed Β£ amount per hit,
1148
+ accept total loss as the base case, target 3-5x on the ones that work.
1149
+
1150
+ **The OTC-F problem:**
1151
+ 1,476 of your 2,103 OTC tickers end in 'F' (foreign OTC). Yahoo Finance
1152
+ frequently returns zero or near-zero volume for these, which can generate
1153
+ false Coil signals (looks quiet because the data is missing, not because
1154
+ the stock is genuinely coiling). Always check the chart for OTC-F hits
1155
+ before acting. Non-OTC exchange-listed tickers (NASDAQ/NYSE/AMEX) are
1156
+ the most reliable signals.
1157
+ """)
1158
 
1159
 
 
1160
  # ANALOG PATH PROJECTION
1161
  # =========================================================
1162
 
 
2162
  tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
2163
  "πŸ‹ Whale Monitor",
2164
  "πŸ“ˆ Peak Detector",
2165
+ "πŸ“‘ Pump Scanner",
2166
  "πŸ—’οΈ Signal Tracker",
2167
  "🧭 Rotation Map",
2168
  "🎯 Combined Scanner",
 
2175
  render_peak_detector()
2176
 
2177
  with tab3:
2178
+ render_penny_scanner()
2179
 
2180
  with tab4:
2181
  render_signal_tracker()