import streamlit as st import json import plotly.graph_objects as go import plotly.express as px from datetime import datetime, timezone, timedelta import threading import time import pandas as pd import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from collector import DataCollector from analyzer import SentimentAnalyzer from config import COMMODITY_CONFIGS, REFRESH_INTERVAL_SECONDS from groq_client import GroqAnalyzer import cache_manager import build_landing st.set_page_config( page_title="Commodity Sentiment Dashboard", page_icon="📊", layout="wide", initial_sidebar_state="collapsed", ) BIAS_COLORS = { "Strong Buy": "#30D158", "Buy": "#34C759", "Neutral": "#FFD60A", "Sell": "#FF453A", "Strong Sell": "#FF3B30", } MOOD_ICONS = {"Risk-Off": "🛡️", "Risk-On": "📈"} APPLE_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Inter', Roboto, Helvetica, Arial, sans-serif" MYT = timezone(timedelta(hours=8)) ENV_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env") if os.path.exists(ENV_FILE): with open(ENV_FILE, "r") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: key, _, val = line.partition("=") os.environ.setdefault(key.strip(), val.strip()) groq_client = GroqAnalyzer() # Start background landing.html generator (runs once on server start) if "_landing_started" not in st.session_state: st.session_state["_landing_started"] = True build_landing.run_background(interval_sec=REFRESH_INTERVAL_SECONDS) @st.cache_data(ttl=REFRESH_INTERVAL_SECONDS, show_spinner=False) def _fetch_single(commodity="gold"): """Low-level fetch for one commodity. Cached + parallelized.""" cfg = COMMODITY_CONFIGS.get(commodity, COMMODITY_CONFIGS["gold"]) collector = DataCollector(commodity=commodity) analyzer = SentimentAnalyzer(commodity=commodity, groq_client=groq_client) price_data = collector.fetch_price() market_data = collector.fcpo_market_data() if commodity == "fcpo" else None data = collector.collect_all(groq_client=groq_client) result = analyzer.run_full_analysis(data["articles"]) result["collection_meta"] = { "total_articles": data["total_articles"], "rss_count": data["rss_count"], "web_count": data["web_count"], "timestamp": data["timestamp"], "price_label": cfg["price_label"], } return result, data, price_data, market_data def _prefetch_commodity(comm): """Background thread: fetch one commodity into session cache.""" try: r, d, p, m = _fetch_single(comm) st.session_state["_commodity_data"][comm] = { "result": r, "data": d, "price_data": p, "market_data": m, "loaded_at": datetime.now(timezone.utc).isoformat(), } except Exception: pass _DISK_CACHE_LOCK = threading.Lock() def get_commodity_data(commodity="gold"): """Return cached data for commodity. Priority: session > disk > network.""" cache_key = "_commodity_data" if cache_key not in st.session_state: st.session_state[cache_key] = {} data_dict = st.session_state[cache_key] # 1. Session cache (fastest) if commodity in data_dict and "result" in data_dict[commodity]: d = data_dict[commodity] return d["result"], d["data"], d["price_data"], d["market_data"] # 2. Disk cache (survives refresh/restart) disk_result, disk_data, disk_price, disk_market = cache_manager.load( commodity, ttl_seconds=REFRESH_INTERVAL_SECONDS ) if disk_result is not None: data_dict[commodity] = { "result": disk_result, "data": disk_data, "price_data": disk_price, "market_data": disk_market, "loaded_at": datetime.now(timezone.utc).isoformat(), "source": "disk", } st.session_state[cache_key] = data_dict for comm in ["gold", "wti", "fcpo"]: if comm != commodity and (comm not in data_dict or "error" in data_dict.get(comm, {})): threading.Thread(target=_prefetch_commodity, args=(comm,), daemon=True).start() return disk_result, disk_data, disk_price, disk_market # 3. Network fetch (slowest) r, d, p, m = _fetch_single(commodity) data_dict[commodity] = { "result": r, "data": d, "price_data": p, "market_data": m, "loaded_at": datetime.now(timezone.utc).isoformat(), "source": "network", } st.session_state[cache_key] = data_dict # Persist to disk (thread-safe) with _DISK_CACHE_LOCK: cache_manager.save(commodity, r, d, p, m) # Background prefetch other commodities for comm in ["gold", "wti", "fcpo"]: if comm != commodity and (comm not in data_dict or "error" in data_dict.get(comm, {})): threading.Thread(target=_prefetch_commodity, args=(comm,), daemon=True).start() return r, d, p, m def render_skeleton(): """CSS shimmer loading animation while data loads.""" st.markdown(f"""
""", unsafe_allow_html=True) def render_gauge(score, title, min_val=-100, max_val=100): bar_color = "#FFD60A" if -25 <= score <= 25 else ("#30D158" if score > 25 else "#FF453A") fig = go.Figure(go.Indicator( mode="gauge+number+delta", value=score, domain={"x": [0, 1], "y": [0, 1]}, title={"text": title, "font": {"size": 15, "color": "#86868B", "family": APPLE_FONT}}, delta={"reference": 0, "increasing": {"color": "#30D158", "symbol": "▲"}, "decreasing": {"color": "#FF453A", "symbol": "▼"}}, number={"font": {"size": 36, "color": "#F5F5F7", "family": APPLE_FONT, "weight": 600}}, gauge={ "axis": { "range": [min_val, max_val], "tickwidth": 0.5, "tickcolor": "rgba(142,142,147,0.3)", "tickfont": {"size": 9, "color": "#86868B", "family": APPLE_FONT}, }, "bar": {"color": bar_color, "thickness": 0.6, "line": {"width": 0}}, "bgcolor": "rgba(0,0,0,0)", "steps": [ {"range": [-100, -75], "color": "rgba(255,59,48,0.1)"}, {"range": [-75, -25], "color": "rgba(255,69,58,0.07)"}, {"range": [-25, 25], "color": "rgba(255,214,10,0.06)"}, {"range": [25, 75], "color": "rgba(48,209,88,0.07)"}, {"range": [75, 100], "color": "rgba(52,199,90,0.1)"}, ], "threshold": { "line": {"color": "#F5F5F7", "width": 2}, "thickness": 0.9, "value": score, }, }, )) fig.update_layout( height=260, margin=dict(l=10, r=10, t=50, b=10), paper_bgcolor="rgba(0,0,0,0)", font={"color": "#F5F5F7", "family": APPLE_FONT}, ) return fig def render_category_bar(category_counts): if not category_counts: return None cats = list(category_counts.keys()) vals = list(category_counts.values()) colors = ["#FF9F0A" if v > 0 else "rgba(142,142,147,0.15)" for v in vals] fig = go.Figure(go.Bar( x=cats, y=vals, marker_color=colors, text=vals, textposition="auto", marker_line_width=0, marker_line_color="rgba(0,0,0,0)", textfont={"size": 12, "color": "#F5F5F7", "family": APPLE_FONT}, )) fig.update_layout( height=260, margin=dict(l=10, r=10, t=40, b=30), paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", font={"color": "#86868B", "size": 11, "family": APPLE_FONT}, title={"text": "KEYWORD CATEGORY HITS", "font": {"size": 11, "color": "#86868B", "family": APPLE_FONT, "weight": 600}}, xaxis=dict(tickangle=0, gridcolor="rgba(0,0,0,0)", tickfont={"size": 10, "color": "#86868B", "family": APPLE_FONT}), yaxis=dict(gridcolor="rgba(142,142,147,0.08)", tickfont={"size": 10, "color": "#86868B", "family": APPLE_FONT}), ) return fig def render_sentiment_timeline(articles): if not articles: return None df_data = [] for a in articles: vader_s = a.get("vader_score", 0) df_data.append({"title": a["title"][:50], "score": vader_s, "category": ", ".join(a.get("categories", []))[:30]}) df = pd.DataFrame(df_data) fig = px.bar(df, x=df.index, y="score", color="score", color_continuous_scale=["#FF453A", "#FFD60A", "#30D158"], hover_data=["title"]) fig.update_traces(marker_line_width=0, marker_line_color="rgba(0,0,0,0)") fig.update_layout( height=260, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", font={"color": "#86868B", "size": 11, "family": APPLE_FONT}, title={"text": "ARTICLE SENTIMENT DISTRIBUTION", "font": {"size": 11, "color": "#86868B", "family": APPLE_FONT, "weight": 600}}, xaxis=dict(title="", gridcolor="rgba(0,0,0,0)", tickfont={"size": 9, "color": "#86868B"}), yaxis=dict(title="", gridcolor="rgba(142,142,147,0.08)", tickfont={"size": 9, "color": "#86868B"}), coloraxis_colorbar=dict( title="", tickfont={"size": 9, "color": "#86868B"}, thickness=12, len=0.6, ), ) return fig def metric_card(label, value, delta=None, delta_color=None): delta_html = "" if delta is not None: dc = delta_color or ("#30D158" if "+" in str(delta) else "#FF453A" if "-" in str(delta) else "#86868B") delta_html = f'
{delta}
' return f"""
{label}
{value}
{delta_html}
""" def main(): st.markdown(f""" """, unsafe_allow_html=True) with st.sidebar: st.markdown(f"
ABOUT
", unsafe_allow_html=True) st.markdown(f"
Real-time sentiment for Gold, WTI Crude Oil & FCPO Palm Oil.

Groq AI + VADER NLP engine scanning RSS feeds and news articles.

Daily Telegram report at 6:01 AM MYT.

Prepared by @PedotTTRG
", unsafe_allow_html=True) if "commodity" not in st.session_state: st.session_state["commodity"] = "gold" commodity = st.session_state["commodity"] cfg = COMMODITY_CONFIGS.get(commodity, COMMODITY_CONFIGS["gold"]) TELEGRAM_BOT = os.environ.get("TELEGRAM_BOT_USERNAME", "SentimentIntelligence26Bot") SENANGPAY_URL = os.environ.get("SENANGPAY_URL", "https://app.senangpay.my/payment/177739832230") st.markdown(f'''
Commodity Sentiment Intelligence
{cfg["display_name"]}
{datetime.now(MYT).strftime("%I:%M %p")} MYT
Auto-refresh 5 min
✈️ Get Via Telegram ☕ Support Us
''', unsafe_allow_html=True) col_gold, col_wti, col_fcpo = st.columns([1, 1, 1]) with col_gold: if st.button("🥇 GOLD", key="btn_gold", use_container_width=True): st.session_state["commodity"] = "gold" st.rerun() with col_wti: if st.button("🛢️ WTI CRUDE OIL", key="btn_wti", use_container_width=True): st.session_state["commodity"] = "wti" st.rerun() with col_fcpo: if st.button("🌴 FCPO PALM OIL", key="btn_fcpo", use_container_width=True): st.session_state["commodity"] = "fcpo" st.rerun() if st.button("Refresh Analysis", use_container_width=False): st.cache_data.clear() st.rerun() # Show skeleton while data loads for first time cache_key = "_commodity_data" if cache_key not in st.session_state: st.session_state[cache_key] = {} has_cached = commodity in st.session_state[cache_key] and "result" in st.session_state[cache_key][commodity] if not has_cached: render_skeleton() result, data, price_data, market_data = get_commodity_data(commodity) a1 = result["analysis_1_macro"] a2 = result["analysis_2_sentiment"] a3 = result["analysis_3_dxy"] fs = result["final_synthesis"] meta = result["meta"] cm = result["collection_meta"] sk = cfg["score_key"] bias_key = f"final_{sk}_bias" score_key = f"{sk}_sentiment_score" bias_color = BIAS_COLORS.get(fs[bias_key], "#FFD60A") currency = cfg.get("currency", "$") price_str = "" if price_data and price_data.get("price"): price_val = price_data["price"] price_str = f'{currency}{price_val:,.2f}' if price_data.get("change") is not None: chg = price_data["change"] pct = price_data["change_pct"] chg_color = "#30D158" if chg >= 0 else "#FF453A" sign = "+" if chg >= 0 else "" price_str += f'
{sign}{chg:.2f} ({sign}{pct:.2f}%)
' pull_time_str = "" try: pull_dt = datetime.fromisoformat(cm["timestamp"].replace("Z", "+00:00")).astimezone(MYT) pull_time_str = pull_dt.strftime("%I:%M %p") except Exception: pull_time_str = "—" ai_badge = groq_client.get_badge_html() if groq_client and groq_client.available else "" st.markdown(f'''
Signal{ai_badge}
{fs[bias_key]}
{fs["justification"]}
{cfg["price_label"]}
{price_str}
Data as of {pull_time_str} MYT
''', unsafe_allow_html=True) col1, col2, col3, col4 = st.columns(4) with col1: st.markdown(metric_card("Sentiment Score", f"{a2[score_key]}", a2["sentiment_label"]), unsafe_allow_html=True) with col2: st.markdown(metric_card("Market Mood", a1["overall_market_mood"]), unsafe_allow_html=True) with col3: if commodity == "fcpo": myr_bias = meta.get("myr_bias", "Neutral") myr_delta = "↓ Ringgit" if myr_bias == "Bearish" else "↑ Ringgit" if myr_bias == "Bullish" else "—" myr_dc = "#30D158" if myr_bias == "Bearish" else "#FF453A" if myr_bias == "Bullish" else "#8E8E93" st.markdown(metric_card("MYR (Ringgit)", myr_bias, myr_delta, myr_dc), unsafe_allow_html=True) else: dxy_delta = "↑ Dollar" if a3["dxy_directional_bias"] == "Bullish" else "↓ Dollar" if a3["dxy_directional_bias"] == "Bearish" else "—" dxy_dc = "#FF453A" if a3["dxy_directional_bias"] == "Bullish" else "#30D158" if a3["dxy_directional_bias"] == "Bearish" else "#86868B" st.markdown(metric_card("DXY Bias", a3["dxy_directional_bias"], dxy_delta, dxy_dc), unsafe_allow_html=True) with col4: if commodity in ("wti", "fcpo"): supply_score = meta.get("supply_score", 0) supply_label = "Tight" if supply_score > 0.15 else "Oversupply" if supply_score < -0.15 else "Balanced" supply_dc = "#30D158" if supply_score > 0.15 else "#FF453A" if supply_score < -0.15 else "#FFD60A" st.markdown(metric_card("Supply", supply_label, f"{supply_score:+d}", supply_dc), unsafe_allow_html=True) else: ca_delta = "Over-leveraged" if a2["contrarian_signal"] == "YES" else "Normal range" ca_dc = "#FF9F0A" if a2["contrarian_signal"] == "YES" else "#30D158" st.markdown(metric_card("Contrarian Alert", a2["contrarian_signal"], ca_delta, ca_dc), unsafe_allow_html=True) if commodity == "fcpo" and market_data: md = market_data currency = cfg.get("currency", "RM") vol_display = md.get("volume_display") or "—" vol_raw = md.get("volume") vol_delta = f"{int(vol_raw):,} lots" if isinstance(vol_raw, (int, float)) and vol_raw else "" open_str = f"{currency}{md['open']:,.2f}" if md.get("open") else "—" high_str = f"{currency}{md['high']:,.2f}" if md.get("high") else "—" low_str = f"{currency}{md['low']:,.2f}" if md.get("low") else "—" prev_str = f"{currency}{md['prev_close']:,.2f}" if md.get("prev_close") else "—" day_range_str = md.get("day_range") or "—" week_range_str = md.get("week_range_52") or "—" settlement = md.get("settlement_type") or "Physical" contract = md.get("contract_size") or "25 MT" point_val = md.get("point_value") or "" st.markdown(f'''
Market Data — Last Session
''', unsafe_allow_html=True) mc1, mc2, mc3, mc4, mc5 = st.columns(5) with mc1: st.markdown(metric_card("Volume", vol_display, vol_delta, "#0A84FF"), unsafe_allow_html=True) with mc2: st.markdown(metric_card("Open", open_str, None), unsafe_allow_html=True) with mc3: st.markdown(metric_card("High", high_str, None, "#30D158"), unsafe_allow_html=True) with mc4: st.markdown(metric_card("Low", low_str, None, "#FF453A"), unsafe_allow_html=True) with mc5: st.markdown(metric_card("Prev Close", prev_str, None), unsafe_allow_html=True) contract_info = f"Settlement: {settlement} | Contract: {contract}" if point_val: contract_info += f" | Point: {point_val}" st.markdown(f'''
Day Range: {day_range_str} 52W Range: {week_range_str} {contract_info}
''', unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) col_gauge, col_bar, col_timeline = st.columns([1, 1, 1.5]) with col_gauge: fig_gauge = render_gauge(a2[score_key], "SENTIMENT GAUGE") st.plotly_chart(fig_gauge, width="stretch") with col_bar: fig_cat = render_category_bar(meta["category_counts"]) if fig_cat: st.plotly_chart(fig_cat, width="stretch") with col_timeline: fig_tl = render_sentiment_timeline(data["articles"]) if fig_tl: st.plotly_chart(fig_tl, width="stretch") st.markdown("
", unsafe_allow_html=True) col_macro, col_geo = st.columns(2) with col_macro: if commodity == "fcpo": st.markdown(f'
Supply & Policy
{a1["macro_event_impact"]}
Supply: {meta.get("supply_score",0):+d}
', unsafe_allow_html=True) else: st.markdown(f'
Macro & Fed
{a1["macro_event_impact"]}
Bias: {meta["macro_bias"]}
', unsafe_allow_html=True) with col_geo: st.markdown(f'
Geopolitical
{a1["geopolitical_summary"]}
Intensity: {meta["geo_intensity"]}
', unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown(f"
How to Read
", unsafe_allow_html=True) g1, g2, g3 = st.columns(3) with g1: st.markdown(f"
Sentiment Score
Range −100 to +100.
+50/+100 Bullish · −50/−100 Bearish
-20/+20 Neutral
VADER x keyword weight
", unsafe_allow_html=True) st.markdown(f"
DXY Bias
US Dollar direction.
Weak dollar = commodities go up
Strong dollar = commodities go down
", unsafe_allow_html=True) with g2: st.markdown(f"
Market Mood
📈 Risk-On = bullish for commodities
🛡️ Risk-Off = safe haven (gold up, oil demand down)
", unsafe_allow_html=True) st.markdown(f"
Contrarian Alert
⚠️ YES = sentiment over-leveraged, reversal possible
✅ Normal = within safe range
", unsafe_allow_html=True) with g3: st.markdown(f"
VADER (per article)
🟢 > +0.05 positive article
🟡 −0.05 to +0.05 neutral
🔴 < −0.05 negative article
", unsafe_allow_html=True) st.markdown(f"
Supply (WTI Only)
Tight = bullish (OPEC cuts, war)
Balanced = neutral
Oversupply = bearish
", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown(f'
Intelligence Feed
{len(data["articles"])} articles from {cm["total_articles"]} collected · {cm["rss_count"]} RSS · {cm["web_count"]} web
', unsafe_allow_html=True) articles_to_show = data["articles"][:20] if articles_to_show: for i, article in enumerate(articles_to_show): cat_str = " · ".join(article.get("categories", [])) vader_s = article.get("vader_score", 0) ic = "#30D158" if vader_s > 0.05 else "#FF453A" if vader_s < -0.05 else "#FFD60A" ks = article.get("keyword_score", 0) badge = f'{ks}' src = f'
Source
' if article.get("link") else "" age = article.get("age") age_html = f'🕐 {age} ago' if age else "" st.markdown(f'
{article["title"][:90]}
{badge}
{cat_str}
VADER {vader_s:.3f}{age_html}
{article["summary"][:200]}
{src}
', unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) st.markdown(f'
Daily reports at 6:01 AM MYT · /report /report\\_wti /report\\_fcpo on-demand · VADER + Groq AI Engine

Prepared by @PedotTTRG
', unsafe_allow_html=True) try: from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=REFRESH_INTERVAL_SECONDS * 1000, key="datarefresh") except ImportError: pass if __name__ == "__main__": main()