aboutsummaryrefslogtreecommitdiff
path: root/components/macro.py
blob: c8e8b0caab7023305eff9041473535f8431a87a6 (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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""Macro tab — market-wide panels: Index Performance, Yield Curve, Sector Heatmap."""
import streamlit as st
import streamlit.components.v1 as _html
import plotly.graph_objects as go
import yfinance as yf
import pandas as pd
from datetime import date as _date


_INDICES = {
    "S&P 500": "^GSPC",
    "NASDAQ":  "^IXIC",
    "DOW":     "^DJI",
    "Russell": "^RUT",
    "VIX":     "^VIX",
}

_YIELDS = {
    "3M":  "^IRX",
    "5Y":  "^FVX",
    "10Y": "^TNX",
    "30Y": "^TYX",
}

_SECTORS = {
    "Technology":   "XLK",
    "Financials":   "XLF",
    "Healthcare":   "XLV",
    "Energy":       "XLE",
    "Industrials":  "XLI",
    "Cons. Disc.":  "XLY",
    "Cons. Stap.":  "XLP",
    "Utilities":    "XLU",
    "Real Estate":  "XLRE",
    "Materials":    "XLB",
    "Comm. Svcs.":  "XLC",
}


# ── Data fetch ────────────────────────────────────────────────────────────────

@st.cache_data(ttl=300)
def _get_macro_data() -> dict:
    indices = {}
    for name, sym in _INDICES.items():
        try:
            hist = yf.Ticker(sym).history(period="1y")
            if hist.empty:
                indices[name] = None
                continue
            closes = hist["Close"].dropna()
            last = float(closes.iloc[-1])

            def _pct(n):
                if len(closes) > n:
                    return float((closes.iloc[-1] - closes.iloc[-(n + 1)]) / closes.iloc[-(n + 1)] * 100)
                return None

            p1d = _pct(1)
            p1w = _pct(5)
            p1m = _pct(21)

            today = _date.today()
            jan1 = pd.Timestamp(today.year, 1, 1)
            idx = closes.index
            if idx.tz is not None:
                jan1 = jan1.tz_localize(idx.tz)
            ytd_slice = closes[idx.normalize() >= jan1.normalize()]
            pytd = float((last - float(ytd_slice.iloc[0])) / float(ytd_slice.iloc[0]) * 100) if not ytd_slice.empty else None

            indices[name] = {"price": last, "1d": p1d, "1w": p1w, "1m": p1m, "ytd": pytd}
        except Exception:
            indices[name] = None

    yields = {}
    for label, sym in _YIELDS.items():
        try:
            hist = yf.Ticker(sym).history(period="5d")
            if hist.empty:
                yields[label] = None
                continue
            closes = hist["Close"].dropna()
            curr = float(closes.iloc[-1])
            prev = float(closes.iloc[-2]) if len(closes) >= 2 else None
            yields[label] = {"rate": curr, "change_1d": (curr - prev) if prev is not None else None}
        except Exception:
            yields[label] = None

    sectors = {}
    for name, etf in _SECTORS.items():
        try:
            hist = yf.Ticker(etf).history(period="2d")
            if len(hist) >= 2:
                pct = float((hist["Close"].iloc[-1] - hist["Close"].iloc[-2]) / hist["Close"].iloc[-2] * 100)
                price = float(hist["Close"].iloc[-1])
            elif len(hist) == 1:
                pct = 0.0
                price = float(hist["Close"].iloc[-1])
            else:
                sectors[name] = None
                continue
            sectors[name] = {"etf": etf, "pct": pct, "price": price}
        except Exception:
            sectors[name] = None

    return {"indices": indices, "yields": yields, "sectors": sectors}


# ── Helpers ───────────────────────────────────────────────────────────────────

def _pct_cell(v) -> str:
    """Return an HTML <span> with color class for a % value."""
    if v is None:
        return "<span class='flat'>—</span>"
    sign = "+" if v >= 0 else ""
    cls = "pos" if v > 0.005 else ("neg" if v < -0.005 else "flat")
    return "<span class='" + cls + "'>" + sign + f"{v:.2f}%" + "</span>"


def _sector_bg(pct: float) -> str:
    """Interpolate background color between neutral and pos/neg based on magnitude."""
    neutral = (24, 29, 38)
    pos_bg  = (21, 36, 26)
    neg_bg  = (42, 21, 23)
    intensity = min(1.0, abs(pct) / 3.0)
    target = pos_bg if pct >= 0 else neg_bg
    r = int(neutral[0] + (target[0] - neutral[0]) * intensity)
    g = int(neutral[1] + (target[1] - neutral[1]) * intensity)
    b = int(neutral[2] + (target[2] - neutral[2]) * intensity)
    return "rgb(" + str(r) + "," + str(g) + "," + str(b) + ")"


# ── Panel renderers ───────────────────────────────────────────────────────────

def _render_index_table(indices: dict) -> None:
    css = (
        "<style>"
        "* { margin:0; padding:0; box-sizing:border-box; }"
        "body { background:#0B0E13; font-family:'IBM Plex Mono',monospace; overflow:hidden; }"
        "table { width:100%; border-collapse:collapse; }"
        "thead th {"
        "  font-family:'IBM Plex Sans',sans-serif; font-size:10px; font-weight:600;"
        "  text-transform:uppercase; letter-spacing:0.14em; color:#5E5849;"
        "  padding:7px 12px 7px; border-bottom:1px solid #232934; text-align:right; }"
        "thead th:first-child { text-align:left; }"
        "tbody tr { border-bottom:1px solid #181D26; }"
        "tbody td { padding:9px 12px; font-size:13px; color:#C7C0AE; text-align:right; "
        "  font-variant-numeric:tabular-nums; }"
        "tbody td:first-child { text-align:left; color:#F2ECDC; font-size:12px; letter-spacing:0.02em; }"
        ".pos { color:#4F8C5E; } .neg { color:#B5494B; } .flat { color:#5E5849; }"
        "</style>"
    )
    head = (
        "<table><thead><tr>"
        "<th>Index</th><th>Price</th><th>1D</th><th>1W</th><th>1M</th><th>YTD</th>"
        "</tr></thead><tbody>"
    )
    rows = ""
    for name, d in indices.items():
        if d is None:
            rows += "<tr><td>" + name + "</td><td>—</td><td>—</td><td>—</td><td>—</td><td>—</td></tr>"
            continue
        price = f"{d['price']:,.2f}"
        rows += (
            "<tr><td>" + name + "</td>"
            "<td>" + price + "</td>"
            "<td>" + _pct_cell(d["1d"]) + "</td>"
            "<td>" + _pct_cell(d["1w"]) + "</td>"
            "<td>" + _pct_cell(d["1m"]) + "</td>"
            "<td>" + _pct_cell(d["ytd"]) + "</td>"
            "</tr>"
        )
    _html.html(css + head + rows + "</tbody></table>", height=290, scrolling=False)


def _render_yield_curve(yields: dict) -> None:
    labels = list(yields.keys())
    rates = [yields[lbl]["rate"] if yields[lbl] else None for lbl in labels]
    valid = [(lbl, r) for lbl, r in zip(labels, rates) if r is not None]

    fig = go.Figure()
    if valid:
        xl, yl = zip(*valid)
        fig.add_trace(go.Scatter(
            x=list(xl),
            y=list(yl),
            mode="lines+markers",
            line=dict(color="#C2AA7A", width=2),
            marker=dict(size=7, color="#C2AA7A", line=dict(width=1, color="#8F7A50")),
            hovertemplate="%{x}: %{y:.2f}%<extra></extra>",
        ))

    fig.update_layout(
        xaxis_title="Maturity",
        yaxis=dict(tickformat=".2f", ticksuffix="%"),
        height=240,
        margin=dict(l=52, r=16, t=16, b=40),
    )
    st.plotly_chart(fig, use_container_width=True)


def _render_yield_table(yields: dict) -> None:
    css = (
        "<style>"
        "* { margin:0; padding:0; box-sizing:border-box; }"
        "body { background:#0B0E13; font-family:'IBM Plex Mono',monospace; overflow:hidden; }"
        "table { width:100%; border-collapse:collapse; }"
        "thead th { font-family:'IBM Plex Sans',sans-serif; font-size:10px; font-weight:600;"
        "  text-transform:uppercase; letter-spacing:0.14em; color:#5E5849;"
        "  padding:6px 10px; border-bottom:1px solid #232934; text-align:right; }"
        "thead th:first-child { text-align:left; }"
        "tbody tr { border-bottom:1px solid #181D26; }"
        "tbody td { padding:8px 10px; font-size:13px; color:#C7C0AE; text-align:right;"
        "  font-variant-numeric:tabular-nums; }"
        "tbody td:first-child { text-align:left; color:#F2ECDC; }"
        ".pos { color:#4F8C5E; } .neg { color:#B5494B; } .flat { color:#5E5849; }"
        "</style>"
    )
    head = (
        "<table><thead><tr>"
        "<th>Maturity</th><th>Yield</th><th>1D Chg</th>"
        "</tr></thead><tbody>"
    )
    rows = ""
    for label, d in yields.items():
        if d is None:
            rows += "<tr><td>" + label + "</td><td>—</td><td>—</td></tr>"
            continue
        rate = f"{d['rate']:.2f}%"
        chg = d["change_1d"]
        sign = "+" if chg is not None and chg >= 0 else ""
        chg_s = (sign + f"{chg:.2f}%") if chg is not None else "—"
        cls = "pos" if (chg or 0) > 0.001 else ("neg" if (chg or 0) < -0.001 else "flat")
        rows += (
            "<tr><td>" + label + "</td>"
            "<td>" + rate + "</td>"
            "<td><span class='" + cls + "'>" + chg_s + "</span></td>"
            "</tr>"
        )
    _html.html(css + head + rows + "</tbody></table>", height=240, scrolling=False)


def _render_sector_heatmap(sectors: dict) -> None:
    css = (
        "<style>"
        "* { margin:0; padding:0; box-sizing:border-box; }"
        "body { background:#0B0E13; font-family:'IBM Plex Sans',sans-serif; overflow:hidden; }"
        ".grid { display:grid; grid-template-columns:repeat(4,1fr); gap:4px; padding:2px; }"
        ".cell { padding:10px 12px; border-radius:2px; border:1px solid #232934; }"
        ".cell .name { font-size:11px; font-weight:600; color:#C7C0AE; letter-spacing:0.01em; }"
        ".cell .etf { font-family:'IBM Plex Mono',monospace; font-size:10px; color:#5E5849; margin-top:1px; }"
        ".cell .pct { font-family:'IBM Plex Mono',monospace; font-size:14px; font-weight:500; margin-top:5px;"
        "  font-variant-numeric:tabular-nums; }"
        ".pos { color:#4F8C5E; } .neg { color:#B5494B; } .flat { color:#5E5849; }"
        "</style>"
        "<div class='grid'>"
    )
    cells = ""
    for name, d in sectors.items():
        if d is None:
            cells += (
                "<div class='cell' style='background:#11151C'>"
                "<div class='name'>" + name + "</div>"
                "<div class='pct flat'>—</div>"
                "</div>"
            )
            continue
        pct = d["pct"]
        bg = _sector_bg(pct)
        sign = "+" if pct >= 0 else ""
        cls = "pos" if pct > 0.005 else ("neg" if pct < -0.005 else "flat")
        cells += (
            "<div class='cell' style='background:" + bg + "'>"
            "<div class='name'>" + name + "</div>"
            "<div class='etf'>" + d["etf"] + "</div>"
            "<div class='pct " + cls + "'>" + sign + f"{pct:.2f}%" + "</div>"
            "</div>"
        )
    _html.html(css + cells + "</div>", height=340, scrolling=False)


# ── Public entry point ────────────────────────────────────────────────────────

def render_macro() -> None:
    with st.spinner("Loading macro data…"):
        data = _get_macro_data()

    st.markdown(
        "<h5 style='font-family:\"IBM Plex Sans\",sans-serif;font-size:10px;font-weight:600;"
        "text-transform:uppercase;letter-spacing:0.14em;color:#5E5849;margin-bottom:8px;'>Index Performance</h5>",
        unsafe_allow_html=True,
    )
    _render_index_table(data["indices"])

    st.markdown("<div style='height:24px'></div>", unsafe_allow_html=True)

    col1, col2 = st.columns([3, 2])
    with col1:
        st.markdown(
            "<h5 style='font-family:\"IBM Plex Sans\",sans-serif;font-size:10px;font-weight:600;"
            "text-transform:uppercase;letter-spacing:0.14em;color:#5E5849;margin-bottom:8px;'>Yield Curve</h5>",
            unsafe_allow_html=True,
        )
        _render_yield_curve(data["yields"])
    with col2:
        st.markdown(
            "<h5 style='font-family:\"IBM Plex Sans\",sans-serif;font-size:10px;font-weight:600;"
            "text-transform:uppercase;letter-spacing:0.14em;color:#5E5849;margin-bottom:8px;'>Treasury Yields</h5>",
            unsafe_allow_html=True,
        )
        _render_yield_table(data["yields"])

    st.markdown("<div style='height:24px'></div>", unsafe_allow_html=True)

    st.markdown(
        "<h5 style='font-family:\"IBM Plex Sans\",sans-serif;font-size:10px;font-weight:600;"
        "text-transform:uppercase;letter-spacing:0.14em;color:#5E5849;margin-bottom:8px;'>Sector Performance — Today</h5>",
        unsafe_allow_html=True,
    )
    _render_sector_heatmap(data["sectors"])