""" Reusable UI components: premium dark financial dashboard styling. """ import html import pandas as pd from typing import Any, Callable import plotly.graph_objects as go from plotly.subplots import make_subplots import streamlit as st from config import COLORS, MA_PERIODS def inject_custom_css() -> None: """Inject premium dark financial dashboard CSS.""" st.markdown( """ """, unsafe_allow_html=True, ) def render_ticker_card( ticker: str, stats: dict, is_active: bool, key: str ) -> bool: """ Render a mini ticker card for the top row. Returns True if this card was clicked. """ price = stats.get("current_price", 0) return_pct = stats.get("return_pct", 0) vol = stats.get("avg_volume", 0) vol_str = f"{vol/1e6:.1f}M" if vol >= 1e6 else f"{vol/1e3:.0f}K" arrow = "▲" if return_pct >= 0 else "▼" # Card as button - clicking selects this ticker btn_label = f"{ticker} · ${price:.2f} · {arrow}{return_pct:+.2f}%" btn_type = "primary" if is_active else "secondary" if st.button(btn_label, key=key, use_container_width=True, type=btn_type): return True return False def metric_card(label: str, value: str, delta: str | None = None) -> None: """Render a styled metric card.""" st.metric(label=label, value=value, delta=delta if delta else None) def _confidence_dots(level: str) -> str: """Return dot representation: Low ●●○○○, Medium ●●●○○, High ●●●●●.""" level_lower = (level or "").lower() if "high" in level_lower: return "●●●●●" if "medium" in level_lower or "med" in level_lower: return "●●●○○" return "●●○○○" def _escape_html(s: str) -> str: """Escape HTML to prevent broken rendering and XSS.""" return html.escape(str(s)).replace("\n", "
") if s else "" def render_analysis_display(parsed: dict[str, Any]) -> None: """ Render the structured AI analysis: summary card, quick stats, confidence, and collapsible detailed sections. """ trend = (parsed.get("trend") or "Neutral").strip() trend_lower = trend.lower() if "bear" in trend_lower: badge_class = "badge-bearish" elif "bull" in trend_lower: badge_class = "badge-bullish" else: badge_class = "badge-neutral" summary = _escape_html(parsed.get("summary") or "No summary available.") confidence = parsed.get("confidence") or "Medium" quick_stats = parsed.get("quick_stats") or {} sections = parsed.get("sections") or {} # Summary card st.markdown( f'
' f'{_escape_html(trend.upper())}' f'

{summary}

' f'
' f'Signal: {_escape_html(quick_stats.get("signal", "N/A"))}' f'Target: {_escape_html(quick_stats.get("target_price", "N/A"))}' f'Stop: {_escape_html(quick_stats.get("stop_loss", "N/A"))}' f'Horizon: {_escape_html(quick_stats.get("time_horizon", "N/A"))}' f'
' f'

' f'Confidence: {confidence} {_confidence_dots(confidence)}' f'

' f'
', unsafe_allow_html=True, ) # Detailed analysis (collapsible) with st.expander("▼ View Detailed Analysis", expanded=False): section_config = [ ("trend_analysis", "📈 Trend Analysis"), ("key_levels", "🎯 Key Levels"), ("pattern_recognition", "🔍 Pattern Recognition"), ("risk_factors", "⚠️ Risk Factors"), ("short_term_outlook", "🔭 Short-Term Outlook"), ] for key, title in section_config: text = _escape_html(sections.get(key) or "No content.") st.markdown( f'
' f'

{title}

' f'

{text}

' f'
', unsafe_allow_html=True, ) def render_analysis_carousel_modal( analysis_results: dict[str, dict], analysis_raw: dict[str, str], on_close: Callable | None = None, ) -> None: """Render a pop-out dialog with tabbed carousel to switch between all ticker analyses.""" tickers_with_analysis = list(analysis_results.keys()) tickers_with_raw = [t for t in analysis_raw.keys() if t not in analysis_results] all_tickers = tickers_with_analysis + tickers_with_raw if not all_tickers: st.info("No analyses yet. Run **Run Analysis** for a ticker first.") return tabs = st.tabs([f"📊 {t}" for t in all_tickers]) for i, ticker in enumerate(all_tickers): with tabs[i]: if ticker in analysis_results: render_analysis_display(analysis_results[ticker]) else: with st.expander("⚠️ Raw response (JSON parse failed)", expanded=True): st.text(analysis_raw.get(ticker, "")) st.markdown("---") if st.button("Close", type="primary", use_container_width=True) and on_close: on_close() st.rerun() def build_candlestick_chart( df: pd.DataFrame, ticker: str, show_ma: bool = True, show_bollinger: bool = False, show_volume: bool = True, ) -> go.Figure: """ Build candlestick chart with volume subplot, optional MAs and Bollinger Bands. Premium dark theme with green/red candles. """ row_heights = [0.7, 0.3] if show_volume else [1.0] fig = make_subplots( rows=2 if show_volume else 1, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=row_heights, subplot_titles=(f"{ticker} Price", "Volume") if show_volume else (f"{ticker} Price",), ) # Candlestick (Plotly doesn't support 8-digit hex for fillcolor, use rgba) fig.add_trace( go.Candlestick( x=df.index, open=df["Open"], high=df["High"], low=df["Low"], close=df["Close"], name="OHLC", increasing_line_color=COLORS["green"], decreasing_line_color=COLORS["red"], increasing_fillcolor="rgba(16, 185, 129, 0.2)", decreasing_fillcolor="rgba(239, 68, 68, 0.2)", ), row=1, col=1, ) # Moving averages if show_ma and "MA_20" in df.columns: fig.add_trace( go.Scatter( x=df.index, y=df["MA_20"], name="MA 20", line=dict(color="#2563EB", width=1.5), ), row=1, col=1, ) if show_ma and "MA_50" in df.columns: fig.add_trace( go.Scatter( x=df.index, y=df["MA_50"], name="MA 50", line=dict(color="#F59E0B", width=1.5), ), row=1, col=1, ) # Bollinger Bands if show_bollinger and "BB_upper" in df.columns: fig.add_trace( go.Scatter( x=df.index, y=df["BB_upper"], name="BB Upper", line=dict(color=COLORS["green"], width=1, dash="dot"), ), row=1, col=1, ) fig.add_trace( go.Scatter( x=df.index, y=df["BB_lower"], name="BB Lower", line=dict(color=COLORS["red"], width=1, dash="dot"), ), row=1, col=1, ) fig.add_trace( go.Scatter( x=df.index, y=df["BB_middle"], name="BB Middle", line=dict(color=COLORS["text_muted"], width=1), ), row=1, col=1, ) # Volume bars if show_volume: colors = [ COLORS["green"] if df["Close"].iloc[i] >= df["Open"].iloc[i] else COLORS["red"] for i in range(len(df)) ] fig.add_trace( go.Bar( x=df.index, y=df["Volume"], name="Volume", marker_color=colors, showlegend=False, ), row=2, col=1, ) # Layout - premium dark theme fig.update_layout( template="plotly_dark", paper_bgcolor="#0D1117", plot_bgcolor="#0D1117", font=dict(family="Inter", color="#6B7280", size=11), xaxis_rangeslider_visible=False, height=500, margin=dict(l=0, r=0, t=30, b=0), legend=dict( orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1, bgcolor="#0D1117", bordercolor="#1F2937", ), bargap=0.1, hoverlabel=dict( bgcolor="#111827", bordercolor="#2563EB", font=dict(color="#F9FAFB"), ), ) fig.update_xaxes( gridcolor="#1F2937", showgrid=True, zeroline=False, ) fig.update_yaxes( gridcolor="#1F2937", showgrid=True, zeroline=False, ) return fig