Spaces:
Running
Running
Update src/streamlit_app.py
Browse files- 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:
|
| 571 |
# =========================================================
|
| 572 |
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 608 |
-
|
| 609 |
-
if len(df) < 200:
|
| 610 |
return None
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 619 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 620 |
try:
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 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 |
-
|
| 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 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 659 |
|
| 660 |
-
for b, i in enumerate(range(0, len(_tickers), batch_size)):
|
| 661 |
-
batch = _tickers[i:i + batch_size]
|
| 662 |
try:
|
| 663 |
-
|
| 664 |
-
|
|
|
|
| 665 |
except Exception:
|
| 666 |
-
|
| 667 |
-
text=f"Batch {b + 1}/{total_batches} failed, continuing...")
|
| 668 |
continue
|
| 669 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 670 |
try:
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
|
|
|
|
|
|
|
|
|
| 677 |
continue
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
if
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
except Exception:
|
|
|
|
| 694 |
continue
|
| 695 |
-
progress.progress((b + 1) / total_batches, text=f"Scanned batch {b + 1}/{total_batches}...")
|
| 696 |
|
| 697 |
-
|
| 698 |
-
return pd.DataFrame(results)
|
| 699 |
|
|
|
|
|
|
|
|
|
|
| 700 |
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
if
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
if
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 747 |
st.pyplot(fig)
|
| 748 |
plt.close(fig)
|
| 749 |
|
| 750 |
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 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 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
|
|
|
|
|
|
| 784 |
|
| 785 |
|
| 786 |
-
|
| 787 |
-
|
|
|
|
|
|
|
| 788 |
st.caption(
|
| 789 |
-
"
|
| 790 |
-
"
|
| 791 |
-
"
|
| 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("
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
}
|
| 816 |
|
|
|
|
| 817 |
st.subheader("Analyze a single ticker")
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
|
|
|
|
|
|
| 827 |
else:
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 832 |
else:
|
| 833 |
-
|
| 834 |
-
if
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 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 |
-
|
| 868 |
-
render_quick_forecast(single_ticker)
|
| 869 |
|
|
|
|
| 870 |
st.markdown("---")
|
| 871 |
-
st.subheader("Full
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 872 |
st.caption(
|
| 873 |
-
"
|
| 874 |
-
"
|
| 875 |
-
f"
|
| 876 |
)
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
if not
|
| 880 |
-
st.error("No tickers
|
| 881 |
else:
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 886 |
)
|
| 887 |
-
st.session_state["
|
| 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 "
|
| 893 |
-
|
| 894 |
-
if
|
| 895 |
-
st.info("No tickers
|
| 896 |
else:
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 901 |
if pick:
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
"
|
| 1917 |
"ποΈ Signal Tracker",
|
| 1918 |
"π§ Rotation Map",
|
| 1919 |
"π― Combined Scanner",
|
|
@@ -1926,7 +2175,7 @@ with tab2:
|
|
| 1926 |
render_peak_detector()
|
| 1927 |
|
| 1928 |
with tab3:
|
| 1929 |
-
|
| 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()
|