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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
|
"""Valuation panel — key ratios, models, comparable companies, analyst targets, earnings history."""
import json
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
import streamlit.components.v1 as components
from services.data_service import (
get_company_info,
get_latest_price,
get_shares_outstanding,
get_market_cap_computed,
get_free_cash_flow_series,
get_free_cash_flow_ttm,
get_revenue_ttm,
get_balance_sheet_bridge_items,
get_analyst_price_targets,
get_recommendations_summary,
get_earnings_history,
get_next_earnings_date,
)
from services.fmp_service import (
get_key_ratios,
get_peers,
get_ratios_for_tickers,
get_historical_ratios,
get_historical_key_metrics,
get_analyst_estimates,
)
from services.valuation_service import (
run_dcf,
run_ev_ebitda,
run_ev_revenue,
run_price_to_book,
compute_historical_growth_rate,
compute_raw_historical_growth_rate,
)
from utils.formatters import fmt_ratio, fmt_pct, fmt_large, fmt_currency
FINANCIAL_SECTORS = {"Financial Services"}
FINANCIAL_INDUSTRY_KEYWORDS = (
"bank",
"insurance",
"asset management",
"capital markets",
"financial data",
"credit services",
"mortgage",
"reit",
)
INDUSTRY_PEER_MAP = {
"consumer electronics": ["AAPL", "SONY", "DELL", "HPQ", "LOGI"],
"software - infrastructure": ["MSFT", "ORCL", "CRM", "NOW", "SNOW"],
"semiconductors": ["NVDA", "AMD", "AVGO", "QCOM", "INTC"],
"internet content & information": ["GOOGL", "META", "PINS", "SNAP", "RDDT"],
"banks - diversified": ["JPM", "BAC", "WFC", "C", "GS"],
"credit services": ["V", "MA", "AXP", "DFS", "COF"],
"insurance - diversified": ["BRK-B", "AIG", "ALL", "TRV", "CB"],
"reit - industrial": ["PLD", "PSA", "EXR", "COLD", "REXR"],
}
SECTOR_PEER_MAP = {
"Technology": ["AAPL", "MSFT", "NVDA", "ORCL", "ADBE"],
"Communication Services": ["GOOGL", "META", "NFLX", "TMUS", "DIS"],
"Consumer Cyclical": ["AMZN", "TSLA", "HD", "MCD", "NKE"],
"Consumer Defensive": ["WMT", "COST", "PG", "KO", "PEP"],
"Financial Services": ["JPM", "BAC", "WFC", "GS", "MS"],
"Healthcare": ["LLY", "UNH", "JNJ", "MRK", "PFE"],
"Industrials": ["GE", "CAT", "RTX", "UPS", "UNP"],
"Energy": ["XOM", "CVX", "COP", "SLB", "EOG"],
"Utilities": ["NEE", "DUK", "SO", "AEP", "XEL"],
"Real Estate": ["PLD", "AMT", "EQIX", "O", "SPG"],
}
def _is_financial_company(info: dict) -> bool:
sector = str(info.get("sector") or "").strip()
industry = str(info.get("industry") or "").strip().lower()
if sector in FINANCIAL_SECTORS:
return True
return any(keyword in industry for keyword in FINANCIAL_INDUSTRY_KEYWORDS)
def _suggest_peer_tickers(ticker: str, info: dict) -> list[str]:
industry = str(info.get("industry") or "").strip().lower()
sector = str(info.get("sector") or "").strip()
candidates = []
if industry in INDUSTRY_PEER_MAP:
candidates.extend(INDUSTRY_PEER_MAP[industry])
if not candidates and sector in SECTOR_PEER_MAP:
candidates.extend(SECTOR_PEER_MAP[sector])
candidates = [c.upper() for c in candidates if c.upper() != ticker.upper()]
seen = set()
deduped = []
for c in candidates:
if c not in seen:
deduped.append(c)
seen.add(c)
return deduped[:8]
def _coerce_float(value) -> float | None:
try:
out = float(value)
except (TypeError, ValueError):
return None
return None if pd.isna(out) else out
def _escape_markdown_currency(value: str) -> str:
return value.replace("$", r"\$")
def render_valuation(ticker: str):
tabs = st.tabs([
"Key Ratios",
"Historical Ratios",
"Models",
"Comps",
"Forward Estimates",
"Analyst Targets",
"Earnings History",
])
tab_ratios, tab_hist, tab_models, tab_comps, tab_fwd, tab_analyst, tab_earnings = tabs
with tab_ratios:
_render_ratios(ticker)
with tab_hist:
try:
_render_historical_ratios(ticker)
except Exception as e:
st.error(f"Historical ratios unavailable: {e}")
with tab_models:
_render_models(ticker)
with tab_comps:
_render_comps(ticker)
with tab_fwd:
try:
_render_forward_estimates(ticker)
except Exception as e:
st.error(f"Forward estimates unavailable: {e}")
with tab_analyst:
try:
_render_analyst_targets(ticker)
except Exception as e:
st.error(f"Analyst targets unavailable: {e}")
with tab_earnings:
try:
_render_earnings_history(ticker)
except Exception as e:
st.error(f"Earnings history unavailable: {e}")
# ── Key Ratios ───────────────────────────────────────────────────────────────
def _render_ratios(ticker: str):
ratios = get_key_ratios(ticker)
info = get_company_info(ticker)
if not ratios and not info:
st.info("Ratio data unavailable.")
return
def _normalized_label(label: str) -> str:
return " ".join(str(label).replace("/", " ").replace("-", " ").split()).strip().lower()
def _display_value(key: str, fmt=fmt_ratio):
val = ratios.get(key) if ratios else None
return fmt(val) if val is not None else "—"
def _company_context() -> dict:
return info or {}
def _display_reasoned_metric(key: str, fmt=fmt_ratio) -> str:
val = ratios.get(key) if ratios else None
if val is not None:
return fmt(val)
ctx = _company_context()
if key == "peRatioTTM":
trailing_pe = ctx.get("trailingPE")
if trailing_pe is not None:
return fmt_ratio(trailing_pe)
if ratios and ratios.get("netProfitMarginTTM") is not None and ratios.get("netProfitMarginTTM") < 0:
return "N/M (neg. TTM earnings)"
trailing_eps = ctx.get("trailingEps")
if trailing_eps is not None:
try:
if float(trailing_eps) <= 0:
return "N/M (neg. TTM earnings)"
except (TypeError, ValueError):
pass
return "—"
if key == "priceToBookRatioTTM":
book_value = ctx.get("bookValue")
if book_value is not None:
try:
if float(book_value) <= 0:
return "N/M (neg. equity)"
except (TypeError, ValueError):
pass
return "—"
if key == "enterpriseValueMultipleTTM":
ebitda = ratios.get("ebitdaTTM") if ratios else None
if ebitda is not None:
try:
if float(ebitda) <= 0:
return "N/M (neg. EBITDA)"
except (TypeError, ValueError):
pass
return "—"
if key == "dividendPayoutRatioTTM":
payout_ratio = ctx.get("payoutRatio")
if payout_ratio is not None:
try:
if float(payout_ratio) <= 0:
return "—"
except (TypeError, ValueError):
pass
if ratios and ratios.get("netProfitMarginTTM") is not None and ratios.get("netProfitMarginTTM") < 0:
return "N/M (neg. earnings)"
return "—"
if key == "returnOnEquityTTM":
book_value = ctx.get("bookValue")
if book_value is not None:
try:
if float(book_value) <= 0:
return "N/M (neg. equity)"
except (TypeError, ValueError):
pass
return "—"
if key == "debtToEquityRatioTTM":
book_value = ctx.get("bookValue")
if book_value is not None:
try:
if float(book_value) <= 0:
return "N/M (neg. equity)"
except (TypeError, ValueError):
pass
return "—"
if key == "interestCoverageRatioTTM":
operating_margins = ctx.get("operatingMargins")
if operating_margins is not None:
try:
if float(operating_margins) <= 0:
return "N/M (neg. EBIT)"
except (TypeError, ValueError):
pass
return "—"
return "—"
def _dedupe_metrics(metrics: list[tuple[str, str]]) -> list[tuple[str, str]]:
deduped: list[tuple[str, str]] = []
seen_labels: set[str] = set()
for label, val in metrics:
norm = _normalized_label(label)
if norm in seen_labels:
continue
seen_labels.add(norm)
deduped.append((label, val))
return deduped
rows = [
("Valuation", _dedupe_metrics([
("P/E (TTM)", _display_reasoned_metric("peRatioTTM")),
("Forward P/E", _display_value("forwardPE")),
("P/S (TTM)", _display_value("priceToSalesRatioTTM")),
("P/B", _display_reasoned_metric("priceToBookRatioTTM")),
("EV/EBITDA", _display_reasoned_metric("enterpriseValueMultipleTTM")),
("EV/Revenue", _display_value("evToSalesTTM")),
])),
("Profitability", _dedupe_metrics([
("Gross Margin", _display_value("grossProfitMarginTTM", fmt=fmt_pct)),
("Operating Margin", _display_value("operatingProfitMarginTTM", fmt=fmt_pct)),
("Net Margin", _display_value("netProfitMarginTTM", fmt=fmt_pct)),
("ROE", _display_reasoned_metric("returnOnEquityTTM", fmt=fmt_pct)),
("ROA", _display_value("returnOnAssetsTTM", fmt=fmt_pct)),
("ROIC", _display_value("returnOnInvestedCapitalTTM", fmt=fmt_pct)),
])),
("Leverage & Liquidity", _dedupe_metrics([
("Debt/Equity", _display_reasoned_metric("debtToEquityRatioTTM")),
("Current Ratio", _display_value("currentRatioTTM")),
("Quick Ratio", _display_value("quickRatioTTM")),
("Interest Coverage", _display_reasoned_metric("interestCoverageRatioTTM")),
("Dividend Yield", _display_value("dividendYieldTTM", fmt=fmt_pct)),
("Payout Ratio", _display_reasoned_metric("dividendPayoutRatioTTM", fmt=fmt_pct)),
])),
]
for section_name, metrics in rows:
st.markdown(f"**{section_name}**")
cols = st.columns(6)
for col, (label, val) in zip(cols, metrics):
col.metric(label, val)
st.write("")
# ── Models ───────────────────────────────────────────────────────────────────
def _net_debt_label(value: float) -> str:
return "Net Cash" if value < 0 else "Net Debt"
def _build_model_context(ticker: str) -> dict:
info = get_company_info(ticker)
ratios_data = get_key_ratios(ticker)
shares = get_shares_outstanding(ticker)
current_price = get_latest_price(ticker)
market_cap = get_market_cap_computed(ticker)
bridge_items = get_balance_sheet_bridge_items(ticker)
total_debt = float(bridge_items["total_debt"])
cash_and_equivalents = float(bridge_items["cash_and_equivalents"])
preferred_equity = float(bridge_items["preferred_equity"])
minority_interest = float(bridge_items["minority_interest"])
fcf_series_raw = get_free_cash_flow_series(ticker)
if fcf_series_raw is None or fcf_series_raw.empty:
fcf_series = pd.Series(dtype=float)
else:
try:
fcf_series = fcf_series_raw.sort_index().dropna().astype(float)
except Exception:
fcf_series = pd.Series(dtype=float)
base_fcf = _coerce_float(get_free_cash_flow_ttm(ticker))
hist_growth = compute_historical_growth_rate(fcf_series) if len(fcf_series) >= 2 else None
hist_growth_raw = compute_raw_historical_growth_rate(fcf_series) if len(fcf_series) >= 2 else None
ebitda = _coerce_float(ratios_data.get("ebitdaTTM"))
revenue_ttm = _coerce_float(get_revenue_ttm(ticker))
if revenue_ttm is None or revenue_ttm <= 0:
revenue_ttm = _coerce_float(info.get("totalRevenue"))
if revenue_ttm is None or revenue_ttm <= 0:
ps_ratio = _coerce_float(ratios_data.get("priceToSalesRatioTTM"))
if market_cap and market_cap > 0 and ps_ratio and ps_ratio > 0:
revenue_ttm = float(market_cap) / float(ps_ratio)
book_value_per_share = _coerce_float(info.get("bookValue"))
is_financial = _is_financial_company(info)
dcf_reason = None
if is_financial:
dcf_reason = "Not suitable for financial companies."
elif not shares or shares <= 0:
dcf_reason = "Shares outstanding unavailable."
elif fcf_series.empty:
dcf_reason = "Free cash flow history unavailable."
elif len(fcf_series) < 2:
dcf_reason = "Need at least two FCF periods."
elif base_fcf is None or base_fcf <= 0:
dcf_reason = "Base free cash flow is zero or negative."
ev_reason = None
if not shares or shares <= 0:
ev_reason = "Shares outstanding unavailable."
elif ebitda is None:
ev_reason = "EBITDA unavailable."
elif ebitda <= 0:
ev_reason = "EBITDA is zero or negative."
ev_revenue_reason = None
if is_financial:
ev_revenue_reason = "Not preferred for financial companies."
elif not shares or shares <= 0:
ev_revenue_reason = "Shares outstanding unavailable."
elif revenue_ttm is None:
ev_revenue_reason = "Revenue unavailable."
elif revenue_ttm <= 0:
ev_revenue_reason = "Revenue is zero or negative."
pb_reason = None
if book_value_per_share is None:
pb_reason = "Book value per share unavailable."
elif book_value_per_share <= 0:
pb_reason = "Book value per share is zero or negative."
dcf_available = dcf_reason is None
ev_available = ev_reason is None
ev_revenue_available = ev_revenue_reason is None
pb_available = pb_reason is None
ev_value = None
ev_ebitda_current = None
ev_revenue_current = None
other_claims = preferred_equity + minority_interest
if market_cap and market_cap > 0 and ebitda and ebitda > 0:
ev_value = float(market_cap) + total_debt - cash_and_equivalents + other_claims
if ev_value > 0:
ev_ebitda_current = ev_value / ebitda
elif market_cap and market_cap > 0:
ev_value = float(market_cap) + total_debt - cash_and_equivalents + other_claims
if ev_value and ev_value > 0 and revenue_ttm and revenue_ttm > 0:
ev_revenue_current = ev_value / revenue_ttm
pb_current = None
if current_price and current_price > 0 and book_value_per_share and book_value_per_share > 0:
pb_current = current_price / book_value_per_share
if is_financial and pb_available:
summary = "P/B is the primary method here because this looks like a financial company."
elif dcf_available:
summary = "DCF is the primary method because the business has usable free cash flow history and positive base FCF."
elif ev_available:
summary = "EV/EBITDA is the best fit because EBITDA is positive while DCF is not suitable."
elif ev_revenue_available:
summary = "EV/Revenue is the best fit because the company has revenue but cash-flow-based models are not suitable."
elif pb_available:
summary = "P/B is the fallback because book value is positive while cash-flow-based models are not suitable."
else:
summary = "No valuation model is currently robust enough to show. Use ratios, comps, earnings history, and analyst targets instead."
return {
"ticker": ticker.upper(),
"info": info,
"ratios_data": ratios_data,
"shares": shares,
"current_price": current_price,
"market_cap": market_cap,
"bridge_items": bridge_items,
"total_debt": total_debt,
"cash_and_equivalents": cash_and_equivalents,
"preferred_equity": preferred_equity,
"minority_interest": minority_interest,
"fcf_series": fcf_series,
"base_fcf": base_fcf,
"hist_growth": hist_growth,
"hist_growth_raw": hist_growth_raw,
"ebitda": ebitda,
"revenue_ttm": revenue_ttm,
"book_value_per_share": book_value_per_share,
"is_financial": is_financial,
"dcf_available": dcf_available,
"dcf_reason": dcf_reason or "Usable free cash flow history and positive base FCF.",
"ev_available": ev_available,
"ev_reason": ev_reason or "Positive EBITDA and shares outstanding are available.",
"ev_revenue_available": ev_revenue_available,
"ev_revenue_reason": ev_revenue_reason or "Positive revenue and shares outstanding are available.",
"pb_available": pb_available,
"pb_reason": pb_reason or "Positive book value per share is available.",
"ev_ebitda_current": ev_ebitda_current,
"ev_revenue_current": ev_revenue_current,
"pb_current": pb_current,
"summary": summary,
}
def _render_model_availability(ctx: dict):
dcf_ok = ctx["dcf_available"]
ev_ok = ctx["ev_available"]
rev_ok = ctx["ev_revenue_available"]
pb_ok = ctx["pb_available"]
pb_limited = pb_ok and not ctx["is_financial"]
pb_color = "#C49545" if pb_limited else ("#4F8C5E" if pb_ok else "#5E5849")
pb_glyph = "◐" if pb_limited else "●"
dcf_c = "#4F8C5E" if dcf_ok else "#5E5849"
ev_c = "#4F8C5E" if ev_ok else "#5E5849"
rev_c = "#4F8C5E" if rev_ok else "#5E5849"
st.markdown(
f'<div style="font-family:\'IBM Plex Sans\',sans-serif;font-size:12px;color:#8E8676;'
f'display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin-bottom:4px">'
f'<span>Applicable</span>'
f'<span><span style="color:{dcf_c}">●</span> DCF</span>'
f'<span><span style="color:{ev_c}">●</span> EV/EBITDA</span>'
f'<span><span style="color:{rev_c}">●</span> EV/Revenue</span>'
f'<span><span style="color:{pb_color}">{pb_glyph}</span> P/Book</span>'
f'</div>',
unsafe_allow_html=True,
)
_DCF_CANVAS_CSS = """
*,*::before,*::after{box-sizing:border-box}
:root{
--ink-0:#0B0E13;--ink-1:#11151C;--ink-2:#181D26;--ink-3:#222934;
--line-1:#232934;--line-2:#2E3645;
--fg-1:#F2ECDC;--fg-2:#C7C0AE;--fg-3:#8E8676;--fg-4:#5E5849;
--brass:#C2AA7A;--brass-bright:#DCC79E;--brass-deep:#8F7A50;
--oxford:#1F3B5E;--oxford-light:#243E5A;
--positive:#4F8C5E;--positive-bg:#15241A;
--negative:#B5494B;--negative-bg:#2A1517;
--font-display:'EB Garamond',Georgia,serif;
--font-sans:'IBM Plex Sans',system-ui,sans-serif;
--font-mono:'IBM Plex Mono',monospace;
}
body{margin:0;padding:0;background:transparent;font-family:var(--font-sans);color:var(--fg-2);-webkit-font-smoothing:antialiased}
.num{font-family:var(--font-mono);font-variant-numeric:tabular-nums}
.va-canvas{display:flex;flex-direction:column;gap:24px;padding-bottom:32px}
/* Verdict */
.va-verdict{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;position:relative;overflow:hidden;box-shadow:0 8px 24px -8px rgba(0,0,0,.5)}
.va-verdict .top{display:grid;grid-template-columns:1fr auto 1fr;gap:48px;align-items:center;padding:32px 48px;position:relative;z-index:1}
.va-verdict .col{display:flex;flex-direction:column;gap:6px}
.va-verdict .lbl{font-family:var(--font-sans);font-size:12px;text-transform:uppercase;letter-spacing:.18em;color:var(--fg-3)}
.va-verdict .big{font-family:var(--font-mono);font-variant-numeric:tabular-nums;font-size:56px;font-weight:500;color:var(--fg-1);line-height:.95;letter-spacing:-.02em}
.va-verdict .big.market{color:var(--fg-2)}
.va-verdict .sub{font-family:var(--font-sans);font-size:13px;color:var(--fg-3)}
.va-verdict .arrow{font-family:var(--font-display);font-size:32px;color:var(--fg-4);font-style:italic;font-weight:400;text-align:center}
.va-verdict .pill{display:inline-flex;align-items:center;gap:6px;font-family:var(--font-mono);font-size:13px;padding:4px 10px;border-radius:2px;align-self:flex-start;margin-top:4px}
.va-verdict .pill.neg{color:var(--negative);background:var(--negative-bg);border:1px solid rgba(181,73,75,.35)}
.va-verdict .pill.pos{color:var(--positive);background:var(--positive-bg);border:1px solid rgba(79,140,94,.35)}
.va-verdict .band{display:flex;align-items:baseline;justify-content:space-between;border-top:1px solid var(--line-1);padding:12px 48px;font-family:var(--font-sans);font-size:13px;color:var(--fg-2);position:relative;z-index:1;background:var(--ink-1)}
.va-verdict .band .reading{font-family:var(--font-display);font-style:italic;font-size:20px;color:var(--fg-1)}
.va-verdict .band .mono{font-family:var(--font-mono);font-variant-numeric:tabular-nums;color:var(--fg-1)}
/* Projection */
.va-projection{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden}
.va-projection .head{padding:16px 24px;border-bottom:1px solid var(--line-1);display:flex;justify-content:space-between;align-items:baseline}
.va-projection .head h3{font-family:var(--font-display);font-size:20px;font-weight:500;color:var(--fg-1);margin:0}
.va-projection .head .units{font-family:var(--font-mono);font-size:12px;color:var(--fg-3)}
.va-cf-table{width:100%;border-collapse:collapse;border-top:1px solid var(--line-1)}
.va-cf-table th,.va-cf-table td{padding:8px 14px;text-align:right;font-family:var(--font-mono);font-variant-numeric:tabular-nums;font-size:12px;border-bottom:1px solid var(--line-1)}
.va-cf-table th{font-family:var(--font-sans);text-transform:uppercase;font-size:11px;letter-spacing:.08em;color:var(--fg-3);font-weight:600;background:var(--ink-2)}
.va-cf-table th:first-child,.va-cf-table td:first-child{text-align:left;color:var(--fg-2);font-size:12px}
.va-cf-table td.brass{color:var(--brass-bright)}
.va-cf-table tr:last-child td{border-bottom:none}
.va-cf-table tr.total td{border-top:1px solid var(--line-2);font-weight:600;color:var(--fg-1);background:var(--ink-2)}
/* Bridge */
.va-bridge{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;padding:24px;display:flex;flex-direction:column;gap:16px}
.va-bridge .bhead{display:flex;justify-content:space-between;align-items:baseline}
.va-bridge .bhead h3{font-family:var(--font-display);font-size:20px;font-weight:500;color:var(--fg-1);margin:0}
.va-bridge .bhead .bdate{font-family:var(--font-mono);font-size:12px;color:var(--fg-3)}
.va-bridge .flow{display:grid;grid-template-columns:1fr auto 1fr auto 1fr auto 1fr;align-items:stretch;gap:12px}
.va-bridge .node{display:flex;flex-direction:column;gap:4px;padding:12px 16px;background:var(--ink-2);border:1px solid var(--line-2);border-radius:4px;min-height:80px;justify-content:center}
.va-bridge .node.start{border-color:var(--oxford);background:rgba(74,120,181,.06)}
.va-bridge .node.result{border-color:rgba(194,170,122,.4);background:rgba(194,170,122,.06)}
.va-bridge .node .lbl{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.18em;color:var(--fg-3)}
.va-bridge .node .v{font-family:var(--font-mono);font-variant-numeric:tabular-nums;font-size:20px;color:var(--fg-1)}
.va-bridge .node.result .v{color:var(--brass-bright)}
.va-bridge .op{display:flex;flex-direction:column;align-items:center;justify-content:center;font-family:var(--font-mono);font-size:16px;color:var(--fg-3);min-width:20px}
.va-bridge .op .sub{font-family:var(--font-sans);font-size:10px;color:var(--fg-4);text-transform:uppercase;letter-spacing:.18em;margin-top:6px}
.va-bridge .bfoot{font-family:var(--font-sans);font-size:12px;color:var(--fg-3);display:flex;gap:12px;flex-wrap:wrap}
/* Recon */
.va-recon{display:grid;grid-template-columns:1.4fr 1fr 1fr 1fr;background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden}
.va-recon .cell{padding:16px 24px;border-right:1px solid var(--line-1);display:flex;flex-direction:column;gap:4px}
.va-recon .cell:last-child{border-right:none}
.va-recon .cell .lbl{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.18em;color:var(--fg-3);font-weight:600}
.va-recon .cell .v{font-family:var(--font-mono);font-variant-numeric:tabular-nums;font-size:28px;color:var(--fg-1);font-weight:500;line-height:1}
.va-recon .cell .sub{font-family:var(--font-mono);font-size:11px;color:var(--fg-3)}
.va-recon .cell.intrinsic .v{color:var(--brass-bright)}
/* Cross-check */
.va-cx{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden}
.va-cx-head{padding:16px 24px;border-bottom:1px solid var(--line-1);display:flex;justify-content:space-between;align-items:baseline}
.va-cx-head h3{font-family:var(--font-display);font-size:20px;font-weight:500;color:var(--fg-1);margin:0}
.va-cx-head .hint{font-family:var(--font-mono);font-size:12px;color:var(--fg-3)}
.va-cx-grid{display:grid;grid-template-columns:1.2fr 1fr 1fr 1fr}
.va-cx-cell{padding:16px 24px;border-right:1px solid var(--line-1);display:flex;flex-direction:column;gap:6px}
.va-cx-cell:last-child{border-right:none}
.va-cx-cell .lbl{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.18em;color:var(--fg-3);font-weight:600}
.va-cx-cell .v{font-family:var(--font-mono);font-variant-numeric:tabular-nums;font-size:26px;color:var(--fg-1);font-weight:500;line-height:1}
.va-cx-cell.dcf{background:rgba(194,170,122,.05)}
.va-cx-cell.dcf .v{color:var(--brass-bright)}
.va-cx-cell.dcf .lbl{color:var(--brass)}
.va-cx-cell .delta{font-family:var(--font-mono);font-variant-numeric:tabular-nums;font-size:12px}
.va-cx-cell .delta.neg{color:var(--negative)}
.va-cx-cell .delta.pos{color:var(--positive)}
.va-cx-cell .delta.na{color:var(--fg-4)}
.va-cx-cell .meta{font-family:var(--font-sans);font-size:11px;color:var(--fg-3);border-top:1px solid var(--line-1);padding-top:6px;margin-top:auto;line-height:1.4}
/* Footer */
.va-foot{font-family:var(--font-sans);font-size:12px;color:var(--fg-3);line-height:1.6;padding:12px 20px;border:1px solid var(--line-1);border-radius:4px;background:var(--ink-1);display:flex;justify-content:space-between;align-items:center;gap:24px}
.va-foot a{color:var(--brass-bright);text-decoration:none;white-space:nowrap;flex-shrink:0}
.va-foot a:hover{color:var(--brass)}
"""
_DCF_RAIL_CSS = """<style>
@import url('https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,400;0,500;1,400;1,500&family=IBM+Plex+Mono:wght@300;400;500;600&family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap');
.dcf-eyebrow{font-family:'IBM Plex Sans',sans-serif;font-size:12px;text-transform:uppercase;letter-spacing:.18em;color:#8E8676;font-weight:600;line-height:1}
.dcf-title{font-family:'EB Garamond',Georgia,serif;font-size:22px;font-weight:500;letter-spacing:-.01em;color:#F2ECDC;margin:4px 0 0;line-height:1.2}
.dcf-sub{font-family:'IBM Plex Sans',sans-serif;font-size:12px;color:#8E8676;margin-top:6px;line-height:1.5}
.dcf-divider{border:none;border-top:1px solid #232934;margin:4px 0 0}
.dcf-filings-eyebrow{font-family:'IBM Plex Sans',sans-serif;font-size:11px;text-transform:uppercase;letter-spacing:.18em;color:#8E8676;font-weight:600;margin-bottom:10px}
.dcf-filing-row{display:flex;justify-content:space-between;align-items:baseline;font-family:'IBM Plex Mono',monospace;font-size:12px;color:#C7C0AE;margin-bottom:6px}
.dcf-filing-val{color:#F2ECDC;font-variant-numeric:tabular-nums}
.dcf-actions{display:flex;gap:8px;padding-top:4px}
/* Streamlit slider thumb */
[data-baseweb="slider"] [role="slider"]{background-color:#C2AA7A !important;border:2px solid #0B0E13 !important;width:14px !important;height:14px !important}
[data-testid="stSlider"] > label > div > p{font-family:'IBM Plex Sans',sans-serif !important;font-size:13px !important;color:#C7C0AE !important}
[data-testid="stSlider"] [data-testid="stTickBarMin"],[data-testid="stSlider"] [data-testid="stTickBarMax"]{font-family:'IBM Plex Mono',monospace !important;font-size:10px !important;color:#5E5849 !important}
/* Primary button — brass bg, dark ink text */
[data-testid="stBaseButton-primary"]{color:#17120A !important;background-color:#C2AA7A !important}
button[kind="primary"]{color:#17120A !important}
[data-testid="stBaseButton-primary"] p,[data-testid="stBaseButton-primary"] span{color:#17120A !important}
</style>"""
_MULT_CANVAS_CSS = """
.vm-body{display:flex;flex-direction:column;gap:24px;padding:24px 32px 48px}
/* Summary band */
.vm-summary{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden;display:grid;grid-template-columns:1.4fr 2fr}
.vm-summary-head{padding:24px;display:flex;flex-direction:column;gap:8px;border-right:1px solid var(--line-1)}
.vm-summary-head .eyebrow{font-family:var(--font-sans);font-size:12px;text-transform:uppercase;letter-spacing:.18em;color:var(--fg-3);font-weight:600}
.vm-summary-head .ttl{font-family:var(--font-display);font-size:22px;font-weight:500;color:var(--fg-1);margin:0;line-height:1.2}
.vm-summary-head .lede{font-family:var(--font-sans);font-size:13px;color:var(--fg-2);line-height:1.5;margin:0}
.vm-summary-strip{background:var(--ink-2);display:grid;grid-template-columns:repeat(4,1fr)}
.vm-sum-cell{padding:16px;display:flex;flex-direction:column;gap:4px;border-right:1px solid var(--line-1)}
.vm-sum-cell:last-child{border-right:none}
.vm-sum-cell.market{background:rgba(74,120,181,.05);border-left:1px solid var(--line-2)}
.vm-sum-cell .lbl{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.12em;color:var(--fg-3)}
.vm-sum-cell .v{font-family:var(--font-mono);font-size:20px;color:var(--fg-1);font-variant-numeric:tabular-nums}
.vm-sum-cell.market .v{color:var(--fg-2)}
.vm-sum-cell .d{font-family:var(--font-mono);font-size:11px}
.d.pos{color:var(--positive)}.d.neg{color:var(--negative)}.d.na{color:var(--fg-4)}
/* Comparison card */
.vm-compare{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden}
.vm-compare-head{padding:16px 24px;border-bottom:1px solid var(--line-1);display:flex;align-items:baseline;gap:12px}
.vm-compare-head h3{font-family:var(--font-display);font-size:20px;font-weight:500;color:var(--fg-1);margin:0}
.vm-compare-head .units{font-family:var(--font-sans);font-size:11px;color:var(--fg-3)}
.vm-grid{display:grid;grid-template-columns:220px 1fr 1fr 1fr;border-bottom:1px solid var(--line-1)}
.vm-grid:last-child{border-bottom:none}
.vm-row-lbl{padding:12px 16px;background:var(--ink-2);border-right:1px solid var(--line-1);font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.12em;color:var(--fg-3);display:flex;flex-direction:column;gap:4px;align-items:flex-start;justify-content:center}
.vm-row-lbl .sub{font-family:var(--font-sans);font-size:10px;color:var(--fg-4);text-transform:none;letter-spacing:0}
.vm-row-lbl.strong{color:var(--brass);background:rgba(194,170,122,.06)}
.vm-cell{padding:12px 16px;display:flex;flex-direction:column;gap:4px;justify-content:center}
.vm-cell .v{font-family:var(--font-mono);font-size:20px;color:var(--fg-1);font-variant-numeric:tabular-nums}
.vm-cell .v.dash{color:var(--fg-4)}
.vm-cell .cap{font-family:var(--font-sans);font-size:11px;color:var(--fg-3)}
.vm-cell.faded{background:rgba(255,255,255,.005)}
.vm-cell.faded .v{color:var(--fg-4)}
.vm-col-head{padding:16px}
.vm-col-title{display:flex;align-items:center;gap:8px;margin-bottom:8px}
.vm-col-title .n{font-family:var(--font-display);font-style:italic;font-size:16px;color:var(--brass)}
.vm-col-title h4{font-family:var(--font-sans);font-size:14px;font-weight:600;color:var(--fg-1);margin:0}
.vm-col-title .fit{font-family:var(--font-sans);font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.1em;padding:2px 6px;border-radius:2px}
.vm-col-title .fit.ok{color:var(--positive);background:var(--positive-bg)}
.vm-col-title .fit.warn{color:var(--warning);background:var(--warning-bg)}
.vm-col-head .lede{font-family:var(--font-sans);font-size:12px;color:var(--fg-3);line-height:1.5;margin:0}
.vm-grid.result .vm-row-lbl{color:var(--brass);background:rgba(194,170,122,.06)}
.vm-grid.result .vm-cell{background:rgba(194,170,122,.04)}
.vm-grid.result .vm-cell .v{font-size:28px;color:var(--brass-bright)}
.vm-grid.result .vm-cell .delta{font-family:var(--font-mono);font-size:12px}
.delta.pos{color:var(--positive)}.delta.neg{color:var(--negative)}.delta.na{color:var(--fg-4)}
/* Subject multiple slider */
.vm-cell.mult{gap:6px}
.mult-top{display:flex;align-items:baseline;gap:8px}
.mult-top .big{font-family:var(--font-mono);font-size:24px;color:var(--brass-bright);font-variant-numeric:tabular-nums}
.mult-top .sector{font-family:var(--font-mono);font-size:11px;color:var(--fg-3)}
.mult-slider{position:relative;height:18px;margin:2px 0}
.mult-slider .track{position:absolute;inset:7px 0;background:var(--ink-3);border-radius:999px;pointer-events:none}
.mult-slider .track .band{position:absolute;inset:0;background:rgba(74,120,181,.18)}
.mult-slider .track .marker{position:absolute;top:-3px;bottom:-3px;width:2px;background:var(--oxford-light);border-radius:1px}
.mult-slider input[type=range]{position:absolute;inset:0;width:100%;height:18px;background:transparent;-webkit-appearance:none;appearance:none;cursor:pointer;outline:none}
.mult-slider input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:14px;height:14px;border-radius:50%;background:var(--brass);border:2px solid #0B0E13;box-shadow:0 0 0 1px var(--brass-deep);cursor:pointer}
.mult-slider input[type=range]::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--brass);border:2px solid #0B0E13;box-shadow:0 0 0 1px var(--brass-deep);cursor:pointer;border:none}
.mult-slider input[type=range]::-webkit-slider-runnable-track{background:transparent}
.mult-slider input[type=range]::-moz-range-track{background:transparent;height:4px}
.mult-meta{display:flex;justify-content:space-between;font-family:var(--font-mono);font-size:10px;color:var(--fg-4)}
/* Sensitivity strip */
.vm-sensitivity{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden}
.vm-sensitivity-head{padding:16px 24px;border-bottom:1px solid var(--line-1);display:flex;align-items:baseline;gap:12px}
.vm-sensitivity-head h3{font-family:var(--font-display);font-size:20px;font-weight:500;color:var(--fg-1);margin:0}
.vm-sensitivity-head .hint{font-family:var(--font-sans);font-size:11px;color:var(--fg-3)}
.vm-sens-grid{display:grid;grid-template-columns:repeat(3,1fr)}
.vm-sens-cell{padding:16px;border-right:1px solid var(--line-1)}
.vm-sens-cell:last-child{border-right:none}
.vm-sens-cell>.lbl{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.12em;color:var(--fg-3);display:block;margin-bottom:10px}
.vm-sens-row{display:grid;grid-template-columns:1fr auto 1fr;gap:8px;align-items:center;margin-bottom:10px;padding-bottom:10px;border-bottom:1px solid var(--line-1)}
.vm-sens-row .col{display:flex;flex-direction:column;gap:2px}
.vm-sens-row .col .sub{font-family:var(--font-mono);font-size:10px;color:var(--fg-3)}
.vm-sens-row .col .v{font-family:var(--font-mono);font-size:18px;color:var(--fg-1);font-variant-numeric:tabular-nums}
.vm-sens-row .col .v.brass{color:var(--brass-bright)}
.vm-sens-row .col .d{font-family:var(--font-mono);font-size:11px}
.vm-sens-row .arrow{font-family:var(--font-display);font-style:italic;font-size:20px;color:var(--fg-4);text-align:center}
.vm-sens-cell>.meta{font-family:var(--font-sans);font-size:11px;color:var(--fg-3)}
.vm-sens-cell>.meta .num{font-family:var(--font-mono);color:var(--fg-2)}
/* Cross-check vs DCF */
.vm-cx{background:var(--ink-1);border:1px solid var(--line-1);border-radius:6px;overflow:hidden}
.vm-cx-head{padding:16px 24px;border-bottom:1px solid var(--line-1);display:flex;align-items:baseline;gap:12px}
.vm-cx-head h3{font-family:var(--font-display);font-size:20px;font-weight:500;color:var(--fg-1);margin:0}
.vm-cx-head .hint{font-family:var(--font-sans);font-size:11px;color:var(--fg-3)}
.vm-cx-grid{display:grid;grid-template-columns:1.2fr 1fr 1fr 1fr}
.vm-cx-cell{padding:16px 24px;border-right:1px solid var(--line-1);display:flex;flex-direction:column;gap:4px}
.vm-cx-cell:last-child{border-right:none}
.vm-cx-cell .lbl{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.12em;color:var(--fg-3)}
.vm-cx-cell .v{font-family:var(--font-mono);font-size:24px;color:var(--fg-1);font-variant-numeric:tabular-nums}
.vm-cx-cell .delta{font-family:var(--font-mono);font-size:12px}
.vm-cx-cell .meta{font-family:var(--font-sans);font-size:11px;color:var(--fg-4);margin-top:4px}
.vm-cx-cell.dcf{background:rgba(194,170,122,.05)}
.vm-cx-cell.dcf .lbl{color:var(--brass-deep)}
.vm-cx-cell.dcf .v{color:var(--brass-bright)}
"""
def _fmt_b(v_dollars: float) -> str:
b = v_dollars / 1e9
if abs(b) >= 1000:
return f"${b / 1000:.2f}T"
return f"${b:.2f}B"
def _build_dcf_canvas_html(
ctx: dict,
result: dict,
wacc_pct: float,
tg_pct: float,
yrs: int,
g_pct: float,
ev_ebitda_price: float | None,
ev_rev_price: float | None,
pb_price: float | None,
) -> str:
iv = result["intrinsic_value_per_share"]
market = float(ctx["current_price"] or 0)
has_market = market > 0
upside_pct = (iv - market) / market * 100 if has_market else 0.0
is_pos = upside_pct >= 0
gap = iv - market
# Bridge
ev_b = _fmt_b(result["enterprise_value"])
net_debt_b = _fmt_b(abs(result["net_debt"]))
other_claims_b = _fmt_b(ctx["preferred_equity"] + ctx["minority_interest"])
equity_b = _fmt_b(result["equity_value"])
total_debt_b = _fmt_b(ctx["total_debt"])
cash_b = _fmt_b(ctx["cash_and_equivalents"])
other_b_val = ctx["preferred_equity"] + ctx["minority_interest"]
shares_b = ctx["shares"] / 1e9
source_date = ctx["bridge_items"].get("source_date", "")
# Forecast sequences (capped at yrs)
discounted = result["discounted_fcfs"][:yrs]
projected = result["projected_fcfs"][:yrs]
tv_pv = result["terminal_value_pv"]
terminal_fcf = projected[-1] * (1 + tg_pct / 100) if projected else 0.0
disc_factors = [1.0 / (1 + wacc_pct / 100) ** (i + 1) for i in range(len(discounted))]
disc_tv_factor = 1.0 / (1 + wacc_pct / 100) ** yrs
# Plotly chart data
bar_x = [f"Year {i + 1}" for i in range(len(discounted))] + ["Terminal"]
bar_y = [v / 1e9 for v in discounted] + [tv_pv / 1e9]
bar_colors = ["#243E5A"] * len(discounted) + ["#C2AA7A"]
bar_line_colors = ["#1F3B5E"] * len(discounted) + ["#DCC79E"]
bar_text = [_fmt_b(v) for v in discounted] + [_fmt_b(tv_pv)]
plotly_data = json.dumps([{
"type": "bar",
"x": bar_x,
"y": bar_y,
"marker": {"color": bar_colors, "line": {"color": bar_line_colors, "width": 1}},
"text": bar_text,
"textposition": "outside",
"textfont": {"family": "IBM Plex Mono", "size": 10, "color": "#C7C0AE"},
"hovertemplate": "%{x}: %{text}<extra></extra>",
"cliponaxis": False,
}])
plotly_layout = json.dumps({
"paper_bgcolor": "#11151C",
"plot_bgcolor": "#11151C",
"margin": {"l": 48, "r": 8, "t": 28, "b": 36},
"xaxis": {
"gridcolor": "rgba(0,0,0,0)",
"linecolor": "#232934",
"tickfont": {"family": "IBM Plex Sans", "size": 11, "color": "#8E8676"},
"fixedrange": True,
},
"yaxis": {
"gridcolor": "#232934",
"linecolor": "rgba(0,0,0,0)",
"tickfont": {"family": "IBM Plex Mono", "size": 10, "color": "#8E8676"},
"tickprefix": "$",
"ticksuffix": "B",
"fixedrange": True,
"zeroline": False,
},
"bargap": 0.35,
"showlegend": False,
"uniformtext": {"mode": "hide", "minsize": 8},
})
# Verdict
verdict_gradient = (
"linear-gradient(110deg,transparent 35%,rgba(79,140,94,.07) 100%)"
if is_pos else
"linear-gradient(110deg,transparent 35%,rgba(181,73,75,.07) 100%)"
)
pill_cls = "pos" if is_pos else "neg"
pill_arrow = "▲" if is_pos else "▼"
pill_sign = "+" if is_pos else "−"
pill_text = f"{pill_arrow} {pill_sign}{abs(upside_pct):.1f}% {'upside' if is_pos else 'downside'}"
reading = "Constructive" if is_pos else "Cautious"
gap_dir = "above" if gap >= 0 else "below"
iv_str = f"${iv:,.2f}"
market_str = f"${market:,.2f}" if has_market else "—"
gap_str = f"${abs(gap):,.2f}"
# Cash-flow table
n = len(discounted)
hdr_cells = "".join(f"<th>Yr {i + 1}</th>" for i in range(n)) + "<th>Terminal</th>"
fcf_cells = "".join(f"<td>{_fmt_b(v)}</td>" for v in projected)
fcf_cells += f'<td class="brass">{_fmt_b(terminal_fcf)}</td>'
df_cells = "".join(f"<td>{disc_factors[i]:.3f}</td>" for i in range(n))
df_cells += f"<td>{disc_tv_factor:.3f}</td>"
pv_cells = "".join(f"<td>{_fmt_b(v)}</td>" for v in discounted)
pv_cells += f'<td class="brass">{_fmt_b(tv_pv)}</td>'
# Cross-check cells
def cx_cell(cls, lbl, val_str, delta_pct, meta):
if delta_pct is not None and has_market:
dcls = "pos" if delta_pct >= 0 else "neg"
dsign = "+" if delta_pct >= 0 else ""
dhtml = f'<span class="delta {dcls}">{dsign}{delta_pct:.1f}% vs market</span>'
else:
dhtml = '<span class="delta na">—</span>'
return (
f'<div class="{cls}">'
f'<span class="lbl">{lbl}</span>'
f'<span class="v num">{val_str}</span>'
f"{dhtml}"
f'<span class="meta">{meta}</span>'
f"</div>"
)
dcf_delta = upside_pct if has_market else None
cx_dcf = cx_cell(
"va-cx-cell dcf", "DCF · THIS MODEL", iv_str, dcf_delta,
f"Firm-value DCF · {yrs}-yr explicit · WACC {wacc_pct:.1f}%",
)
def _cx_multiple_cell(label, implied, market_multiple, mult_label):
if implied is not None and has_market:
delta = (implied - market) / market * 100
val = f"${implied:,.2f}"
meta = f"Market multiple {market_multiple:.1f}× · {mult_label}" if market_multiple else mult_label
else:
delta = None
val = "—"
meta = "Unavailable for this company"
return cx_cell("va-cx-cell", label, val, delta, meta)
cx_ev = _cx_multiple_cell(
"EV / EBITDA", ev_ebitda_price,
ctx.get("ev_ebitda_current") or 0, "based on current market multiple",
)
cx_rev = _cx_multiple_cell(
"EV / REVENUE", ev_rev_price,
ctx.get("ev_revenue_current") or 0, "based on current market multiple",
)
cx_pb = _cx_multiple_cell(
"P / BOOK", pb_price,
ctx.get("pb_current") or 0, "based on current market multiple",
)
# Recon gap cell color
gap_color = "var(--positive)" if gap >= 0 else "var(--negative)"
gap_sign = "+" if gap >= 0 else ""
gap_display = f"{gap_sign}${gap:,.2f}" if has_market else "—"
gap_pct_str = f"{upside_pct:.1f}% vs market" if has_market else "—"
html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,400;0,500;1,400;1,500&family=IBM+Plex+Mono:wght@300;400;500;600&family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.plot.ly/plotly-2.35.2.min.js" charset="utf-8"></script>
<style>{_DCF_CANVAS_CSS}</style>
</head>
<body>
<div class="va-canvas">
<section class="va-verdict" style="--verdict-gradient:{verdict_gradient}">
<div style="position:absolute;inset:0;background:{verdict_gradient};pointer-events:none;z-index:0"></div>
<div class="top">
<div class="col">
<span class="lbl">DCF Intrinsic Value</span>
<span class="big num">{iv_str}</span>
<span class="sub">per share · firm value method · {yrs}-yr horizon</span>
</div>
<span class="arrow">vs</span>
<div class="col" style="align-items:flex-end">
<span class="lbl">Market Price</span>
<span class="big market num">{market_str}</span>
<span class="pill {pill_cls}">{pill_text}</span>
</div>
</div>
<div class="band">
<span>Reading · DCF implies <span class="mono">{gap_str}</span> {gap_dir} the current market.</span>
<span class="reading">{reading}</span>
</div>
</section>
<section class="va-projection">
<div class="head">
<h3>Enterprise value build — present value of FCFs + terminal</h3>
<span class="units">USD · billions · discounted at WACC {wacc_pct:.1f}%</span>
</div>
<div id="dcf-chart" style="width:100%;height:260px"></div>
<table class="va-cf-table">
<thead><tr><th></th>{hdr_cells}</tr></thead>
<tbody>
<tr><td>Forecast FCF</td>{fcf_cells}</tr>
<tr><td>Discount factor</td>{df_cells}</tr>
<tr class="total"><td>Present value</td>{pv_cells}</tr>
</tbody>
</table>
</section>
<section class="va-bridge">
<div class="bhead">
<h3>From enterprise to equity</h3>
<span class="bdate">Balance-sheet bridge{(' · ' + source_date) if source_date else ''}</span>
</div>
<div class="flow">
<div class="node start"><span class="lbl">Enterprise value</span><span class="v num">{ev_b}</span></div>
<div class="op">−<span class="sub">Net debt</span></div>
<div class="node"><span class="lbl">Net debt</span><span class="v num">{net_debt_b}</span></div>
<div class="op">−<span class="sub">Other claims</span></div>
<div class="node"><span class="lbl">Other claims</span><span class="v num">{other_claims_b}</span></div>
<div class="op">=</div>
<div class="node result"><span class="lbl">Equity value</span><span class="v num">{equity_b}</span></div>
</div>
<div class="bfoot">
<span>Total debt {total_debt_b}</span>
<span>·</span>
<span>Cash & equiv. {cash_b}</span>
<span>·</span>
<span>Preferred + minority {_fmt_b(other_b_val)}</span>
</div>
</section>
<section class="va-recon">
<div class="cell intrinsic">
<span class="lbl">Intrinsic · Per Share</span>
<span class="v num">{iv_str}</span>
<span class="sub">Equity value ÷ shares</span>
</div>
<div class="cell">
<span class="lbl">Market · Last</span>
<span class="v num">{market_str}</span>
<span class="sub"> </span>
</div>
<div class="cell">
<span class="lbl">Gap</span>
<span class="v num" style="color:{gap_color}">{gap_display}</span>
<span class="sub">{gap_pct_str}</span>
</div>
<div class="cell">
<span class="lbl">Shares Outstanding</span>
<span class="v num">{shares_b:.2f} B</span>
<span class="sub">diluted</span>
</div>
</section>
<section class="va-cx">
<div class="va-cx-head">
<h3>Cross-check against the multiples</h3>
<span class="hint">Same business, different lenses · implied per-share</span>
</div>
<div class="va-cx-grid">
{cx_dcf}
{cx_ev}
{cx_rev}
{cx_pb}
</div>
</section>
<div class="va-foot">
<span>Firm-value DCF · enterprise value bridged to equity using debt & cash from the most recent balance sheet. Negative-FCF years are excluded from the base; terminal value uses Gordon Growth Model.</span>
<a href="#">Methodology & sources ↗</a>
</div>
</div>
<script>
var data = {plotly_data};
var layout = {plotly_layout};
Plotly.newPlot('dcf-chart', data, layout, {{displayModeBar: false, responsive: true}});
</script>
</body>
</html>"""
return html
def _build_multiples_canvas_html(ctx: dict) -> str:
market = float(ctx["current_price"] or 0)
shares = float(ctx["shares"] or 0)
total_debt = float(ctx["total_debt"] or 0)
cash = float(ctx["cash_and_equivalents"] or 0)
net_debt = total_debt - cash
ebitda = float(ctx["ebitda"]) if ctx.get("ebitda") and ctx["ebitda"] > 0 else 0.0
revenue = float(ctx["revenue_ttm"]) if ctx.get("revenue_ttm") and ctx["revenue_ttm"] > 0 else 0.0
book_ps = float(ctx["book_value_per_share"]) if ctx.get("book_value_per_share") and ctx["book_value_per_share"] > 0 else 0.0
eb_ok = ebitda > 0 and shares > 0
rv_ok = revenue > 0 and shares > 0
pb_ok = book_ps > 0
has_market = market > 0
def _clamp(v, lo, hi):
try:
return max(lo, min(hi, float(v)))
except (TypeError, ValueError):
return lo
eb_init = _clamp(ctx.get("ev_ebitda_current") or 15.0, 8.0, 32.0)
rv_init = _clamp(ctx.get("ev_revenue_current") or 5.0, 4.0, 20.0)
pb_init = _clamp(ctx.get("pb_current") or 5.0, 4.0, 60.0)
# Sector medians — try peers, fall back to defaults
eb_sector, rv_sector, pb_sector = 12.0, 3.0, 4.0
try:
info = ctx.get("info") or {}
peers = get_peers(ctx["ticker"]) or _suggest_peer_tickers(ctx["ticker"], info)
if peers:
pr = get_ratios_for_tickers(peers[:6])
if pr:
import statistics as _stats
eb_vs = [float(r["enterpriseValueMultipleTTM"]) for r in pr.values()
if r and r.get("enterpriseValueMultipleTTM") and 2 < r["enterpriseValueMultipleTTM"] < 100]
rv_vs = [float(r["priceToSalesRatioTTM"]) for r in pr.values()
if r and r.get("priceToSalesRatioTTM") and 0.1 < r["priceToSalesRatioTTM"] < 50]
pb_vs = [float(r["priceToBookRatioTTM"]) for r in pr.values()
if r and r.get("priceToBookRatioTTM") and 0.5 < r["priceToBookRatioTTM"] < 200]
if eb_vs:
eb_sector = _stats.median(eb_vs)
if rv_vs:
rv_sector = _stats.median(rv_vs)
if pb_vs:
pb_sector = _stats.median(pb_vs)
except Exception:
pass
eb_sector = _clamp(eb_sector, 8.0, 32.0)
rv_sector = _clamp(rv_sector, 4.0, 20.0)
pb_sector = _clamp(pb_sector, 4.0, 60.0)
dcf_iv = st.session_state.get("dcf_intrinsic")
dcf_wacc = st.session_state.get(f"dcf_wacc_{ctx['ticker']}", 10.0)
dcf_tg = st.session_state.get(f"dcf_tg_{ctx['ticker']}", 2.5)
dcf_yrs = st.session_state.get(f"dcf_yrs_{ctx['ticker']}", 5)
def _fb(v):
if v is None or not (isinstance(v, (int, float)) and v == v):
return "—"
b = v / 1e9
if abs(b) >= 1000:
return f"${b / 1000:.2f}T"
return f"${b:.2f}B"
def _fs(v):
if v is None or not (isinstance(v, (int, float)) and v == v):
return "—"
return f"${v:.2f}"
def _fx(v):
return f"{v:.1f}×"
def _dpct(v):
if not has_market or v is None:
return None
return (v - market) / market * 100
def _d_span(val, id_attr=""):
d = _dpct(val)
if d is None:
return f'<span {id_attr} class="delta na">—</span>'
cls = "pos" if d >= 0 else "neg"
arr = "▲" if d >= 0 else "▼"
sign = "+" if d >= 0 else ""
market_str = _fs(market)
return f'<span {id_attr} class="delta num {cls}">{arr} {sign}{d:.1f}% vs {market_str}</span>'
def _ds_span(val, id_attr=""):
d = _dpct(val)
if d is None:
return f'<span {id_attr} class="d na">—</span>'
cls = "pos" if d >= 0 else "neg"
arr = "▲" if d >= 0 else "▼"
sign = "+" if d >= 0 else ""
return f'<span {id_attr} class="d num {cls}">{arr} {sign}{d:.1f}%</span>'
# Initial computed values
if eb_ok:
eb_ev0 = eb_init * ebitda
eb_eq0 = eb_ev0 - net_debt
eb_per0 = eb_eq0 / shares
else:
eb_ev0 = eb_eq0 = eb_per0 = None
if rv_ok:
rv_ev0 = rv_init * revenue
rv_eq0 = rv_ev0 - net_debt
rv_per0 = rv_eq0 / shares
else:
rv_ev0 = rv_eq0 = rv_per0 = None
pb_per0 = pb_init * book_ps if pb_ok else None
# Sector reference values (static)
sec_eb = (eb_sector * ebitda - net_debt) / shares if eb_ok else None
sec_rv = (rv_sector * revenue - net_debt) / shares if rv_ok else None
sec_pb = pb_sector * book_ps if pb_ok else None
# Slider CSS % positions
def _pct(v, lo, hi):
return (v - lo) / (hi - lo) * 100
eb_s_pct = _pct(eb_sector, 8, 32)
eb_bl_pct = _pct(14, 8, 32)
eb_bh_pct = _pct(26, 8, 32)
rv_s_pct = _pct(rv_sector, 4, 20)
rv_bl_pct = _pct(6, 4, 20)
rv_bh_pct = _pct(13, 4, 20)
pb_s_pct = _pct(pb_sector, 4, 60)
pb_bl_pct = _pct(8, 4, 60)
pb_bh_pct = _pct(14, 4, 60)
shares_str = f"{shares / 1e9:.2f} B" if shares > 0 else "—"
# P/Book fit badge depends on whether company is financial
pb_fit_cls = "ok" if ctx.get("is_financial") else "warn"
pb_fit_lbl = "Strong fit" if ctx.get("is_financial") else "Limited fit"
# Sensitivity re-rating strings (static sector side)
def _rr(subj_per, sect_per):
if subj_per is None or sect_per is None or subj_per == 0:
return "—"
rr = (sect_per - subj_per) / abs(subj_per) * 100
sign = "+" if rr >= 0 else ""
cls = "pos" if rr >= 0 else "neg"
return f'<span class="num {cls}">{sign}{rr:.1f}%</span>'
# DCF cross-check cell
if dcf_iv is not None:
dcf_d = _dpct(float(dcf_iv))
if dcf_d is not None:
dcf_cls = "pos" if dcf_d >= 0 else "neg"
dcf_arr = "▲" if dcf_d >= 0 else "▼"
dcf_sign = "+" if dcf_d >= 0 else ""
dcf_delta_html = f'<span class="delta num {dcf_cls}">{dcf_arr} {dcf_sign}{dcf_d:.1f}% vs market</span>'
else:
dcf_delta_html = '<span class="delta na">—</span>'
dcf_val_str = _fs(float(dcf_iv))
dcf_meta_str = f"WACC {dcf_wacc:.1f}% · TG {dcf_tg:.1f}% · {dcf_yrs}-yr explicit"
else:
dcf_delta_html = '<span class="delta na">Run DCF tab first</span>'
dcf_val_str = "—"
dcf_meta_str = "Switch to DCF tab to compute"
ticker = ctx["ticker"]
exchange = (ctx.get("info") or {}).get("exchange") or "—"
data_json = json.dumps({
"market": market, "shares": shares, "netDebt": net_debt,
"totalDebt": total_debt, "cash": cash,
"ebitda": ebitda, "revenue": revenue, "bookPs": book_ps,
"ebOk": eb_ok, "rvOk": rv_ok, "pbOk": pb_ok, "hasMarket": has_market,
"ebSector": eb_sector, "rvSector": rv_sector, "pbSector": pb_sector,
})
html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
{_DCF_CANVAS_CSS}
{_MULT_CANVAS_CSS}
</style>
</head>
<body>
<div class="vm-body">
<section class="vm-summary">
<div class="vm-summary-head">
<span class="eyebrow">Multiples</span>
<h2 class="ttl">Three relative-valuation lenses — implied per-share</h2>
<p class="lede">Subject multiple × normalized TTM metric, bridged to equity per share. Compare across columns to see which lens the market is leaning on.</p>
</div>
<div class="vm-summary-strip">
<div class="vm-sum-cell">
<span class="lbl">EV / EBITDA</span>
<span class="v num" id="sum-eb-val">{_fs(eb_per0)}</span>
{_ds_span(eb_per0, 'id="sum-eb-d"')}
</div>
<div class="vm-sum-cell">
<span class="lbl">EV / Revenue</span>
<span class="v num" id="sum-rv-val">{_fs(rv_per0)}</span>
{_ds_span(rv_per0, 'id="sum-rv-d"')}
</div>
<div class="vm-sum-cell">
<span class="lbl">P / Book</span>
<span class="v num" id="sum-pb-val">{_fs(pb_per0)}</span>
{_ds_span(pb_per0, 'id="sum-pb-d"')}
</div>
<div class="vm-sum-cell market">
<span class="lbl">Market · last</span>
<span class="v num">{_fs(market) if has_market else "—"}</span>
<span class="d num" style="color:var(--fg-3)">{ticker} · {exchange}</span>
</div>
</div>
</section>
<section class="vm-compare">
<div class="vm-compare-head">
<h3>Method comparison</h3>
<span class="units">USD · TTM metrics · balance-sheet bridge</span>
</div>
<div class="vm-grid head">
<div class="vm-row-lbl">Method</div>
<div class="vm-col-head">
<div class="vm-col-title"><span class="n">I</span><h4>EV / EBITDA</h4><span class="fit ok">Strong fit</span></div>
<p class="lede">Enterprise value normalized by operating cash profit. Strips depreciation and capital structure so different capex profiles compare cleanly.</p>
</div>
<div class="vm-col-head">
<div class="vm-col-title"><span class="n">II</span><h4>EV / Revenue</h4><span class="fit ok">Strong fit</span></div>
<p class="lede">Topline multiple — useful when margins are volatile or the business is reinvesting through profitability. Less sensitive to one-off charges.</p>
</div>
<div class="vm-col-head">
<div class="vm-col-title"><span class="n">III</span><h4>P / Book</h4><span class="fit {pb_fit_cls}">{pb_fit_lbl}</span></div>
<p class="lede">Equity multiple — works for balance-sheet-heavy businesses (banks, insurers, REITs). Limited signal for asset-light software & services.</p>
</div>
</div>
<div class="vm-grid">
<div class="vm-row-lbl">Subject multiple<span class="sub">drag to flex the lens</span></div>
<div class="vm-cell mult">
<div class="mult-top"><span class="big num" id="big-eb">{_fx(eb_init)}</span><span class="sector num">sector {_fx(eb_sector)}</span></div>
<div class="mult-slider">
<div class="track">
<span class="band" style="left:{eb_bl_pct:.1f}%;right:{100-eb_bh_pct:.1f}%"></span>
<span class="marker" style="left:{eb_s_pct:.1f}%"></span>
</div>
<input type="range" id="sl-eb" min="8" max="32" step="0.1" value="{eb_init:.1f}"{' disabled' if not eb_ok else ''}>
</div>
<div class="mult-meta"><span>8×</span><span>typical 14×–26×</span><span>32×</span></div>
</div>
<div class="vm-cell mult">
<div class="mult-top"><span class="big num" id="big-rv">{_fx(rv_init)}</span><span class="sector num">sector {_fx(rv_sector)}</span></div>
<div class="mult-slider">
<div class="track">
<span class="band" style="left:{rv_bl_pct:.1f}%;right:{100-rv_bh_pct:.1f}%"></span>
<span class="marker" style="left:{rv_s_pct:.1f}%"></span>
</div>
<input type="range" id="sl-rv" min="4" max="20" step="0.1" value="{rv_init:.1f}"{' disabled' if not rv_ok else ''}>
</div>
<div class="mult-meta"><span>4×</span><span>typical 6×–13×</span><span>20×</span></div>
</div>
<div class="vm-cell mult">
<div class="mult-top"><span class="big num" id="big-pb">{_fx(pb_init)}</span><span class="sector num">sector {_fx(pb_sector)}</span></div>
<div class="mult-slider">
<div class="track">
<span class="band" style="left:{pb_bl_pct:.1f}%;right:{100-pb_bh_pct:.1f}%"></span>
<span class="marker" style="left:{pb_s_pct:.1f}%"></span>
</div>
<input type="range" id="sl-pb" min="4" max="60" step="0.1" value="{pb_init:.1f}"{' disabled' if not pb_ok else ''}>
</div>
<div class="mult-meta"><span>4×</span><span>typical 8×–14×</span><span>60×</span></div>
</div>
</div>
<div class="vm-grid">
<div class="vm-row-lbl">× Normalized metric<span class="sub">from TTM filings</span></div>
<div class="vm-cell"><span class="v num">{_fb(ebitda) if eb_ok else "—"}</span><span class="cap">EBITDA · TTM</span></div>
<div class="vm-cell"><span class="v num">{_fb(revenue) if rv_ok else "—"}</span><span class="cap">Revenue · TTM</span></div>
<div class="vm-cell"><span class="v num">{_fs(book_ps) if pb_ok else "—"}</span><span class="cap">Book value · /share</span></div>
</div>
<div class="vm-grid">
<div class="vm-row-lbl">= Enterprise value</div>
<div class="vm-cell"><span class="v num" id="eb-ev-val">{_fb(eb_ev0)}</span><span class="cap">multiple × metric</span></div>
<div class="vm-cell"><span class="v num" id="rv-ev-val">{_fb(rv_ev0)}</span><span class="cap">multiple × metric</span></div>
<div class="vm-cell faded"><span class="v num dash">—</span><span class="cap">P/B is an equity multiple — no EV step</span></div>
</div>
<div class="vm-grid">
<div class="vm-row-lbl">− Net debt</div>
<div class="vm-cell"><span class="v num">{_fb(net_debt)}</span><span class="cap">total {_fb(total_debt)} − cash {_fb(cash)}</span></div>
<div class="vm-cell"><span class="v num">{_fb(net_debt)}</span><span class="cap">total {_fb(total_debt)} − cash {_fb(cash)}</span></div>
<div class="vm-cell faded"><span class="v num dash">—</span></div>
</div>
<div class="vm-grid">
<div class="vm-row-lbl">= Equity value</div>
<div class="vm-cell"><span class="v num" id="eb-eq-val">{_fb(eb_eq0)}</span><span class="cap">EV − net debt</span></div>
<div class="vm-cell"><span class="v num" id="rv-eq-val">{_fb(rv_eq0)}</span><span class="cap">EV − net debt</span></div>
<div class="vm-cell faded"><span class="v num dash">—</span></div>
</div>
<div class="vm-grid">
<div class="vm-row-lbl">÷ Shares outstanding</div>
<div class="vm-cell"><span class="v num">{shares_str}</span><span class="cap">diluted</span></div>
<div class="vm-cell"><span class="v num">{shares_str}</span><span class="cap">diluted</span></div>
<div class="vm-cell faded"><span class="v num dash">—</span></div>
</div>
<div class="vm-grid result">
<div class="vm-row-lbl strong">= Implied per share</div>
<div class="vm-cell result">
<span class="v num" id="eb-per-val">{_fs(eb_per0)}</span>
{_d_span(eb_per0, 'id="eb-per-d"')}
</div>
<div class="vm-cell result">
<span class="v num" id="rv-per-val">{_fs(rv_per0)}</span>
{_d_span(rv_per0, 'id="rv-per-d"')}
</div>
<div class="vm-cell result">
<span class="v num" id="pb-per-val">{_fs(pb_per0)}</span>
{_d_span(pb_per0, 'id="pb-per-d"')}
</div>
</div>
</section>
<section class="vm-sensitivity">
<div class="vm-sensitivity-head">
<h3>If the lens shifted to sector</h3>
<span class="hint">Same metrics, subject multiple replaced by sector median</span>
</div>
<div class="vm-sens-grid">
<div class="vm-sens-cell">
<span class="lbl">EV / EBITDA</span>
<div class="vm-sens-row">
<div class="col">
<span class="sub" id="sens-eb-subj-lbl">At subject {_fx(eb_init)}</span>
<span class="v num" id="sens-eb-subj-v">{_fs(eb_per0)}</span>
{_ds_span(eb_per0, 'id="sens-eb-subj-d"')}
</div>
<span class="arrow">→</span>
<div class="col">
<span class="sub">At sector {_fx(eb_sector)}</span>
<span class="v num brass">{_fs(sec_eb)}</span>
{_ds_span(sec_eb)}
</div>
</div>
<span class="meta" id="sens-eb-meta">Re-rating Δ {_rr(eb_per0, sec_eb)} per share if the subject converged to peers</span>
</div>
<div class="vm-sens-cell">
<span class="lbl">EV / Revenue</span>
<div class="vm-sens-row">
<div class="col">
<span class="sub" id="sens-rv-subj-lbl">At subject {_fx(rv_init)}</span>
<span class="v num" id="sens-rv-subj-v">{_fs(rv_per0)}</span>
{_ds_span(rv_per0, 'id="sens-rv-subj-d"')}
</div>
<span class="arrow">→</span>
<div class="col">
<span class="sub">At sector {_fx(rv_sector)}</span>
<span class="v num brass">{_fs(sec_rv)}</span>
{_ds_span(sec_rv)}
</div>
</div>
<span class="meta" id="sens-rv-meta">Re-rating Δ {_rr(rv_per0, sec_rv)} per share if the subject converged to peers</span>
</div>
<div class="vm-sens-cell">
<span class="lbl">P / Book</span>
<div class="vm-sens-row">
<div class="col">
<span class="sub" id="sens-pb-subj-lbl">At subject {_fx(pb_init)}</span>
<span class="v num" id="sens-pb-subj-v">{_fs(pb_per0)}</span>
{_ds_span(pb_per0, 'id="sens-pb-subj-d"')}
</div>
<span class="arrow">→</span>
<div class="col">
<span class="sub">At sector {_fx(pb_sector)}</span>
<span class="v num brass">{_fs(sec_pb)}</span>
{_ds_span(sec_pb)}
</div>
</div>
<span class="meta" id="sens-pb-meta">Re-rating Δ {_rr(pb_per0, sec_pb)} per share if the subject converged to peers</span>
</div>
</div>
</section>
<section class="vm-cx">
<div class="vm-cx-head">
<h3>Cross-check against DCF</h3>
<span class="hint">DCF intrinsic from the firm-value model on the previous tab</span>
</div>
<div class="vm-cx-grid">
<div class="vm-cx-cell dcf">
<span class="lbl">DCF · firm value</span>
<span class="v num">{dcf_val_str}</span>
{dcf_delta_html}
<span class="meta">{dcf_meta_str}</span>
</div>
<div class="vm-cx-cell">
<span class="lbl">EV / EBITDA</span>
<span class="v num" id="cx-eb-val">{_fs(eb_per0)}</span>
{_d_span(eb_per0, 'id="cx-eb-d"')}
<span class="meta" id="cx-eb-meta">Subject {_fx(eb_init)} · sector {_fx(eb_sector)}</span>
</div>
<div class="vm-cx-cell">
<span class="lbl">EV / Revenue</span>
<span class="v num" id="cx-rv-val">{_fs(rv_per0)}</span>
{_d_span(rv_per0, 'id="cx-rv-d"')}
<span class="meta" id="cx-rv-meta">Subject {_fx(rv_init)} · sector {_fx(rv_sector)}</span>
</div>
<div class="vm-cx-cell">
<span class="lbl">P / Book</span>
<span class="v num" id="cx-pb-val">{_fs(pb_per0)}</span>
{_d_span(pb_per0, 'id="cx-pb-d"')}
<span class="meta" id="cx-pb-meta">Subject {_fx(pb_init)} · sector {_fx(pb_sector)} · low-signal</span>
</div>
</div>
</section>
<div class="va-foot">
<span>Multiples · TTM metrics, balance sheet. Net-debt adjustment applies to EV-based methods only; P/B reads directly off book equity per share. Sector medians from peer group analysis.</span>
<a href="#">Methodology & sources ↗</a>
</div>
</div>
<script>
var D = {data_json};
function fB(n) {{ var b=n/1e9; return Math.abs(b)>=1000 ? '$'+(b/1000).toFixed(2)+'T' : '$'+b.toFixed(2)+'B'; }}
function fS(n) {{ return '$'+n.toFixed(2); }}
function fX(n) {{ return n.toFixed(1)+'×'; }}
function dPct(v) {{ return D.hasMarket ? (v-D.market)/D.market*100 : 0; }}
function dStr(d) {{
var cls=d>=0?'pos':'neg', arr=d>=0?'▲':'▼', sign=d>=0?'+':'';
return '<span class="d num '+cls+'">'+arr+' '+sign+d.toFixed(1)+'%</span>';
}}
function dVsStr(d) {{
var cls=d>=0?'pos':'neg', arr=d>=0?'▲':'▼', sign=d>=0?'+':'';
return '<span class="delta num '+cls+'">'+arr+' '+sign+d.toFixed(1)+'% vs '+fS(D.market)+'</span>';
}}
function setText(id,t) {{ var e=document.getElementById(id); if(e) e.textContent=t; }}
function setHtml(id,h) {{ var e=document.getElementById(id); if(e) e.innerHTML=h; }}
function update() {{
var ebX=+document.getElementById('sl-eb').value;
var rvX=+document.getElementById('sl-rv').value;
var pbX=+document.getElementById('sl-pb').value;
if (D.ebOk) {{
var ebEV=ebX*D.ebitda, ebEq=ebEV-D.netDebt, ebPer=ebEq/D.shares, ebD=dPct(ebPer);
var secEbPer=(D.ebSector*D.ebitda-D.netDebt)/D.shares;
var rrEb=ebPer!==0?(secEbPer-ebPer)/Math.abs(ebPer)*100:0;
setText('big-eb', fX(ebX));
setText('sum-eb-val', fS(ebPer)); setHtml('sum-eb-d', dStr(ebD));
setText('eb-ev-val', fB(ebEV)); setText('eb-eq-val', fB(ebEq));
setText('eb-per-val', fS(ebPer)); setHtml('eb-per-d', dVsStr(ebD));
setText('sens-eb-subj-lbl', 'At subject '+fX(ebX));
setText('sens-eb-subj-v', fS(ebPer)); setHtml('sens-eb-subj-d', dStr(ebD));
var rrCls=rrEb>=0?'pos':'neg', rrSign=rrEb>=0?'+':'';
setHtml('sens-eb-meta', 'Re-rating Δ <span class="num '+rrCls+'">'+rrSign+rrEb.toFixed(1)+'%</span> per share if the subject converged to peers');
setText('cx-eb-val', fS(ebPer)); setHtml('cx-eb-d', dVsStr(ebD));
setText('cx-eb-meta', 'Subject '+fX(ebX)+' · sector '+fX(D.ebSector));
}}
if (D.rvOk) {{
var rvEV=rvX*D.revenue, rvEq=rvEV-D.netDebt, rvPer=rvEq/D.shares, rvD=dPct(rvPer);
var secRvPer=(D.rvSector*D.revenue-D.netDebt)/D.shares;
var rrRv=rvPer!==0?(secRvPer-rvPer)/Math.abs(rvPer)*100:0;
setText('big-rv', fX(rvX));
setText('sum-rv-val', fS(rvPer)); setHtml('sum-rv-d', dStr(rvD));
setText('rv-ev-val', fB(rvEV)); setText('rv-eq-val', fB(rvEq));
setText('rv-per-val', fS(rvPer)); setHtml('rv-per-d', dVsStr(rvD));
setText('sens-rv-subj-lbl', 'At subject '+fX(rvX));
setText('sens-rv-subj-v', fS(rvPer)); setHtml('sens-rv-subj-d', dStr(rvD));
var rrCls=rrRv>=0?'pos':'neg', rrSign=rrRv>=0?'+':'';
setHtml('sens-rv-meta', 'Re-rating Δ <span class="num '+rrCls+'">'+rrSign+rrRv.toFixed(1)+'%</span> per share if the subject converged to peers');
setText('cx-rv-val', fS(rvPer)); setHtml('cx-rv-d', dVsStr(rvD));
setText('cx-rv-meta', 'Subject '+fX(rvX)+' · sector '+fX(D.rvSector));
}}
if (D.pbOk) {{
var pbPer=pbX*D.bookPs, pbD=dPct(pbPer);
var secPbPer=D.pbSector*D.bookPs;
var rrPb=pbPer!==0?(secPbPer-pbPer)/Math.abs(pbPer)*100:0;
setText('big-pb', fX(pbX));
setText('sum-pb-val', fS(pbPer)); setHtml('sum-pb-d', dStr(pbD));
setText('pb-per-val', fS(pbPer)); setHtml('pb-per-d', dVsStr(pbD));
setText('sens-pb-subj-lbl', 'At subject '+fX(pbX));
setText('sens-pb-subj-v', fS(pbPer)); setHtml('sens-pb-subj-d', dStr(pbD));
var rrCls=rrPb>=0?'pos':'neg', rrSign=rrPb>=0?'+':'';
setHtml('sens-pb-meta', 'Re-rating Δ <span class="num '+rrCls+'">'+rrSign+rrPb.toFixed(1)+'%</span> per share if the subject converged to peers');
setText('cx-pb-val', fS(pbPer)); setHtml('cx-pb-d', dVsStr(pbD));
setText('cx-pb-meta', 'Subject '+fX(pbX)+' · sector '+fX(D.pbSector)+' · low-signal');
}}
}}
document.getElementById('sl-eb').addEventListener('input', update);
document.getElementById('sl-rv').addEventListener('input', update);
document.getElementById('sl-pb').addEventListener('input', update);
</script>
</body>
</html>"""
return html
def _render_dcf_model(ctx: dict):
hist_growth_raw = ctx["hist_growth_raw"]
hist_growth_raw_pct = hist_growth_raw * 100 if hist_growth_raw is not None else -5.0
slider_default = float(max(-15.0, min(20.0, hist_growth_raw_pct)))
st.markdown(_DCF_RAIL_CSS, unsafe_allow_html=True)
rail_col, canvas_col = st.columns([1, 3], gap="medium")
with rail_col:
st.markdown(
'<span class="dcf-eyebrow">Assumptions</span>'
'<div class="dcf-title">3-stage DCF</div>'
'<div class="dcf-sub">Firm-value DCF — projects free cash flow, discounts to today, bridges to equity per share.</div>',
unsafe_allow_html=True,
)
wacc_pct = st.slider(
"WACC (%)",
min_value=4.0, max_value=15.0, value=10.0, step=0.25,
key=f"dcf_wacc_{ctx['ticker']}",
)
tg_pct = st.slider(
"Terminal growth (%)",
min_value=0.0, max_value=5.0, value=2.5, step=0.1,
key=f"dcf_tg_{ctx['ticker']}",
)
yrs = st.slider(
"Forecast horizon (yr)",
min_value=3, max_value=10, value=5, step=1,
key=f"dcf_yrs_{ctx['ticker']}",
)
g_pct = st.slider(
"FCF growth (%)",
min_value=-15.0, max_value=20.0, value=round(slider_default, 1), step=0.1,
key=f"dcf_g_{ctx['ticker']}",
)
st.markdown('<hr class="dcf-divider">', unsafe_allow_html=True)
net_debt_raw = ctx["total_debt"] - ctx["cash_and_equivalents"]
st.markdown(
'<div class="dcf-filings-eyebrow">From the filings</div>'
f'<div class="dcf-filing-row"><span>Base FCF (TTM)</span><span class="dcf-filing-val">{_fmt_b(ctx["base_fcf"])}</span></div>'
f'<div class="dcf-filing-row"><span>FCF · 5-yr median</span><span class="dcf-filing-val">{hist_growth_raw_pct:+.1f}%</span></div>'
f'<div class="dcf-filing-row"><span>Net debt</span><span class="dcf-filing-val">{_fmt_b(net_debt_raw)}</span></div>'
f'<div class="dcf-filing-row"><span>Shares outstanding</span><span class="dcf-filing-val">{ctx["shares"] / 1e9:.2f} B</span></div>',
unsafe_allow_html=True,
)
st.markdown('<hr class="dcf-divider">', unsafe_allow_html=True)
btn_reset, btn_save, btn_recompute = st.columns(3)
with btn_reset:
if st.button("Reset", key=f"dcf_reset_{ctx['ticker']}", use_container_width=True):
st.session_state[f"dcf_wacc_{ctx['ticker']}"] = 10.0
st.session_state[f"dcf_tg_{ctx['ticker']}"] = 2.5
st.session_state[f"dcf_yrs_{ctx['ticker']}"] = 5
st.session_state[f"dcf_g_{ctx['ticker']}"] = round(slider_default, 1)
st.rerun()
with btn_save:
st.button("Save scenario", key=f"dcf_save_{ctx['ticker']}", disabled=True, use_container_width=True)
with btn_recompute:
if st.button("Recompute", key=f"dcf_recompute_{ctx['ticker']}", type="primary", use_container_width=True):
get_free_cash_flow_ttm.clear()
get_balance_sheet_bridge_items.clear()
st.rerun()
# Guard: WACC must exceed terminal growth
if wacc_pct <= tg_pct:
with canvas_col:
st.warning(f"WACC ({wacc_pct:.2f}%) must be greater than terminal growth ({tg_pct:.2f}%). Adjust the sliders.")
return
result = run_dcf(
fcf_series=ctx["fcf_series"],
shares_outstanding=ctx["shares"],
wacc=wacc_pct / 100,
terminal_growth=tg_pct / 100,
projection_years=yrs,
growth_rate_override=g_pct / 100,
total_debt=ctx["total_debt"],
cash_and_equivalents=ctx["cash_and_equivalents"],
preferred_equity=ctx["preferred_equity"],
minority_interest=ctx["minority_interest"],
base_fcf_override=ctx["base_fcf"],
)
if not result:
with canvas_col:
st.warning("Insufficient data to run DCF model.")
return
if result.get("error"):
with canvas_col:
st.warning(result["error"])
return
st.session_state["dcf_intrinsic"] = result["intrinsic_value_per_share"]
st.session_state[f"dcf_params_{ctx['ticker']}"] = {"wacc": wacc_pct, "tg": tg_pct, "yrs": yrs}
# Cross-check: run other models at their current market multiples
ev_ebitda_price = None
if ctx["ev_available"] and ctx.get("ev_ebitda_current"):
ev_r = run_ev_ebitda(
ebitda=float(ctx["ebitda"]),
total_debt=ctx["total_debt"],
total_cash=ctx["cash_and_equivalents"],
preferred_equity=ctx["preferred_equity"],
minority_interest=ctx["minority_interest"],
shares_outstanding=float(ctx["shares"]),
target_multiple=float(ctx["ev_ebitda_current"]),
)
ev_ebitda_price = ev_r.get("implied_price_per_share")
ev_rev_price = None
if ctx["ev_revenue_available"] and ctx.get("ev_revenue_current") and ctx.get("revenue_ttm"):
rev_r = run_ev_revenue(
revenue=float(ctx["revenue_ttm"]),
total_debt=ctx["total_debt"],
total_cash=ctx["cash_and_equivalents"],
preferred_equity=ctx["preferred_equity"],
minority_interest=ctx["minority_interest"],
shares_outstanding=float(ctx["shares"]),
target_multiple=float(ctx["ev_revenue_current"]),
)
ev_rev_price = rev_r.get("implied_price_per_share")
pb_price = None
if ctx["pb_available"] and ctx.get("pb_current") and ctx.get("book_value_per_share"):
pb_r = run_price_to_book(
book_value_per_share=float(ctx["book_value_per_share"]),
target_multiple=float(ctx["pb_current"]),
)
pb_price = pb_r.get("implied_price_per_share")
canvas_html = _build_dcf_canvas_html(
ctx, result, wacc_pct, tg_pct, yrs, g_pct,
ev_ebitda_price, ev_rev_price, pb_price,
)
with canvas_col:
# Height: base sections + per-year table width is constant in rows
canvas_height = 1620
components.html(canvas_html, height=canvas_height, scrolling=False)
def _render_multiples_model(ctx: dict):
st.markdown(_DCF_RAIL_CSS, unsafe_allow_html=True)
rail_col, canvas_col = st.columns([1, 4], gap="medium")
with rail_col:
st.markdown(
'<span class="dcf-eyebrow">Multiples</span>'
'<div class="dcf-title">Three relative-valuation lenses</div>'
'<div class="dcf-sub">Subject multiple × normalized TTM metric, bridged to equity per share.</div>',
unsafe_allow_html=True,
)
st.markdown('<hr class="dcf-divider">', unsafe_allow_html=True)
net_debt_raw = ctx["total_debt"] - ctx["cash_and_equivalents"]
ebitda_str = _fmt_b(ctx["ebitda"]) if ctx.get("ebitda") and ctx["ebitda"] > 0 else "—"
rev_str = _fmt_b(ctx["revenue_ttm"]) if ctx.get("revenue_ttm") and ctx["revenue_ttm"] > 0 else "—"
bps_str = f"${ctx['book_value_per_share']:.2f}" if ctx.get("book_value_per_share") and ctx["book_value_per_share"] > 0 else "—"
st.markdown(
'<div class="dcf-filings-eyebrow">From the filings</div>'
f'<div class="dcf-filing-row"><span>EBITDA (TTM)</span><span class="dcf-filing-val">{ebitda_str}</span></div>'
f'<div class="dcf-filing-row"><span>Revenue (TTM)</span><span class="dcf-filing-val">{rev_str}</span></div>'
f'<div class="dcf-filing-row"><span>Book value / share</span><span class="dcf-filing-val">{bps_str}</span></div>'
f'<div class="dcf-filing-row"><span>Net debt</span><span class="dcf-filing-val">{_fmt_b(net_debt_raw)}</span></div>'
f'<div class="dcf-filing-row"><span>Shares outstanding</span><span class="dcf-filing-val">{ctx["shares"] / 1e9:.2f} B</span></div>',
unsafe_allow_html=True,
)
st.markdown('<hr class="dcf-divider">', unsafe_allow_html=True)
if st.button("Refresh data", key=f"mult_refresh_{ctx['ticker']}", type="primary", use_container_width=True):
get_balance_sheet_bridge_items.clear()
st.rerun()
canvas_html = _build_multiples_canvas_html(ctx)
with canvas_col:
components.html(canvas_html, height=1620, scrolling=False)
def _render_ev_ebitda_model(ctx: dict):
st.markdown("**EV/EBITDA Valuation**")
st.caption(
"This is the better fallback when EBITDA is positive but free cash flow is weak, volatile, or currently negative."
)
default_multiple = float(ctx["ev_ebitda_current"]) if ctx["ev_ebitda_current"] else 15.0
default_multiple = max(1.0, min(50.0, round(default_multiple, 1)))
help_text = (
f"Current market multiple: {ctx['ev_ebitda_current']:.1f}x"
if ctx["ev_ebitda_current"] else "Current multiple unavailable"
)
target_multiple = st.slider(
"Target EV/EBITDA",
min_value=1.0,
max_value=50.0,
value=default_multiple,
step=0.5,
help=help_text,
key=f"ev_ebitda_multiple_{ctx['ticker']}",
)
ev_result = run_ev_ebitda(
ebitda=float(ctx["ebitda"]),
total_debt=ctx["total_debt"],
total_cash=ctx["cash_and_equivalents"],
preferred_equity=ctx["preferred_equity"],
minority_interest=ctx["minority_interest"],
shares_outstanding=float(ctx["shares"]),
target_multiple=target_multiple,
)
if not ev_result:
st.warning("Could not compute EV/EBITDA valuation.")
return
imp_price = ev_result["implied_price_per_share"]
current_price = ctx["current_price"]
market_cap = ctx["market_cap"]
market_enterprise_value = None
if market_cap and market_cap > 0:
market_enterprise_value = (
float(market_cap)
+ float(ctx["total_debt"])
- float(ctx["cash_and_equivalents"])
+ float(ctx["preferred_equity"])
+ float(ctx["minority_interest"])
)
st.caption(
"This model applies a target EV/EBITDA multiple to current EBITDA, then bridges from enterprise value to equity value per share."
)
calc_a, calc_b, calc_c, calc_d = st.columns(4)
calc_a.metric("EBITDA Used", fmt_large(ctx["ebitda"]))
calc_b.metric("Target Multiple", f"{target_multiple:.1f}x")
calc_c.metric("Implied Enterprise Value", fmt_large(ev_result["implied_ev"]))
calc_d.metric("Implied Equity Value", fmt_large(ev_result["equity_value"]))
st.caption(
f"EBITDA: {fmt_large(ctx['ebitda'])} · "
f"{_net_debt_label(ev_result['net_debt'])}: {fmt_large(abs(ev_result['net_debt']))} · "
f"Other claims: {fmt_large(ev_result['other_claims'])} · "
f"Equity Value: {fmt_large(ev_result['equity_value'])}"
)
source_date = ctx["bridge_items"].get("source_date")
if source_date:
st.caption(f"EV/EBITDA bridge source date: **{source_date}**")
if market_cap and market_cap > 0:
st.markdown("**Market Comparison**")
compare_a, compare_b = st.columns(2)
if market_enterprise_value and market_enterprise_value > 0:
ev_delta = (ev_result["implied_ev"] - market_enterprise_value) / market_enterprise_value
compare_a.metric(
"Market Enterprise Value",
fmt_large(market_enterprise_value),
delta=f"{ev_delta * 100:+.1f}%",
)
equity_delta = (ev_result["equity_value"] - market_cap) / market_cap
compare_b.metric("Market Cap", fmt_large(market_cap), delta=f"{equity_delta * 100:+.1f}%")
summary_rows = [
{
"Step": "1. Start with EBITDA",
"Value": fmt_large(ctx["ebitda"]),
"What it means": "Current EBITDA used as the operating earnings base.",
},
{
"Step": "2. Apply target multiple",
"Value": f"{target_multiple:.1f}x",
"What it means": "Chosen EV/EBITDA multiple applied to EBITDA.",
},
{
"Step": "3. Arrive at enterprise value",
"Value": fmt_large(ev_result["implied_ev"]),
"What it means": "Implied value of the operating business before capital structure.",
},
{
"Step": "4. Bridge to equity value",
"Value": fmt_large(ev_result["equity_value"]),
"What it means": "Enterprise value less net debt and other claims.",
},
{
"Step": "5. Convert to value per share",
"Value": fmt_currency(imp_price),
"What it means": "Equity value divided by shares outstanding.",
},
]
st.dataframe(pd.DataFrame(summary_rows), use_container_width=True, hide_index=True)
st.markdown("**EV/EBITDA Conclusion**")
ev_m1, ev_m2, ev_m3, ev_m4 = st.columns(4)
ev_m1.metric("Implied Price / Share", fmt_currency(imp_price))
if current_price:
ev_upside = (imp_price - current_price) / current_price
ev_m2.metric("Current Price", fmt_currency(current_price))
ev_m3.metric(
"Upside / Downside",
f"{ev_upside * 100:+.1f}%",
delta=f"{ev_upside * 100:+.1f}%",
)
ev_m4.metric("Implied EV", fmt_large(ev_result["implied_ev"]))
if current_price and current_price > 0:
valuation_gap = imp_price - current_price
market_message = "above" if valuation_gap > 0 else "below"
if abs(valuation_gap) < 0.005:
market_message = "roughly in line with"
implied_value = _escape_markdown_currency(fmt_currency(imp_price))
gap_value = _escape_markdown_currency(fmt_currency(abs(valuation_gap)))
current_value = _escape_markdown_currency(fmt_currency(current_price))
st.markdown(
f"At **{target_multiple:.1f}x EBITDA**, the model implies **{implied_value} per share**, "
f"which is **{gap_value} {market_message}** the current market price of "
f"**{current_value}**."
)
def _render_ev_revenue_model(ctx: dict):
st.markdown("**EV/Revenue Valuation**")
st.caption(
"This is the better fallback for scaled companies that have revenue but little or no EBITDA or free cash flow."
)
default_multiple = float(ctx["ev_revenue_current"]) if ctx["ev_revenue_current"] else 4.0
default_multiple = max(0.5, min(30.0, round(default_multiple, 1)))
help_text = (
f"Current market multiple: {ctx['ev_revenue_current']:.2f}x"
if ctx["ev_revenue_current"] else "Current multiple unavailable"
)
target_multiple = st.slider(
"Target EV/Revenue",
min_value=0.5,
max_value=30.0,
value=default_multiple,
step=0.1,
help=help_text,
key=f"ev_revenue_multiple_{ctx['ticker']}",
)
ev_revenue_result = run_ev_revenue(
revenue=float(ctx["revenue_ttm"]),
total_debt=ctx["total_debt"],
total_cash=ctx["cash_and_equivalents"],
preferred_equity=ctx["preferred_equity"],
minority_interest=ctx["minority_interest"],
shares_outstanding=float(ctx["shares"]),
target_multiple=target_multiple,
)
if not ev_revenue_result:
st.warning("Could not compute EV/Revenue valuation.")
return
implied_price = ev_revenue_result["implied_price_per_share"]
current_price = ctx["current_price"]
market_cap = ctx["market_cap"]
market_enterprise_value = None
if market_cap and market_cap > 0:
market_enterprise_value = (
float(market_cap)
+ float(ctx["total_debt"])
- float(ctx["cash_and_equivalents"])
+ float(ctx["preferred_equity"])
+ float(ctx["minority_interest"])
)
st.caption(
"This model applies a target EV/Revenue multiple to TTM revenue, then bridges from enterprise value to equity value per share."
)
calc_a, calc_b, calc_c, calc_d = st.columns(4)
calc_a.metric("Revenue Used", fmt_large(ctx["revenue_ttm"]))
calc_b.metric("Target Multiple", f"{target_multiple:.1f}x")
calc_c.metric("Implied Enterprise Value", fmt_large(ev_revenue_result["implied_ev"]))
calc_d.metric("Implied Equity Value", fmt_large(ev_revenue_result["equity_value"]))
st.caption(
f"Revenue: {fmt_large(ctx['revenue_ttm'])} · "
f"{_net_debt_label(ev_revenue_result['net_debt'])}: {fmt_large(abs(ev_revenue_result['net_debt']))} · "
f"Other claims: {fmt_large(ev_revenue_result['other_claims'])} · "
f"Equity Value: {fmt_large(ev_revenue_result['equity_value'])}"
)
source_date = ctx["bridge_items"].get("source_date")
if source_date:
st.caption(f"EV/Revenue bridge source date: **{source_date}**")
if market_cap and market_cap > 0:
st.markdown("**Market Comparison**")
compare_a, compare_b = st.columns(2)
if market_enterprise_value and market_enterprise_value > 0:
ev_delta = (ev_revenue_result["implied_ev"] - market_enterprise_value) / market_enterprise_value
compare_a.metric(
"Market Enterprise Value",
fmt_large(market_enterprise_value),
delta=f"{ev_delta * 100:+.1f}%",
)
equity_delta = (ev_revenue_result["equity_value"] - market_cap) / market_cap
compare_b.metric("Market Cap", fmt_large(market_cap), delta=f"{equity_delta * 100:+.1f}%")
summary_rows = [
{
"Step": "1. Start with TTM revenue",
"Value": fmt_large(ctx["revenue_ttm"]),
"What it means": "Trailing twelve-month revenue used as the operating base.",
},
{
"Step": "2. Apply target multiple",
"Value": f"{target_multiple:.1f}x",
"What it means": "Chosen EV/Revenue multiple applied to TTM revenue.",
},
{
"Step": "3. Arrive at enterprise value",
"Value": fmt_large(ev_revenue_result["implied_ev"]),
"What it means": "Implied value of the operating business before capital structure.",
},
{
"Step": "4. Bridge to equity value",
"Value": fmt_large(ev_revenue_result["equity_value"]),
"What it means": "Enterprise value less net debt and other claims.",
},
{
"Step": "5. Convert to value per share",
"Value": fmt_currency(implied_price),
"What it means": "Equity value divided by shares outstanding.",
},
]
st.dataframe(pd.DataFrame(summary_rows), use_container_width=True, hide_index=True)
st.markdown("**EV/Revenue Conclusion**")
evr_m1, evr_m2, evr_m3, evr_m4 = st.columns(4)
evr_m1.metric("Implied Price / Share", fmt_currency(implied_price))
if current_price:
evr_upside = (implied_price - current_price) / current_price
evr_m2.metric("Current Price", fmt_currency(current_price))
evr_m3.metric(
"Upside / Downside",
f"{evr_upside * 100:+.1f}%",
delta=f"{evr_upside * 100:+.1f}%",
)
evr_m4.metric("Implied EV", fmt_large(ev_revenue_result["implied_ev"]))
if current_price and current_price > 0:
valuation_gap = implied_price - current_price
market_message = "above" if valuation_gap > 0 else "below"
if abs(valuation_gap) < 0.005:
market_message = "roughly in line with"
implied_value = _escape_markdown_currency(fmt_currency(implied_price))
gap_value = _escape_markdown_currency(fmt_currency(abs(valuation_gap)))
current_value = _escape_markdown_currency(fmt_currency(current_price))
st.markdown(
f"At **{target_multiple:.1f}x revenue**, the model implies **{implied_value} per share**, "
f"which is **{gap_value} {market_message}** the current market price of "
f"**{current_value}**."
)
def _render_price_to_book_model(ctx: dict):
st.markdown("**Price / Book Valuation**")
if ctx["is_financial"]:
st.caption(
"P/B is often a better anchor for financial companies than cash-flow models because book value is closer to the operating asset base."
)
else:
st.caption(
"P/B is a useful fallback when book value is meaningful and cash-flow-based models are not reliable."
)
default_multiple = float(ctx["pb_current"]) if ctx["pb_current"] else (1.2 if ctx["is_financial"] else 2.0)
default_multiple = max(0.2, min(10.0, round(default_multiple, 1)))
help_text = (
f"Current market multiple: {ctx['pb_current']:.2f}x"
if ctx["pb_current"] else "Current multiple unavailable"
)
target_multiple = st.slider(
"Target P/B",
min_value=0.2,
max_value=10.0,
value=default_multiple,
step=0.1,
help=help_text,
key=f"pb_multiple_{ctx['ticker']}",
)
pb_result = run_price_to_book(
book_value_per_share=float(ctx["book_value_per_share"]),
target_multiple=target_multiple,
)
if not pb_result:
st.warning("Could not compute P/B valuation.")
return
implied_price = pb_result["implied_price_per_share"]
current_price = ctx["current_price"]
pb_m1, pb_m2, pb_m3, pb_m4 = st.columns(4)
pb_m1.metric("Implied Price / Share", fmt_currency(implied_price))
pb_m2.metric("Book Value / Share", fmt_currency(ctx["book_value_per_share"]))
if current_price:
pb_upside = (implied_price - current_price) / current_price
pb_m3.metric("Current Price", fmt_currency(current_price))
pb_m4.metric(
"Upside / Downside",
f"{pb_upside * 100:+.1f}%",
delta=f"{pb_upside * 100:+.1f}%",
)
else:
pb_m3.metric("Target P/B", fmt_ratio(target_multiple))
pb_m4.metric("Current P/B", fmt_ratio(ctx["pb_current"]) if ctx["pb_current"] else "—")
st.caption(
f"Book value/share: {fmt_currency(ctx['book_value_per_share'])} · "
f"Target P/B: {fmt_ratio(target_multiple)}"
)
if current_price and ctx["pb_current"]:
st.caption(f"Current market P/B: **{ctx['pb_current']:.2f}x**")
def _render_models(ticker: str):
ctx = _build_model_context(ticker)
st.caption(ctx["summary"])
_render_model_availability(ctx)
if "models_view" not in st.session_state:
st.session_state["models_view"] = "dcf"
st.markdown(_DCF_RAIL_CSS, unsafe_allow_html=True)
_pc1, _pc2 = st.columns(2)
with _pc1:
if st.button(
"Discounted Cash Flow",
key=f"pick_dcf_{ticker}",
type="primary" if st.session_state["models_view"] == "dcf" else "secondary",
use_container_width=True,
):
st.session_state["models_view"] = "dcf"
st.rerun()
with _pc2:
if st.button(
"Multiples",
key=f"pick_mult_{ticker}",
type="primary" if st.session_state["models_view"] == "multiples" else "secondary",
use_container_width=True,
):
st.session_state["models_view"] = "multiples"
st.rerun()
st.markdown("---")
view = st.session_state.get("models_view", "dcf")
if view == "dcf":
if ctx["dcf_available"]:
_render_dcf_model(ctx)
else:
st.warning(f"DCF model not available: {ctx['dcf_reason']}")
if st.expander("Show available alternatives", expanded=True):
_render_multiples_model(ctx)
else:
_render_multiples_model(ctx)
unavailable = []
if not ctx["dcf_available"]:
unavailable.append(f"- **DCF:** {ctx['dcf_reason']}")
if not ctx["ev_available"]:
unavailable.append(f"- **EV/EBITDA:** {ctx['ev_reason']}")
if not ctx["ev_revenue_available"]:
unavailable.append(f"- **EV/Revenue:** {ctx['ev_revenue_reason']}")
if not ctx["pb_available"]:
unavailable.append(f"- **P/B:** {ctx['pb_reason']}")
if unavailable:
with st.expander("Why some models are unavailable", expanded=False):
st.markdown("\n".join(unavailable))
# ── Comps Table ──────────────────────────────────────────────────────────────
def _render_comps(ticker: str):
info = get_company_info(ticker)
auto_peers = get_peers(ticker)
suggested_peers = _suggest_peer_tickers(ticker, info)
default_peer_string = ", ".join(auto_peers or suggested_peers)
manual_peer_string = st.text_input(
"Peer tickers",
value=default_peer_string,
help="Edit the comparable-company set manually. Comma-separated tickers.",
key=f"peer_input_{ticker.upper()}",
)
if auto_peers:
st.caption("Using FMP-discovered peers.")
elif suggested_peers:
st.caption("Using Prism fallback peers based on sector/industry. Edit them if you want a tighter comp set.")
else:
st.caption("No automatic peer set found. Enter peer tickers manually to build a comps table.")
manual_peers = [p.strip().upper() for p in manual_peer_string.split(",") if p.strip()]
peer_list = []
seen = {ticker.upper()}
for peer in manual_peers:
if peer not in seen:
peer_list.append(peer)
seen.add(peer)
all_tickers = [ticker.upper()] + peer_list[:9]
with st.spinner("Loading comps..."):
ratios_list = get_ratios_for_tickers(all_tickers)
if not ratios_list:
st.info("Could not load ratios for the selected peer companies.")
return
display_cols = {
"symbol": "Ticker",
"peRatioTTM": "P/E",
"priceToSalesRatioTTM": "P/S",
"priceToBookRatioTTM": "P/B",
"enterpriseValueMultipleTTM": "EV/EBITDA",
"evToEBITDATTM": "EV/EBITDA",
"netProfitMarginTTM": "Net Margin",
"returnOnEquityTTM": "ROE",
"debtToEquityRatioTTM": "D/E",
}
df = pd.DataFrame(ratios_list)
if "enterpriseValueMultipleTTM" not in df.columns and "evToEBITDATTM" in df.columns:
df["enterpriseValueMultipleTTM"] = df["evToEBITDATTM"]
if "debtToEquityRatioTTM" not in df.columns and "debtEquityRatioTTM" in df.columns:
df["debtToEquityRatioTTM"] = df["debtEquityRatioTTM"]
available = [c for c in ["symbol", "peRatioTTM", "priceToSalesRatioTTM", "priceToBookRatioTTM", "enterpriseValueMultipleTTM", "netProfitMarginTTM", "returnOnEquityTTM", "debtToEquityRatioTTM"] if c in df.columns]
df = df[available].rename(columns=display_cols)
def _format_comp_value(column: str, value):
if value is None:
return "—"
try:
v = float(value)
except (TypeError, ValueError):
return "—"
if column == "P/E":
return fmt_ratio(v) if v > 0 else "N/M (neg. earnings)"
if column == "P/B":
return fmt_ratio(v) if v > 0 else "N/M (neg. equity)"
if column == "EV/EBITDA":
return fmt_ratio(v) if v > 0 else "N/M (neg. EBITDA)"
if column == "D/E":
return fmt_ratio(v) if v >= 0 else "N/M (neg. equity)"
if column in {"Net Margin", "ROE"}:
return fmt_pct(v)
return fmt_ratio(v) if v > 0 else "—"
for col in df.columns:
if col == "Ticker":
continue
df[col] = df[col].apply(lambda v, c=col: _format_comp_value(c, v))
def highlight_subject(row):
if row["Ticker"] == ticker.upper():
return ["background-color: rgba(79,142,247,0.15)"] * len(row)
return [""] * len(row)
st.dataframe(
df.style.apply(highlight_subject, axis=1),
use_container_width=True,
hide_index=True,
)
# ── Analyst Targets ──────────────────────────────────────────────────────────
def _render_analyst_targets(ticker: str):
targets = get_analyst_price_targets(ticker)
recs = get_recommendations_summary(ticker)
if not targets and (recs is None or recs.empty):
st.info("Analyst data unavailable for this ticker.")
return
if targets:
st.markdown("**Analyst Price Targets**")
current = targets.get("current")
mean_t = targets.get("mean")
t1, t2, t3, t4, t5 = st.columns(5)
t1.metric("Low", fmt_currency(targets.get("low")))
t2.metric("Mean", fmt_currency(mean_t))
t3.metric("Median", fmt_currency(targets.get("median")))
t4.metric("High", fmt_currency(targets.get("high")))
if current and mean_t:
upside = (mean_t - current) / current
t5.metric("Upside to Mean", f"{upside * 100:+.1f}%", delta=f"{upside * 100:+.1f}%")
else:
t5.metric("Current Price", fmt_currency(current))
st.write("")
if recs is not None and not recs.empty:
st.markdown("**Analyst Recommendations (Current Month)**")
current_row = recs[recs["period"] == "0m"] if "period" in recs.columns else pd.DataFrame()
if current_row.empty:
current_row = recs.iloc[[0]]
row = current_row.iloc[0]
counts = {
"Strong Buy": int(row.get("strongBuy", 0)),
"Buy": int(row.get("buy", 0)),
"Hold": int(row.get("hold", 0)),
"Sell": int(row.get("sell", 0)),
"Strong Sell": int(row.get("strongSell", 0)),
}
total = sum(counts.values())
cols = st.columns(5)
for col, (label, count) in zip(cols, counts.items()):
pct = f"{count / total * 100:.0f}%" if total > 0 else "—"
col.metric(label, str(count), delta=pct, delta_color="off")
st.write("")
colors = ["#4F8C5E", "#4F8C5E", "#C49545", "#8F7A50", "#B5494B"]
fig = go.Figure(go.Bar(
x=list(counts.keys()),
y=list(counts.values()),
marker_color=colors,
text=list(counts.values()),
textposition="outside",
))
fig.update_layout(
title="Analyst Recommendation Distribution",
yaxis_title="# Analysts",
plot_bgcolor="rgba(0,0,0,0)",
paper_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=40, b=0),
height=280,
)
st.plotly_chart(fig, use_container_width=True)
# ── Earnings History ──────────────────────────────────────────────────────────
def _render_earnings_history(ticker: str):
eh = get_earnings_history(ticker)
next_date = get_next_earnings_date(ticker)
if next_date:
st.info(f"Next earnings date: **{next_date}**")
if eh is None or eh.empty:
st.info("Earnings history unavailable for this ticker.")
return
st.markdown("**Historical EPS: Actual vs. Estimate**")
df = eh.copy().sort_index(ascending=False)
df.index = df.index.astype(str)
df.index.name = "Quarter"
display = pd.DataFrame(index=df.index)
display["EPS Actual"] = df["epsActual"].apply(fmt_currency)
display["EPS Estimate"] = df["epsEstimate"].apply(fmt_currency)
display["Surprise"] = df["epsDifference"].apply(
lambda v: f"{'+' if float(v) >= 0 else ''}{fmt_currency(v)}"
if pd.notna(v) else "—"
)
display["Surprise %"] = df["surprisePercent"].apply(
lambda v: f"{float(v) * 100:+.2f}%" if pd.notna(v) else "—"
)
def highlight_surprise(row):
try:
pct_str = row["Surprise %"].replace("%", "").replace("+", "")
val = float(pct_str)
color = "rgba(46,204,113,0.15)" if val >= 0 else "rgba(231,76,60,0.15)"
return ["", "", f"background-color: {color}", f"background-color: {color}"]
except Exception:
return [""] * len(row)
st.dataframe(
display.style.apply(highlight_surprise, axis=1),
use_container_width=True,
hide_index=False,
)
st.download_button(
"Download CSV",
display.to_csv().encode(),
file_name=f"{ticker.upper()}_earnings_history.csv",
mime="text/csv",
key=f"dl_earnings_{ticker}",
)
# EPS chart — oldest to newest
df_chart = eh.sort_index()
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df_chart.index.astype(str),
y=df_chart["epsActual"],
name="Actual EPS",
mode="lines+markers",
line=dict(color="#C2AA7A", width=2),
))
fig.add_trace(go.Scatter(
x=df_chart.index.astype(str),
y=df_chart["epsEstimate"],
name="Estimated EPS",
mode="lines+markers",
line=dict(color="#C49545", width=2, dash="dash"),
))
fig.update_layout(
title="EPS: Actual vs. Estimate",
yaxis_title="EPS ($)",
plot_bgcolor="rgba(0,0,0,0)",
paper_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=40, b=0),
height=280,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
)
st.plotly_chart(fig, use_container_width=True)
# ── Historical Ratios ────────────────────────────────────────────────────────
_HIST_RATIO_OPTIONS = {
"P/E": ("peRatio", "priceToEarningsRatio", None),
"P/B": ("priceToBookRatio", None, None),
"P/S": ("priceToSalesRatio", None, None),
"EV/EBITDA": ("enterpriseValueMultiple", "evToEBITDA", None),
"Net Margin": ("netProfitMargin", None, "pct"),
"Operating Margin": ("operatingProfitMargin", None, "pct"),
"Gross Margin": ("grossProfitMargin", None, "pct"),
"ROE": ("returnOnEquity", None, "pct"),
"ROA": ("returnOnAssets", None, "pct"),
"Debt/Equity": ("debtEquityRatio", None, None),
}
_CHART_COLORS = [
"#C2AA7A", "#C49545", "#4F8C5E", "#B5494B",
"#9b59b6", "#1abc9c", "#f39c12", "#e67e22",
]
def _extract_hist_series(rows: list[dict], primary: str, alt: str | None) -> dict[str, float]:
"""Extract {year: value} from FMP historical rows."""
out = {}
for row in rows:
date = str(row.get("date", ""))[:4]
val = row.get(primary)
if val is None and alt:
val = row.get(alt)
if val is not None:
try:
out[date] = float(val)
except (TypeError, ValueError):
pass
return out
def _render_historical_ratios(ticker: str):
with st.spinner("Loading historical ratios…"):
ratio_rows = get_historical_ratios(ticker)
metric_rows = get_historical_key_metrics(ticker)
if not ratio_rows and not metric_rows:
st.info("Historical ratio data unavailable.")
return
# Merge both lists by date
combined: dict[str, dict] = {}
for row in ratio_rows + metric_rows:
date = str(row.get("date", ""))[:4]
if date:
combined.setdefault(date, {}).update(row)
merged_rows = [{"date": d, **v} for d, v in sorted(combined.items(), reverse=True)]
selected = st.multiselect(
"Metrics to plot",
options=list(_HIST_RATIO_OPTIONS.keys()),
default=["P/E", "EV/EBITDA", "Net Margin", "ROE"],
)
if not selected:
st.info("Select at least one metric to plot.")
return
fig = go.Figure()
for i, label in enumerate(selected):
primary, alt, fmt = _HIST_RATIO_OPTIONS[label]
series = _extract_hist_series(merged_rows, primary, alt)
if not series:
continue
years = sorted(series.keys())
values = [series[y] * (100 if fmt == "pct" else 1) for y in years]
y_label = f"{label} (%)" if fmt == "pct" else label
fig.add_trace(go.Scatter(
x=years,
y=values,
name=y_label,
mode="lines+markers",
line=dict(color=_CHART_COLORS[i % len(_CHART_COLORS)], width=2),
))
fig.update_layout(
title="Historical Ratios & Metrics",
xaxis_title="Year",
plot_bgcolor="rgba(0,0,0,0)",
paper_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=40, b=0),
height=380,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
hovermode="x unified",
)
st.plotly_chart(fig, use_container_width=True)
# Raw data table
with st.expander("Raw data"):
display_cols = {}
for label in selected:
primary, alt, fmt = _HIST_RATIO_OPTIONS[label]
display_cols[label] = (primary, alt, fmt)
def _format_hist_value(label: str, value, fmt: str | None) -> str:
if value is None:
return "—"
try:
v = float(value)
except (TypeError, ValueError):
return "—"
if fmt == "pct":
return f"{v * 100:.2f}%"
if label == "P/E":
return f"{v:.2f}x" if v > 0 else "N/M (neg. earnings)"
if label == "EV/EBITDA":
return f"{v:.2f}x" if v > 0 else "N/M (neg. EBITDA)"
if label == "P/B":
return f"{v:.2f}x" if v > 0 else "N/M (neg. equity)"
if label == "Debt/Equity":
return f"{v:.2f}x" if v >= 0 else "N/M (neg. equity)"
return f"{v:.2f}x" if v > 0 else "—"
table_rows = []
for row in merged_rows:
r: dict = {"Year": str(row.get("date", ""))[:4]}
for label, (primary, alt, fmt) in display_cols.items():
val = row.get(primary) or (row.get(alt) if alt else None)
r[label] = _format_hist_value(label, val, fmt)
table_rows.append(r)
if table_rows:
st.dataframe(pd.DataFrame(table_rows), use_container_width=True, hide_index=True)
# ── Forward Estimates ────────────────────────────────────────────────────────
def _render_forward_estimates(ticker: str):
with st.spinner("Loading forward estimates…"):
estimates = get_analyst_estimates(ticker)
annual = estimates.get("annual", [])
quarterly = estimates.get("quarterly", [])
if not annual and not quarterly:
st.info("Forward estimates unavailable. Requires FMP API key.")
return
info = get_company_info(ticker)
current_price = get_latest_price(ticker)
tab_ann, tab_qtr = st.tabs(["Annual", "Quarterly"])
def _build_estimates_table(rows: list[dict]) -> pd.DataFrame:
table = []
for row in sorted(rows, key=lambda r: str(r.get("date", ""))):
date = str(row.get("date", ""))[:7]
# FMP stable endpoint uses revenueAvg / epsAvg (no "estimated" prefix)
rev_avg = row.get("revenueAvg") or row.get("estimatedRevenueAvg")
rev_lo = row.get("revenueLow") or row.get("estimatedRevenueLow")
rev_hi = row.get("revenueHigh") or row.get("estimatedRevenueHigh")
eps_avg = row.get("epsAvg") or row.get("estimatedEpsAvg")
eps_lo = row.get("epsLow") or row.get("estimatedEpsLow")
eps_hi = row.get("epsHigh") or row.get("estimatedEpsHigh")
ebitda_avg = row.get("ebitdaAvg") or row.get("estimatedEbitdaAvg")
num_analysts = row.get("numAnalystsRevenue") or row.get("numAnalystsEps") or row.get("numberAnalystEstimatedRevenue") or row.get("numberAnalysts")
table.append({
"Period": date,
"Rev Low": fmt_large(rev_lo) if rev_lo else "—",
"Rev Avg": fmt_large(rev_avg) if rev_avg else "—",
"Rev High": fmt_large(rev_hi) if rev_hi else "—",
"EPS Low": fmt_currency(eps_lo) if eps_lo else "—",
"EPS Avg": fmt_currency(eps_avg) if eps_avg else "—",
"EPS High": fmt_currency(eps_hi) if eps_hi else "—",
"EBITDA Avg": fmt_large(ebitda_avg) if ebitda_avg else "—",
"# Analysts": str(int(num_analysts)) if num_analysts else "—",
})
return pd.DataFrame(table)
def _render_eps_chart(rows: list[dict], title: str):
"""Overlay historical EPS actuals with forward estimates."""
eh = get_earnings_history(ticker)
fwd_dates, fwd_eps = [], []
for row in sorted(rows, key=lambda r: str(r.get("date", ""))):
date = str(row.get("date", ""))[:7]
eps = row.get("epsAvg") or row.get("estimatedEpsAvg")
eps_lo = row.get("epsLow") or row.get("estimatedEpsLow")
eps_hi = row.get("epsHigh") or row.get("estimatedEpsHigh")
if eps is not None:
fwd_dates.append(date)
fwd_eps.append(float(eps))
fig = go.Figure()
if eh is not None and not eh.empty:
hist = eh.sort_index()
fig.add_trace(go.Scatter(
x=hist.index.astype(str),
y=hist["epsActual"],
name="EPS Actual",
mode="lines+markers",
line=dict(color="#C2AA7A", width=2),
))
if fwd_dates:
# Low/high band
fwd_lo = [float(r.get("epsLow") or r.get("estimatedEpsLow")) for r in sorted(rows, key=lambda r: str(r.get("date", "")))
if (r.get("epsLow") or r.get("estimatedEpsLow")) is not None]
fwd_hi = [float(r.get("epsHigh") or r.get("estimatedEpsHigh")) for r in sorted(rows, key=lambda r: str(r.get("date", "")))
if (r.get("epsHigh") or r.get("estimatedEpsHigh")) is not None]
if fwd_lo and fwd_hi and len(fwd_lo) == len(fwd_dates):
fig.add_trace(go.Scatter(
x=fwd_dates + fwd_dates[::-1],
y=fwd_hi + fwd_lo[::-1],
fill="toself",
fillcolor="rgba(247,162,79,0.15)",
line=dict(color="rgba(0,0,0,0)"),
name="Est. Range",
hoverinfo="skip",
))
fig.add_trace(go.Scatter(
x=fwd_dates,
y=fwd_eps,
name="EPS Est. (Avg)",
mode="lines+markers",
line=dict(color="#C49545", width=2, dash="dash"),
))
fig.update_layout(
title=title,
yaxis_title="EPS ($)",
plot_bgcolor="rgba(0,0,0,0)",
paper_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=40, b=0),
height=320,
hovermode="x unified",
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
)
st.plotly_chart(fig, use_container_width=True)
with tab_ann:
if annual:
df = _build_estimates_table(annual)
st.dataframe(df, use_container_width=True, hide_index=True)
st.write("")
_render_eps_chart(annual, "Annual EPS: Historical Actuals + Forward Estimates")
else:
st.info("No annual estimates available.")
with tab_qtr:
if quarterly:
df = _build_estimates_table(quarterly)
st.dataframe(df, use_container_width=True, hide_index=True)
st.write("")
_render_eps_chart(quarterly, "Quarterly EPS: Historical Actuals + Forward Estimates")
else:
st.info("No quarterly estimates available.")
|