aboutsummaryrefslogtreecommitdiff
path: root/components/financials.py
blob: 83e9a1662afaeedd3be21192db870913a25d7f9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""Financial statements — organized and raw views for Income Statement, Balance Sheet, Cash Flow."""
import pandas as pd
import streamlit as st
from services.data_service import get_income_statement, get_balance_sheet, get_cash_flow, get_balance_sheet_bridge_items
from utils.formatters import fmt_large

# Rows where an increase is bad (decline = green, increase = red).
# Labels must match yfinance row names (case-insensitive after .strip().lower()).
_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",
    ],
}


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 "—"
    return fmt_large(v)


def _yoy_raw(current, previous):
    try:
        c, p = float(current), float(previous)
        if p == 0:
            return None
        return (c - p) / abs(p) * 100
    except (TypeError, ValueError):
        return None


def _yoy_str(pct) -> str:
    if pct is None:
        return "—"
    arrow = "▲" if pct >= 0 else "▼"
    return f"{arrow} {abs(pct):.1f}%"


def _build_statement(df: pd.DataFrame):
    df = df.copy()
    df.columns = [str(c)[:10] for c in df.columns]
    cols = list(df.columns)

    display = pd.DataFrame(index=df.index)
    colors = pd.DataFrame(index=df.index)

    for i, col in enumerate(cols):
        display[col] = df[col].apply(_fmt_cell)
        colors[col] = ""

        if i + 1 < len(cols):
            prev_col = cols[i + 1]
            yoy_label = f"YoY {col[:4]}"
            raw_yoy = df.apply(lambda row: _yoy_raw(row[col], row[prev_col]), axis=1)
            display[yoy_label] = raw_yoy.apply(_yoy_str)

            def cell_color(row_label, pct):
                if pct is None:
                    return ""
                inverse = _is_inverse(row_label)
                positive_change = pct >= 0
                good = positive_change if not inverse else not positive_change
                return "green" if good else "red"

            colors[yoy_label] = pd.Series(
                [cell_color(idx, pct) for idx, pct in zip(df.index, raw_yoy)],
                index=df.index,
            )

    return display, colors


def _style(display: pd.DataFrame, colors: pd.DataFrame):
    GREEN_BG = "background-color: rgba(46, 204, 113, 0.18); color: #7ce3a1;"
    RED_BG = "background-color: rgba(231, 76, 60, 0.18); color: #ff8a8a;"

    def apply_colors(row):
        return [
            GREEN_BG if colors.loc[row.name, col] == "green"
            else RED_BG if colors.loc[row.name, col] == "red"
            else ""
            for col in display.columns
        ]

    return display.style.apply(apply_colors, axis=1)


def _augment_balance_sheet(df: pd.DataFrame, ticker: str, quarterly: bool) -> pd.DataFrame:
    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 _pick_existing_rows(df: pd.DataFrame, candidates: list[str]) -> list[str]:
    return [row for row in candidates if row in df.index]


def _render_grouped_statement(df: pd.DataFrame, groups: dict[str, list[str]], empty_msg: str):
    grouped_rows = []
    for section, candidates in groups.items():
        rows = _pick_existing_rows(df, candidates)
        if not rows:
            continue
        grouped_rows.extend(rows)
        with st.expander(section, expanded=(section == list(groups.keys())[0])):
            section_df = df.loc[rows]
            display, colors = _build_statement(section_df)
            st.dataframe(_style(display, colors), use_container_width=True)

    remaining = [row for row in df.index if row not in grouped_rows]
    if remaining:
        with st.expander("Other Reported Line Items", expanded=False):
            display, colors = _build_statement(df.loc[remaining])
            st.dataframe(_style(display, colors), use_container_width=True)
    elif not grouped_rows:
        st.info(empty_msg)


def _render_statement_block(title: str, df: pd.DataFrame, groups: dict[str, list[str]] | None, download_name: str, raw_key: str, empty_msg: str):
    if df.empty:
        st.info(empty_msg)
        return

    view = st.radio(
        f"{title} view",
        ["Organized", "Raw"],
        horizontal=True,
        key=f"view_{raw_key}",
        label_visibility="collapsed",
    )

    if view == "Organized" and groups:
        _render_grouped_statement(df, groups, empty_msg)
    else:
        display, colors = _build_statement(df)
        st.dataframe(_style(display, colors), use_container_width=True)

    st.download_button(
        "Download CSV",
        df.to_csv().encode(),
        file_name=download_name,
        mime="text/csv",
        key=f"dl_{raw_key}",
    )


def render_financials(ticker: str):
    col1, col2 = st.columns([1, 3])
    with col1:
        freq = st.radio("Frequency", ["Annual", "Quarterly"], horizontal=False)
    quarterly = freq == "Quarterly"

    tab_income, tab_balance, tab_cashflow = st.tabs([
        "Income Statement", "Balance Sheet", "Cash Flow"
    ])

    with tab_income:
        df = get_income_statement(ticker, quarterly=quarterly)
        _render_statement_block(
            "Income Statement",
            df,
            INCOME_GROUPS,
            f"{ticker.upper()}_income_{'quarterly' if quarterly else 'annual'}.csv",
            f"income_{ticker}_{quarterly}",
            "Income statement data unavailable.",
        )

    with tab_balance:
        df = get_balance_sheet(ticker, quarterly=quarterly)
        df = _augment_balance_sheet(df, ticker, quarterly)
        if not quarterly and not df.empty:
            st.caption("Prism Net Debt is calculated as Total Debt - Cash & Equivalents using the same bridge logic as Valuation.")
        _render_statement_block(
            "Balance Sheet",
            df,
            BALANCE_GROUPS,
            f"{ticker.upper()}_balance_{'quarterly' if quarterly else 'annual'}.csv",
            f"balance_{ticker}_{quarterly}",
            "Balance sheet data unavailable.",
        )

    with tab_cashflow:
        df = get_cash_flow(ticker, quarterly=quarterly)
        _render_statement_block(
            "Cash Flow",
            df,
            CASHFLOW_GROUPS,
            f"{ticker.upper()}_cashflow_{'quarterly' if quarterly else 'annual'}.csv",
            f"cashflow_{ticker}_{quarterly}",
            "Cash flow data unavailable.",
        )