Spaces:
Sleeping
Sleeping
Download ui/components.py from PrinceTires/PrinceAI: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/PrinceTires/PrinceAI/resolve/main/ui/components.py
- Command line
-
hf download hf://spaces/PrinceTires/PrinceAI/ui/components.py
-
curl -L -o components.py https://huggingface.co/spaces/PrinceTires/PrinceAI/resolve/main/ui/components.py
14.8 kB
| """ | |
| 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( | |
| """ | |
| <style> | |
| @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@400;500&display=swap'); | |
| /* Reset */ | |
| .stApp { background: #050810; } | |
| * { font-family: 'Inter', sans-serif; } | |
| /* Hide default streamlit header */ | |
| header[data-testid="stHeader"] { display: none; } | |
| /* Custom app header bar */ | |
| .app-header { | |
| background: #080C14; | |
| border-bottom: 1px solid #1F2937; | |
| padding: 0.75rem 1.5rem; | |
| display: flex; | |
| align-items: center; | |
| gap: 1rem; | |
| margin: -1rem -1rem 1.5rem -1rem; | |
| } | |
| .app-logo { | |
| font-family: 'Space Grotesk', sans-serif; | |
| font-size: 1.25rem; | |
| font-weight: 700; | |
| color: #F9FAFB; | |
| } | |
| .app-logo span { color: #2563EB; } | |
| /* Sidebar */ | |
| section[data-testid="stSidebar"] { | |
| background: #080C14 !important; | |
| border-right: 1px solid #1F2937; | |
| } | |
| section[data-testid="stSidebar"] .stMarkdown { color: #F9FAFB; } | |
| section[data-testid="stSidebar"] .stTextInput input { | |
| background: #0D1117; | |
| border: 1px solid #1F2937; | |
| border-radius: 6px; | |
| color: #F9FAFB; | |
| font-size: 0.85rem; | |
| } | |
| section[data-testid="stSidebar"] .stTextInput input:focus { | |
| border-color: #2563EB; | |
| box-shadow: 0 0 0 2px #2563EB22; | |
| } | |
| section[data-testid="stSidebar"] .stSelectbox > div { | |
| background: #0D1117; | |
| border: 1px solid #1F2937; | |
| border-radius: 6px; | |
| } | |
| /* Buttons */ | |
| .stButton button { | |
| background: #2563EB; | |
| color: white; | |
| border: none; | |
| border-radius: 8px; | |
| font-weight: 600; | |
| letter-spacing: 0.02em; | |
| transition: all 0.2s; | |
| } | |
| .stButton button:hover { | |
| background: #1D4ED8; | |
| box-shadow: 0 0 20px #2563EB44; | |
| transform: translateY(-1px); | |
| } | |
| .stButton button[kind="secondary"] { | |
| background: transparent; | |
| border: 1px solid #1F2937; | |
| color: #6B7280; | |
| } | |
| .stButton button[kind="secondary"]:hover { | |
| background: #111827; | |
| border-color: #2563EB; | |
| color: #F9FAFB; | |
| } | |
| /* Ticker card buttons - card-like appearance for secondary buttons in first row */ | |
| .main .block-container > div:first-of-type [data-testid="column"] .stButton button[kind="secondary"] { | |
| background: #0D1117 !important; | |
| border: 1px solid #1F2937 !important; | |
| border-radius: 12px !important; | |
| color: #F9FAFB !important; | |
| font-size: 0.85rem !important; | |
| padding: 1rem !important; | |
| text-align: center !important; | |
| } | |
| .main .block-container > div:first-of-type [data-testid="column"] .stButton button[kind="secondary"]:hover { | |
| border-color: #2563EB !important; | |
| box-shadow: 0 0 20px #2563EB22 !important; | |
| transform: translateY(-2px); | |
| } | |
| /* Chart container */ | |
| .chart-container { | |
| background: #0D1117; | |
| border: 1px solid #1F2937; | |
| border-radius: 16px; | |
| padding: 1.5rem; | |
| margin: 1rem 0; | |
| } | |
| /* Time range pill buttons */ | |
| .pill-btn { | |
| display: inline-block; | |
| padding: 4px 12px; | |
| border-radius: 20px; | |
| font-size: 0.8rem; | |
| font-weight: 500; | |
| cursor: pointer; | |
| border: 1px solid #1F2937; | |
| background: #0D1117; | |
| color: #6B7280; | |
| } | |
| .pill-btn.active { | |
| background: #2563EB; | |
| border-color: #2563EB; | |
| color: white; | |
| } | |
| /* Metric cards */ | |
| [data-testid="metric-container"] { | |
| background: #0D1117; | |
| border: 1px solid #1F2937; | |
| border-radius: 10px; | |
| padding: 1rem; | |
| } | |
| /* Headers */ | |
| h1, h2, h3 { | |
| font-family: 'Space Grotesk', sans-serif; | |
| color: #F9FAFB; | |
| } | |
| /* Plotly chart */ | |
| .js-plotly-plot { border-radius: 12px; } | |
| /* Expander */ | |
| .streamlit-expanderHeader { | |
| background: #0D1117 !important; | |
| border: 1px solid #1F2937 !important; | |
| border-radius: 8px !important; | |
| color: #6B7280 !important; | |
| font-size: 0.85rem; | |
| } | |
| /* Analysis summary card */ | |
| .analysis-card { | |
| background: #0D1117; | |
| border: 1px solid #1F2937; | |
| border-left: 3px solid #2563EB; | |
| border-radius: 8px; | |
| padding: 1.2rem 1.5rem; | |
| margin-bottom: 0.75rem; | |
| } | |
| /* Trend badge */ | |
| .badge-bearish { | |
| background: #EF444422; | |
| color: #EF4444; | |
| border: 1px solid #EF4444; | |
| border-radius: 4px; | |
| padding: 2px 10px; | |
| font-size: 0.75rem; | |
| font-family: monospace; | |
| letter-spacing: 0.1em; | |
| } | |
| .badge-bullish { | |
| background: #10B98122; | |
| color: #10B981; | |
| border: 1px solid #10B981; | |
| border-radius: 4px; | |
| padding: 2px 10px; | |
| font-size: 0.75rem; | |
| font-family: monospace; | |
| letter-spacing: 0.1em; | |
| } | |
| .badge-neutral { | |
| background: #F59E0B22; | |
| color: #F59E0B; | |
| border: 1px solid #F59E0B; | |
| border-radius: 4px; | |
| padding: 2px 10px; | |
| font-size: 0.75rem; | |
| font-family: monospace; | |
| letter-spacing: 0.1em; | |
| } | |
| /* Quick stat chips */ | |
| .stat-chip { | |
| display: inline-block; | |
| background: #111827; | |
| border: 1px solid #1F2937; | |
| border-radius: 4px; | |
| padding: 3px 10px; | |
| margin: 3px; | |
| font-size: 0.78rem; | |
| font-family: monospace; | |
| color: #6B7280; | |
| } | |
| /* Detail section cards */ | |
| .detail-card { | |
| background: #0D1117; | |
| border: 1px solid #1F2937; | |
| border-radius: 6px; | |
| padding: 1rem 1.2rem; | |
| margin-bottom: 0.6rem; | |
| } | |
| .detail-card h4 { | |
| color: #2563EB; | |
| font-size: 0.85rem; | |
| margin-bottom: 0.5rem; | |
| font-family: 'Space Grotesk', sans-serif; | |
| } | |
| .detail-card p { | |
| color: #6B7280; | |
| font-size: 0.88rem; | |
| line-height: 1.6; | |
| margin: 0; | |
| } | |
| /* Main content */ | |
| .main .block-container { padding: 2rem 3rem; max-width: 100%; } | |
| </style> | |
| """, | |
| 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", "<br>") 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'<div class="analysis-card">' | |
| f'<span class="{badge_class}">{_escape_html(trend.upper())}</span>' | |
| f'<p style="color:#6B7280; font-size:0.9rem; line-height:1.6; margin:0.75rem 0 0 0;">{summary}</p>' | |
| f'<div style="margin-top:0.75rem;">' | |
| f'<span class="stat-chip">Signal: {_escape_html(quick_stats.get("signal", "N/A"))}</span>' | |
| f'<span class="stat-chip">Target: {_escape_html(quick_stats.get("target_price", "N/A"))}</span>' | |
| f'<span class="stat-chip">Stop: {_escape_html(quick_stats.get("stop_loss", "N/A"))}</span>' | |
| f'<span class="stat-chip">Horizon: {_escape_html(quick_stats.get("time_horizon", "N/A"))}</span>' | |
| f'</div>' | |
| f'<p style="color:#6B7280; font-size:0.8rem; margin-top:0.8rem;">' | |
| f'Confidence: {confidence} {_confidence_dots(confidence)}' | |
| f'</p>' | |
| f'</div>', | |
| 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'<div class="detail-card">' | |
| f'<h4>{title}</h4>' | |
| f'<p>{text}</p>' | |
| f'</div>', | |
| 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 | |