📊 FinScope Dashboard
Real-time financial intelligence powered by Yahoo Finance • {datetime.now().strftime('%A, %B %d, %Y')}
import streamlit as st import yfinance as yf import plotly.graph_objects as go import plotly.express as px from plotly.subplots import make_subplots import pandas as pd import numpy as np from datetime import datetime, timedelta from fpdf import FPDF import io import base64 import json import tempfile import os import json # ───────────────────────────────────────────── # PAGE CONFIG & THEME # ───────────────────────────────────────────── st.set_page_config( page_title="FinScope | Global Financial Dashboard", page_icon="📊", layout="wide", initial_sidebar_state="expanded", ) # ───────────────────────────────────────────── # CUSTOM CSS # ───────────────────────────────────────────── st.markdown(""" """, unsafe_allow_html=True) # ───────────────────────────────────────────── # CONSTANTS # ───────────────────────────────────────────── GLOBAL_INDICES = { # Indices "S&P 500": "^GSPC", "NASDAQ": "^IXIC", "Dow Jones": "^DJI", "FTSE 100": "^FTSE", "DAX": "^GDAXI", "Nikkei 225": "^N225", "Hang Seng": "^HSI", "SENSEX": "^BSESN", "NIFTY 50": "^NSEI", "ASX 200": "^AXJO", # Currencies "EUR/USD": "EURUSD=X", "GBP/USD": "GBPUSD=X", "USD/JPY": "JPY=X", # Commodities "Gold": "GC=F", "Brent Oil": "BZ=F", "Silver": "SI=F", # Crypto "Bitcoin": "BTC-USD", "Ethereum": "ETH-USD", } POPULAR_STOCKS = [ "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "BRK-B", "JPM", "V", "JNJ", "WMT", "PG", "MA", "UNH", "HD", "DIS", "BAC", "XOM", "NFLX", "ADBE", "CRM", "AMD", "INTC", "CSCO", "PFE", "KO", "PEP", "ABT", "MRK", "COST", "NKE", "ORCL", "LLY", "TMO", "AVGO", "TXN", "QCOM", "PYPL", "INTU", "AMAT", "ISRG", "BKNG", "GILD", "MDLZ", "ADP", "REGN", "VRTX", "LRCX", "MU", ] PERIOD_MAP = { "1 Day": "1d", "5 Days": "5d", "1 Month": "1mo", "3 Months": "3mo", "6 Months": "6mo", "1 Year": "1y", "2 Years": "2y", "5 Years": "5y", "10 Years": "10y", "Max": "max", } INTERVAL_MAP = { "1 Day": "5m", "5 Days": "15m", "1 Month": "1d", "3 Months": "1d", "6 Months": "1d", "1 Year": "1wk", "2 Years": "1wk", "5 Years": "1mo", "10 Years": "1mo", "Max": "1mo", } # ───────────────────────────────────────────── # DATA FETCHING HELPERS # ───────────────────────────────────────────── @st.cache_data(ttl=3600) def search_ticker(query: str): """Search for tickers based on a company name query.""" try: search = yf.Search(query, max_results=8) results = [] for res in search.quotes: if res.get('quoteType') in ('EQUITY', 'ETF', 'MUTUALFUND', 'INDEX', 'CRYPTOCURRENCY'): name = res.get('shortname') or res.get('longname') or res.get('symbol') results.append({ "symbol": res['symbol'], "name": name, "type": res.get('quoteType'), "exchange": res.get('exchDisp', 'N/A') }) return results except Exception: return [] def get_industry_peers(industry: str, sector: str): """Get a list of top 3 peer tickers for a given industry/sector.""" # Mapping of common industries to global leaders (tickers) peer_map = { "Consumer Electronics": ["MSFT", "GOOGL", "NVDA"], "Software—Infrastructure": ["AMZN", "GOOGL", "ORCL"], "Internet Content & Information": ["META", "GOOGL", "SNAP"], "Semiconductors": ["NVDA", "TSM", "AMD"], "Electric Vehicles": ["TSLA", "BYDDF", "NIO"], "Auto Manufacturers": ["TM", "TSLA", "VOW3.DE"], "Banks—Diversified": ["JPM", "BAC", "HSBC"], "Retailers": ["WMT", "AMZN", "COST"], "Energy": ["XOM", "CVX", "SHEL.L"], "Beverages—Non-Alcoholic": ["KO", "PEP", "MNST"], "Entertainment": ["DIS", "NFLX", "WBD"] } peers = peer_map.get(industry) if not peers: # Fallback to search-based discovery for niche industries try: search = yf.Search(industry, max_results=5) peers = [q['symbol'] for q in search.quotes if q.get('quoteType') == 'EQUITY'][:3] except Exception: peers = ["AAPL", "MSFT", "GOOGL"] # Final fallback return peers @st.cache_data(ttl=300) def fetch_peer_data(tickers: list): """Fetch key comparison metrics for a list of tickers.""" data = [] for t in tickers: try: s = yf.Ticker(t) i = s.info data.append({ "Ticker": t, "Name": i.get("shortName") or i.get("longName") or t, "Price": i.get("currentPrice") or i.get("regularMarketPrice"), "Market Cap": i.get("marketCap"), "P/E Ratio": i.get("trailingPE"), "Div Yield": i.get("dividendYield"), "Revenue": i.get("totalRevenue"), "Currency": i.get("currency", "USD") }) except Exception: continue return pd.DataFrame(data) # ───────────────────────────────────────────── # CACHING (Stock Data) # ───────────────────────────────────────────── @st.cache_data(ttl=300) def fetch_stock_data(ticker: str): """Fetch comprehensive stock data from yfinance.""" stock = yf.Ticker(ticker) info = {} try: info = stock.info if not info or 'longName' not in info: # Fallback for missing info hist = stock.history(period="1d") if not hist.empty: info['currentPrice'] = hist['Close'].iloc[-1] info['longName'] = ticker except Exception: pass return info @st.cache_data(ttl=120) def fetch_history(ticker: str, period: str, interval: str): """Fetch historical price data.""" stock = yf.Ticker(ticker) return stock.history(period=period, interval=interval) @st.cache_data(ttl=600) def fetch_index_data(symbol: str): """Fetch current index price.""" try: t = yf.Ticker(symbol) hist = t.history(period="2d") if len(hist) >= 2: current = hist["Close"].iloc[-1] prev = hist["Close"].iloc[-2] change = current - prev pct = (change / prev) * 100 return current, change, pct elif len(hist) == 1: return hist["Close"].iloc[-1], 0, 0 except Exception: pass return None, None, None @st.cache_data(ttl=300) def fetch_recommendations(ticker: str): """Fetch analyst recommendations.""" try: stock = yf.Ticker(ticker) recs = stock.recommendations if recs is not None and not recs.empty: return recs except Exception: pass return pd.DataFrame() @st.cache_data(ttl=300) def fetch_actions(ticker: str): """Fetch stock actions (dividends, splits).""" try: stock = yf.Ticker(ticker) return stock.actions except Exception: return pd.DataFrame() @st.cache_data(ttl=300) def fetch_financials(ticker: str): """Fetch financial statements.""" try: stock = yf.Ticker(ticker) income = stock.income_stmt balance = stock.balance_sheet cashflow = stock.cashflow return income, balance, cashflow except Exception: return pd.DataFrame(), pd.DataFrame(), pd.DataFrame() @st.cache_data(ttl=300) def fetch_news(ticker: str): """Fetch latest stock news.""" try: stock = yf.Ticker(ticker) return stock.news except Exception: return [] # ───────────────────────────────────────────── # PDF REPORT GENERATOR # ───────────────────────────────────────────── class EquityResearchPDF(FPDF): """Custom PDF class for equity research reports.""" def __init__(self): super().__init__() self.set_auto_page_break(auto=True, margin=20) def header(self): self.set_fill_color(15, 12, 41) self.rect(0, 0, 210, 35, 'F') self.set_font("Helvetica", "B", 18) self.set_text_color(255, 255, 255) self.set_y(8) self.cell(0, 10, "FinScope Equity Research Report", align="C", new_x="LMARGIN", new_y="NEXT") self.set_font("Helvetica", "", 9) self.set_text_color(180, 180, 200) self.cell(0, 6, f"Generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}", align="C", new_x="LMARGIN", new_y="NEXT") self.ln(10) def footer(self): self.set_y(-15) self.set_font("Helvetica", "I", 8) self.set_text_color(128, 128, 128) self.cell(0, 10, f"FinScope Research | Page {self.page_no()}/{{nb}} | For informational purposes only", align="C") def section_title(self, title): self.set_font("Helvetica", "B", 13) self.set_text_color(48, 43, 99) self.cell(0, 10, title, new_x="LMARGIN", new_y="NEXT") self.set_draw_color(102, 126, 234) self.set_line_width(0.8) self.line(10, self.get_y(), 200, self.get_y()) self.ln(4) def sub_title(self, title): self.set_font("Helvetica", "B", 11) self.set_text_color(80, 80, 100) self.cell(0, 8, title, new_x="LMARGIN", new_y="NEXT") self.ln(1) def body_text(self, text): self.set_font("Helvetica", "", 10) self.set_text_color(60, 60, 60) self.multi_cell(0, 5.5, text) self.ln(2) def key_value(self, key, value): self.set_font("Helvetica", "B", 10) self.set_text_color(80, 80, 100) self.cell(65, 6, str(key), new_x="RIGHT") self.set_font("Helvetica", "", 10) self.set_text_color(40, 40, 40) self.cell(0, 6, str(value), new_x="LMARGIN", new_y="NEXT") def add_table(self, headers, data, col_widths=None): if col_widths is None: col_widths = [190 / len(headers)] * len(headers) # Header self.set_fill_color(48, 43, 99) self.set_text_color(255, 255, 255) self.set_font("Helvetica", "B", 9) for i, h in enumerate(headers): self.cell(col_widths[i], 8, str(h), border=1, fill=True, align="C") self.ln() # Data self.set_font("Helvetica", "", 9) self.set_text_color(60, 60, 60) fill = False for row in data: if fill: self.set_fill_color(240, 240, 250) else: self.set_fill_color(255, 255, 255) for i, val in enumerate(row): self.cell(col_widths[i], 7, str(val), border=1, fill=True, align="C") self.ln() fill = not fill self.ln(3) def generate_research_pdf(ticker: str, info: dict, hist: pd.DataFrame, recs: pd.DataFrame, actions: pd.DataFrame, income: pd.DataFrame, balance: pd.DataFrame, cashflow: pd.DataFrame): """Generate a comprehensive equity research PDF report.""" pdf = EquityResearchPDF() pdf.alias_nb_pages() pdf.add_page() name = info.get("longName", ticker) sector = info.get("sector", "N/A") industry = info.get("industry", "N/A") country = info.get("country", "N/A") exchange = info.get("exchange", "N/A") currency = info.get("currency", "USD") # ── Cover Info pdf.set_font("Helvetica", "B", 22) pdf.set_text_color(15, 12, 41) pdf.cell(0, 12, f"{name} ({ticker})", new_x="LMARGIN", new_y="NEXT") pdf.set_font("Helvetica", "", 11) pdf.set_text_color(100, 100, 120) pdf.cell(0, 7, f"{sector} | {industry} | {exchange} | {country}", new_x="LMARGIN", new_y="NEXT") pdf.ln(8) # ── Company Overview pdf.section_title("1. Company Overview") summary = info.get("longBusinessSummary", "No business summary available.") pdf.body_text(summary) # ── Key Metrics pdf.section_title("2. Key Financial Metrics") def fmt(val, prefix="", suffix="", div=1): if val is None or val == "N/A": return "N/A" try: v = float(val) / div if div >= 1e9: return f"{prefix}{v:.2f}B{suffix}" elif div >= 1e6: return f"{prefix}{v:.2f}M{suffix}" return f"{prefix}{v:,.2f}{suffix}" except (ValueError, TypeError): return str(val) metrics = [ ("Market Cap", fmt(info.get("marketCap"), prefix=f"{currency} ", div=1e9)), ("Enterprise Value", fmt(info.get("enterpriseValue"), prefix=f"{currency} ", div=1e9)), ("Current Price", fmt(info.get("currentPrice"), prefix=f"{currency} ")), ("52-Week High", fmt(info.get("fiftyTwoWeekHigh"), prefix=f"{currency} ")), ("52-Week Low", fmt(info.get("fiftyTwoWeekLow"), prefix=f"{currency} ")), ("P/E Ratio (Trailing)", fmt(info.get("trailingPE"))), ("P/E Ratio (Forward)", fmt(info.get("forwardPE"))), ("PEG Ratio", fmt(info.get("pegRatio"))), ("Price to Book", fmt(info.get("priceToBook"))), ("EPS (Trailing)", fmt(info.get("trailingEps"), prefix=f"{currency} ")), ("EPS (Forward)", fmt(info.get("forwardEps"), prefix=f"{currency} ")), ("Dividend Yield", fmt(info.get("dividendYield", 0) * 100 if info.get("dividendYield") else None, suffix="%")), ("Beta", fmt(info.get("beta"))), ("Revenue", fmt(info.get("totalRevenue"), prefix=f"{currency} ", div=1e9)), ("Gross Margins", fmt(info.get("grossMargins", 0) * 100 if info.get("grossMargins") else None, suffix="%")), ("Operating Margins", fmt(info.get("operatingMargins", 0) * 100 if info.get("operatingMargins") else None, suffix="%")), ("Profit Margins", fmt(info.get("profitMargins", 0) * 100 if info.get("profitMargins") else None, suffix="%")), ("ROE", fmt(info.get("returnOnEquity", 0) * 100 if info.get("returnOnEquity") else None, suffix="%")), ("Debt to Equity", fmt(info.get("debtToEquity"))), ("Free Cash Flow", fmt(info.get("freeCashflow"), prefix=f"{currency} ", div=1e9)), ] for key, val in metrics: pdf.key_value(key, val) pdf.ln(4) # ── Price Performance pdf.section_title("3. Historical Price Performance") if not hist.empty: pdf.sub_title("Recent Price Summary") recent = hist.tail(20) headers = ["Date", "Open", "High", "Low", "Close", "Volume"] data = [] for idx, row in recent.iterrows(): date_str = idx.strftime("%Y-%m-%d") if hasattr(idx, 'strftime') else str(idx)[:10] data.append([ date_str, f"{row.get('Open', 0):.2f}", f"{row.get('High', 0):.2f}", f"{row.get('Low', 0):.2f}", f"{row.get('Close', 0):.2f}", f"{int(row.get('Volume', 0)):,}", ]) pdf.add_table(headers, data, col_widths=[30, 28, 28, 28, 28, 48]) # Performance stats if len(hist) > 1: pdf.sub_title("Performance Statistics") close = hist["Close"] returns = close.pct_change().dropna() pdf.key_value("Period Return", f"{((close.iloc[-1] / close.iloc[0]) - 1) * 100:.2f}%") pdf.key_value("Average Daily Return", f"{returns.mean() * 100:.4f}%") pdf.key_value("Volatility (Std Dev)", f"{returns.std() * 100:.4f}%") pdf.key_value("Max Drawdown", f"{((close / close.cummax()) - 1).min() * 100:.2f}%") pdf.key_value("Highest Close", f"{currency} {close.max():.2f}") pdf.key_value("Lowest Close", f"{currency} {close.min():.2f}") pdf.ln(3) # ── Analyst Recommendations pdf.section_title("4. Analyst Recommendations") target_high = info.get("targetHighPrice") target_low = info.get("targetLowPrice") target_mean = info.get("targetMeanPrice") target_median = info.get("targetMedianPrice") rec = info.get("recommendationKey", "N/A") num_analysts = info.get("numberOfAnalystOpinions", "N/A") pdf.key_value("Consensus Recommendation", rec.upper() if rec != "N/A" else "N/A") pdf.key_value("Number of Analysts", str(num_analysts)) pdf.key_value("Price Target (Mean)", fmt(target_mean, prefix=f"{currency} ")) pdf.key_value("Price Target (Median)", fmt(target_median, prefix=f"{currency} ")) pdf.key_value("Price Target (High)", fmt(target_high, prefix=f"{currency} ")) pdf.key_value("Price Target (Low)", fmt(target_low, prefix=f"{currency} ")) pdf.ln(2) if not recs.empty: pdf.sub_title("Recent Analyst Actions") recent_recs = recs.tail(15) headers_r = ["Date", "Firm", "To Grade", "From Grade", "Action"] data_r = [] for idx, row in recent_recs.iterrows(): date_str = idx.strftime("%Y-%m-%d") if hasattr(idx, 'strftime') else str(idx)[:10] firm = str(row.get("Firm", "N/A"))[:25] to_grade = str(row.get("To Grade", row.get("toGrade", "N/A"))) from_grade = str(row.get("From Grade", row.get("fromGrade", "-"))) action = str(row.get("Action", row.get("action", "N/A"))) data_r.append([date_str, firm, to_grade, from_grade, action]) pdf.add_table(headers_r, data_r, col_widths=[28, 55, 38, 38, 31]) # ── Stock Actions pdf.section_title("5. Corporate Actions (Dividends & Splits)") if not actions.empty: recent_actions = actions.tail(20) headers_a = ["Date"] if "Dividends" in recent_actions.columns: headers_a.append("Dividend") if "Stock Splits" in recent_actions.columns: headers_a.append("Split Ratio") data_a = [] for idx, row in recent_actions.iterrows(): date_str = idx.strftime("%Y-%m-%d") if hasattr(idx, 'strftime') else str(idx)[:10] r = [date_str] if "Dividends" in recent_actions.columns: d = row.get("Dividends", 0) r.append(f"{currency} {d:.4f}" if d > 0 else "-") if "Stock Splits" in recent_actions.columns: s = row.get("Stock Splits", 0) r.append(f"{s:.1f}" if s > 0 else "-") data_a.append(r) widths = [60] + [65] * (len(headers_a) - 1) pdf.add_table(headers_a, data_a, col_widths=widths) else: pdf.body_text("No corporate actions data available for this security.") # ── Financial Statements Summary pdf.section_title("6. Financial Statements Summary") if not income.empty: pdf.sub_title("Income Statement Highlights") key_rows = ["Total Revenue", "Gross Profit", "Operating Income", "Net Income", "EBITDA"] for row_name in key_rows: if row_name in income.index: vals = income.loc[row_name] latest = vals.iloc[0] if len(vals) > 0 else None if latest is not None: pdf.key_value(row_name, fmt(latest, prefix=f"{currency} ", div=1e9)) pdf.ln(2) if not balance.empty: pdf.sub_title("Balance Sheet Highlights") key_rows_b = ["Total Assets", "Total Liabilities Net Minority Interest", "Stockholders Equity", "Total Debt", "Cash And Cash Equivalents"] for row_name in key_rows_b: if row_name in balance.index: vals = balance.loc[row_name] latest = vals.iloc[0] if len(vals) > 0 else None if latest is not None: pdf.key_value(row_name, fmt(latest, prefix=f"{currency} ", div=1e9)) pdf.ln(2) if not cashflow.empty: pdf.sub_title("Cash Flow Highlights") key_rows_c = ["Operating Cash Flow", "Capital Expenditure", "Free Cash Flow", "Investing Cash Flow", "Financing Cash Flow"] for row_name in key_rows_c: if row_name in cashflow.index: vals = cashflow.loc[row_name] latest = vals.iloc[0] if len(vals) > 0 else None if latest is not None: pdf.key_value(row_name, fmt(latest, prefix=f"{currency} ", div=1e9)) # ── Disclaimer pdf.add_page() pdf.section_title("Disclaimer") pdf.body_text( "This report is generated automatically by FinScope using publicly available data from Yahoo Finance " "(yfinance). It is intended for informational and educational purposes only and does not constitute " "financial, investment, or trading advice. The information provided may not be accurate, complete, " "or current. Past performance does not guarantee future results.\n\n" "Users should conduct their own due diligence and consult qualified financial advisors before making " "any investment decisions. FinScope assumes no liability for any losses or damages arising from the " "use of this report." ) return bytes(pdf.output()) # ───────────────────────────────────────────── # SIDEBAR # ───────────────────────────────────────────── with st.sidebar: st.markdown("""
Global Financial Intelligence
🌏 Global Overview
""", unsafe_allow_html=True) market_categories = { "📉 Indices": ["S&P 500", "NASDAQ", "Dow Jones", "FTSE 100", "DAX", "Nikkei 225", "Hang Seng", "SENSEX", "NIFTY 50", "ASX 200"], "💱 Currencies": ["EUR/USD", "GBP/USD", "USD/JPY"], "🏗️ Commodities": ["Gold", "Brent Oil", "Silver"], "₿ Crypto": ["Bitcoin", "Ethereum"] } for cat_name, symbols in market_categories.items(): with st.sidebar.expander(cat_name, expanded=(cat_name == "📉 Indices")): for name in symbols: symbol = GLOBAL_INDICES.get(name) if symbol: data = fetch_index_data(symbol) if data: price, change, pct = data color = "#00e676" if change >= 0 else "#ff5252" arrow = "▲" if change >= 0 else "▼" st.markdown(f"""
Data from Yahoo Finance
Last refresh: {datetime.now().strftime('%H:%M:%S')}
Real-time financial intelligence powered by Yahoo Finance • {datetime.now().strftime('%A, %B %d, %Y')}
{selected_ticker} • {sector} • {industry} • {info.get('exchange', 'N/A')}
""", unsafe_allow_html=True) with col_price: delta_class = "metric-delta-pos" if price_change >= 0 else "metric-delta-neg" arrow = "▲" if price_change >= 0 else "▼" st.markdown(f"""{n.get('publisher', 'Unknown')} • {pub_time}
""", unsafe_allow_html=True) st.markdown('', unsafe_allow_html=True) else: st.info(f"No recent news found for {selected_ticker}.") # ── TAB 4: PEER COMPARISON with tab4: st.markdown('FinScope © 2025 • Data sourced from Yahoo Finance via yfinance • For informational purposes only — not financial advice