aboutsummaryrefslogtreecommitdiff
path: root/components/top_movers.py
blob: 5589df65834d55bfb3948c25c00328d46d15913f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""Top Movers component — day gainers, losers, most active."""
from html import escape

import streamlit as st
import yfinance as yf

DEFAULT_VISIBLE_MOVERS = 3
MAX_MOVERS = 8


def _toggle_mover_tab(state_key: str):
    st.session_state[state_key] = not st.session_state.get(state_key, False)


def _inject_styles():
    st.markdown(
        """
        <style>
          .prism-mover-list {
            display: grid;
            gap: 0.12rem;
          }
          .prism-mover-row {
            display: grid;
            grid-template-columns: minmax(72px, 0.8fr) minmax(0, 2.6fr) minmax(90px, 1fr) minmax(110px, 1.1fr);
            gap: 0.85rem;
            align-items: center;
            padding: 0.18rem 0;
          }
          .prism-mover-symbol {
            font-size: 1rem;
            font-weight: 700;
            line-height: 1.1;
          }
          .prism-mover-name {
            color: #9aa0b0;
            font-size: 0.84rem;
            line-height: 1.15;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .prism-mover-price {
            font-size: 0.98rem;
            line-height: 1.1;
          }
          .prism-mover-change {
            font-size: 0.98rem;
            font-weight: 600;
            line-height: 1.1;
          }
          .prism-mover-change-meta {
            font-size: 0.74rem;
            color: #9aa0b0;
            margin-left: 0.2rem;
          }
          @media (max-width: 900px) {
            .prism-mover-row {
              grid-template-columns: minmax(68px, 0.9fr) minmax(0, 2.2fr) minmax(82px, 1fr) minmax(96px, 1fr);
              gap: 0.55rem;
            }
          }
        </style>
        """,
        unsafe_allow_html=True,
    )


@st.cache_data(ttl=180)
def _fetch_movers(screen: str, count: int = MAX_MOVERS) -> list[dict]:
    try:
        result = yf.screen(screen, count=count)
        return result.get("quotes", [])
    except Exception:
        return []


def _fmt_price(val) -> str:
    try:
        return f"${float(val):,.2f}"
    except Exception:
        return "—"


def _mover_row_html(q: dict) -> str:
    symbol = escape(str(q.get("symbol", "")))
    name = escape(str(q.get("shortName") or q.get("longName") or symbol))
    price = q.get("regularMarketPrice")
    chg_pct = q.get("regularMarketChangePercent")
    chg_abs = q.get("regularMarketChange")

    try:
        chg_f = float(chg_pct)
        color = "#2ecc71" if chg_f >= 0 else "#e74c3c"
        sign = "+" if chg_f >= 0 else ""
        pct_str = f"{sign}{chg_f:.2f}%"
    except Exception:
        color = "#9aa0b0"
        pct_str = "—"

    try:
        abs_str = f"({'+' if float(chg_abs) >= 0 else ''}{float(chg_abs):.2f})"
    except Exception:
        abs_str = ""
    abs_str = escape(abs_str)

    return (
        "<div class='prism-mover-row'>"
        f"<div class='prism-mover-symbol'>{symbol}</div>"
        f"<div class='prism-mover-name'>{name}</div>"
        f"<div class='prism-mover-price'>{_fmt_price(price)}</div>"
        "<div>"
        f"<span class='prism-mover-change' style='color:{color}'>{pct_str}</span>"
        f"<span class='prism-mover-change-meta'>{abs_str}</span>"
        "</div>"
        "</div>"
    )


def _render_mover_tab(screen: str, state_key: str):
    quotes = _fetch_movers(screen)
    if not quotes:
        st.caption("No data available.")
        return

    expanded = st.session_state.get(state_key, False)
    visible_count = len(quotes) if expanded else min(DEFAULT_VISIBLE_MOVERS, len(quotes))

    rows_html = "".join(_mover_row_html(q) for q in quotes[:visible_count])
    st.markdown(f"<div class='prism-mover-list'>{rows_html}</div>", unsafe_allow_html=True)

    if len(quotes) > DEFAULT_VISIBLE_MOVERS:
        button_label = "Show Less" if expanded else f"Show More ({len(quotes) - DEFAULT_VISIBLE_MOVERS} more)"
        st.button(
            button_label,
            key=f"{state_key}_button",
            use_container_width=True,
            on_click=_toggle_mover_tab,
            args=(state_key,),
        )


@st.fragment
def render_top_movers():
    _inject_styles()
    st.markdown("#### 🔥 Top Movers")

    tab_gainers, tab_losers, tab_active = st.tabs([
        "📈 Gainers", "📉 Losers", "⚡ Most Active"
    ])

    screens = {
        "gainers": "day_gainers",
        "losers": "day_losers",
        "active": "most_actives",
    }

    with tab_gainers:
        _render_mover_tab(screens["gainers"], "top_movers_gainers_expanded")

    with tab_losers:
        _render_mover_tab(screens["losers"], "top_movers_losers_expanded")

    with tab_active:
        _render_mover_tab(screens["active"], "top_movers_active_expanded")