"""Financial statements — Income Statement, Balance Sheet, Cash Flow.""" import pandas as pd import streamlit.components.v1 as components from services.data_service import ( get_income_statement, get_balance_sheet, get_cash_flow, get_balance_sheet_bridge_items, get_company_info, get_latest_price, ) from utils.formatters import fmt_large _INVERSE_ROWS = { # ── Income statement ────────────────────────────────────────────────────── "cost of revenue", "reconciled cost of revenue", "operating expense", "research and development", "selling general and administration", "total expenses", "interest expense", "interest expense non operating", "tax provision", "reconciled depreciation", # ── Balance sheet ───────────────────────────────────────────────────────── "net debt", "prism net debt", "total debt", "long term debt", "long term debt and capital lease obligation", "long term capital lease obligation", "current debt", "current debt and capital lease obligation", "current capital lease obligation", "capital lease obligations", "other current borrowings", "commercial paper", "total liabilities net minority interest", "total non current liabilities net minority interest", "current liabilities", "accounts payable", "payables and accrued expenses", "payables", "current accrued expenses", "total tax payable", "income tax payable", "current deferred liabilities", "current deferred revenue", "tradeand other payables non current", # ── Cash flow ───────────────────────────────────────────────────────────── "issuance of debt", "long term debt issuance", "net long term debt issuance", "net short term debt issuance", "net issuance payments of debt", "issuance of capital stock", "common stock issuance", "net common stock issuance", "income tax paid supplemental data", "interest paid supplemental data", "repurchase of capital stock", "common stock payments", } INCOME_GROUPS = { "Revenue": [ "Total Revenue", "Cost Of Revenue", "Reconciled Cost Of Revenue", "Gross Profit", ], "Operating Expenses": [ "Research And Development", "Selling General And Administration", "Operating Expense", "Total Expenses", ], "Profitability": [ "Operating Income", "EBIT", "EBITDA", "Normalized EBITDA", "Pretax Income", "Tax Provision", "Net Income", ], "Other": [ "Interest Expense", "Interest Expense Non Operating", "Diluted EPS", "Basic EPS", ], } BALANCE_GROUPS = { "Prism Bridge Metrics": [ "Prism Net Debt", "Net Debt", "Total Debt", "Current Debt", "Long Term Debt", "Cash And Cash Equivalents", "Cash Cash Equivalents And Short Term Investments", "Cash", "Preferred Stock", "Minority Interest", "Minority Interests", ], "Assets": [ "Cash And Cash Equivalents", "Cash Cash Equivalents And Short Term Investments", "Cash", "Short Term Investments", "Receivables", "Inventory", "Current Assets", "Net PPE", "Gross PPE", "Goodwill", "Other Intangible Assets", "Total Assets", ], "Liabilities": [ "Accounts Payable", "Payables And Accrued Expenses", "Payables", "Current Liabilities", "Current Debt", "Current Debt And Capital Lease Obligation", "Long Term Debt", "Long Term Debt And Capital Lease Obligation", "Total Debt", "Total Liabilities Net Minority Interest", "Total Non Current Liabilities Net Minority Interest", ], "Equity": [ "Common Stock Equity", "Stockholders Equity", "Retained Earnings", "Total Equity Gross Minority Interest", "Preferred Stock", "Minority Interest", "Minority Interests", ], } CASHFLOW_GROUPS = { "Operating Cash Flow": [ "Operating Cash Flow", "Net Income From Continuing Operations", "Depreciation And Amortization", "Deferred Tax", "Stock Based Compensation", "Change In Working Capital", ], "Investing Cash Flow": [ "Investing Cash Flow", "Capital Expenditure", "Net Business Purchase And Sale", "Purchase Of Investment", "Sale Of Investment", ], "Financing Cash Flow": [ "Financing Cash Flow", "Issuance Of Debt", "Repayment Of Debt", "Net Issuance Payments Of Debt", "Issuance Of Capital Stock", "Repurchase Of Capital Stock", "Cash Dividends Paid", "Common Stock Dividend Paid", ], "Free Cash Flow & Returns": [ "Free Cash Flow", "Operating Cash Flow", "Capital Expenditure", "Repurchase Of Capital Stock", "Cash Dividends Paid", ], } _XMAP = {"NYQ": "NYSE", "NMS": "NASDAQ", "NGM": "NASDAQ", "NCM": "NASDAQ", "ASE": "AMEX"} def _esc(s: str) -> str: return s.replace("&", "&").replace("<", "<").replace(">", ">") def _is_inverse(label: str) -> bool: return label.strip().lower() in _INVERSE_ROWS def _fmt_cell(value) -> str: try: v = float(value) except (TypeError, ValueError): return "—" if v != v: return "—" return fmt_large(v) def _yoy_pct(current, previous): try: c = float(current) p = float(previous) except (TypeError, ValueError): return None if c != c or p != p or p == 0: return None return (c - p) / abs(p) * 100 def _yoy_html(pct, inverse: bool) -> str: if pct is None: return '' arrow = "▲" if pct >= 0 else "▼" pct_str = str(round(abs(pct), 1)) + "%" if abs(pct) < 1.0: return ( '' + arrow + " " + pct_str + '' ) positive = pct > 0 good = positive if not inverse else not positive color = "var(--positive)" if good else "var(--negative)" bg = "var(--positive-bg)" if good else "var(--negative-bg)" return ( '' + arrow + " " + pct_str + '' ) def _build_table_html(df, groups: dict, stmt_id: str, n_periods: int, display_none: bool) -> str: display_style = "display:none" if display_none else "display:block" if df is None or df.empty: return ( '
' '
Data unavailable for this statement.
' '
' ) cols = list(df.columns[:n_periods]) n_cols = len(cols) if n_cols == 0: return ( '
' '
No periods available.
' '
' ) year_labels = [str(c)[:4] for c in cols] grid_cols = "2fr " + " ".join(["1fr"] * n_cols) + " 1fr" header = '
Metric
' for yr in year_labels: header += '
' + yr + '
' header += '
YoY Δ
' rendered = set() body = "" row_idx = 0 for section, candidates in groups.items(): section_rows = [r for r in candidates if r in df.index and r not in rendered] if not section_rows: continue body += ( '
' + _esc(section) + '
' ) for row_lbl in section_rows: rendered.add(row_lbl) row_data = df.loc[row_lbl] yoy_pct = _yoy_pct(row_data.iloc[0], row_data.iloc[1]) if n_cols >= 2 else None inv = _is_inverse(row_lbl) bg = "var(--ink-1)" if row_idx % 2 == 1 else "var(--ink-0)" cs = "background:" + bg + ";" body += '
' + _esc(row_lbl) + '
' for col in cols: body += '
' + _fmt_cell(row_data.get(col)) + '
' body += '
' + _yoy_html(yoy_pct, inv) + '
' row_idx += 1 other_rows = [r for r in df.index if r not in rendered] if other_rows: body += ( '
' 'Other Reported Line Items
' ) for row_lbl in other_rows: row_data = df.loc[row_lbl] yoy_pct = _yoy_pct(row_data.iloc[0], row_data.iloc[1]) if n_cols >= 2 else None inv = _is_inverse(row_lbl) bg = "var(--ink-1)" if row_idx % 2 == 1 else "var(--ink-0)" cs = "background:" + bg + ";" body += '
' + _esc(row_lbl) + '
' for col in cols: body += '
' + _fmt_cell(row_data.get(col)) + '
' body += '
' + _yoy_html(yoy_pct, inv) + '
' row_idx += 1 return ( '
' '
' '
' '
' + header + body + '
' ) def _augment_balance_sheet(df, ticker: str, quarterly: bool): if quarterly or df is None or df.empty: return df bridge = get_balance_sheet_bridge_items(ticker) prism_net_debt = bridge.get("net_debt") if prism_net_debt is None: return df out = df.copy() if "Prism Net Debt" not in out.index: out.loc["Prism Net Debt"] = [float("nan")] * len(out.columns) out.loc["Prism Net Debt", out.columns[0]] = prism_net_debt return out def render_financials(ticker: str): import json as _json info = get_company_info(ticker) or {} price = get_latest_price(ticker) df_income_ann = get_income_statement(ticker, quarterly=False) df_income_qtr = get_income_statement(ticker, quarterly=True) df_balance_ann = _augment_balance_sheet( get_balance_sheet(ticker, quarterly=False), ticker, False ) df_balance_qtr = get_balance_sheet(ticker, quarterly=True) df_cashflow_ann = get_cash_flow(ticker, quarterly=False) df_cashflow_qtr = get_cash_flow(ticker, quarterly=True) # Context bar values prev_close = info.get("previousClose") if price and prev_close and prev_close > 0: chg_pct = (price - prev_close) / prev_close * 100 sign = "+" if chg_pct >= 0 else "" arrow = "▲" if chg_pct >= 0 else "▼" chg_str = arrow + " " + sign + f"{chg_pct:.2f}%" chg_cls = "chg-pos" if chg_pct >= 0 else "chg-neg" else: chg_str, chg_cls = "—", "" raw_x = info.get("exchange") or "" exchange = _XMAP.get(raw_x, raw_x) or "—" co_name = _esc(info.get("longName") or info.get("shortName") or ticker.upper()) price_str = f"${price:,.2f}" if price else "—" most_recent = "—" if df_income_ann is not None and not df_income_ann.empty and len(df_income_ann.columns) > 0: most_recent = str(df_income_ann.columns[0])[:10] # Build all six statement HTML blobs income_ann_html = _build_table_html(df_income_ann, INCOME_GROUPS, "stmt-income-annual", 4, False) income_qtr_html = _build_table_html(df_income_qtr, INCOME_GROUPS, "stmt-income-quarterly", 8, True) balance_ann_html = _build_table_html(df_balance_ann, BALANCE_GROUPS, "stmt-balance-annual", 4, True) balance_qtr_html = _build_table_html(df_balance_qtr, BALANCE_GROUPS, "stmt-balance-quarterly", 8, True) cashflow_ann_html = _build_table_html(df_cashflow_ann, CASHFLOW_GROUPS, "stmt-cashflow-annual", 4, True) cashflow_qtr_html = _build_table_html(df_cashflow_qtr, CASHFLOW_GROUPS, "stmt-cashflow-quarterly",8, True) def _safe_len(d): return 0 if d is None or d.empty else len(d) max_rows = max( _safe_len(df_income_ann), _safe_len(df_balance_ann), _safe_len(df_cashflow_ann), _safe_len(df_income_qtr), _safe_len(df_balance_qtr), _safe_len(df_cashflow_qtr), ) height = 1400 + max_rows * 34 _ROOT = ( "" ) fonts_link = ( "" "" ) _FS_CSS = """""" ctx_html = ( '
' '' + ticker.upper() + '' '' + co_name + '' '' 'Financials · Income Statement' '
' '' + exchange + '' '' + price_str + '' '' + chg_str + '' '
' ) lede_html = ( '
' '
' 'Financial Statements' '
Three statements, one picture
' '

Income statement, balance sheet, and cash flow for ' + ticker.upper() + '. ' 'Toggle Annual / Quarterly and switch between statements using the controls below. ' 'YoY column reflects change vs. the prior period.

' '
' '
' '
' 'Source' 'yfinance' 'Yahoo Finance API' '
' '
' 'Period' 'Annual' 'fiscal year end' '
' '
' 'As of' '' + most_recent + '' 'most recent filing' '
' '
' '
' ) controls_html = ( '
' '
' '' '' '
' '
' '' '' '' '
' '
' ) js = ( '' ) foot_html = ( '
' 'Financial data provided by Yahoo Finance via yfinance · ' 'Values in USD unless noted · Annual figures use fiscal year end dates' '
' ) doc = ( "" + fonts_link + _ROOT + _FS_CSS + "
" + ctx_html + '
' + lede_html + controls_html + income_ann_html + income_qtr_html + balance_ann_html + balance_qtr_html + cashflow_ann_html + cashflow_qtr_html + foot_html + '
' + js + "" ) components.html(doc, height=height, scrolling=False)