Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- builders/build_docx.py +8 -8
- builders/build_excel.py +19 -19
- builders/build_pptx.py +1 -1
- config.py +44 -44
- pipeline/analyst.py +788 -788
- pipeline/calculator.py +361 -361
- pipeline/fetcher.py +0 -0
- pipeline/google_login.py +182 -182
- pipeline/key_validator.py +186 -186
- pipeline/peer_selector.py +185 -185
- pipeline/resolver.py +21 -21
- web_app/app.py +71 -48
builders/build_docx.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
builders/build_docx.py
|
| 4 |
Sections: Cover, Executive Summary, Company Profile, Industry Profile,
|
| 5 |
SWOT, Industry Trends, Financial Trends, Ratios, DuPont, Peer Comparison,
|
| 6 |
Key Insights, Risks, Things to Watch, Limitations, Sources.
|
|
@@ -19,12 +19,12 @@ try:
|
|
| 19 |
except ImportError:
|
| 20 |
print("ERROR: pip install python-docx", file=sys.stderr); sys.exit(1)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
NAVY = RGBColor(0x1F, 0x4E, 0x78)
|
| 24 |
GRAY = RGBColor(0x59, 0x59, 0x59)
|
| 25 |
GREEN_DARK = RGBColor(0x37, 0x5A, 0x3D)
|
| 26 |
|
| 27 |
-
#
|
| 28 |
|
| 29 |
def _shd(cell, hex_color):
|
| 30 |
tcp = cell._tc.get_or_add_tcPr()
|
|
@@ -84,7 +84,7 @@ def _fmt_v(v, kind="money", currency="INR", units="Crores"):
|
|
| 84 |
def _page_break(doc):
|
| 85 |
p = doc.add_paragraph(); p.add_run().add_break()
|
| 86 |
|
| 87 |
-
#
|
| 88 |
|
| 89 |
def _table(doc, headers, rows, formats=None, currency="INR", units="Crores"):
|
| 90 |
t = doc.add_table(rows=1+len(rows), cols=len(headers))
|
|
@@ -106,7 +106,7 @@ def _table(doc, headers, rows, formats=None, currency="INR", units="Crores"):
|
|
| 106 |
p = cells[ci].paragraphs[0]
|
| 107 |
kind = formats[ci] if formats and ci < len(formats) else "money"
|
| 108 |
if ci == 0:
|
| 109 |
-
text = str(val) if val is not None else "
|
| 110 |
else:
|
| 111 |
text = _fmt_v(val, kind, currency, units)
|
| 112 |
r = p.add_run(text); r.font.size = Pt(10); r.font.name = "Calibri"
|
|
@@ -119,7 +119,7 @@ def _gather(items, src, years):
|
|
| 119 |
return [[label] + [(src.get(key) or [None]*len(years))[:len(years)][i]
|
| 120 |
for i in range(len(years))] for label, key in items]
|
| 121 |
|
| 122 |
-
#
|
| 123 |
|
| 124 |
def _cover(doc, data):
|
| 125 |
co = data.get("company", {})
|
|
@@ -316,7 +316,7 @@ def _sources_section(doc, data):
|
|
| 316 |
url_r = p.add_run(src.get("url",""))
|
| 317 |
url_r.font.size=Pt(10); url_r.font.color.rgb=RGBColor(0x05,0x63,0xC1); url_r.font.name="Calibri"
|
| 318 |
suffix = ""
|
| 319 |
-
if src.get("description"): suffix += f"
|
| 320 |
if src.get("retrieved"): suffix += f" (retrieved {src['retrieved']})"
|
| 321 |
if suffix:
|
| 322 |
sr = p.add_run(suffix); sr.font.size=Pt(10); sr.font.color.rgb=GRAY; sr.font.name="Calibri"
|
|
@@ -333,7 +333,7 @@ def _disclaimer(doc):
|
|
| 333 |
p.paragraph_format.space_before=Pt(12)
|
| 334 |
|
| 335 |
|
| 336 |
-
#
|
| 337 |
|
| 338 |
def build_document(data: dict, output_path: str) -> None:
|
| 339 |
doc = Document()
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
builders/build_docx.py -- Enhanced Word report builder.
|
| 4 |
Sections: Cover, Executive Summary, Company Profile, Industry Profile,
|
| 5 |
SWOT, Industry Trends, Financial Trends, Ratios, DuPont, Peer Comparison,
|
| 6 |
Key Insights, Risks, Things to Watch, Limitations, Sources.
|
|
|
|
| 19 |
except ImportError:
|
| 20 |
print("ERROR: pip install python-docx", file=sys.stderr); sys.exit(1)
|
| 21 |
|
| 22 |
+
# -- Colors --------------------------------------------------------------------
|
| 23 |
NAVY = RGBColor(0x1F, 0x4E, 0x78)
|
| 24 |
GRAY = RGBColor(0x59, 0x59, 0x59)
|
| 25 |
GREEN_DARK = RGBColor(0x37, 0x5A, 0x3D)
|
| 26 |
|
| 27 |
+
# -- Formatting helpers --------------------------------------------------------
|
| 28 |
|
| 29 |
def _shd(cell, hex_color):
|
| 30 |
tcp = cell._tc.get_or_add_tcPr()
|
|
|
|
| 84 |
def _page_break(doc):
|
| 85 |
p = doc.add_paragraph(); p.add_run().add_break()
|
| 86 |
|
| 87 |
+
# -- Table builder -------------------------------------------------------------
|
| 88 |
|
| 89 |
def _table(doc, headers, rows, formats=None, currency="INR", units="Crores"):
|
| 90 |
t = doc.add_table(rows=1+len(rows), cols=len(headers))
|
|
|
|
| 106 |
p = cells[ci].paragraphs[0]
|
| 107 |
kind = formats[ci] if formats and ci < len(formats) else "money"
|
| 108 |
if ci == 0:
|
| 109 |
+
text = str(val) if val is not None else "--"
|
| 110 |
else:
|
| 111 |
text = _fmt_v(val, kind, currency, units)
|
| 112 |
r = p.add_run(text); r.font.size = Pt(10); r.font.name = "Calibri"
|
|
|
|
| 119 |
return [[label] + [(src.get(key) or [None]*len(years))[:len(years)][i]
|
| 120 |
for i in range(len(years))] for label, key in items]
|
| 121 |
|
| 122 |
+
# -- Section builders ----------------------------------------------------------
|
| 123 |
|
| 124 |
def _cover(doc, data):
|
| 125 |
co = data.get("company", {})
|
|
|
|
| 316 |
url_r = p.add_run(src.get("url",""))
|
| 317 |
url_r.font.size=Pt(10); url_r.font.color.rgb=RGBColor(0x05,0x63,0xC1); url_r.font.name="Calibri"
|
| 318 |
suffix = ""
|
| 319 |
+
if src.get("description"): suffix += f" -- {src['description']}"
|
| 320 |
if src.get("retrieved"): suffix += f" (retrieved {src['retrieved']})"
|
| 321 |
if suffix:
|
| 322 |
sr = p.add_run(suffix); sr.font.size=Pt(10); sr.font.color.rgb=GRAY; sr.font.name="Calibri"
|
|
|
|
| 333 |
p.paragraph_format.space_before=Pt(12)
|
| 334 |
|
| 335 |
|
| 336 |
+
# -- Orchestrator --------------------------------------------------------------
|
| 337 |
|
| 338 |
def build_document(data: dict, output_path: str) -> None:
|
| 339 |
doc = Document()
|
builders/build_excel.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
builders/build_excel.py
|
| 4 |
Reads the skill's original builder and adds DuPont, SWOT, and Indian unit support.
|
| 5 |
"""
|
| 6 |
import json, sys, datetime
|
|
@@ -14,7 +14,7 @@ try:
|
|
| 14 |
except ImportError:
|
| 15 |
print("ERROR: pip install openpyxl", file=sys.stderr); sys.exit(1)
|
| 16 |
|
| 17 |
-
#
|
| 18 |
HDR_FILL = PatternFill("solid", fgColor="1F4E78")
|
| 19 |
HDR_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
| 20 |
SEC_FILL = PatternFill("solid", fgColor="D9E1F2")
|
|
@@ -34,13 +34,13 @@ CENTER = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
|
| 34 |
LEFT = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
| 35 |
RIGHT = Alignment(horizontal="right", vertical="center")
|
| 36 |
|
| 37 |
-
FMT_MONEY = '#,##0;(#,##0);"
|
| 38 |
-
FMT_DEC = '#,##0.00;(#,##0.00);"
|
| 39 |
-
FMT_PCT = '0.0%;(0.0%);"
|
| 40 |
-
FMT_RATIO = '0.00;(0.00);"
|
| 41 |
-
FMT_DAYS = '0.0;"
|
| 42 |
|
| 43 |
-
#
|
| 44 |
|
| 45 |
def _safe(arr, i, default=None):
|
| 46 |
try: return arr[i] if arr and arr[i] is not None else default
|
|
@@ -62,7 +62,7 @@ def _data_row(ws, row, label, values, fmt=FMT_MONEY, start=1):
|
|
| 62 |
c = ws.cell(row=row, column=start, value=label)
|
| 63 |
c.font, c.alignment, c.border = LBL_FONT, LEFT, THIN
|
| 64 |
for i, v in enumerate(values):
|
| 65 |
-
cell = ws.cell(row=row, column=start+1+i, value=v if v is not None else "
|
| 66 |
cell.font, cell.alignment, cell.border = DAT_FONT, RIGHT, THIN
|
| 67 |
if v is not None and isinstance(v, (int, float)):
|
| 68 |
cell.number_format = fmt
|
|
@@ -85,7 +85,7 @@ def _last(arr):
|
|
| 85 |
if v is not None: return v
|
| 86 |
return None
|
| 87 |
|
| 88 |
-
#
|
| 89 |
|
| 90 |
def _stmt_section(ws, row, title, items, data_dict, years, fmt=FMT_MONEY):
|
| 91 |
_sec(ws, row, title, 1+len(years))
|
|
@@ -97,14 +97,14 @@ def _stmt_section(ws, row, title, items, data_dict, years, fmt=FMT_MONEY):
|
|
| 97 |
row += 1
|
| 98 |
return row
|
| 99 |
|
| 100 |
-
#
|
| 101 |
|
| 102 |
def _summary_sheet(wb, data):
|
| 103 |
ws = wb.create_sheet("Summary")
|
| 104 |
co = data.get("company", {})
|
| 105 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 106 |
currency = data.get("currency", co.get("currency", "INR"))
|
| 107 |
-
_title(ws, f"{co.get('name','')} ({co.get('ticker','')})
|
| 108 |
f"Report date: {co.get('report_date', datetime.date.today().isoformat())}")
|
| 109 |
r = 4
|
| 110 |
for label, val in [
|
|
@@ -134,7 +134,7 @@ def _income_sheet(wb, data):
|
|
| 134 |
co, years = data.get("company",{}), data.get("years",[])
|
| 135 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 136 |
currency = data.get("currency", co.get("currency", "INR"))
|
| 137 |
-
_title(ws, f"Income Statement
|
| 138 |
f"All figures in {units_label}")
|
| 139 |
_hdr(ws, 4, [f"({units_label})"] + years)
|
| 140 |
inc = data.get("income_statement", {})
|
|
@@ -177,7 +177,7 @@ def _balance_sheet(wb, data):
|
|
| 177 |
ws = wb.create_sheet("Balance Sheet")
|
| 178 |
co, years = data.get("company",{}), data.get("years",[])
|
| 179 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 180 |
-
_title(ws, f"Balance Sheet
|
| 181 |
f"As of fiscal year-end. {units_label}")
|
| 182 |
_hdr(ws, 4, [f"({units_label})"] + years)
|
| 183 |
bs = data.get("balance_sheet", {})
|
|
@@ -211,7 +211,7 @@ def _cashflow_sheet(wb, data):
|
|
| 211 |
ws = wb.create_sheet("Cash Flow")
|
| 212 |
co, years = data.get("company",{}), data.get("years",[])
|
| 213 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 214 |
-
_title(ws, f"Cash Flow Statement
|
| 215 |
f"All figures in {units_label}")
|
| 216 |
_hdr(ws, 4, [f"({units_label})"] + years)
|
| 217 |
cf = data.get("cash_flow", {})
|
|
@@ -265,7 +265,7 @@ RATIO_SECTIONS = [
|
|
| 265 |
def _ratios_sheet(wb, data):
|
| 266 |
ws = wb.create_sheet("Ratios")
|
| 267 |
years = data.get("years", [])
|
| 268 |
-
_title(ws, f"Financial Ratios
|
| 269 |
_hdr(ws, 4, ["Ratio"] + years)
|
| 270 |
ratios = data.get("ratios", {})
|
| 271 |
r = 5
|
|
@@ -324,7 +324,7 @@ def _growth_sheet(wb, data):
|
|
| 324 |
def _peers_sheet(wb, data):
|
| 325 |
ws = wb.create_sheet("Peer Comparison")
|
| 326 |
co = data.get("company", {})
|
| 327 |
-
_title(ws, f"Peer Comparison
|
| 328 |
cols = ["Company","Ticker","Revenue","Gross Margin","Op Margin","Net Margin",
|
| 329 |
"ROE","ROIC","D/E","Current Ratio","FCF Margin","P/E","EV/EBITDA","Rationale"]
|
| 330 |
_hdr(ws, 4, cols)
|
|
@@ -359,7 +359,7 @@ def _write_peer_row(ws, row, values, fmts, is_target=False):
|
|
| 359 |
fmt_map = {"money":FMT_MONEY,"pct":FMT_PCT,"ratio":FMT_RATIO}
|
| 360 |
fill = PatternFill("solid", fgColor="FFF2CC") if is_target else None
|
| 361 |
for i, v in enumerate(values):
|
| 362 |
-
c = ws.cell(row=row, column=i+1, value=v if v is not None else "
|
| 363 |
c.border = THIN
|
| 364 |
c.font = Font(name="Calibri", size=11, bold=is_target)
|
| 365 |
if fill: c.fill = fill
|
|
@@ -554,7 +554,7 @@ def _sources_sheet(wb, data):
|
|
| 554 |
_widths(ws, [6,70,50,16])
|
| 555 |
|
| 556 |
|
| 557 |
-
#
|
| 558 |
|
| 559 |
def build_workbook(data: dict, output_path: str) -> None:
|
| 560 |
wb = Workbook()
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
builders/build_excel.py -- Enhanced Excel workbook builder.
|
| 4 |
Reads the skill's original builder and adds DuPont, SWOT, and Indian unit support.
|
| 5 |
"""
|
| 6 |
import json, sys, datetime
|
|
|
|
| 14 |
except ImportError:
|
| 15 |
print("ERROR: pip install openpyxl", file=sys.stderr); sys.exit(1)
|
| 16 |
|
| 17 |
+
# -- Style constants -----------------------------------------------------------
|
| 18 |
HDR_FILL = PatternFill("solid", fgColor="1F4E78")
|
| 19 |
HDR_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
| 20 |
SEC_FILL = PatternFill("solid", fgColor="D9E1F2")
|
|
|
|
| 34 |
LEFT = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
| 35 |
RIGHT = Alignment(horizontal="right", vertical="center")
|
| 36 |
|
| 37 |
+
FMT_MONEY = '#,##0;(#,##0);"--"'
|
| 38 |
+
FMT_DEC = '#,##0.00;(#,##0.00);"--"'
|
| 39 |
+
FMT_PCT = '0.0%;(0.0%);"--"'
|
| 40 |
+
FMT_RATIO = '0.00;(0.00);"--"'
|
| 41 |
+
FMT_DAYS = '0.0;"--"'
|
| 42 |
|
| 43 |
+
# -- Helpers -------------------------------------------------------------------
|
| 44 |
|
| 45 |
def _safe(arr, i, default=None):
|
| 46 |
try: return arr[i] if arr and arr[i] is not None else default
|
|
|
|
| 62 |
c = ws.cell(row=row, column=start, value=label)
|
| 63 |
c.font, c.alignment, c.border = LBL_FONT, LEFT, THIN
|
| 64 |
for i, v in enumerate(values):
|
| 65 |
+
cell = ws.cell(row=row, column=start+1+i, value=v if v is not None else "--")
|
| 66 |
cell.font, cell.alignment, cell.border = DAT_FONT, RIGHT, THIN
|
| 67 |
if v is not None and isinstance(v, (int, float)):
|
| 68 |
cell.number_format = fmt
|
|
|
|
| 85 |
if v is not None: return v
|
| 86 |
return None
|
| 87 |
|
| 88 |
+
# -- Statement section helper --------------------------------------------------
|
| 89 |
|
| 90 |
def _stmt_section(ws, row, title, items, data_dict, years, fmt=FMT_MONEY):
|
| 91 |
_sec(ws, row, title, 1+len(years))
|
|
|
|
| 97 |
row += 1
|
| 98 |
return row
|
| 99 |
|
| 100 |
+
# -- Sheet builders ------------------------------------------------------------
|
| 101 |
|
| 102 |
def _summary_sheet(wb, data):
|
| 103 |
ws = wb.create_sheet("Summary")
|
| 104 |
co = data.get("company", {})
|
| 105 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 106 |
currency = data.get("currency", co.get("currency", "INR"))
|
| 107 |
+
_title(ws, f"{co.get('name','')} ({co.get('ticker','')}) -- Financial Analysis",
|
| 108 |
f"Report date: {co.get('report_date', datetime.date.today().isoformat())}")
|
| 109 |
r = 4
|
| 110 |
for label, val in [
|
|
|
|
| 134 |
co, years = data.get("company",{}), data.get("years",[])
|
| 135 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 136 |
currency = data.get("currency", co.get("currency", "INR"))
|
| 137 |
+
_title(ws, f"Income Statement -- {co.get('ticker','')}",
|
| 138 |
f"All figures in {units_label}")
|
| 139 |
_hdr(ws, 4, [f"({units_label})"] + years)
|
| 140 |
inc = data.get("income_statement", {})
|
|
|
|
| 177 |
ws = wb.create_sheet("Balance Sheet")
|
| 178 |
co, years = data.get("company",{}), data.get("years",[])
|
| 179 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 180 |
+
_title(ws, f"Balance Sheet -- {co.get('ticker','')}",
|
| 181 |
f"As of fiscal year-end. {units_label}")
|
| 182 |
_hdr(ws, 4, [f"({units_label})"] + years)
|
| 183 |
bs = data.get("balance_sheet", {})
|
|
|
|
| 211 |
ws = wb.create_sheet("Cash Flow")
|
| 212 |
co, years = data.get("company",{}), data.get("years",[])
|
| 213 |
units_label = data.get("units_label", data.get("units", "Crores"))
|
| 214 |
+
_title(ws, f"Cash Flow Statement -- {co.get('ticker','')}",
|
| 215 |
f"All figures in {units_label}")
|
| 216 |
_hdr(ws, 4, [f"({units_label})"] + years)
|
| 217 |
cf = data.get("cash_flow", {})
|
|
|
|
| 265 |
def _ratios_sheet(wb, data):
|
| 266 |
ws = wb.create_sheet("Ratios")
|
| 267 |
years = data.get("years", [])
|
| 268 |
+
_title(ws, f"Financial Ratios -- {data.get('company',{}).get('ticker','')}", "5-year trend")
|
| 269 |
_hdr(ws, 4, ["Ratio"] + years)
|
| 270 |
ratios = data.get("ratios", {})
|
| 271 |
r = 5
|
|
|
|
| 324 |
def _peers_sheet(wb, data):
|
| 325 |
ws = wb.create_sheet("Peer Comparison")
|
| 326 |
co = data.get("company", {})
|
| 327 |
+
_title(ws, f"Peer Comparison -- {co.get('ticker','')}", "Latest fiscal year")
|
| 328 |
cols = ["Company","Ticker","Revenue","Gross Margin","Op Margin","Net Margin",
|
| 329 |
"ROE","ROIC","D/E","Current Ratio","FCF Margin","P/E","EV/EBITDA","Rationale"]
|
| 330 |
_hdr(ws, 4, cols)
|
|
|
|
| 359 |
fmt_map = {"money":FMT_MONEY,"pct":FMT_PCT,"ratio":FMT_RATIO}
|
| 360 |
fill = PatternFill("solid", fgColor="FFF2CC") if is_target else None
|
| 361 |
for i, v in enumerate(values):
|
| 362 |
+
c = ws.cell(row=row, column=i+1, value=v if v is not None else "--")
|
| 363 |
c.border = THIN
|
| 364 |
c.font = Font(name="Calibri", size=11, bold=is_target)
|
| 365 |
if fill: c.fill = fill
|
|
|
|
| 554 |
_widths(ws, [6,70,50,16])
|
| 555 |
|
| 556 |
|
| 557 |
+
# -- Orchestrator --------------------------------------------------------------
|
| 558 |
|
| 559 |
def build_workbook(data: dict, output_path: str) -> None:
|
| 560 |
wb = Workbook()
|
builders/build_pptx.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
builders/build_pptx.py
|
| 3 |
|
| 4 |
Generates a widescreen (16:9) PPTX presentation summarizing the financial analysis
|
| 5 |
and AI narrative, strictly matching user-defined theme, colors, and layout structure.
|
|
|
|
| 1 |
"""
|
| 2 |
+
builders/build_pptx.py -- PowerPoint presentation builder.
|
| 3 |
|
| 4 |
Generates a widescreen (16:9) PPTX presentation summarizing the financial analysis
|
| 5 |
and AI narrative, strictly matching user-defined theme, colors, and layout structure.
|
config.py
CHANGED
|
@@ -1,44 +1,44 @@
|
|
| 1 |
-
"""
|
| 2 |
-
config.py
|
| 3 |
-
"""
|
| 4 |
-
import os
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
from dotenv import load_dotenv
|
| 7 |
-
|
| 8 |
-
# Load .env from the app root
|
| 9 |
-
_ENV_PATH = Path(__file__).parent / ".env"
|
| 10 |
-
load_dotenv(_ENV_PATH)
|
| 11 |
-
|
| 12 |
-
#
|
| 13 |
-
FMP_API_KEY: str = os.environ.get("FMP_API_KEY", "")
|
| 14 |
-
GEMINI_API_KEY: str = os.environ.get("GEMINI_API_KEY", "")
|
| 15 |
-
CLAUDE_API_KEY: str = os.environ.get("CLAUDE_API_KEY", "")
|
| 16 |
-
OPENAI_API_KEY: str = os.environ.get("OPENAI_API_KEY", "")
|
| 17 |
-
GROQ_API_KEY: str = os.environ.get("GROQ_API_KEY", "")
|
| 18 |
-
NVIDIA_API_KEY: str = os.environ.get("NVIDIA_API_KEY", "")
|
| 19 |
-
HF_API_KEY: str = os.environ.get("HF_API_KEY", "")
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
DEFAULT_YEARS: int = 5
|
| 23 |
-
CACHE_TTL_DAYS: int = 7 # days before cached data expires
|
| 24 |
-
FMP_BASE: str = "https://financialmodelingprep.com/api"
|
| 25 |
-
SCREENER_BASE: str = "https://screener.in/company"
|
| 26 |
-
REQUEST_TIMEOUT: int = 20
|
| 27 |
-
|
| 28 |
-
#
|
| 29 |
-
OUTPUT_DIR: Path = Path(__file__).parent / "outputs"
|
| 30 |
-
OUTPUT_DIR.mkdir(exist_ok=True)
|
| 31 |
-
|
| 32 |
-
DB_PATH: Path = Path(__file__).parent / "storage" / "history.db"
|
| 33 |
-
DB_PATH.parent.mkdir(exist_ok=True)
|
| 34 |
-
|
| 35 |
-
#
|
| 36 |
-
GEMINI_MODEL: str = "gemini-2.0-flash"
|
| 37 |
-
CLAUDE_MODEL: str = "claude-3-5-haiku-20241022"
|
| 38 |
-
OPENAI_MODEL: str = "gpt-4o-mini"
|
| 39 |
-
GROQ_MODEL: str = "llama-3.3-70b-versatile" # free, high-quality
|
| 40 |
-
NVIDIA_MODEL: str = "meta/llama-3.1-405b-instruct"
|
| 41 |
-
|
| 42 |
-
#
|
| 43 |
-
APP_NAME: str = "Financial Analyzer"
|
| 44 |
-
APP_VERSION: str = "1.0.0"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
config.py -- App-wide constants and environment loading.
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# Load .env from the app root
|
| 9 |
+
_ENV_PATH = Path(__file__).parent / ".env"
|
| 10 |
+
load_dotenv(_ENV_PATH)
|
| 11 |
+
|
| 12 |
+
# -- API Keys ------------------------------------------------------------------
|
| 13 |
+
FMP_API_KEY: str = os.environ.get("FMP_API_KEY", "")
|
| 14 |
+
GEMINI_API_KEY: str = os.environ.get("GEMINI_API_KEY", "")
|
| 15 |
+
CLAUDE_API_KEY: str = os.environ.get("CLAUDE_API_KEY", "")
|
| 16 |
+
OPENAI_API_KEY: str = os.environ.get("OPENAI_API_KEY", "")
|
| 17 |
+
GROQ_API_KEY: str = os.environ.get("GROQ_API_KEY", "")
|
| 18 |
+
NVIDIA_API_KEY: str = os.environ.get("NVIDIA_API_KEY", "")
|
| 19 |
+
HF_API_KEY: str = os.environ.get("HF_API_KEY", "")
|
| 20 |
+
|
| 21 |
+
# -- Data settings -------------------------------------------------------------
|
| 22 |
+
DEFAULT_YEARS: int = 5
|
| 23 |
+
CACHE_TTL_DAYS: int = 7 # days before cached data expires
|
| 24 |
+
FMP_BASE: str = "https://financialmodelingprep.com/api"
|
| 25 |
+
SCREENER_BASE: str = "https://screener.in/company"
|
| 26 |
+
REQUEST_TIMEOUT: int = 20
|
| 27 |
+
|
| 28 |
+
# -- Output --------------------------------------------------------------------
|
| 29 |
+
OUTPUT_DIR: Path = Path(__file__).parent / "outputs"
|
| 30 |
+
OUTPUT_DIR.mkdir(exist_ok=True)
|
| 31 |
+
|
| 32 |
+
DB_PATH: Path = Path(__file__).parent / "storage" / "history.db"
|
| 33 |
+
DB_PATH.parent.mkdir(exist_ok=True)
|
| 34 |
+
|
| 35 |
+
# -- AI Models -----------------------------------------------------------------
|
| 36 |
+
GEMINI_MODEL: str = "gemini-2.0-flash"
|
| 37 |
+
CLAUDE_MODEL: str = "claude-3-5-haiku-20241022"
|
| 38 |
+
OPENAI_MODEL: str = "gpt-4o-mini"
|
| 39 |
+
GROQ_MODEL: str = "llama-3.3-70b-versatile" # free, high-quality
|
| 40 |
+
NVIDIA_MODEL: str = "meta/llama-3.1-405b-instruct"
|
| 41 |
+
|
| 42 |
+
# -- App metadata --------------------------------------------------------------
|
| 43 |
+
APP_NAME: str = "Financial Analyzer"
|
| 44 |
+
APP_VERSION: str = "1.0.0"
|
pipeline/analyst.py
CHANGED
|
@@ -1,788 +1,788 @@
|
|
| 1 |
-
"""
|
| 2 |
-
pipeline/analyst.py
|
| 3 |
-
|
| 4 |
-
Supports Google Gemini and Anthropic Claude.
|
| 5 |
-
Each model generates the full narrative; if both selected,
|
| 6 |
-
outputs are combined with a comparison section.
|
| 7 |
-
"""
|
| 8 |
-
from __future__ import annotations
|
| 9 |
-
|
| 10 |
-
import json
|
| 11 |
-
import sys
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
from typing import Dict, List, Optional
|
| 14 |
-
|
| 15 |
-
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
-
from config import GEMINI_API_KEY, CLAUDE_API_KEY, GEMINI_MODEL, CLAUDE_MODEL, OPENAI_API_KEY, OPENAI_MODEL, GROQ_API_KEY, GROQ_MODEL, NVIDIA_API_KEY, NVIDIA_MODEL
|
| 17 |
-
import config
|
| 18 |
-
import time
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
def _pct(v):
|
| 24 |
-
return f"{v*100:.1f}%" if v is not None else "N/A"
|
| 25 |
-
|
| 26 |
-
def _num(v, dec=2):
|
| 27 |
-
return f"{v:.{dec}f}" if v is not None else "N/A"
|
| 28 |
-
|
| 29 |
-
def _money(v, currency="INR", units="Crores"):
|
| 30 |
-
"""Format a pre-scaled monetary value. Data is already in Crores (INR) or Millions (USD)."""
|
| 31 |
-
if v is None:
|
| 32 |
-
return "N/A"
|
| 33 |
-
sym = "\u20b9" if currency == "INR" else "$"
|
| 34 |
-
av = abs(v)
|
| 35 |
-
if currency == "INR":
|
| 36 |
-
# Data already in Crores
|
| 37 |
-
if av >= 100000:
|
| 38 |
-
return f"{sym}{v/100000:,.2f} L.Cr"
|
| 39 |
-
return f"{sym}{v:,.2f} Cr"
|
| 40 |
-
else:
|
| 41 |
-
# Data already in Millions
|
| 42 |
-
if av >= 1000:
|
| 43 |
-
return f"{sym}{v/1000:,.2f}B"
|
| 44 |
-
return f"{sym}{v:,.2f}M"
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
def _with_retries(func, log_fn=None, max_retries=3, backoff_factor=2):
|
| 49 |
-
"""Wrap an API call with exponential backoff for rate limits."""
|
| 50 |
-
def wrapper(*args, **kwargs):
|
| 51 |
-
retries = 0
|
| 52 |
-
while retries <= max_retries:
|
| 53 |
-
try:
|
| 54 |
-
res = func(*args, **kwargs)
|
| 55 |
-
if res:
|
| 56 |
-
return res
|
| 57 |
-
# If None returned (handled internally without raising), assume fail
|
| 58 |
-
except Exception as e:
|
| 59 |
-
err_str = str(e).lower()
|
| 60 |
-
if "429" in err_str or "too many requests" in err_str or "quota" in err_str:
|
| 61 |
-
if retries == max_retries:
|
| 62 |
-
if log_fn: log_fn(f"[Error] Max retries reached for {func.__name__}")
|
| 63 |
-
return None
|
| 64 |
-
sleep_time = backoff_factor ** retries
|
| 65 |
-
if log_fn: log_fn(f"[Warning] Rate limited in {func.__name__}, retrying in {sleep_time}s...")
|
| 66 |
-
time.sleep(sleep_time)
|
| 67 |
-
retries += 1
|
| 68 |
-
continue
|
| 69 |
-
else:
|
| 70 |
-
if log_fn: log_fn(f"[Error] {func.__name__} failed: {e}")
|
| 71 |
-
return None
|
| 72 |
-
return None
|
| 73 |
-
return None
|
| 74 |
-
return wrapper
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
#
|
| 78 |
-
|
| 79 |
-
def _build_context(data: Dict, meta: Dict) -> str:
|
| 80 |
-
"""Build a rich textual context string from all financial data."""
|
| 81 |
-
years = data.get("years", [])
|
| 82 |
-
inc = data.get("income_statement", {})
|
| 83 |
-
bal = data.get("balance_sheet", {})
|
| 84 |
-
cf = data.get("cash_flow", {})
|
| 85 |
-
rat = data.get("ratios", {})
|
| 86 |
-
gr = data.get("growth_metrics", {})
|
| 87 |
-
dp = data.get("dupont", {})
|
| 88 |
-
cur = data.get("currency", "INR")
|
| 89 |
-
|
| 90 |
-
def row(label, arr, fmt="money"):
|
| 91 |
-
units = data.get("units", "Crores")
|
| 92 |
-
vals = " | ".join([
|
| 93 |
-
(_money(v, cur, units) if fmt == "money" else _pct(v) if fmt == "pct" else _num(v))
|
| 94 |
-
for v in (arr or [])
|
| 95 |
-
])
|
| 96 |
-
return f" {label}: {vals}"
|
| 97 |
-
|
| 98 |
-
lines = [
|
| 99 |
-
f"COMPANY: {meta.get('name', '')} ({meta.get('ticker', '')})",
|
| 100 |
-
f"EXCHANGE: {meta.get('exchange', '')} | SECTOR: {meta.get('sector', '')} | INDUSTRY: {meta.get('industry', '')}",
|
| 101 |
-
f"COUNTRY: {meta.get('country', '')} | CURRENCY: {cur}",
|
| 102 |
-
f"YEARS (oldest
|
| 103 |
-
"",
|
| 104 |
-
"=== INCOME STATEMENT ===",
|
| 105 |
-
row("Revenue", inc.get("revenue")),
|
| 106 |
-
row("Gross Profit", inc.get("gross_profit")),
|
| 107 |
-
row("Operating Income", inc.get("operating_income")),
|
| 108 |
-
row("EBITDA", inc.get("ebitda")),
|
| 109 |
-
row("Net Income", inc.get("net_income")),
|
| 110 |
-
row("Diluted EPS", inc.get("diluted_eps"), "num"),
|
| 111 |
-
"",
|
| 112 |
-
"=== BALANCE SHEET ===",
|
| 113 |
-
row("Total Assets", bal.get("total_assets")),
|
| 114 |
-
row("Total Equity", bal.get("total_equity")),
|
| 115 |
-
row("Total Liabilities", bal.get("total_liabilities")),
|
| 116 |
-
row("Long-term Debt", bal.get("long_term_debt")),
|
| 117 |
-
row("Cash", bal.get("cash_and_equivalents")),
|
| 118 |
-
row("Current Assets", bal.get("total_current_assets")),
|
| 119 |
-
row("Current Liabilities",bal.get("total_current_liabilities")),
|
| 120 |
-
"",
|
| 121 |
-
"=== CASH FLOW ===",
|
| 122 |
-
row("Cash from Operations", cf.get("cash_from_operations")),
|
| 123 |
-
row("Capex", cf.get("capex")),
|
| 124 |
-
row("Free Cash Flow", cf.get("free_cash_flow")),
|
| 125 |
-
"",
|
| 126 |
-
"=== PROFITABILITY RATIOS ===",
|
| 127 |
-
row("Gross Margin", rat.get("gross_margin"), "pct"),
|
| 128 |
-
row("Operating Margin", rat.get("operating_margin"), "pct"),
|
| 129 |
-
row("Net Margin", rat.get("net_margin"), "pct"),
|
| 130 |
-
row("ROE", rat.get("roe"), "pct"),
|
| 131 |
-
row("ROA", rat.get("roa"), "pct"),
|
| 132 |
-
row("ROIC", rat.get("roic"), "pct"),
|
| 133 |
-
"",
|
| 134 |
-
"=== LIQUIDITY & SOLVENCY ===",
|
| 135 |
-
row("Current Ratio", rat.get("current_ratio"), "num"),
|
| 136 |
-
row("Quick Ratio", rat.get("quick_ratio"), "num"),
|
| 137 |
-
row("Debt-to-Equity", rat.get("debt_to_equity"), "num"),
|
| 138 |
-
row("Net Debt/EBITDA", rat.get("net_debt_to_ebitda"), "num"),
|
| 139 |
-
row("Interest Coverage", rat.get("interest_coverage"), "num"),
|
| 140 |
-
"",
|
| 141 |
-
"=== EFFICIENCY ===",
|
| 142 |
-
row("Asset Turnover", rat.get("asset_turnover"), "num"),
|
| 143 |
-
row("DSO (days)", rat.get("days_sales_outstanding"), "num"),
|
| 144 |
-
row("DPO (days)", rat.get("days_payables"), "num"),
|
| 145 |
-
row("Cash Conversion Cycle",rat.get("cash_conversion_cycle"), "num"),
|
| 146 |
-
"",
|
| 147 |
-
"=== DUPONT DECOMPOSITION ===",
|
| 148 |
-
row("Net Margin", dp.get("net_margin"), "pct"),
|
| 149 |
-
row("Asset Turnover", dp.get("asset_turnover"), "num"),
|
| 150 |
-
row("Equity Multiplier", dp.get("equity_multiplier"), "num"),
|
| 151 |
-
row("ROE (DuPont)", dp.get("roe_computed"), "pct"),
|
| 152 |
-
"",
|
| 153 |
-
"=== GROWTH METRICS ===",
|
| 154 |
-
row("Revenue YoY", gr.get("revenue_yoy"), "pct"),
|
| 155 |
-
f" Revenue 5yr CAGR: {_pct(gr.get('revenue_cagr_5y'))}",
|
| 156 |
-
row("Net Income YoY", gr.get("net_income_yoy"), "pct"),
|
| 157 |
-
f" Net Income 5yr CAGR: {_pct(gr.get('net_income_cagr_5y'))}",
|
| 158 |
-
row("FCF YoY", gr.get("fcf_yoy"), "pct"),
|
| 159 |
-
]
|
| 160 |
-
|
| 161 |
-
# Valuation
|
| 162 |
-
val = data.get("valuation_snapshot", {})
|
| 163 |
-
if val:
|
| 164 |
-
lines += [
|
| 165 |
-
"",
|
| 166 |
-
"=== VALUATION SNAPSHOT ===",
|
| 167 |
-
f" P/E (TTM): {_num(val.get('pe_ttm'))}",
|
| 168 |
-
f" P/B: {_num(val.get('pb'))}",
|
| 169 |
-
f" EV/EBITDA: {_num(val.get('ev_ebitda'))}",
|
| 170 |
-
f" FCF Yield: {_pct(val.get('fcf_yield'))}",
|
| 171 |
-
f" Dividend Yield: {_pct(val.get('dividend_yield'))}",
|
| 172 |
-
]
|
| 173 |
-
|
| 174 |
-
# Peers
|
| 175 |
-
peers = data.get("peers", [])
|
| 176 |
-
if peers:
|
| 177 |
-
lines += ["", "=== PEER BENCHMARKING ==="]
|
| 178 |
-
for p in peers:
|
| 179 |
-
lines.append(
|
| 180 |
-
f" {p.get('name')} ({p.get('ticker')}): "
|
| 181 |
-
f"Rev={_money(p.get('revenue'), p.get('currency','USD'))} | "
|
| 182 |
-
f"OpM={_pct(p.get('operating_margin'))} | "
|
| 183 |
-
f"ROE={_pct(p.get('roe'))} | "
|
| 184 |
-
f"D/E={_num(p.get('debt_to_equity'))}"
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
# Optional Annual Report Text (MD&A)
|
| 188 |
-
ar_text = data.get("annual_report_context", "")
|
| 189 |
-
if ar_text:
|
| 190 |
-
lines += ["", "=== ANNUAL REPORT EXCERPT (10-K MD&A) ==="]
|
| 191 |
-
lines.append(ar_text[:15000]) # Cap at 15k chars to save tokens
|
| 192 |
-
|
| 193 |
-
return "\n".join(lines)
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
#
|
| 197 |
-
|
| 198 |
-
SYSTEM_PROMPT = """You are a senior financial analyst with expertise in Indian and global equity markets.
|
| 199 |
-
You write rigorous, opinionated, data-driven financial analysis reports.
|
| 200 |
-
|
| 201 |
-
Guidelines:
|
| 202 |
-
- Be specific: cite exact numbers from the data provided, not generic statements
|
| 203 |
-
- Be opinionated: state what the numbers actually mean, not just what they are
|
| 204 |
-
- Use Indian financial terminology where appropriate (Crores, Lakhs, SEBI, NSE/BSE)
|
| 205 |
-
- Flag data gaps honestly rather than speculating
|
| 206 |
-
- Keep commentary professional but readable
|
| 207 |
-
- Do NOT use markdown formatting in your response
|
| 208 |
-
- Paragraph breaks only (use double newline to separate paragraphs)
|
| 209 |
-
- Numbers should be expressed in appropriate units (Cr for large INR amounts, B/M for USD)
|
| 210 |
-
"""
|
| 211 |
-
|
| 212 |
-
#
|
| 213 |
-
|
| 214 |
-
SYNTHESIS_PROMPT = """You are a master financial editor. You have been given {num_drafts} different AI-generated drafts for the '{section}' section of a financial report.
|
| 215 |
-
Your job is to synthesize these drafts into a single, cohesive, authoritative, and brilliantly written section.
|
| 216 |
-
|
| 217 |
-
Guidelines:
|
| 218 |
-
- Combine the best insights and data points from all drafts.
|
| 219 |
-
- Resolve any contradictions by taking the most logical or well-supported viewpoint.
|
| 220 |
-
- Write in a professional, direct, and opinionated financial analyst tone.
|
| 221 |
-
- Do NOT mention that this is a synthesis of multiple drafts or AI models.
|
| 222 |
-
- Output ONLY the final synthesized text, with NO markdown formatting, NO introductory text, and NO commentary. Just the plain text paragraphs.
|
| 223 |
-
"""
|
| 224 |
-
|
| 225 |
-
GENERATE_PPT_JSON = """You are a professional investment banker creating a pitch deck from financial data.
|
| 226 |
-
Your task is to generate the structure and content for a PowerPoint presentation summarizing the company's financial health.
|
| 227 |
-
Output a strict JSON array of slide objects. Each slide object MUST have:
|
| 228 |
-
- "title": A short, punchy title for the slide
|
| 229 |
-
- "bullets": An array of 3-5 strings, each containing a compelling insight, metric, or trend based on the data.
|
| 230 |
-
|
| 231 |
-
Do not include any markdown fences, introduction, or conclusion. Just the raw JSON array.
|
| 232 |
-
Focus on: Executive Summary, Revenue & Margin Trends, Cash Flow Health, Valuation, and Key Risks.
|
| 233 |
-
"""
|
| 234 |
-
|
| 235 |
-
#
|
| 236 |
-
|
| 237 |
-
SECTION_PROMPTS = {
|
| 238 |
-
"executive_summary": """
|
| 239 |
-
Write a 250-300 word executive summary of this company's financial health.
|
| 240 |
-
Answer these questions directly:
|
| 241 |
-
1. Is the business financially healthy or deteriorating?
|
| 242 |
-
2. What is the most important trend in the numbers?
|
| 243 |
-
3. How does it stack up against peers?
|
| 244 |
-
4. What is the key risk visible in the data?
|
| 245 |
-
5. What is the key opportunity?
|
| 246 |
-
Be direct and opinionated. No hedging.
|
| 247 |
-
""",
|
| 248 |
-
"company_profile": """
|
| 249 |
-
Write a 2-paragraph company profile covering:
|
| 250 |
-
- What the company does, its key business segments, and geographic presence
|
| 251 |
-
- Its position in the market, key products/services, major customers or clients if known
|
| 252 |
-
Use public knowledge about this company; supplement with the financial data provided.
|
| 253 |
-
""",
|
| 254 |
-
"industry_profile": """
|
| 255 |
-
Write a 2-paragraph industry profile for this company's sector/industry covering:
|
| 256 |
-
- Market size and structure (fragmented/consolidated, key players)
|
| 257 |
-
- Key growth drivers and headwinds for this industry in the Indian/global context
|
| 258 |
-
- Regulatory environment relevant to this industry
|
| 259 |
-
""",
|
| 260 |
-
"swot": """
|
| 261 |
-
Perform a rigorous SWOT analysis grounded in the financial data and industry knowledge.
|
| 262 |
-
Format your response as four sections:
|
| 263 |
-
|
| 264 |
-
STRENGTHS:
|
| 265 |
-
[3-4 specific, data-grounded strengths]
|
| 266 |
-
|
| 267 |
-
WEAKNESSES:
|
| 268 |
-
[3-4 specific, data-grounded weaknesses]
|
| 269 |
-
|
| 270 |
-
OPPORTUNITIES:
|
| 271 |
-
[3-4 specific opportunities for this company/industry]
|
| 272 |
-
|
| 273 |
-
THREATS:
|
| 274 |
-
[3-4 specific threats, including competitive and regulatory]
|
| 275 |
-
|
| 276 |
-
Be specific
|
| 277 |
-
""",
|
| 278 |
-
"industry_trends": """
|
| 279 |
-
Write 2-3 paragraphs on current and emerging trends in this company's industry, covering:
|
| 280 |
-
- Macro trends (digitization, ESG, AI, PLI schemes for Indian companies, etc.)
|
| 281 |
-
- Competitive dynamics and consolidation
|
| 282 |
-
- Technology disruption if applicable
|
| 283 |
-
- Regulatory changes (SEBI, RBI, sector-specific regulators for Indian companies)
|
| 284 |
-
Ground trends in the financial data where possible (e.g., if margins are compressing, is it industry-wide?).
|
| 285 |
-
""",
|
| 286 |
-
"trend_analysis_revenue": """
|
| 287 |
-
Write 2-3 paragraphs analyzing the revenue and profitability trends over the analysis period.
|
| 288 |
-
Specifically address:
|
| 289 |
-
- Revenue trajectory (acceleration/deceleration/volatility)
|
| 290 |
-
- Gross margin trend and what it reveals about pricing power
|
| 291 |
-
- Operating leverage (are operating margins improving as revenue grows?)
|
| 292 |
-
- Quality of earnings (is net income growing in line with revenue?)
|
| 293 |
-
Reference specific numbers from the data.
|
| 294 |
-
""",
|
| 295 |
-
"trend_analysis_balance_sheet": """
|
| 296 |
-
Write 2 paragraphs analyzing balance sheet strength and capital structure trends.
|
| 297 |
-
Address:
|
| 298 |
-
- Liquidity position (current ratio, cash levels)
|
| 299 |
-
- Leverage trajectory (is debt rising or falling relative to equity/earnings?)
|
| 300 |
-
- Asset quality (goodwill, receivables trends)
|
| 301 |
-
- Working capital efficiency
|
| 302 |
-
""",
|
| 303 |
-
"trend_analysis_cashflow": """
|
| 304 |
-
Write 2 paragraphs analyzing cash flow quality and capital allocation.
|
| 305 |
-
Address:
|
| 306 |
-
- OCF quality (does it consistently exceed net income, or lag it
|
| 307 |
-
- Capex intensity and investment cycle
|
| 308 |
-
- Free cash flow generation and its trajectory
|
| 309 |
-
- How is FCF being allocated (buybacks, dividends, debt repayment, acquisitions)?
|
| 310 |
-
""",
|
| 311 |
-
"ratio_commentary": """
|
| 312 |
-
Write 2-3 paragraphs interpreting the ratio analysis.
|
| 313 |
-
Focus on:
|
| 314 |
-
- Which ratios show the most significant trends (positive or negative)?
|
| 315 |
-
- Any ratios that are outliers vs. industry norms?
|
| 316 |
-
- What do the efficiency ratios (DSO, DPO, CCC) tell us about operational quality?
|
| 317 |
-
- DuPont decomposition: which driver is most responsible for ROE trends?
|
| 318 |
-
""",
|
| 319 |
-
"peer_commentary": """
|
| 320 |
-
Write 2 paragraphs benchmarking this company against its peers.
|
| 321 |
-
Address:
|
| 322 |
-
- Where does the company rank on the most important metrics for this industry?
|
| 323 |
-
- What explains the gaps vs. peers (structural, cyclical, or management decisions)?
|
| 324 |
-
- Is the company gaining or losing competitive position?
|
| 325 |
-
""",
|
| 326 |
-
"key_insights": """
|
| 327 |
-
List 4-6 key insights, one per line. Each insight must:
|
| 328 |
-
- Be substantive and specific (not generic)
|
| 329 |
-
- Reference a specific number or trend from the data
|
| 330 |
-
- Convey an analytical judgment, not just a fact
|
| 331 |
-
|
| 332 |
-
Format: One insight per line, starting with a dash (-).
|
| 333 |
-
""",
|
| 334 |
-
"risks": """
|
| 335 |
-
List the top 5-7 risks facing this company. For each risk, use this format:
|
| 336 |
-
CATEGORY | Risk description (specific, grounded in data or industry knowledge)
|
| 337 |
-
|
| 338 |
-
Categories to use: Financial, Business, Industry, Regulatory, ESG
|
| 339 |
-
""",
|
| 340 |
-
"things_to_watch": """
|
| 341 |
-
List 4-5 specific, monitorable metrics or events that would change the investment picture.
|
| 342 |
-
Format: One per line starting with a dash (-).
|
| 343 |
-
Be concrete: e.g., 'Watch for gross margin recovery above 30% in FY26' not 'watch margins'.
|
| 344 |
-
""",
|
| 345 |
-
"limitations": """
|
| 346 |
-
List any material analytical limitations in 3-5 bullet points. Include:
|
| 347 |
-
- Data gaps (which line items are missing or estimated)
|
| 348 |
-
- Comparability issues (fiscal year changes, acquisitions)
|
| 349 |
-
- Data source caveats (scraped vs. filed data)
|
| 350 |
-
- Any ratios that could not be computed meaningfully (negative equity, etc.)
|
| 351 |
-
Format: One per line starting with a dash (-).
|
| 352 |
-
""",
|
| 353 |
-
}
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
#
|
| 357 |
-
|
| 358 |
-
def _gemini_generate(context: str, section: str, log_fn=None) -> str:
|
| 359 |
-
"""Generate using Gemini
|
| 360 |
-
prompt = f"{SYSTEM_PROMPT}\n\nFINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 361 |
-
|
| 362 |
-
#
|
| 363 |
-
if GEMINI_API_KEY:
|
| 364 |
-
try:
|
| 365 |
-
from google import genai
|
| 366 |
-
from google.genai import types as gtypes
|
| 367 |
-
client = genai.Client(api_key=GEMINI_API_KEY)
|
| 368 |
-
response = client.models.generate_content(
|
| 369 |
-
model=GEMINI_MODEL,
|
| 370 |
-
contents=prompt,
|
| 371 |
-
config=gtypes.GenerateContentConfig(temperature=0.2, max_output_tokens=1024),
|
| 372 |
-
)
|
| 373 |
-
return response.text.strip()
|
| 374 |
-
except Exception:
|
| 375 |
-
pass
|
| 376 |
-
# Fallback to old SDK
|
| 377 |
-
try:
|
| 378 |
-
import google.generativeai as genai_old
|
| 379 |
-
genai_old.configure(api_key=GEMINI_API_KEY)
|
| 380 |
-
model = genai_old.GenerativeModel(model_name=GEMINI_MODEL, system_instruction=SYSTEM_PROMPT)
|
| 381 |
-
response = model.generate_content(prompt)
|
| 382 |
-
return response.text.strip()
|
| 383 |
-
except Exception as e2:
|
| 384 |
-
if log_fn: log_fn(f"[Warning] Gemini failed for {section}: {str(e2)[:80]}")
|
| 385 |
-
return None
|
| 386 |
-
|
| 387 |
-
return None
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
#
|
| 392 |
-
|
| 393 |
-
def _openai_generate(context: str, section: str, log_fn=None) -> str:
|
| 394 |
-
try:
|
| 395 |
-
from openai import OpenAI
|
| 396 |
-
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 397 |
-
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 398 |
-
resp = client.chat.completions.create(
|
| 399 |
-
model=OPENAI_MODEL,
|
| 400 |
-
messages=[
|
| 401 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 402 |
-
{"role": "user", "content": prompt},
|
| 403 |
-
],
|
| 404 |
-
temperature=0.2,
|
| 405 |
-
max_tokens=1024,
|
| 406 |
-
)
|
| 407 |
-
return resp.choices[0].message.content.strip()
|
| 408 |
-
except Exception as e:
|
| 409 |
-
if log_fn: log_fn(f"[Warning] ChatGPT failed for {section}: {str(e)[:80]}")
|
| 410 |
-
return None
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
#
|
| 414 |
-
|
| 415 |
-
def _groq_generate(context: str, section: str, log_fn=None) -> str:
|
| 416 |
-
"""Generate using Groq's OpenAI-compatible API (free tier, Llama 3.3 70B)."""
|
| 417 |
-
try:
|
| 418 |
-
from openai import OpenAI
|
| 419 |
-
client = OpenAI(
|
| 420 |
-
api_key=GROQ_API_KEY,
|
| 421 |
-
base_url="https://api.groq.com/openai/v1",
|
| 422 |
-
)
|
| 423 |
-
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 424 |
-
resp = client.chat.completions.create(
|
| 425 |
-
model=GROQ_MODEL,
|
| 426 |
-
messages=[
|
| 427 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 428 |
-
{"role": "user", "content": prompt},
|
| 429 |
-
],
|
| 430 |
-
temperature=0.2,
|
| 431 |
-
max_tokens=1024,
|
| 432 |
-
)
|
| 433 |
-
return resp.choices[0].message.content.strip()
|
| 434 |
-
except Exception as e:
|
| 435 |
-
if log_fn: log_fn(f"[Warning] Groq failed for {section}: {str(e)[:80]}")
|
| 436 |
-
return None
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
#
|
| 440 |
-
|
| 441 |
-
def _nvidia_generate(context: str, section: str, log_fn=None) -> Optional[str]:
|
| 442 |
-
"""Generate using NVIDIA NIM OpenAI-compatible API."""
|
| 443 |
-
try:
|
| 444 |
-
from openai import OpenAI
|
| 445 |
-
client = OpenAI(
|
| 446 |
-
api_key=NVIDIA_API_KEY,
|
| 447 |
-
base_url="https://integrate.api.nvidia.com/v1",
|
| 448 |
-
)
|
| 449 |
-
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 450 |
-
resp = client.chat.completions.create(
|
| 451 |
-
model=NVIDIA_MODEL,
|
| 452 |
-
messages=[
|
| 453 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 454 |
-
{"role": "user", "content": prompt},
|
| 455 |
-
],
|
| 456 |
-
temperature=0.2,
|
| 457 |
-
max_tokens=1024,
|
| 458 |
-
)
|
| 459 |
-
return resp.choices[0].message.content.strip()
|
| 460 |
-
except Exception as e:
|
| 461 |
-
if log_fn: log_fn(f"[Warning] NVIDIA NIM failed for {section}: {str(e)[:80]}")
|
| 462 |
-
return None
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
#
|
| 466 |
-
|
| 467 |
-
def _claude_generate(context: str, section: str, log_fn=None) -> str:
|
| 468 |
-
try:
|
| 469 |
-
import anthropic
|
| 470 |
-
client = anthropic.Anthropic(api_key=CLAUDE_API_KEY)
|
| 471 |
-
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 472 |
-
message = client.messages.create(
|
| 473 |
-
model=CLAUDE_MODEL,
|
| 474 |
-
max_tokens=1024,
|
| 475 |
-
system=SYSTEM_PROMPT,
|
| 476 |
-
messages=[{"role": "user", "content": prompt}],
|
| 477 |
-
)
|
| 478 |
-
return message.content[0].text.strip()
|
| 479 |
-
except Exception as e:
|
| 480 |
-
if log_fn: log_fn(f"[Warning] Claude failed for {section}: {str(e)[:80]}")
|
| 481 |
-
return None
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
#
|
| 485 |
-
|
| 486 |
-
def _hf_generate(context: str, section: str, log_fn=None) -> Optional[str]:
|
| 487 |
-
"""Generate using Hugging Face Inference API (DeepSeek)."""
|
| 488 |
-
hf_key = getattr(config, "HF_API_KEY", "")
|
| 489 |
-
if not hf_key:
|
| 490 |
-
return None
|
| 491 |
-
|
| 492 |
-
try:
|
| 493 |
-
from huggingface_hub import InferenceClient
|
| 494 |
-
client = InferenceClient(api_key=hf_key)
|
| 495 |
-
|
| 496 |
-
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}\n\nRespond ONLY with the requested analysis text."
|
| 497 |
-
|
| 498 |
-
messages = [
|
| 499 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 500 |
-
{"role": "user", "content": prompt}
|
| 501 |
-
]
|
| 502 |
-
|
| 503 |
-
# We use the recommended chat_completion method
|
| 504 |
-
response = client.chat_completion(
|
| 505 |
-
model="deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
|
| 506 |
-
messages=messages,
|
| 507 |
-
max_tokens=1024,
|
| 508 |
-
temperature=0.2
|
| 509 |
-
)
|
| 510 |
-
|
| 511 |
-
if response and response.choices:
|
| 512 |
-
text = response.choices[0].message.content
|
| 513 |
-
# Strip <think> tags if DeepSeek outputs them
|
| 514 |
-
import re
|
| 515 |
-
text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
|
| 516 |
-
return text
|
| 517 |
-
|
| 518 |
-
return None
|
| 519 |
-
|
| 520 |
-
except Exception as e:
|
| 521 |
-
err_str = str(e).lower()
|
| 522 |
-
if "429" in err_str or "too many" in err_str or "rate limit" in err_str:
|
| 523 |
-
raise Exception("429 Too Many Requests") # Let the retry wrapper catch it
|
| 524 |
-
|
| 525 |
-
if log_fn: log_fn(f"[Warning] HF DeepSeek failed for {section}: {str(e)[:80]}")
|
| 526 |
-
return None
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
#
|
| 530 |
-
|
| 531 |
-
def _parse_swot(text: str) -> Dict:
|
| 532 |
-
"""Parse SWOT text into a structured dict."""
|
| 533 |
-
result = {"strengths": [], "weaknesses": [], "opportunities": [], "threats": [], "raw": text}
|
| 534 |
-
current = None
|
| 535 |
-
for line in text.split("\n"):
|
| 536 |
-
l = line.strip()
|
| 537 |
-
if l.upper().startswith("STRENGTH"):
|
| 538 |
-
current = "strengths"
|
| 539 |
-
elif l.upper().startswith("WEAKNESS"):
|
| 540 |
-
current = "weaknesses"
|
| 541 |
-
elif l.upper().startswith("OPPORTUNIT"):
|
| 542 |
-
current = "opportunities"
|
| 543 |
-
elif l.upper().startswith("THREAT"):
|
| 544 |
-
current = "threats"
|
| 545 |
-
elif current and l and not l.upper() in ("STRENGTHS:", "WEAKNESSES:", "OPPORTUNITIES:", "THREATS:"):
|
| 546 |
-
clean = l.lstrip("-β’* ")
|
| 547 |
-
if clean:
|
| 548 |
-
result[current].append(clean)
|
| 549 |
-
return result
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
def _parse_bullets(text: str) -> List[str]:
|
| 553 |
-
"""Parse a bulleted list response into a list of strings."""
|
| 554 |
-
items = []
|
| 555 |
-
for line in text.split("\n"):
|
| 556 |
-
l = line.strip().lstrip("-β’* ")
|
| 557 |
-
if l:
|
| 558 |
-
items.append(l)
|
| 559 |
-
return items
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
def _parse_risks(text: str) -> List[Dict]:
|
| 563 |
-
"""Parse risk list into categorized dicts."""
|
| 564 |
-
risks = []
|
| 565 |
-
for line in text.split("\n"):
|
| 566 |
-
l = line.strip().lstrip("-β’* ")
|
| 567 |
-
if "|" in l:
|
| 568 |
-
parts = l.split("|", 1)
|
| 569 |
-
risks.append({"category": parts[0].strip(), "description": parts[1].strip()})
|
| 570 |
-
elif l:
|
| 571 |
-
risks.append({"category": "General", "description": l})
|
| 572 |
-
return risks
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
#
|
| 576 |
-
|
| 577 |
-
def generate_narrative(
|
| 578 |
-
data: Dict,
|
| 579 |
-
meta: Dict,
|
| 580 |
-
models: List[str],
|
| 581 |
-
log_fn=None,
|
| 582 |
-
) -> Dict:
|
| 583 |
-
"""
|
| 584 |
-
Generate full narrative analysis using selected AI models.
|
| 585 |
-
|
| 586 |
-
Args:
|
| 587 |
-
data: Calculated financial data dict.
|
| 588 |
-
meta: CompanyMeta.to_dict()
|
| 589 |
-
models: List of model names, e.g. ['gemini', 'claude'] or ['gemini']
|
| 590 |
-
log_fn: Optional progress callback.
|
| 591 |
-
|
| 592 |
-
Returns:
|
| 593 |
-
Dict with all narrative fields populated.
|
| 594 |
-
"""
|
| 595 |
-
def log(msg):
|
| 596 |
-
if log_fn:
|
| 597 |
-
log_fn(msg)
|
| 598 |
-
|
| 599 |
-
use_gemini = "gemini" in models and bool(GEMINI_API_KEY)
|
| 600 |
-
use_claude = "claude" in models and bool(CLAUDE_API_KEY)
|
| 601 |
-
use_openai = "openai" in models and bool(OPENAI_API_KEY)
|
| 602 |
-
use_groq = "groq" in models and bool(GROQ_API_KEY)
|
| 603 |
-
use_nvidia = "nvidia" in models and bool(NVIDIA_API_KEY)
|
| 604 |
-
use_hf = "huggingface" in models and bool(getattr(config, "HF_API_KEY", ""))
|
| 605 |
-
|
| 606 |
-
if not any([use_gemini, use_claude, use_openai, use_groq, use_nvidia, use_hf]):
|
| 607 |
-
log("No AI models configured. Running data-only analysis (no narrative).")
|
| 608 |
-
return _empty_narrative()
|
| 609 |
-
|
| 610 |
-
context = _build_context(data, meta)
|
| 611 |
-
active = [m for m, ok in [("Gemini",use_gemini),("Claude",use_claude),("ChatGPT",use_openai),("Groq",use_groq),("NVIDIA",use_nvidia),("HF-DeepSeek",use_hf)] if ok]
|
| 612 |
-
log(f"Generating AI narrative ({', '.join(active)}) ...")
|
| 613 |
-
|
| 614 |
-
def _synthesize_drafts(section: str, drafts: Dict[str, str]) -> str:
|
| 615 |
-
"""Use the best available model to merge drafts into a single consensus response."""
|
| 616 |
-
# Pick the synthesizer based on perceived quality/capability
|
| 617 |
-
synthesizer = None
|
| 618 |
-
if use_openai: synthesizer = ("ChatGPT", _openai_generate)
|
| 619 |
-
elif use_claude: synthesizer = ("Claude", _claude_generate)
|
| 620 |
-
elif use_nvidia: synthesizer = ("NVIDIA", _nvidia_generate)
|
| 621 |
-
elif use_gemini: synthesizer = ("Gemini", _gemini_generate)
|
| 622 |
-
elif use_groq: synthesizer = ("Groq", _groq_generate)
|
| 623 |
-
elif use_hf: synthesizer = ("HF-DeepSeek", _hf_generate)
|
| 624 |
-
|
| 625 |
-
if not synthesizer:
|
| 626 |
-
return list(drafts.values())[0]
|
| 627 |
-
|
| 628 |
-
name, fn = synthesizer
|
| 629 |
-
log(f" > Synthesizing {len(drafts)} drafts using {name}...")
|
| 630 |
-
|
| 631 |
-
draft_text = "\n\n".join([f"--- Draft from {agent} ---\n{text}" for agent, text in drafts.items()])
|
| 632 |
-
prompt = SYNTHESIS_PROMPT.format(section=section, num_drafts=len(drafts)) + "\n\n" + draft_text
|
| 633 |
-
|
| 634 |
-
# We reuse the context parameter to pass the prompt, and bypass the section wrapping by mocking it
|
| 635 |
-
# Actually, let's just create a custom direct call for synthesis to avoid section wrapping issues.
|
| 636 |
-
# But to reuse the functions easily, we can temporarily override the SECTION_PROMPTS.
|
| 637 |
-
original_prompt = SECTION_PROMPTS.get(section, "")
|
| 638 |
-
SECTION_PROMPTS[section] = prompt
|
| 639 |
-
try:
|
| 640 |
-
res = fn("", section) # Context empty because prompt contains everything
|
| 641 |
-
finally:
|
| 642 |
-
SECTION_PROMPTS[section] = original_prompt
|
| 643 |
-
|
| 644 |
-
if res: return res
|
| 645 |
-
|
| 646 |
-
# If synthesis fails, fallback to simple concatenation
|
| 647 |
-
return "\n\n".join([f"[{a}]\n{t}" for a, t in drafts.items()])
|
| 648 |
-
|
| 649 |
-
import concurrent.futures
|
| 650 |
-
|
| 651 |
-
def gen(section: str) -> str:
|
| 652 |
-
tasks = {}
|
| 653 |
-
# Max workers set to 3 to avoid extreme rate limits on free tiers (like Groq's 30 RPM)
|
| 654 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
| 655 |
-
if use_gemini: tasks[executor.submit(_with_retries(_gemini_generate, log_fn), context, section)] = "Gemini"
|
| 656 |
-
if use_claude: tasks[executor.submit(_with_retries(_claude_generate, log_fn), context, section)] = "Claude"
|
| 657 |
-
if use_openai: tasks[executor.submit(_with_retries(_openai_generate, log_fn), context, section)] = "ChatGPT"
|
| 658 |
-
if use_groq: tasks[executor.submit(_with_retries(_groq_generate, log_fn), context, section)] = "Groq"
|
| 659 |
-
if use_nvidia: tasks[executor.submit(_with_retries(_nvidia_generate, log_fn), context, section)] = "NVIDIA"
|
| 660 |
-
if use_hf: tasks[executor.submit(_with_retries(_hf_generate, log_fn), context, section)] = "HF-DeepSeek"
|
| 661 |
-
|
| 662 |
-
drafts = {}
|
| 663 |
-
for future in concurrent.futures.as_completed(tasks):
|
| 664 |
-
name = tasks[future]
|
| 665 |
-
try:
|
| 666 |
-
res = future.result()
|
| 667 |
-
if res: drafts[name] = res
|
| 668 |
-
except Exception as e:
|
| 669 |
-
if log_fn: log_fn(f"[Warning] {name} thread failed: {e}")
|
| 670 |
-
|
| 671 |
-
if len(drafts) == 0:
|
| 672 |
-
return ""
|
| 673 |
-
if len(drafts) == 1:
|
| 674 |
-
return list(drafts.values())[0]
|
| 675 |
-
|
| 676 |
-
return _synthesize_drafts(section, drafts)
|
| 677 |
-
|
| 678 |
-
def _generate_ppt_json() -> str:
|
| 679 |
-
# Pick the smartest model available for structured JSON generation
|
| 680 |
-
synthesizer = None
|
| 681 |
-
if use_openai: synthesizer = ("ChatGPT", _openai_generate)
|
| 682 |
-
elif use_claude: synthesizer = ("Claude", _claude_generate)
|
| 683 |
-
elif use_gemini: synthesizer = ("Gemini", _gemini_generate)
|
| 684 |
-
elif use_nvidia: synthesizer = ("NVIDIA", _nvidia_generate)
|
| 685 |
-
elif use_groq: synthesizer = ("Groq", _groq_generate)
|
| 686 |
-
|
| 687 |
-
if not synthesizer:
|
| 688 |
-
return ""
|
| 689 |
-
|
| 690 |
-
name, fn = synthesizer
|
| 691 |
-
log(f"\n[PPT] Generating PowerPoint Structure using {name} ...")
|
| 692 |
-
|
| 693 |
-
original_prompt = SECTION_PROMPTS.get("ppt_json", "")
|
| 694 |
-
SECTION_PROMPTS["ppt_json"] = GENERATE_PPT_JSON
|
| 695 |
-
try:
|
| 696 |
-
res = fn(context, "ppt_json")
|
| 697 |
-
finally:
|
| 698 |
-
if "ppt_json" in SECTION_PROMPTS:
|
| 699 |
-
del SECTION_PROMPTS["ppt_json"]
|
| 700 |
-
|
| 701 |
-
return res if res else ""
|
| 702 |
-
|
| 703 |
-
log(" > Executing section: Executive Summary")
|
| 704 |
-
exec_summary = gen("executive_summary")
|
| 705 |
-
|
| 706 |
-
log(" Generating company profile
|
| 707 |
-
company_overview = gen("company_profile")
|
| 708 |
-
|
| 709 |
-
log(" Generating industry profile
|
| 710 |
-
industry_profile = gen("industry_profile")
|
| 711 |
-
|
| 712 |
-
log(" Generating SWOT
|
| 713 |
-
swot_raw = gen("swot")
|
| 714 |
-
swot = _parse_swot(swot_raw)
|
| 715 |
-
|
| 716 |
-
log(" Generating industry trends
|
| 717 |
-
industry_trends = gen("industry_trends")
|
| 718 |
-
|
| 719 |
-
log(" Generating trend analysis
|
| 720 |
-
trend_revenue = gen("trend_analysis_revenue")
|
| 721 |
-
trend_bs = gen("trend_analysis_balance_sheet")
|
| 722 |
-
trend_cf = gen("trend_analysis_cashflow")
|
| 723 |
-
|
| 724 |
-
log(" Generating ratio commentary
|
| 725 |
-
ratio_commentary = gen("ratio_commentary")
|
| 726 |
-
|
| 727 |
-
log(" Generating peer commentary
|
| 728 |
-
peer_commentary = gen("peer_commentary")
|
| 729 |
-
|
| 730 |
-
log(" Generating insights
|
| 731 |
-
insights_raw = gen("key_insights")
|
| 732 |
-
insights = _parse_bullets(insights_raw)
|
| 733 |
-
|
| 734 |
-
log(" Generating risks
|
| 735 |
-
risks_raw = gen("risks")
|
| 736 |
-
risks = _parse_risks(risks_raw)
|
| 737 |
-
|
| 738 |
-
log(" Generating things to watch
|
| 739 |
-
watch_raw = gen("things_to_watch")
|
| 740 |
-
things_to_watch = _parse_bullets(watch_raw)
|
| 741 |
-
|
| 742 |
-
log(" Generating limitations
|
| 743 |
-
lim_raw = gen("limitations")
|
| 744 |
-
limitations = _parse_bullets(lim_raw)
|
| 745 |
-
|
| 746 |
-
ppt_json = _generate_ppt_json()
|
| 747 |
-
|
| 748 |
-
log("
|
| 749 |
-
|
| 750 |
-
return {
|
| 751 |
-
"executive_summary": exec_summary,
|
| 752 |
-
"company_overview": company_overview,
|
| 753 |
-
"industry_profile": industry_profile,
|
| 754 |
-
"swot": swot,
|
| 755 |
-
"industry_trends": industry_trends,
|
| 756 |
-
"trend_analysis": {
|
| 757 |
-
"revenue_and_profitability": trend_revenue,
|
| 758 |
-
"balance_sheet_strength": trend_bs,
|
| 759 |
-
"cash_flow_generation": trend_cf,
|
| 760 |
-
},
|
| 761 |
-
"ratio_analysis_commentary": ratio_commentary,
|
| 762 |
-
"peer_comparison_commentary": peer_commentary,
|
| 763 |
-
"key_insights": insights,
|
| 764 |
-
"risks": risks,
|
| 765 |
-
"things_to_watch": things_to_watch,
|
| 766 |
-
"limitations_and_caveats": limitations,
|
| 767 |
-
"models_used": models,
|
| 768 |
-
"ppt_json": ppt_json,
|
| 769 |
-
}
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
def _empty_narrative() -> Dict:
|
| 773 |
-
return {
|
| 774 |
-
"executive_summary": "AI narrative not generated (no API keys configured).",
|
| 775 |
-
"company_overview": "",
|
| 776 |
-
"industry_profile": "",
|
| 777 |
-
"swot": {"strengths": [], "weaknesses": [], "opportunities": [], "threats": []},
|
| 778 |
-
"industry_trends": "",
|
| 779 |
-
"trend_analysis": {"revenue_and_profitability": "", "balance_sheet_strength": "", "cash_flow_generation": ""},
|
| 780 |
-
"ratio_analysis_commentary": "",
|
| 781 |
-
"peer_comparison_commentary":"",
|
| 782 |
-
"key_insights": [],
|
| 783 |
-
"risks": [],
|
| 784 |
-
"things_to_watch": [],
|
| 785 |
-
"limitations_and_caveats": [],
|
| 786 |
-
"models_used": [],
|
| 787 |
-
"ppt_json": "",
|
| 788 |
-
}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pipeline/analyst.py -- Multi-model AI narrative generation.
|
| 3 |
+
|
| 4 |
+
Supports Google Gemini and Anthropic Claude.
|
| 5 |
+
Each model generates the full narrative; if both selected,
|
| 6 |
+
outputs are combined with a comparison section.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Dict, List, Optional
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
+
from config import GEMINI_API_KEY, CLAUDE_API_KEY, GEMINI_MODEL, CLAUDE_MODEL, OPENAI_API_KEY, OPENAI_MODEL, GROQ_API_KEY, GROQ_MODEL, NVIDIA_API_KEY, NVIDIA_MODEL
|
| 17 |
+
import config
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# -- Formatting helpers --------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
def _pct(v):
|
| 24 |
+
return f"{v*100:.1f}%" if v is not None else "N/A"
|
| 25 |
+
|
| 26 |
+
def _num(v, dec=2):
|
| 27 |
+
return f"{v:.{dec}f}" if v is not None else "N/A"
|
| 28 |
+
|
| 29 |
+
def _money(v, currency="INR", units="Crores"):
|
| 30 |
+
"""Format a pre-scaled monetary value. Data is already in Crores (INR) or Millions (USD)."""
|
| 31 |
+
if v is None:
|
| 32 |
+
return "N/A"
|
| 33 |
+
sym = "\u20b9" if currency == "INR" else "$"
|
| 34 |
+
av = abs(v)
|
| 35 |
+
if currency == "INR":
|
| 36 |
+
# Data already in Crores
|
| 37 |
+
if av >= 100000:
|
| 38 |
+
return f"{sym}{v/100000:,.2f} L.Cr"
|
| 39 |
+
return f"{sym}{v:,.2f} Cr"
|
| 40 |
+
else:
|
| 41 |
+
# Data already in Millions
|
| 42 |
+
if av >= 1000:
|
| 43 |
+
return f"{sym}{v/1000:,.2f}B"
|
| 44 |
+
return f"{sym}{v:,.2f}M"
|
| 45 |
+
|
| 46 |
+
# -- Retry Wrapper -------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
def _with_retries(func, log_fn=None, max_retries=3, backoff_factor=2):
|
| 49 |
+
"""Wrap an API call with exponential backoff for rate limits."""
|
| 50 |
+
def wrapper(*args, **kwargs):
|
| 51 |
+
retries = 0
|
| 52 |
+
while retries <= max_retries:
|
| 53 |
+
try:
|
| 54 |
+
res = func(*args, **kwargs)
|
| 55 |
+
if res:
|
| 56 |
+
return res
|
| 57 |
+
# If None returned (handled internally without raising), assume fail
|
| 58 |
+
except Exception as e:
|
| 59 |
+
err_str = str(e).lower()
|
| 60 |
+
if "429" in err_str or "too many requests" in err_str or "quota" in err_str:
|
| 61 |
+
if retries == max_retries:
|
| 62 |
+
if log_fn: log_fn(f"[Error] Max retries reached for {func.__name__}")
|
| 63 |
+
return None
|
| 64 |
+
sleep_time = backoff_factor ** retries
|
| 65 |
+
if log_fn: log_fn(f"[Warning] Rate limited in {func.__name__}, retrying in {sleep_time}s...")
|
| 66 |
+
time.sleep(sleep_time)
|
| 67 |
+
retries += 1
|
| 68 |
+
continue
|
| 69 |
+
else:
|
| 70 |
+
if log_fn: log_fn(f"[Error] {func.__name__} failed: {e}")
|
| 71 |
+
return None
|
| 72 |
+
return None
|
| 73 |
+
return None
|
| 74 |
+
return wrapper
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# -- Context builder -----------------------------------------------------------
|
| 78 |
+
|
| 79 |
+
def _build_context(data: Dict, meta: Dict) -> str:
|
| 80 |
+
"""Build a rich textual context string from all financial data."""
|
| 81 |
+
years = data.get("years", [])
|
| 82 |
+
inc = data.get("income_statement", {})
|
| 83 |
+
bal = data.get("balance_sheet", {})
|
| 84 |
+
cf = data.get("cash_flow", {})
|
| 85 |
+
rat = data.get("ratios", {})
|
| 86 |
+
gr = data.get("growth_metrics", {})
|
| 87 |
+
dp = data.get("dupont", {})
|
| 88 |
+
cur = data.get("currency", "INR")
|
| 89 |
+
|
| 90 |
+
def row(label, arr, fmt="money"):
|
| 91 |
+
units = data.get("units", "Crores")
|
| 92 |
+
vals = " | ".join([
|
| 93 |
+
(_money(v, cur, units) if fmt == "money" else _pct(v) if fmt == "pct" else _num(v))
|
| 94 |
+
for v in (arr or [])
|
| 95 |
+
])
|
| 96 |
+
return f" {label}: {vals}"
|
| 97 |
+
|
| 98 |
+
lines = [
|
| 99 |
+
f"COMPANY: {meta.get('name', '')} ({meta.get('ticker', '')})",
|
| 100 |
+
f"EXCHANGE: {meta.get('exchange', '')} | SECTOR: {meta.get('sector', '')} | INDUSTRY: {meta.get('industry', '')}",
|
| 101 |
+
f"COUNTRY: {meta.get('country', '')} | CURRENCY: {cur}",
|
| 102 |
+
f"YEARS (oldest->newest): {' | '.join(str(y) for y in years)}",
|
| 103 |
+
"",
|
| 104 |
+
"=== INCOME STATEMENT ===",
|
| 105 |
+
row("Revenue", inc.get("revenue")),
|
| 106 |
+
row("Gross Profit", inc.get("gross_profit")),
|
| 107 |
+
row("Operating Income", inc.get("operating_income")),
|
| 108 |
+
row("EBITDA", inc.get("ebitda")),
|
| 109 |
+
row("Net Income", inc.get("net_income")),
|
| 110 |
+
row("Diluted EPS", inc.get("diluted_eps"), "num"),
|
| 111 |
+
"",
|
| 112 |
+
"=== BALANCE SHEET ===",
|
| 113 |
+
row("Total Assets", bal.get("total_assets")),
|
| 114 |
+
row("Total Equity", bal.get("total_equity")),
|
| 115 |
+
row("Total Liabilities", bal.get("total_liabilities")),
|
| 116 |
+
row("Long-term Debt", bal.get("long_term_debt")),
|
| 117 |
+
row("Cash", bal.get("cash_and_equivalents")),
|
| 118 |
+
row("Current Assets", bal.get("total_current_assets")),
|
| 119 |
+
row("Current Liabilities",bal.get("total_current_liabilities")),
|
| 120 |
+
"",
|
| 121 |
+
"=== CASH FLOW ===",
|
| 122 |
+
row("Cash from Operations", cf.get("cash_from_operations")),
|
| 123 |
+
row("Capex", cf.get("capex")),
|
| 124 |
+
row("Free Cash Flow", cf.get("free_cash_flow")),
|
| 125 |
+
"",
|
| 126 |
+
"=== PROFITABILITY RATIOS ===",
|
| 127 |
+
row("Gross Margin", rat.get("gross_margin"), "pct"),
|
| 128 |
+
row("Operating Margin", rat.get("operating_margin"), "pct"),
|
| 129 |
+
row("Net Margin", rat.get("net_margin"), "pct"),
|
| 130 |
+
row("ROE", rat.get("roe"), "pct"),
|
| 131 |
+
row("ROA", rat.get("roa"), "pct"),
|
| 132 |
+
row("ROIC", rat.get("roic"), "pct"),
|
| 133 |
+
"",
|
| 134 |
+
"=== LIQUIDITY & SOLVENCY ===",
|
| 135 |
+
row("Current Ratio", rat.get("current_ratio"), "num"),
|
| 136 |
+
row("Quick Ratio", rat.get("quick_ratio"), "num"),
|
| 137 |
+
row("Debt-to-Equity", rat.get("debt_to_equity"), "num"),
|
| 138 |
+
row("Net Debt/EBITDA", rat.get("net_debt_to_ebitda"), "num"),
|
| 139 |
+
row("Interest Coverage", rat.get("interest_coverage"), "num"),
|
| 140 |
+
"",
|
| 141 |
+
"=== EFFICIENCY ===",
|
| 142 |
+
row("Asset Turnover", rat.get("asset_turnover"), "num"),
|
| 143 |
+
row("DSO (days)", rat.get("days_sales_outstanding"), "num"),
|
| 144 |
+
row("DPO (days)", rat.get("days_payables"), "num"),
|
| 145 |
+
row("Cash Conversion Cycle",rat.get("cash_conversion_cycle"), "num"),
|
| 146 |
+
"",
|
| 147 |
+
"=== DUPONT DECOMPOSITION ===",
|
| 148 |
+
row("Net Margin", dp.get("net_margin"), "pct"),
|
| 149 |
+
row("Asset Turnover", dp.get("asset_turnover"), "num"),
|
| 150 |
+
row("Equity Multiplier", dp.get("equity_multiplier"), "num"),
|
| 151 |
+
row("ROE (DuPont)", dp.get("roe_computed"), "pct"),
|
| 152 |
+
"",
|
| 153 |
+
"=== GROWTH METRICS ===",
|
| 154 |
+
row("Revenue YoY", gr.get("revenue_yoy"), "pct"),
|
| 155 |
+
f" Revenue 5yr CAGR: {_pct(gr.get('revenue_cagr_5y'))}",
|
| 156 |
+
row("Net Income YoY", gr.get("net_income_yoy"), "pct"),
|
| 157 |
+
f" Net Income 5yr CAGR: {_pct(gr.get('net_income_cagr_5y'))}",
|
| 158 |
+
row("FCF YoY", gr.get("fcf_yoy"), "pct"),
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
# Valuation
|
| 162 |
+
val = data.get("valuation_snapshot", {})
|
| 163 |
+
if val:
|
| 164 |
+
lines += [
|
| 165 |
+
"",
|
| 166 |
+
"=== VALUATION SNAPSHOT ===",
|
| 167 |
+
f" P/E (TTM): {_num(val.get('pe_ttm'))}",
|
| 168 |
+
f" P/B: {_num(val.get('pb'))}",
|
| 169 |
+
f" EV/EBITDA: {_num(val.get('ev_ebitda'))}",
|
| 170 |
+
f" FCF Yield: {_pct(val.get('fcf_yield'))}",
|
| 171 |
+
f" Dividend Yield: {_pct(val.get('dividend_yield'))}",
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
# Peers
|
| 175 |
+
peers = data.get("peers", [])
|
| 176 |
+
if peers:
|
| 177 |
+
lines += ["", "=== PEER BENCHMARKING ==="]
|
| 178 |
+
for p in peers:
|
| 179 |
+
lines.append(
|
| 180 |
+
f" {p.get('name')} ({p.get('ticker')}): "
|
| 181 |
+
f"Rev={_money(p.get('revenue'), p.get('currency','USD'))} | "
|
| 182 |
+
f"OpM={_pct(p.get('operating_margin'))} | "
|
| 183 |
+
f"ROE={_pct(p.get('roe'))} | "
|
| 184 |
+
f"D/E={_num(p.get('debt_to_equity'))}"
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# Optional Annual Report Text (MD&A)
|
| 188 |
+
ar_text = data.get("annual_report_context", "")
|
| 189 |
+
if ar_text:
|
| 190 |
+
lines += ["", "=== ANNUAL REPORT EXCERPT (10-K MD&A) ==="]
|
| 191 |
+
lines.append(ar_text[:15000]) # Cap at 15k chars to save tokens
|
| 192 |
+
|
| 193 |
+
return "\n".join(lines)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# -- System prompt -------------------------------------------------------------
|
| 197 |
+
|
| 198 |
+
SYSTEM_PROMPT = """You are a senior financial analyst with expertise in Indian and global equity markets.
|
| 199 |
+
You write rigorous, opinionated, data-driven financial analysis reports.
|
| 200 |
+
|
| 201 |
+
Guidelines:
|
| 202 |
+
- Be specific: cite exact numbers from the data provided, not generic statements
|
| 203 |
+
- Be opinionated: state what the numbers actually mean, not just what they are
|
| 204 |
+
- Use Indian financial terminology where appropriate (Crores, Lakhs, SEBI, NSE/BSE)
|
| 205 |
+
- Flag data gaps honestly rather than speculating
|
| 206 |
+
- Keep commentary professional but readable
|
| 207 |
+
- Do NOT use markdown formatting in your response -- plain prose only
|
| 208 |
+
- Paragraph breaks only (use double newline to separate paragraphs)
|
| 209 |
+
- Numbers should be expressed in appropriate units (Cr for large INR amounts, B/M for USD)
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
# -- Synthesis & PPT Prompts ----------------------------------------------------------
|
| 213 |
+
|
| 214 |
+
SYNTHESIS_PROMPT = """You are a master financial editor. You have been given {num_drafts} different AI-generated drafts for the '{section}' section of a financial report.
|
| 215 |
+
Your job is to synthesize these drafts into a single, cohesive, authoritative, and brilliantly written section.
|
| 216 |
+
|
| 217 |
+
Guidelines:
|
| 218 |
+
- Combine the best insights and data points from all drafts.
|
| 219 |
+
- Resolve any contradictions by taking the most logical or well-supported viewpoint.
|
| 220 |
+
- Write in a professional, direct, and opinionated financial analyst tone.
|
| 221 |
+
- Do NOT mention that this is a synthesis of multiple drafts or AI models.
|
| 222 |
+
- Output ONLY the final synthesized text, with NO markdown formatting, NO introductory text, and NO commentary. Just the plain text paragraphs.
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
GENERATE_PPT_JSON = """You are a professional investment banker creating a pitch deck from financial data.
|
| 226 |
+
Your task is to generate the structure and content for a PowerPoint presentation summarizing the company's financial health.
|
| 227 |
+
Output a strict JSON array of slide objects. Each slide object MUST have:
|
| 228 |
+
- "title": A short, punchy title for the slide
|
| 229 |
+
- "bullets": An array of 3-5 strings, each containing a compelling insight, metric, or trend based on the data.
|
| 230 |
+
|
| 231 |
+
Do not include any markdown fences, introduction, or conclusion. Just the raw JSON array.
|
| 232 |
+
Focus on: Executive Summary, Revenue & Margin Trends, Cash Flow Health, Valuation, and Key Risks.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
# -- Section prompts -----------------------------------------------------------
|
| 236 |
+
|
| 237 |
+
SECTION_PROMPTS = {
|
| 238 |
+
"executive_summary": """
|
| 239 |
+
Write a 250-300 word executive summary of this company's financial health.
|
| 240 |
+
Answer these questions directly:
|
| 241 |
+
1. Is the business financially healthy or deteriorating?
|
| 242 |
+
2. What is the most important trend in the numbers?
|
| 243 |
+
3. How does it stack up against peers?
|
| 244 |
+
4. What is the key risk visible in the data?
|
| 245 |
+
5. What is the key opportunity?
|
| 246 |
+
Be direct and opinionated. No hedging.
|
| 247 |
+
""",
|
| 248 |
+
"company_profile": """
|
| 249 |
+
Write a 2-paragraph company profile covering:
|
| 250 |
+
- What the company does, its key business segments, and geographic presence
|
| 251 |
+
- Its position in the market, key products/services, major customers or clients if known
|
| 252 |
+
Use public knowledge about this company; supplement with the financial data provided.
|
| 253 |
+
""",
|
| 254 |
+
"industry_profile": """
|
| 255 |
+
Write a 2-paragraph industry profile for this company's sector/industry covering:
|
| 256 |
+
- Market size and structure (fragmented/consolidated, key players)
|
| 257 |
+
- Key growth drivers and headwinds for this industry in the Indian/global context
|
| 258 |
+
- Regulatory environment relevant to this industry
|
| 259 |
+
""",
|
| 260 |
+
"swot": """
|
| 261 |
+
Perform a rigorous SWOT analysis grounded in the financial data and industry knowledge.
|
| 262 |
+
Format your response as four sections:
|
| 263 |
+
|
| 264 |
+
STRENGTHS:
|
| 265 |
+
[3-4 specific, data-grounded strengths]
|
| 266 |
+
|
| 267 |
+
WEAKNESSES:
|
| 268 |
+
[3-4 specific, data-grounded weaknesses]
|
| 269 |
+
|
| 270 |
+
OPPORTUNITIES:
|
| 271 |
+
[3-4 specific opportunities for this company/industry]
|
| 272 |
+
|
| 273 |
+
THREATS:
|
| 274 |
+
[3-4 specific threats, including competitive and regulatory]
|
| 275 |
+
|
| 276 |
+
Be specific -- avoid generic SWOT points that could apply to any company.
|
| 277 |
+
""",
|
| 278 |
+
"industry_trends": """
|
| 279 |
+
Write 2-3 paragraphs on current and emerging trends in this company's industry, covering:
|
| 280 |
+
- Macro trends (digitization, ESG, AI, PLI schemes for Indian companies, etc.)
|
| 281 |
+
- Competitive dynamics and consolidation
|
| 282 |
+
- Technology disruption if applicable
|
| 283 |
+
- Regulatory changes (SEBI, RBI, sector-specific regulators for Indian companies)
|
| 284 |
+
Ground trends in the financial data where possible (e.g., if margins are compressing, is it industry-wide?).
|
| 285 |
+
""",
|
| 286 |
+
"trend_analysis_revenue": """
|
| 287 |
+
Write 2-3 paragraphs analyzing the revenue and profitability trends over the analysis period.
|
| 288 |
+
Specifically address:
|
| 289 |
+
- Revenue trajectory (acceleration/deceleration/volatility)
|
| 290 |
+
- Gross margin trend and what it reveals about pricing power
|
| 291 |
+
- Operating leverage (are operating margins improving as revenue grows?)
|
| 292 |
+
- Quality of earnings (is net income growing in line with revenue?)
|
| 293 |
+
Reference specific numbers from the data.
|
| 294 |
+
""",
|
| 295 |
+
"trend_analysis_balance_sheet": """
|
| 296 |
+
Write 2 paragraphs analyzing balance sheet strength and capital structure trends.
|
| 297 |
+
Address:
|
| 298 |
+
- Liquidity position (current ratio, cash levels)
|
| 299 |
+
- Leverage trajectory (is debt rising or falling relative to equity/earnings?)
|
| 300 |
+
- Asset quality (goodwill, receivables trends)
|
| 301 |
+
- Working capital efficiency
|
| 302 |
+
""",
|
| 303 |
+
"trend_analysis_cashflow": """
|
| 304 |
+
Write 2 paragraphs analyzing cash flow quality and capital allocation.
|
| 305 |
+
Address:
|
| 306 |
+
- OCF quality (does it consistently exceed net income, or lag it -- and why?)
|
| 307 |
+
- Capex intensity and investment cycle
|
| 308 |
+
- Free cash flow generation and its trajectory
|
| 309 |
+
- How is FCF being allocated (buybacks, dividends, debt repayment, acquisitions)?
|
| 310 |
+
""",
|
| 311 |
+
"ratio_commentary": """
|
| 312 |
+
Write 2-3 paragraphs interpreting the ratio analysis.
|
| 313 |
+
Focus on:
|
| 314 |
+
- Which ratios show the most significant trends (positive or negative)?
|
| 315 |
+
- Any ratios that are outliers vs. industry norms?
|
| 316 |
+
- What do the efficiency ratios (DSO, DPO, CCC) tell us about operational quality?
|
| 317 |
+
- DuPont decomposition: which driver is most responsible for ROE trends?
|
| 318 |
+
""",
|
| 319 |
+
"peer_commentary": """
|
| 320 |
+
Write 2 paragraphs benchmarking this company against its peers.
|
| 321 |
+
Address:
|
| 322 |
+
- Where does the company rank on the most important metrics for this industry?
|
| 323 |
+
- What explains the gaps vs. peers (structural, cyclical, or management decisions)?
|
| 324 |
+
- Is the company gaining or losing competitive position?
|
| 325 |
+
""",
|
| 326 |
+
"key_insights": """
|
| 327 |
+
List 4-6 key insights, one per line. Each insight must:
|
| 328 |
+
- Be substantive and specific (not generic)
|
| 329 |
+
- Reference a specific number or trend from the data
|
| 330 |
+
- Convey an analytical judgment, not just a fact
|
| 331 |
+
|
| 332 |
+
Format: One insight per line, starting with a dash (-).
|
| 333 |
+
""",
|
| 334 |
+
"risks": """
|
| 335 |
+
List the top 5-7 risks facing this company. For each risk, use this format:
|
| 336 |
+
CATEGORY | Risk description (specific, grounded in data or industry knowledge)
|
| 337 |
+
|
| 338 |
+
Categories to use: Financial, Business, Industry, Regulatory, ESG
|
| 339 |
+
""",
|
| 340 |
+
"things_to_watch": """
|
| 341 |
+
List 4-5 specific, monitorable metrics or events that would change the investment picture.
|
| 342 |
+
Format: One per line starting with a dash (-).
|
| 343 |
+
Be concrete: e.g., 'Watch for gross margin recovery above 30% in FY26' not 'watch margins'.
|
| 344 |
+
""",
|
| 345 |
+
"limitations": """
|
| 346 |
+
List any material analytical limitations in 3-5 bullet points. Include:
|
| 347 |
+
- Data gaps (which line items are missing or estimated)
|
| 348 |
+
- Comparability issues (fiscal year changes, acquisitions)
|
| 349 |
+
- Data source caveats (scraped vs. filed data)
|
| 350 |
+
- Any ratios that could not be computed meaningfully (negative equity, etc.)
|
| 351 |
+
Format: One per line starting with a dash (-).
|
| 352 |
+
""",
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# -- Gemini --------------------------------------------------------------------
|
| 357 |
+
|
| 358 |
+
def _gemini_generate(context: str, section: str, log_fn=None) -> str:
|
| 359 |
+
"""Generate using Gemini -- tries API key first, then Google OAuth login."""
|
| 360 |
+
prompt = f"{SYSTEM_PROMPT}\n\nFINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 361 |
+
|
| 362 |
+
# -- Path 1: API Key (new google-genai SDK) ------------------------------
|
| 363 |
+
if GEMINI_API_KEY:
|
| 364 |
+
try:
|
| 365 |
+
from google import genai
|
| 366 |
+
from google.genai import types as gtypes
|
| 367 |
+
client = genai.Client(api_key=GEMINI_API_KEY)
|
| 368 |
+
response = client.models.generate_content(
|
| 369 |
+
model=GEMINI_MODEL,
|
| 370 |
+
contents=prompt,
|
| 371 |
+
config=gtypes.GenerateContentConfig(temperature=0.2, max_output_tokens=1024),
|
| 372 |
+
)
|
| 373 |
+
return response.text.strip()
|
| 374 |
+
except Exception:
|
| 375 |
+
pass
|
| 376 |
+
# Fallback to old SDK
|
| 377 |
+
try:
|
| 378 |
+
import google.generativeai as genai_old
|
| 379 |
+
genai_old.configure(api_key=GEMINI_API_KEY)
|
| 380 |
+
model = genai_old.GenerativeModel(model_name=GEMINI_MODEL, system_instruction=SYSTEM_PROMPT)
|
| 381 |
+
response = model.generate_content(prompt)
|
| 382 |
+
return response.text.strip()
|
| 383 |
+
except Exception as e2:
|
| 384 |
+
if log_fn: log_fn(f"[Warning] Gemini failed for {section}: {str(e2)[:80]}")
|
| 385 |
+
return None
|
| 386 |
+
|
| 387 |
+
return None
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# -- OpenAI / ChatGPT ---------------------------------------------------------
|
| 392 |
+
|
| 393 |
+
def _openai_generate(context: str, section: str, log_fn=None) -> str:
|
| 394 |
+
try:
|
| 395 |
+
from openai import OpenAI
|
| 396 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 397 |
+
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 398 |
+
resp = client.chat.completions.create(
|
| 399 |
+
model=OPENAI_MODEL,
|
| 400 |
+
messages=[
|
| 401 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 402 |
+
{"role": "user", "content": prompt},
|
| 403 |
+
],
|
| 404 |
+
temperature=0.2,
|
| 405 |
+
max_tokens=1024,
|
| 406 |
+
)
|
| 407 |
+
return resp.choices[0].message.content.strip()
|
| 408 |
+
except Exception as e:
|
| 409 |
+
if log_fn: log_fn(f"[Warning] ChatGPT failed for {section}: {str(e)[:80]}")
|
| 410 |
+
return None
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
# -- Groq (free -- Llama 3.3 70B) ----------------------------------------------
|
| 414 |
+
|
| 415 |
+
def _groq_generate(context: str, section: str, log_fn=None) -> str:
|
| 416 |
+
"""Generate using Groq's OpenAI-compatible API (free tier, Llama 3.3 70B)."""
|
| 417 |
+
try:
|
| 418 |
+
from openai import OpenAI
|
| 419 |
+
client = OpenAI(
|
| 420 |
+
api_key=GROQ_API_KEY,
|
| 421 |
+
base_url="https://api.groq.com/openai/v1",
|
| 422 |
+
)
|
| 423 |
+
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 424 |
+
resp = client.chat.completions.create(
|
| 425 |
+
model=GROQ_MODEL,
|
| 426 |
+
messages=[
|
| 427 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 428 |
+
{"role": "user", "content": prompt},
|
| 429 |
+
],
|
| 430 |
+
temperature=0.2,
|
| 431 |
+
max_tokens=1024,
|
| 432 |
+
)
|
| 433 |
+
return resp.choices[0].message.content.strip()
|
| 434 |
+
except Exception as e:
|
| 435 |
+
if log_fn: log_fn(f"[Warning] Groq failed for {section}: {str(e)[:80]}")
|
| 436 |
+
return None
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# -- NVIDIA NIM (Llama 3.1 405B) ----------------------------------------------
|
| 440 |
+
|
| 441 |
+
def _nvidia_generate(context: str, section: str, log_fn=None) -> Optional[str]:
|
| 442 |
+
"""Generate using NVIDIA NIM OpenAI-compatible API."""
|
| 443 |
+
try:
|
| 444 |
+
from openai import OpenAI
|
| 445 |
+
client = OpenAI(
|
| 446 |
+
api_key=NVIDIA_API_KEY,
|
| 447 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
| 448 |
+
)
|
| 449 |
+
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 450 |
+
resp = client.chat.completions.create(
|
| 451 |
+
model=NVIDIA_MODEL,
|
| 452 |
+
messages=[
|
| 453 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 454 |
+
{"role": "user", "content": prompt},
|
| 455 |
+
],
|
| 456 |
+
temperature=0.2,
|
| 457 |
+
max_tokens=1024,
|
| 458 |
+
)
|
| 459 |
+
return resp.choices[0].message.content.strip()
|
| 460 |
+
except Exception as e:
|
| 461 |
+
if log_fn: log_fn(f"[Warning] NVIDIA NIM failed for {section}: {str(e)[:80]}")
|
| 462 |
+
return None
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# -- Claude --------------------------------------------------------------------
|
| 466 |
+
|
| 467 |
+
def _claude_generate(context: str, section: str, log_fn=None) -> str:
|
| 468 |
+
try:
|
| 469 |
+
import anthropic
|
| 470 |
+
client = anthropic.Anthropic(api_key=CLAUDE_API_KEY)
|
| 471 |
+
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}"
|
| 472 |
+
message = client.messages.create(
|
| 473 |
+
model=CLAUDE_MODEL,
|
| 474 |
+
max_tokens=1024,
|
| 475 |
+
system=SYSTEM_PROMPT,
|
| 476 |
+
messages=[{"role": "user", "content": prompt}],
|
| 477 |
+
)
|
| 478 |
+
return message.content[0].text.strip()
|
| 479 |
+
except Exception as e:
|
| 480 |
+
if log_fn: log_fn(f"[Warning] Claude failed for {section}: {str(e)[:80]}")
|
| 481 |
+
return None
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
# -- Hugging Face (DeepSeek) ---------------------------------------------------
|
| 485 |
+
|
| 486 |
+
def _hf_generate(context: str, section: str, log_fn=None) -> Optional[str]:
|
| 487 |
+
"""Generate using Hugging Face Inference API (DeepSeek)."""
|
| 488 |
+
hf_key = getattr(config, "HF_API_KEY", "")
|
| 489 |
+
if not hf_key:
|
| 490 |
+
return None
|
| 491 |
+
|
| 492 |
+
try:
|
| 493 |
+
from huggingface_hub import InferenceClient
|
| 494 |
+
client = InferenceClient(api_key=hf_key)
|
| 495 |
+
|
| 496 |
+
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}\n\nRespond ONLY with the requested analysis text."
|
| 497 |
+
|
| 498 |
+
messages = [
|
| 499 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 500 |
+
{"role": "user", "content": prompt}
|
| 501 |
+
]
|
| 502 |
+
|
| 503 |
+
# We use the recommended chat_completion method
|
| 504 |
+
response = client.chat_completion(
|
| 505 |
+
model="deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
|
| 506 |
+
messages=messages,
|
| 507 |
+
max_tokens=1024,
|
| 508 |
+
temperature=0.2
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
if response and response.choices:
|
| 512 |
+
text = response.choices[0].message.content
|
| 513 |
+
# Strip <think> tags if DeepSeek outputs them
|
| 514 |
+
import re
|
| 515 |
+
text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
|
| 516 |
+
return text
|
| 517 |
+
|
| 518 |
+
return None
|
| 519 |
+
|
| 520 |
+
except Exception as e:
|
| 521 |
+
err_str = str(e).lower()
|
| 522 |
+
if "429" in err_str or "too many" in err_str or "rate limit" in err_str:
|
| 523 |
+
raise Exception("429 Too Many Requests") # Let the retry wrapper catch it
|
| 524 |
+
|
| 525 |
+
if log_fn: log_fn(f"[Warning] HF DeepSeek failed for {section}: {str(e)[:80]}")
|
| 526 |
+
return None
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# -- Parse structured sections -------------------------------------------------
|
| 530 |
+
|
| 531 |
+
def _parse_swot(text: str) -> Dict:
|
| 532 |
+
"""Parse SWOT text into a structured dict."""
|
| 533 |
+
result = {"strengths": [], "weaknesses": [], "opportunities": [], "threats": [], "raw": text}
|
| 534 |
+
current = None
|
| 535 |
+
for line in text.split("\n"):
|
| 536 |
+
l = line.strip()
|
| 537 |
+
if l.upper().startswith("STRENGTH"):
|
| 538 |
+
current = "strengths"
|
| 539 |
+
elif l.upper().startswith("WEAKNESS"):
|
| 540 |
+
current = "weaknesses"
|
| 541 |
+
elif l.upper().startswith("OPPORTUNIT"):
|
| 542 |
+
current = "opportunities"
|
| 543 |
+
elif l.upper().startswith("THREAT"):
|
| 544 |
+
current = "threats"
|
| 545 |
+
elif current and l and not l.upper() in ("STRENGTHS:", "WEAKNESSES:", "OPPORTUNITIES:", "THREATS:"):
|
| 546 |
+
clean = l.lstrip("-β’* ")
|
| 547 |
+
if clean:
|
| 548 |
+
result[current].append(clean)
|
| 549 |
+
return result
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def _parse_bullets(text: str) -> List[str]:
|
| 553 |
+
"""Parse a bulleted list response into a list of strings."""
|
| 554 |
+
items = []
|
| 555 |
+
for line in text.split("\n"):
|
| 556 |
+
l = line.strip().lstrip("-β’* ")
|
| 557 |
+
if l:
|
| 558 |
+
items.append(l)
|
| 559 |
+
return items
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _parse_risks(text: str) -> List[Dict]:
|
| 563 |
+
"""Parse risk list into categorized dicts."""
|
| 564 |
+
risks = []
|
| 565 |
+
for line in text.split("\n"):
|
| 566 |
+
l = line.strip().lstrip("-β’* ")
|
| 567 |
+
if "|" in l:
|
| 568 |
+
parts = l.split("|", 1)
|
| 569 |
+
risks.append({"category": parts[0].strip(), "description": parts[1].strip()})
|
| 570 |
+
elif l:
|
| 571 |
+
risks.append({"category": "General", "description": l})
|
| 572 |
+
return risks
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
# -- Main entry point ----------------------------------------------------------
|
| 576 |
+
|
| 577 |
+
def generate_narrative(
|
| 578 |
+
data: Dict,
|
| 579 |
+
meta: Dict,
|
| 580 |
+
models: List[str],
|
| 581 |
+
log_fn=None,
|
| 582 |
+
) -> Dict:
|
| 583 |
+
"""
|
| 584 |
+
Generate full narrative analysis using selected AI models.
|
| 585 |
+
|
| 586 |
+
Args:
|
| 587 |
+
data: Calculated financial data dict.
|
| 588 |
+
meta: CompanyMeta.to_dict()
|
| 589 |
+
models: List of model names, e.g. ['gemini', 'claude'] or ['gemini']
|
| 590 |
+
log_fn: Optional progress callback.
|
| 591 |
+
|
| 592 |
+
Returns:
|
| 593 |
+
Dict with all narrative fields populated.
|
| 594 |
+
"""
|
| 595 |
+
def log(msg):
|
| 596 |
+
if log_fn:
|
| 597 |
+
log_fn(msg)
|
| 598 |
+
|
| 599 |
+
use_gemini = "gemini" in models and bool(GEMINI_API_KEY)
|
| 600 |
+
use_claude = "claude" in models and bool(CLAUDE_API_KEY)
|
| 601 |
+
use_openai = "openai" in models and bool(OPENAI_API_KEY)
|
| 602 |
+
use_groq = "groq" in models and bool(GROQ_API_KEY)
|
| 603 |
+
use_nvidia = "nvidia" in models and bool(NVIDIA_API_KEY)
|
| 604 |
+
use_hf = "huggingface" in models and bool(getattr(config, "HF_API_KEY", ""))
|
| 605 |
+
|
| 606 |
+
if not any([use_gemini, use_claude, use_openai, use_groq, use_nvidia, use_hf]):
|
| 607 |
+
log("No AI models configured. Running data-only analysis (no narrative).")
|
| 608 |
+
return _empty_narrative()
|
| 609 |
+
|
| 610 |
+
context = _build_context(data, meta)
|
| 611 |
+
active = [m for m, ok in [("Gemini",use_gemini),("Claude",use_claude),("ChatGPT",use_openai),("Groq",use_groq),("NVIDIA",use_nvidia),("HF-DeepSeek",use_hf)] if ok]
|
| 612 |
+
log(f"Generating AI narrative ({', '.join(active)}) ...")
|
| 613 |
+
|
| 614 |
+
def _synthesize_drafts(section: str, drafts: Dict[str, str]) -> str:
|
| 615 |
+
"""Use the best available model to merge drafts into a single consensus response."""
|
| 616 |
+
# Pick the synthesizer based on perceived quality/capability
|
| 617 |
+
synthesizer = None
|
| 618 |
+
if use_openai: synthesizer = ("ChatGPT", _openai_generate)
|
| 619 |
+
elif use_claude: synthesizer = ("Claude", _claude_generate)
|
| 620 |
+
elif use_nvidia: synthesizer = ("NVIDIA", _nvidia_generate)
|
| 621 |
+
elif use_gemini: synthesizer = ("Gemini", _gemini_generate)
|
| 622 |
+
elif use_groq: synthesizer = ("Groq", _groq_generate)
|
| 623 |
+
elif use_hf: synthesizer = ("HF-DeepSeek", _hf_generate)
|
| 624 |
+
|
| 625 |
+
if not synthesizer:
|
| 626 |
+
return list(drafts.values())[0]
|
| 627 |
+
|
| 628 |
+
name, fn = synthesizer
|
| 629 |
+
log(f" > Synthesizing {len(drafts)} drafts using {name}...")
|
| 630 |
+
|
| 631 |
+
draft_text = "\n\n".join([f"--- Draft from {agent} ---\n{text}" for agent, text in drafts.items()])
|
| 632 |
+
prompt = SYNTHESIS_PROMPT.format(section=section, num_drafts=len(drafts)) + "\n\n" + draft_text
|
| 633 |
+
|
| 634 |
+
# We reuse the context parameter to pass the prompt, and bypass the section wrapping by mocking it
|
| 635 |
+
# Actually, let's just create a custom direct call for synthesis to avoid section wrapping issues.
|
| 636 |
+
# But to reuse the functions easily, we can temporarily override the SECTION_PROMPTS.
|
| 637 |
+
original_prompt = SECTION_PROMPTS.get(section, "")
|
| 638 |
+
SECTION_PROMPTS[section] = prompt
|
| 639 |
+
try:
|
| 640 |
+
res = fn("", section) # Context empty because prompt contains everything
|
| 641 |
+
finally:
|
| 642 |
+
SECTION_PROMPTS[section] = original_prompt
|
| 643 |
+
|
| 644 |
+
if res: return res
|
| 645 |
+
|
| 646 |
+
# If synthesis fails, fallback to simple concatenation
|
| 647 |
+
return "\n\n".join([f"[{a}]\n{t}" for a, t in drafts.items()])
|
| 648 |
+
|
| 649 |
+
import concurrent.futures
|
| 650 |
+
|
| 651 |
+
def gen(section: str) -> str:
|
| 652 |
+
tasks = {}
|
| 653 |
+
# Max workers set to 3 to avoid extreme rate limits on free tiers (like Groq's 30 RPM)
|
| 654 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
| 655 |
+
if use_gemini: tasks[executor.submit(_with_retries(_gemini_generate, log_fn), context, section)] = "Gemini"
|
| 656 |
+
if use_claude: tasks[executor.submit(_with_retries(_claude_generate, log_fn), context, section)] = "Claude"
|
| 657 |
+
if use_openai: tasks[executor.submit(_with_retries(_openai_generate, log_fn), context, section)] = "ChatGPT"
|
| 658 |
+
if use_groq: tasks[executor.submit(_with_retries(_groq_generate, log_fn), context, section)] = "Groq"
|
| 659 |
+
if use_nvidia: tasks[executor.submit(_with_retries(_nvidia_generate, log_fn), context, section)] = "NVIDIA"
|
| 660 |
+
if use_hf: tasks[executor.submit(_with_retries(_hf_generate, log_fn), context, section)] = "HF-DeepSeek"
|
| 661 |
+
|
| 662 |
+
drafts = {}
|
| 663 |
+
for future in concurrent.futures.as_completed(tasks):
|
| 664 |
+
name = tasks[future]
|
| 665 |
+
try:
|
| 666 |
+
res = future.result()
|
| 667 |
+
if res: drafts[name] = res
|
| 668 |
+
except Exception as e:
|
| 669 |
+
if log_fn: log_fn(f"[Warning] {name} thread failed: {e}")
|
| 670 |
+
|
| 671 |
+
if len(drafts) == 0:
|
| 672 |
+
return ""
|
| 673 |
+
if len(drafts) == 1:
|
| 674 |
+
return list(drafts.values())[0]
|
| 675 |
+
|
| 676 |
+
return _synthesize_drafts(section, drafts)
|
| 677 |
+
|
| 678 |
+
def _generate_ppt_json() -> str:
|
| 679 |
+
# Pick the smartest model available for structured JSON generation
|
| 680 |
+
synthesizer = None
|
| 681 |
+
if use_openai: synthesizer = ("ChatGPT", _openai_generate)
|
| 682 |
+
elif use_claude: synthesizer = ("Claude", _claude_generate)
|
| 683 |
+
elif use_gemini: synthesizer = ("Gemini", _gemini_generate)
|
| 684 |
+
elif use_nvidia: synthesizer = ("NVIDIA", _nvidia_generate)
|
| 685 |
+
elif use_groq: synthesizer = ("Groq", _groq_generate)
|
| 686 |
+
|
| 687 |
+
if not synthesizer:
|
| 688 |
+
return ""
|
| 689 |
+
|
| 690 |
+
name, fn = synthesizer
|
| 691 |
+
log(f"\n[PPT] Generating PowerPoint Structure using {name} ...")
|
| 692 |
+
|
| 693 |
+
original_prompt = SECTION_PROMPTS.get("ppt_json", "")
|
| 694 |
+
SECTION_PROMPTS["ppt_json"] = GENERATE_PPT_JSON
|
| 695 |
+
try:
|
| 696 |
+
res = fn(context, "ppt_json")
|
| 697 |
+
finally:
|
| 698 |
+
if "ppt_json" in SECTION_PROMPTS:
|
| 699 |
+
del SECTION_PROMPTS["ppt_json"]
|
| 700 |
+
|
| 701 |
+
return res if res else ""
|
| 702 |
+
|
| 703 |
+
log(" > Executing section: Executive Summary")
|
| 704 |
+
exec_summary = gen("executive_summary")
|
| 705 |
+
|
| 706 |
+
log(" Generating company profile ...")
|
| 707 |
+
company_overview = gen("company_profile")
|
| 708 |
+
|
| 709 |
+
log(" Generating industry profile ...")
|
| 710 |
+
industry_profile = gen("industry_profile")
|
| 711 |
+
|
| 712 |
+
log(" Generating SWOT ...")
|
| 713 |
+
swot_raw = gen("swot")
|
| 714 |
+
swot = _parse_swot(swot_raw)
|
| 715 |
+
|
| 716 |
+
log(" Generating industry trends ...")
|
| 717 |
+
industry_trends = gen("industry_trends")
|
| 718 |
+
|
| 719 |
+
log(" Generating trend analysis ...")
|
| 720 |
+
trend_revenue = gen("trend_analysis_revenue")
|
| 721 |
+
trend_bs = gen("trend_analysis_balance_sheet")
|
| 722 |
+
trend_cf = gen("trend_analysis_cashflow")
|
| 723 |
+
|
| 724 |
+
log(" Generating ratio commentary ...")
|
| 725 |
+
ratio_commentary = gen("ratio_commentary")
|
| 726 |
+
|
| 727 |
+
log(" Generating peer commentary ...")
|
| 728 |
+
peer_commentary = gen("peer_commentary")
|
| 729 |
+
|
| 730 |
+
log(" Generating insights ...")
|
| 731 |
+
insights_raw = gen("key_insights")
|
| 732 |
+
insights = _parse_bullets(insights_raw)
|
| 733 |
+
|
| 734 |
+
log(" Generating risks ...")
|
| 735 |
+
risks_raw = gen("risks")
|
| 736 |
+
risks = _parse_risks(risks_raw)
|
| 737 |
+
|
| 738 |
+
log(" Generating things to watch ...")
|
| 739 |
+
watch_raw = gen("things_to_watch")
|
| 740 |
+
things_to_watch = _parse_bullets(watch_raw)
|
| 741 |
+
|
| 742 |
+
log(" Generating limitations ...")
|
| 743 |
+
lim_raw = gen("limitations")
|
| 744 |
+
limitations = _parse_bullets(lim_raw)
|
| 745 |
+
|
| 746 |
+
ppt_json = _generate_ppt_json()
|
| 747 |
+
|
| 748 |
+
log(" [OK] AI narrative generation complete")
|
| 749 |
+
|
| 750 |
+
return {
|
| 751 |
+
"executive_summary": exec_summary,
|
| 752 |
+
"company_overview": company_overview,
|
| 753 |
+
"industry_profile": industry_profile,
|
| 754 |
+
"swot": swot,
|
| 755 |
+
"industry_trends": industry_trends,
|
| 756 |
+
"trend_analysis": {
|
| 757 |
+
"revenue_and_profitability": trend_revenue,
|
| 758 |
+
"balance_sheet_strength": trend_bs,
|
| 759 |
+
"cash_flow_generation": trend_cf,
|
| 760 |
+
},
|
| 761 |
+
"ratio_analysis_commentary": ratio_commentary,
|
| 762 |
+
"peer_comparison_commentary": peer_commentary,
|
| 763 |
+
"key_insights": insights,
|
| 764 |
+
"risks": risks,
|
| 765 |
+
"things_to_watch": things_to_watch,
|
| 766 |
+
"limitations_and_caveats": limitations,
|
| 767 |
+
"models_used": models,
|
| 768 |
+
"ppt_json": ppt_json,
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def _empty_narrative() -> Dict:
|
| 773 |
+
return {
|
| 774 |
+
"executive_summary": "AI narrative not generated (no API keys configured).",
|
| 775 |
+
"company_overview": "",
|
| 776 |
+
"industry_profile": "",
|
| 777 |
+
"swot": {"strengths": [], "weaknesses": [], "opportunities": [], "threats": []},
|
| 778 |
+
"industry_trends": "",
|
| 779 |
+
"trend_analysis": {"revenue_and_profitability": "", "balance_sheet_strength": "", "cash_flow_generation": ""},
|
| 780 |
+
"ratio_analysis_commentary": "",
|
| 781 |
+
"peer_comparison_commentary":"",
|
| 782 |
+
"key_insights": [],
|
| 783 |
+
"risks": [],
|
| 784 |
+
"things_to_watch": [],
|
| 785 |
+
"limitations_and_caveats": [],
|
| 786 |
+
"models_used": [],
|
| 787 |
+
"ppt_json": "",
|
| 788 |
+
}
|
pipeline/calculator.py
CHANGED
|
@@ -1,361 +1,361 @@
|
|
| 1 |
-
"""
|
| 2 |
-
pipeline/calculator.py
|
| 3 |
-
growth metrics, and scale numbers for display.
|
| 4 |
-
"""
|
| 5 |
-
from __future__ import annotations
|
| 6 |
-
|
| 7 |
-
import math
|
| 8 |
-
from typing import Any, Dict, List, Optional, Tuple
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def _safe_div(num, den, default=None):
|
| 12 |
-
"""Safe division returning default if denominator is None/zero."""
|
| 13 |
-
try:
|
| 14 |
-
if num is None or den is None:
|
| 15 |
-
return default
|
| 16 |
-
if den == 0:
|
| 17 |
-
return default
|
| 18 |
-
return num / den
|
| 19 |
-
except (TypeError, ZeroDivisionError):
|
| 20 |
-
return default
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def _avg(a, b):
|
| 24 |
-
"""Average of two values, None if either is None."""
|
| 25 |
-
if a is None or b is None:
|
| 26 |
-
return None
|
| 27 |
-
return (a + b) / 2
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
def _pct_change(current, previous):
|
| 31 |
-
"""Year-over-year % change."""
|
| 32 |
-
if current is None or previous is None or previous == 0:
|
| 33 |
-
return None
|
| 34 |
-
return (current - previous) / abs(previous)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _cagr(start, end, n):
|
| 38 |
-
"""Compound annual growth rate over n periods."""
|
| 39 |
-
if start is None or end is None or n <= 0:
|
| 40 |
-
return None
|
| 41 |
-
if start <= 0 or end < 0:
|
| 42 |
-
return None
|
| 43 |
-
try:
|
| 44 |
-
return (end / start) ** (1 / n) - 1
|
| 45 |
-
except (ZeroDivisionError, ValueError):
|
| 46 |
-
return None
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def _series(data_dict: Dict, key: str, n: int) -> List[Optional[float]]:
|
| 50 |
-
"""Extract a time-series list, padded/trimmed to length n."""
|
| 51 |
-
vals = data_dict.get(key, [])
|
| 52 |
-
if len(vals) < n:
|
| 53 |
-
vals = vals + [None] * (n - len(vals))
|
| 54 |
-
return vals[:n]
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
def auto_scale(values: List[Optional[float]], currency: str) -> Tuple[List[Optional[float]], str]:
|
| 60 |
-
"""
|
| 61 |
-
Scale a list of monetary values to a human-readable unit.
|
| 62 |
-
Returns (scaled_values, unit_label).
|
| 63 |
-
"""
|
| 64 |
-
non_null = [abs(v) for v in values if v is not None and v != 0]
|
| 65 |
-
if not non_null:
|
| 66 |
-
return values, ""
|
| 67 |
-
mag = max(non_null)
|
| 68 |
-
|
| 69 |
-
if currency == "INR":
|
| 70 |
-
if mag >= 1e7: # >= 1 Crore (in thousands
|
| 71 |
-
# FMP stores in thousands for Indian, screener in Crores
|
| 72 |
-
# We'll just label appropriately
|
| 73 |
-
if mag >= 1e9:
|
| 74 |
-
factor, label = 1e7, "βΉ Crores"
|
| 75 |
-
elif mag >= 1e5:
|
| 76 |
-
factor, label = 1e5, "βΉ Lakhs"
|
| 77 |
-
else:
|
| 78 |
-
factor, label = 1e3, "βΉ Thousands"
|
| 79 |
-
else:
|
| 80 |
-
factor, label = 1, "βΉ"
|
| 81 |
-
# Most FMP returns in actual currency value (not thousands)
|
| 82 |
-
# screener returns in Crores already
|
| 83 |
-
return values, label
|
| 84 |
-
else:
|
| 85 |
-
# USD / other
|
| 86 |
-
if mag >= 1e9:
|
| 87 |
-
factor, label = 1e9, "Billions"
|
| 88 |
-
elif mag >= 1e6:
|
| 89 |
-
factor, label = 1e6, "Millions"
|
| 90 |
-
elif mag >= 1e3:
|
| 91 |
-
factor, label = 1e3, "Thousands"
|
| 92 |
-
else:
|
| 93 |
-
factor, label = 1, ""
|
| 94 |
-
scaled = [v / factor if v is not None else None for v in values]
|
| 95 |
-
return scaled, label
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def smart_format(value: Optional[float], currency: str = "USD") -> str:
|
| 99 |
-
"""Format a single monetary value with smart units."""
|
| 100 |
-
if value is None:
|
| 101 |
-
return "N/A"
|
| 102 |
-
av = abs(value)
|
| 103 |
-
if currency == "INR":
|
| 104 |
-
if av >= 1e7:
|
| 105 |
-
return f"βΉ{value/1e7:,.2f} Cr"
|
| 106 |
-
elif av >= 1e5:
|
| 107 |
-
return f"βΉ{value/1e5:,.2f} L"
|
| 108 |
-
else:
|
| 109 |
-
return f"βΉ{value:,.0f}"
|
| 110 |
-
else:
|
| 111 |
-
sym = "$" if currency == "USD" else ""
|
| 112 |
-
if av >= 1e9:
|
| 113 |
-
return f"{sym}{value/1e9:,.2f}B"
|
| 114 |
-
elif av >= 1e6:
|
| 115 |
-
return f"{sym}{value/1e6:,.2f}M"
|
| 116 |
-
elif av >= 1e3:
|
| 117 |
-
return f"{sym}{value/1e3:,.2f}K"
|
| 118 |
-
else:
|
| 119 |
-
return f"{sym}{value:,.2f}"
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
#
|
| 123 |
-
|
| 124 |
-
def calculate(financial_data: Dict, meta_dict: Dict) -> Dict:
|
| 125 |
-
"""
|
| 126 |
-
Compute all ratios, DuPont, growth metrics from raw financial data.
|
| 127 |
-
|
| 128 |
-
Args:
|
| 129 |
-
financial_data: Output of fetcher.fetch_all()
|
| 130 |
-
meta_dict: CompanyMeta.to_dict()
|
| 131 |
-
|
| 132 |
-
Returns:
|
| 133 |
-
Complete analysis dict ready for analyst.py and builders.
|
| 134 |
-
"""
|
| 135 |
-
years = financial_data.get("years", [])
|
| 136 |
-
n = len(years)
|
| 137 |
-
if n == 0:
|
| 138 |
-
return financial_data # Nothing to compute
|
| 139 |
-
|
| 140 |
-
inc = financial_data.get("income_statement", {})
|
| 141 |
-
bal = financial_data.get("balance_sheet", {})
|
| 142 |
-
cf = financial_data.get("cash_flow", {})
|
| 143 |
-
currency = financial_data.get("currency", meta_dict.get("currency", "USD"))
|
| 144 |
-
|
| 145 |
-
def S(key, src=None):
|
| 146 |
-
src = src or inc
|
| 147 |
-
return _series(src, key, n)
|
| 148 |
-
|
| 149 |
-
#
|
| 150 |
-
revenue = S("revenue")
|
| 151 |
-
cogs = S("cost_of_revenue")
|
| 152 |
-
gross_profit = S("gross_profit")
|
| 153 |
-
op_income = S("operating_income")
|
| 154 |
-
ebitda = S("ebitda")
|
| 155 |
-
da = S("depreciation_amort")
|
| 156 |
-
interest_exp = S("interest_expense")
|
| 157 |
-
pretax_income = S("pretax_income")
|
| 158 |
-
tax_expense = S("tax_expense")
|
| 159 |
-
net_income = S("net_income")
|
| 160 |
-
diluted_eps = S("diluted_eps")
|
| 161 |
-
diluted_shares = S("diluted_shares")
|
| 162 |
-
|
| 163 |
-
total_assets = S("total_assets", bal)
|
| 164 |
-
total_equity = S("total_equity", bal)
|
| 165 |
-
total_liabilities = S("total_liabilities", bal)
|
| 166 |
-
total_curr_assets = S("total_current_assets", bal)
|
| 167 |
-
total_curr_liab = S("total_current_liabilities", bal)
|
| 168 |
-
inventory = S("inventory", bal)
|
| 169 |
-
receivables = S("receivables", bal)
|
| 170 |
-
payables = S("accounts_payable", bal)
|
| 171 |
-
short_debt = S("short_term_debt", bal)
|
| 172 |
-
long_debt = S("long_term_debt", bal)
|
| 173 |
-
cash = S("cash_and_equivalents", bal)
|
| 174 |
-
st_inv = S("short_term_investments", bal)
|
| 175 |
-
|
| 176 |
-
cfo = S("cash_from_operations", cf)
|
| 177 |
-
capex = S("capex", cf)
|
| 178 |
-
fcf = S("free_cash_flow", cf)
|
| 179 |
-
dividends = S("dividends_paid", cf)
|
| 180 |
-
buybacks = S("stock_buybacks", cf)
|
| 181 |
-
|
| 182 |
-
# Compute EBITDA if missing
|
| 183 |
-
for i in range(n):
|
| 184 |
-
if ebitda[i] is None and op_income[i] is not None and da[i] is not None:
|
| 185 |
-
ebitda[i] = op_income[i] + da[i]
|
| 186 |
-
|
| 187 |
-
# Compute FCF if missing
|
| 188 |
-
for i in range(n):
|
| 189 |
-
if fcf[i] is None and cfo[i] is not None and capex[i] is not None:
|
| 190 |
-
fcf[i] = cfo[i] + capex[i] # capex is usually negative in FMP
|
| 191 |
-
|
| 192 |
-
# Total debt
|
| 193 |
-
total_debt = [
|
| 194 |
-
(s or 0) + (l or 0) if (s is not None or l is not None) else None
|
| 195 |
-
for s, l in zip(short_debt, long_debt)
|
| 196 |
-
]
|
| 197 |
-
|
| 198 |
-
# Effective tax rate
|
| 199 |
-
eff_tax_rate = [
|
| 200 |
-
_safe_div(t, p) if p and p > 0 else None
|
| 201 |
-
for t, p in zip(tax_expense, pretax_income)
|
| 202 |
-
]
|
| 203 |
-
|
| 204 |
-
# NOPAT
|
| 205 |
-
nopat = [
|
| 206 |
-
o * (1 - (t or 0)) if o is not None else None
|
| 207 |
-
for o, t in zip(op_income, eff_tax_rate)
|
| 208 |
-
]
|
| 209 |
-
|
| 210 |
-
# Invested capital = Total equity + Total debt - Cash
|
| 211 |
-
inv_capital = [
|
| 212 |
-
(e or 0) + (d or 0) - (c or 0)
|
| 213 |
-
if e is not None or d is not None else None
|
| 214 |
-
for e, d, c in zip(total_equity, total_debt, cash)
|
| 215 |
-
]
|
| 216 |
-
|
| 217 |
-
#
|
| 218 |
-
gross_margin = [_safe_div(g, r) for g, r in zip(gross_profit, revenue)]
|
| 219 |
-
op_margin = [_safe_div(o, r) for o, r in zip(op_income, revenue)]
|
| 220 |
-
ebitda_margin = [_safe_div(e, r) for e, r in zip(ebitda, revenue)]
|
| 221 |
-
net_margin = [_safe_div(n_, r) for n_, r in zip(net_income, revenue)]
|
| 222 |
-
|
| 223 |
-
# ROE, ROA, ROIC use averages
|
| 224 |
-
roe = [_safe_div(n_, _avg(e0, e1)) for n_, e0, e1 in zip(
|
| 225 |
-
net_income, [None] + total_equity[:-1], total_equity)]
|
| 226 |
-
roa = [_safe_div(n_, _avg(a0, a1)) for n_, a0, a1 in zip(
|
| 227 |
-
net_income, [None] + total_assets[:-1], total_assets)]
|
| 228 |
-
roic = [_safe_div(no, _avg(ic0, ic1)) for no, ic0, ic1 in zip(
|
| 229 |
-
nopat, [None] + inv_capital[:-1], inv_capital)]
|
| 230 |
-
|
| 231 |
-
#
|
| 232 |
-
current_ratio = [_safe_div(ca, cl) for ca, cl in zip(total_curr_assets, total_curr_liab)]
|
| 233 |
-
quick_ratio = [
|
| 234 |
-
_safe_div((ca or 0) - (inv or 0), cl)
|
| 235 |
-
if ca is not None and cl else None
|
| 236 |
-
for ca, inv, cl in zip(total_curr_assets, inventory, total_curr_liab)
|
| 237 |
-
]
|
| 238 |
-
cash_ratio = [
|
| 239 |
-
_safe_div((c or 0) + (si or 0), cl)
|
| 240 |
-
if cl else None
|
| 241 |
-
for c, si, cl in zip(cash, st_inv, total_curr_liab)
|
| 242 |
-
]
|
| 243 |
-
|
| 244 |
-
#
|
| 245 |
-
debt_to_equity = [_safe_div(d, e) for d, e in zip(total_debt, total_equity)]
|
| 246 |
-
debt_to_assets = [_safe_div(d, a) for d, a in zip(total_debt, total_assets)]
|
| 247 |
-
net_debt = [(d or 0) - (c or 0) - (si or 0) if d is not None else None
|
| 248 |
-
for d, c, si in zip(total_debt, cash, st_inv)]
|
| 249 |
-
net_debt_ebitda = [_safe_div(nd, e) for nd, e in zip(net_debt, ebitda)]
|
| 250 |
-
interest_cov = [_safe_div(o, ie) for o, ie in zip(op_income, interest_exp)]
|
| 251 |
-
|
| 252 |
-
#
|
| 253 |
-
asset_turnover = [_safe_div(r, _avg(a0, a1)) for r, a0, a1 in zip(
|
| 254 |
-
revenue, [None] + total_assets[:-1], total_assets)]
|
| 255 |
-
inv_turnover = [_safe_div(c, _avg(i0, i1)) for c, i0, i1 in zip(
|
| 256 |
-
cogs, [None] + inventory[:-1], inventory)]
|
| 257 |
-
days_inv = [_safe_div(365, it) for it in inv_turnover]
|
| 258 |
-
rec_turnover = [_safe_div(r, _avg(rc0, rc1)) for r, rc0, rc1 in zip(
|
| 259 |
-
revenue, [None] + receivables[:-1], receivables)]
|
| 260 |
-
days_sales = [_safe_div(365, rt) for rt in rec_turnover]
|
| 261 |
-
pay_turnover = [_safe_div(c, _avg(p0, p1)) for c, p0, p1 in zip(
|
| 262 |
-
cogs, [None] + payables[:-1], payables)]
|
| 263 |
-
days_payable = [_safe_div(365, pt) for pt in pay_turnover]
|
| 264 |
-
ccc = [
|
| 265 |
-
(di or 0) + (ds or 0) - (dp or 0)
|
| 266 |
-
if di is not None and ds is not None and dp is not None else None
|
| 267 |
-
for di, ds, dp in zip(days_inv, days_sales, days_payable)
|
| 268 |
-
]
|
| 269 |
-
|
| 270 |
-
#
|
| 271 |
-
ocf_to_ni = [_safe_div(c, n_) for c, n_ in zip(cfo, net_income)]
|
| 272 |
-
fcf_margin_ = [_safe_div(f, r) for f, r in zip(fcf, revenue)]
|
| 273 |
-
fcf_conversion = [_safe_div(f, n_) for f, n_ in zip(fcf, net_income)]
|
| 274 |
-
capex_intensity = [_safe_div(abs(c) if c else None, r) for c, r in zip(capex, revenue)]
|
| 275 |
-
|
| 276 |
-
#
|
| 277 |
-
def yoy(arr):
|
| 278 |
-
result = [None]
|
| 279 |
-
for i in range(1, len(arr)):
|
| 280 |
-
result.append(_pct_change(arr[i], arr[i-1]))
|
| 281 |
-
return result
|
| 282 |
-
|
| 283 |
-
rev_yoy = yoy(revenue)
|
| 284 |
-
op_yoy = yoy(op_income)
|
| 285 |
-
ni_yoy = yoy(net_income)
|
| 286 |
-
eps_yoy = yoy(diluted_eps)
|
| 287 |
-
fcf_yoy = yoy(fcf)
|
| 288 |
-
|
| 289 |
-
def cagr_5y(arr):
|
| 290 |
-
valid = [v for v in arr if v is not None]
|
| 291 |
-
if len(valid) < 2:
|
| 292 |
-
return None
|
| 293 |
-
return _cagr(valid[0], valid[-1], len(valid) - 1)
|
| 294 |
-
|
| 295 |
-
growth_metrics = {
|
| 296 |
-
"revenue_yoy": rev_yoy,
|
| 297 |
-
"revenue_cagr_5y": cagr_5y(revenue),
|
| 298 |
-
"operating_income_yoy": op_yoy,
|
| 299 |
-
"operating_income_cagr_5y": cagr_5y(op_income),
|
| 300 |
-
"net_income_yoy": ni_yoy,
|
| 301 |
-
"net_income_cagr_5y": cagr_5y(net_income),
|
| 302 |
-
"eps_yoy": eps_yoy,
|
| 303 |
-
"eps_cagr_5y": cagr_5y(diluted_eps),
|
| 304 |
-
"fcf_yoy": fcf_yoy,
|
| 305 |
-
"fcf_cagr_5y": cagr_5y(fcf),
|
| 306 |
-
}
|
| 307 |
-
|
| 308 |
-
#
|
| 309 |
-
# ROE = Net Margin Γ Asset Turnover Γ Equity Multiplier
|
| 310 |
-
equity_multiplier = [_safe_div(a, e) for a, e in zip(total_assets, total_equity)]
|
| 311 |
-
dupont = {
|
| 312 |
-
"net_margin": net_margin,
|
| 313 |
-
"asset_turnover": asset_turnover,
|
| 314 |
-
"equity_multiplier": equity_multiplier,
|
| 315 |
-
"roe_computed": [
|
| 316 |
-
(nm or 0) * (at or 0) * (em or 0)
|
| 317 |
-
if nm is not None and at is not None and em is not None else None
|
| 318 |
-
for nm, at, em in zip(net_margin, asset_turnover, equity_multiplier)
|
| 319 |
-
],
|
| 320 |
-
"roe_reported": roe,
|
| 321 |
-
}
|
| 322 |
-
|
| 323 |
-
#
|
| 324 |
-
ratios = {
|
| 325 |
-
"gross_margin": gross_margin,
|
| 326 |
-
"operating_margin": op_margin,
|
| 327 |
-
"ebitda_margin": ebitda_margin,
|
| 328 |
-
"net_margin": net_margin,
|
| 329 |
-
"roe": roe,
|
| 330 |
-
"roa": roa,
|
| 331 |
-
"roic": roic,
|
| 332 |
-
"current_ratio": current_ratio,
|
| 333 |
-
"quick_ratio": quick_ratio,
|
| 334 |
-
"cash_ratio": cash_ratio,
|
| 335 |
-
"debt_to_equity": debt_to_equity,
|
| 336 |
-
"debt_to_assets": debt_to_assets,
|
| 337 |
-
"net_debt_to_ebitda": net_debt_ebitda,
|
| 338 |
-
"interest_coverage": interest_cov,
|
| 339 |
-
"asset_turnover": asset_turnover,
|
| 340 |
-
"inventory_turnover": inv_turnover,
|
| 341 |
-
"days_inventory": days_inv,
|
| 342 |
-
"days_sales_outstanding": days_sales,
|
| 343 |
-
"days_payables": days_payable,
|
| 344 |
-
"cash_conversion_cycle": ccc,
|
| 345 |
-
"ocf_to_net_income": ocf_to_ni,
|
| 346 |
-
"fcf_margin": fcf_margin_,
|
| 347 |
-
"fcf_conversion": fcf_conversion,
|
| 348 |
-
"capex_intensity": capex_intensity,
|
| 349 |
-
}
|
| 350 |
-
|
| 351 |
-
# Build final output
|
| 352 |
-
result = dict(financial_data)
|
| 353 |
-
result["ratios"] = ratios
|
| 354 |
-
result["growth_metrics"] = growth_metrics
|
| 355 |
-
result["dupont"] = dupont
|
| 356 |
-
result["nopat"] = nopat
|
| 357 |
-
result["total_debt"] = total_debt
|
| 358 |
-
result["net_debt"] = net_debt
|
| 359 |
-
result["currency"] = currency
|
| 360 |
-
|
| 361 |
-
return result
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pipeline/calculator.py -- Compute all financial ratios, DuPont decomposition,
|
| 3 |
+
growth metrics, and scale numbers for display.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _safe_div(num, den, default=None):
|
| 12 |
+
"""Safe division returning default if denominator is None/zero."""
|
| 13 |
+
try:
|
| 14 |
+
if num is None or den is None:
|
| 15 |
+
return default
|
| 16 |
+
if den == 0:
|
| 17 |
+
return default
|
| 18 |
+
return num / den
|
| 19 |
+
except (TypeError, ZeroDivisionError):
|
| 20 |
+
return default
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _avg(a, b):
|
| 24 |
+
"""Average of two values, None if either is None."""
|
| 25 |
+
if a is None or b is None:
|
| 26 |
+
return None
|
| 27 |
+
return (a + b) / 2
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _pct_change(current, previous):
|
| 31 |
+
"""Year-over-year % change."""
|
| 32 |
+
if current is None or previous is None or previous == 0:
|
| 33 |
+
return None
|
| 34 |
+
return (current - previous) / abs(previous)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _cagr(start, end, n):
|
| 38 |
+
"""Compound annual growth rate over n periods."""
|
| 39 |
+
if start is None or end is None or n <= 0:
|
| 40 |
+
return None
|
| 41 |
+
if start <= 0 or end < 0:
|
| 42 |
+
return None
|
| 43 |
+
try:
|
| 44 |
+
return (end / start) ** (1 / n) - 1
|
| 45 |
+
except (ZeroDivisionError, ValueError):
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _series(data_dict: Dict, key: str, n: int) -> List[Optional[float]]:
|
| 50 |
+
"""Extract a time-series list, padded/trimmed to length n."""
|
| 51 |
+
vals = data_dict.get(key, [])
|
| 52 |
+
if len(vals) < n:
|
| 53 |
+
vals = vals + [None] * (n - len(vals))
|
| 54 |
+
return vals[:n]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# -- Auto unit scaling ---------------------------------------------------------
|
| 58 |
+
|
| 59 |
+
def auto_scale(values: List[Optional[float]], currency: str) -> Tuple[List[Optional[float]], str]:
|
| 60 |
+
"""
|
| 61 |
+
Scale a list of monetary values to a human-readable unit.
|
| 62 |
+
Returns (scaled_values, unit_label).
|
| 63 |
+
"""
|
| 64 |
+
non_null = [abs(v) for v in values if v is not None and v != 0]
|
| 65 |
+
if not non_null:
|
| 66 |
+
return values, ""
|
| 67 |
+
mag = max(non_null)
|
| 68 |
+
|
| 69 |
+
if currency == "INR":
|
| 70 |
+
if mag >= 1e7: # >= 1 Crore (in thousands -> multiply)
|
| 71 |
+
# FMP stores in thousands for Indian, screener in Crores
|
| 72 |
+
# We'll just label appropriately
|
| 73 |
+
if mag >= 1e9:
|
| 74 |
+
factor, label = 1e7, "βΉ Crores"
|
| 75 |
+
elif mag >= 1e5:
|
| 76 |
+
factor, label = 1e5, "βΉ Lakhs"
|
| 77 |
+
else:
|
| 78 |
+
factor, label = 1e3, "βΉ Thousands"
|
| 79 |
+
else:
|
| 80 |
+
factor, label = 1, "βΉ"
|
| 81 |
+
# Most FMP returns in actual currency value (not thousands)
|
| 82 |
+
# screener returns in Crores already
|
| 83 |
+
return values, label
|
| 84 |
+
else:
|
| 85 |
+
# USD / other
|
| 86 |
+
if mag >= 1e9:
|
| 87 |
+
factor, label = 1e9, "Billions"
|
| 88 |
+
elif mag >= 1e6:
|
| 89 |
+
factor, label = 1e6, "Millions"
|
| 90 |
+
elif mag >= 1e3:
|
| 91 |
+
factor, label = 1e3, "Thousands"
|
| 92 |
+
else:
|
| 93 |
+
factor, label = 1, ""
|
| 94 |
+
scaled = [v / factor if v is not None else None for v in values]
|
| 95 |
+
return scaled, label
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def smart_format(value: Optional[float], currency: str = "USD") -> str:
|
| 99 |
+
"""Format a single monetary value with smart units."""
|
| 100 |
+
if value is None:
|
| 101 |
+
return "N/A"
|
| 102 |
+
av = abs(value)
|
| 103 |
+
if currency == "INR":
|
| 104 |
+
if av >= 1e7:
|
| 105 |
+
return f"βΉ{value/1e7:,.2f} Cr"
|
| 106 |
+
elif av >= 1e5:
|
| 107 |
+
return f"βΉ{value/1e5:,.2f} L"
|
| 108 |
+
else:
|
| 109 |
+
return f"βΉ{value:,.0f}"
|
| 110 |
+
else:
|
| 111 |
+
sym = "$" if currency == "USD" else ""
|
| 112 |
+
if av >= 1e9:
|
| 113 |
+
return f"{sym}{value/1e9:,.2f}B"
|
| 114 |
+
elif av >= 1e6:
|
| 115 |
+
return f"{sym}{value/1e6:,.2f}M"
|
| 116 |
+
elif av >= 1e3:
|
| 117 |
+
return f"{sym}{value/1e3:,.2f}K"
|
| 118 |
+
else:
|
| 119 |
+
return f"{sym}{value:,.2f}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# -- Main calculation entry ----------------------------------------------------
|
| 123 |
+
|
| 124 |
+
def calculate(financial_data: Dict, meta_dict: Dict) -> Dict:
|
| 125 |
+
"""
|
| 126 |
+
Compute all ratios, DuPont, growth metrics from raw financial data.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
financial_data: Output of fetcher.fetch_all()
|
| 130 |
+
meta_dict: CompanyMeta.to_dict()
|
| 131 |
+
|
| 132 |
+
Returns:
|
| 133 |
+
Complete analysis dict ready for analyst.py and builders.
|
| 134 |
+
"""
|
| 135 |
+
years = financial_data.get("years", [])
|
| 136 |
+
n = len(years)
|
| 137 |
+
if n == 0:
|
| 138 |
+
return financial_data # Nothing to compute
|
| 139 |
+
|
| 140 |
+
inc = financial_data.get("income_statement", {})
|
| 141 |
+
bal = financial_data.get("balance_sheet", {})
|
| 142 |
+
cf = financial_data.get("cash_flow", {})
|
| 143 |
+
currency = financial_data.get("currency", meta_dict.get("currency", "USD"))
|
| 144 |
+
|
| 145 |
+
def S(key, src=None):
|
| 146 |
+
src = src or inc
|
| 147 |
+
return _series(src, key, n)
|
| 148 |
+
|
| 149 |
+
# -- Extract series --------------------------------------------------------
|
| 150 |
+
revenue = S("revenue")
|
| 151 |
+
cogs = S("cost_of_revenue")
|
| 152 |
+
gross_profit = S("gross_profit")
|
| 153 |
+
op_income = S("operating_income")
|
| 154 |
+
ebitda = S("ebitda")
|
| 155 |
+
da = S("depreciation_amort")
|
| 156 |
+
interest_exp = S("interest_expense")
|
| 157 |
+
pretax_income = S("pretax_income")
|
| 158 |
+
tax_expense = S("tax_expense")
|
| 159 |
+
net_income = S("net_income")
|
| 160 |
+
diluted_eps = S("diluted_eps")
|
| 161 |
+
diluted_shares = S("diluted_shares")
|
| 162 |
+
|
| 163 |
+
total_assets = S("total_assets", bal)
|
| 164 |
+
total_equity = S("total_equity", bal)
|
| 165 |
+
total_liabilities = S("total_liabilities", bal)
|
| 166 |
+
total_curr_assets = S("total_current_assets", bal)
|
| 167 |
+
total_curr_liab = S("total_current_liabilities", bal)
|
| 168 |
+
inventory = S("inventory", bal)
|
| 169 |
+
receivables = S("receivables", bal)
|
| 170 |
+
payables = S("accounts_payable", bal)
|
| 171 |
+
short_debt = S("short_term_debt", bal)
|
| 172 |
+
long_debt = S("long_term_debt", bal)
|
| 173 |
+
cash = S("cash_and_equivalents", bal)
|
| 174 |
+
st_inv = S("short_term_investments", bal)
|
| 175 |
+
|
| 176 |
+
cfo = S("cash_from_operations", cf)
|
| 177 |
+
capex = S("capex", cf)
|
| 178 |
+
fcf = S("free_cash_flow", cf)
|
| 179 |
+
dividends = S("dividends_paid", cf)
|
| 180 |
+
buybacks = S("stock_buybacks", cf)
|
| 181 |
+
|
| 182 |
+
# Compute EBITDA if missing
|
| 183 |
+
for i in range(n):
|
| 184 |
+
if ebitda[i] is None and op_income[i] is not None and da[i] is not None:
|
| 185 |
+
ebitda[i] = op_income[i] + da[i]
|
| 186 |
+
|
| 187 |
+
# Compute FCF if missing
|
| 188 |
+
for i in range(n):
|
| 189 |
+
if fcf[i] is None and cfo[i] is not None and capex[i] is not None:
|
| 190 |
+
fcf[i] = cfo[i] + capex[i] # capex is usually negative in FMP
|
| 191 |
+
|
| 192 |
+
# Total debt
|
| 193 |
+
total_debt = [
|
| 194 |
+
(s or 0) + (l or 0) if (s is not None or l is not None) else None
|
| 195 |
+
for s, l in zip(short_debt, long_debt)
|
| 196 |
+
]
|
| 197 |
+
|
| 198 |
+
# Effective tax rate
|
| 199 |
+
eff_tax_rate = [
|
| 200 |
+
_safe_div(t, p) if p and p > 0 else None
|
| 201 |
+
for t, p in zip(tax_expense, pretax_income)
|
| 202 |
+
]
|
| 203 |
+
|
| 204 |
+
# NOPAT
|
| 205 |
+
nopat = [
|
| 206 |
+
o * (1 - (t or 0)) if o is not None else None
|
| 207 |
+
for o, t in zip(op_income, eff_tax_rate)
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
# Invested capital = Total equity + Total debt - Cash
|
| 211 |
+
inv_capital = [
|
| 212 |
+
(e or 0) + (d or 0) - (c or 0)
|
| 213 |
+
if e is not None or d is not None else None
|
| 214 |
+
for e, d, c in zip(total_equity, total_debt, cash)
|
| 215 |
+
]
|
| 216 |
+
|
| 217 |
+
# -- Profitability ratios --------------------------------------------------
|
| 218 |
+
gross_margin = [_safe_div(g, r) for g, r in zip(gross_profit, revenue)]
|
| 219 |
+
op_margin = [_safe_div(o, r) for o, r in zip(op_income, revenue)]
|
| 220 |
+
ebitda_margin = [_safe_div(e, r) for e, r in zip(ebitda, revenue)]
|
| 221 |
+
net_margin = [_safe_div(n_, r) for n_, r in zip(net_income, revenue)]
|
| 222 |
+
|
| 223 |
+
# ROE, ROA, ROIC use averages
|
| 224 |
+
roe = [_safe_div(n_, _avg(e0, e1)) for n_, e0, e1 in zip(
|
| 225 |
+
net_income, [None] + total_equity[:-1], total_equity)]
|
| 226 |
+
roa = [_safe_div(n_, _avg(a0, a1)) for n_, a0, a1 in zip(
|
| 227 |
+
net_income, [None] + total_assets[:-1], total_assets)]
|
| 228 |
+
roic = [_safe_div(no, _avg(ic0, ic1)) for no, ic0, ic1 in zip(
|
| 229 |
+
nopat, [None] + inv_capital[:-1], inv_capital)]
|
| 230 |
+
|
| 231 |
+
# -- Liquidity -------------------------------------------------------------
|
| 232 |
+
current_ratio = [_safe_div(ca, cl) for ca, cl in zip(total_curr_assets, total_curr_liab)]
|
| 233 |
+
quick_ratio = [
|
| 234 |
+
_safe_div((ca or 0) - (inv or 0), cl)
|
| 235 |
+
if ca is not None and cl else None
|
| 236 |
+
for ca, inv, cl in zip(total_curr_assets, inventory, total_curr_liab)
|
| 237 |
+
]
|
| 238 |
+
cash_ratio = [
|
| 239 |
+
_safe_div((c or 0) + (si or 0), cl)
|
| 240 |
+
if cl else None
|
| 241 |
+
for c, si, cl in zip(cash, st_inv, total_curr_liab)
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
# -- Solvency / Leverage ---------------------------------------------------
|
| 245 |
+
debt_to_equity = [_safe_div(d, e) for d, e in zip(total_debt, total_equity)]
|
| 246 |
+
debt_to_assets = [_safe_div(d, a) for d, a in zip(total_debt, total_assets)]
|
| 247 |
+
net_debt = [(d or 0) - (c or 0) - (si or 0) if d is not None else None
|
| 248 |
+
for d, c, si in zip(total_debt, cash, st_inv)]
|
| 249 |
+
net_debt_ebitda = [_safe_div(nd, e) for nd, e in zip(net_debt, ebitda)]
|
| 250 |
+
interest_cov = [_safe_div(o, ie) for o, ie in zip(op_income, interest_exp)]
|
| 251 |
+
|
| 252 |
+
# -- Efficiency ------------------------------------------------------------
|
| 253 |
+
asset_turnover = [_safe_div(r, _avg(a0, a1)) for r, a0, a1 in zip(
|
| 254 |
+
revenue, [None] + total_assets[:-1], total_assets)]
|
| 255 |
+
inv_turnover = [_safe_div(c, _avg(i0, i1)) for c, i0, i1 in zip(
|
| 256 |
+
cogs, [None] + inventory[:-1], inventory)]
|
| 257 |
+
days_inv = [_safe_div(365, it) for it in inv_turnover]
|
| 258 |
+
rec_turnover = [_safe_div(r, _avg(rc0, rc1)) for r, rc0, rc1 in zip(
|
| 259 |
+
revenue, [None] + receivables[:-1], receivables)]
|
| 260 |
+
days_sales = [_safe_div(365, rt) for rt in rec_turnover]
|
| 261 |
+
pay_turnover = [_safe_div(c, _avg(p0, p1)) for c, p0, p1 in zip(
|
| 262 |
+
cogs, [None] + payables[:-1], payables)]
|
| 263 |
+
days_payable = [_safe_div(365, pt) for pt in pay_turnover]
|
| 264 |
+
ccc = [
|
| 265 |
+
(di or 0) + (ds or 0) - (dp or 0)
|
| 266 |
+
if di is not None and ds is not None and dp is not None else None
|
| 267 |
+
for di, ds, dp in zip(days_inv, days_sales, days_payable)
|
| 268 |
+
]
|
| 269 |
+
|
| 270 |
+
# -- Cash flow quality -----------------------------------------------------
|
| 271 |
+
ocf_to_ni = [_safe_div(c, n_) for c, n_ in zip(cfo, net_income)]
|
| 272 |
+
fcf_margin_ = [_safe_div(f, r) for f, r in zip(fcf, revenue)]
|
| 273 |
+
fcf_conversion = [_safe_div(f, n_) for f, n_ in zip(fcf, net_income)]
|
| 274 |
+
capex_intensity = [_safe_div(abs(c) if c else None, r) for c, r in zip(capex, revenue)]
|
| 275 |
+
|
| 276 |
+
# -- Growth metrics --------------------------------------------------------
|
| 277 |
+
def yoy(arr):
|
| 278 |
+
result = [None]
|
| 279 |
+
for i in range(1, len(arr)):
|
| 280 |
+
result.append(_pct_change(arr[i], arr[i-1]))
|
| 281 |
+
return result
|
| 282 |
+
|
| 283 |
+
rev_yoy = yoy(revenue)
|
| 284 |
+
op_yoy = yoy(op_income)
|
| 285 |
+
ni_yoy = yoy(net_income)
|
| 286 |
+
eps_yoy = yoy(diluted_eps)
|
| 287 |
+
fcf_yoy = yoy(fcf)
|
| 288 |
+
|
| 289 |
+
def cagr_5y(arr):
|
| 290 |
+
valid = [v for v in arr if v is not None]
|
| 291 |
+
if len(valid) < 2:
|
| 292 |
+
return None
|
| 293 |
+
return _cagr(valid[0], valid[-1], len(valid) - 1)
|
| 294 |
+
|
| 295 |
+
growth_metrics = {
|
| 296 |
+
"revenue_yoy": rev_yoy,
|
| 297 |
+
"revenue_cagr_5y": cagr_5y(revenue),
|
| 298 |
+
"operating_income_yoy": op_yoy,
|
| 299 |
+
"operating_income_cagr_5y": cagr_5y(op_income),
|
| 300 |
+
"net_income_yoy": ni_yoy,
|
| 301 |
+
"net_income_cagr_5y": cagr_5y(net_income),
|
| 302 |
+
"eps_yoy": eps_yoy,
|
| 303 |
+
"eps_cagr_5y": cagr_5y(diluted_eps),
|
| 304 |
+
"fcf_yoy": fcf_yoy,
|
| 305 |
+
"fcf_cagr_5y": cagr_5y(fcf),
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
# -- DuPont decomposition --------------------------------------------------
|
| 309 |
+
# ROE = Net Margin Γ Asset Turnover Γ Equity Multiplier
|
| 310 |
+
equity_multiplier = [_safe_div(a, e) for a, e in zip(total_assets, total_equity)]
|
| 311 |
+
dupont = {
|
| 312 |
+
"net_margin": net_margin,
|
| 313 |
+
"asset_turnover": asset_turnover,
|
| 314 |
+
"equity_multiplier": equity_multiplier,
|
| 315 |
+
"roe_computed": [
|
| 316 |
+
(nm or 0) * (at or 0) * (em or 0)
|
| 317 |
+
if nm is not None and at is not None and em is not None else None
|
| 318 |
+
for nm, at, em in zip(net_margin, asset_turnover, equity_multiplier)
|
| 319 |
+
],
|
| 320 |
+
"roe_reported": roe,
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
# -- Ratios dict -----------------------------------------------------------
|
| 324 |
+
ratios = {
|
| 325 |
+
"gross_margin": gross_margin,
|
| 326 |
+
"operating_margin": op_margin,
|
| 327 |
+
"ebitda_margin": ebitda_margin,
|
| 328 |
+
"net_margin": net_margin,
|
| 329 |
+
"roe": roe,
|
| 330 |
+
"roa": roa,
|
| 331 |
+
"roic": roic,
|
| 332 |
+
"current_ratio": current_ratio,
|
| 333 |
+
"quick_ratio": quick_ratio,
|
| 334 |
+
"cash_ratio": cash_ratio,
|
| 335 |
+
"debt_to_equity": debt_to_equity,
|
| 336 |
+
"debt_to_assets": debt_to_assets,
|
| 337 |
+
"net_debt_to_ebitda": net_debt_ebitda,
|
| 338 |
+
"interest_coverage": interest_cov,
|
| 339 |
+
"asset_turnover": asset_turnover,
|
| 340 |
+
"inventory_turnover": inv_turnover,
|
| 341 |
+
"days_inventory": days_inv,
|
| 342 |
+
"days_sales_outstanding": days_sales,
|
| 343 |
+
"days_payables": days_payable,
|
| 344 |
+
"cash_conversion_cycle": ccc,
|
| 345 |
+
"ocf_to_net_income": ocf_to_ni,
|
| 346 |
+
"fcf_margin": fcf_margin_,
|
| 347 |
+
"fcf_conversion": fcf_conversion,
|
| 348 |
+
"capex_intensity": capex_intensity,
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
# Build final output
|
| 352 |
+
result = dict(financial_data)
|
| 353 |
+
result["ratios"] = ratios
|
| 354 |
+
result["growth_metrics"] = growth_metrics
|
| 355 |
+
result["dupont"] = dupont
|
| 356 |
+
result["nopat"] = nopat
|
| 357 |
+
result["total_debt"] = total_debt
|
| 358 |
+
result["net_debt"] = net_debt
|
| 359 |
+
result["currency"] = currency
|
| 360 |
+
|
| 361 |
+
return result
|
pipeline/fetcher.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pipeline/google_login.py
CHANGED
|
@@ -1,182 +1,182 @@
|
|
| 1 |
-
"""
|
| 2 |
-
pipeline/google_login.py
|
| 3 |
-
|
| 4 |
-
Uses google-auth-oauthlib InstalledAppFlow to authenticate via browser.
|
| 5 |
-
After login, the access token is used directly with the Generative Language REST API
|
| 6 |
-
so the user NEVER needs to touch an API key manually.
|
| 7 |
-
|
| 8 |
-
Credentials are stored in storage/google_token.json and auto-refreshed.
|
| 9 |
-
"""
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
import json, time, threading
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
from typing import Optional, Tuple
|
| 14 |
-
|
| 15 |
-
# Where we persist the user's OAuth token
|
| 16 |
-
_TOKEN_FILE = Path(__file__).parent.parent / "storage" / "google_token.json"
|
| 17 |
-
|
| 18 |
-
# Gemini generative language scope
|
| 19 |
-
_SCOPES = ["https://www.googleapis.com/auth/generative-language"]
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
# These are "Desktop app" / "Installed app" OAuth 2.0 credentials.
|
| 23 |
-
# They are intentionally public-facing (like VS Code's GitHub OAuth client).
|
| 24 |
-
# They allow users to log in with Google; they cannot access anything beyond
|
| 25 |
-
# what the user explicitly authorises. No secrets are exposed.
|
| 26 |
-
_CLIENT_CONFIG = {
|
| 27 |
-
"installed": {
|
| 28 |
-
"client_id": "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com",
|
| 29 |
-
"client_secret": "d-FL95Q19q7MQmFpd7hHD0Ty",
|
| 30 |
-
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 31 |
-
"token_uri": "https://oauth2.googleapis.com/token",
|
| 32 |
-
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"],
|
| 33 |
-
}
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
def _load_token() -> Optional[dict]:
|
| 40 |
-
if _TOKEN_FILE.exists():
|
| 41 |
-
try:
|
| 42 |
-
return json.loads(_TOKEN_FILE.read_text(encoding="utf-8"))
|
| 43 |
-
except Exception:
|
| 44 |
-
pass
|
| 45 |
-
return None
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _save_token(token_data: dict):
|
| 49 |
-
_TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 50 |
-
_TOKEN_FILE.write_text(json.dumps(token_data, indent=2), encoding="utf-8")
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def _refresh_token(token_data: dict) -> Tuple[bool, dict]:
|
| 54 |
-
"""Use the refresh_token to get a new access_token."""
|
| 55 |
-
try:
|
| 56 |
-
import requests
|
| 57 |
-
r = requests.post(
|
| 58 |
-
_CLIENT_CONFIG["installed"]["token_uri"],
|
| 59 |
-
data={
|
| 60 |
-
"client_id": _CLIENT_CONFIG["installed"]["client_id"],
|
| 61 |
-
"client_secret": _CLIENT_CONFIG["installed"]["client_secret"],
|
| 62 |
-
"refresh_token": token_data.get("refresh_token", ""),
|
| 63 |
-
"grant_type": "refresh_token",
|
| 64 |
-
},
|
| 65 |
-
timeout=15,
|
| 66 |
-
)
|
| 67 |
-
resp = r.json()
|
| 68 |
-
if "access_token" in resp:
|
| 69 |
-
token_data["access_token"] = resp["access_token"]
|
| 70 |
-
token_data["expires_at"] = time.time() + resp.get("expires_in", 3600)
|
| 71 |
-
_save_token(token_data)
|
| 72 |
-
return True, token_data
|
| 73 |
-
return False, token_data
|
| 74 |
-
except Exception as e:
|
| 75 |
-
return False, token_data
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def get_valid_token() -> Optional[str]:
|
| 79 |
-
"""Return a valid access_token, refreshing if needed. None if not logged in."""
|
| 80 |
-
token_data = _load_token()
|
| 81 |
-
if not token_data:
|
| 82 |
-
return None
|
| 83 |
-
if time.time() > token_data.get("expires_at", 0) - 60:
|
| 84 |
-
ok, token_data = _refresh_token(token_data)
|
| 85 |
-
if not ok:
|
| 86 |
-
return None
|
| 87 |
-
return token_data.get("access_token")
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def is_logged_in() -> bool:
|
| 91 |
-
return get_valid_token() is not None
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def logout():
|
| 95 |
-
if _TOKEN_FILE.exists():
|
| 96 |
-
_TOKEN_FILE.unlink()
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
#
|
| 100 |
-
|
| 101 |
-
def login_with_browser(log_fn=None) -> Tuple[bool, str]:
|
| 102 |
-
"""
|
| 103 |
-
Launch Google OAuth in the default browser.
|
| 104 |
-
Blocks until auth completes or fails.
|
| 105 |
-
Returns (success, message).
|
| 106 |
-
"""
|
| 107 |
-
def log(m):
|
| 108 |
-
if log_fn: log_fn(m)
|
| 109 |
-
try:
|
| 110 |
-
from google_auth_oauthlib.flow import InstalledAppFlow
|
| 111 |
-
except ImportError:
|
| 112 |
-
return False, (
|
| 113 |
-
"google-auth-oauthlib not installed.\n"
|
| 114 |
-
"Run: pip install google-auth-oauthlib"
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
try:
|
| 118 |
-
log("Opening browser for Google login
|
| 119 |
-
flow = InstalledAppFlow.from_client_config(_CLIENT_CONFIG, scopes=_SCOPES)
|
| 120 |
-
# Try local server first (most reliable), fallback to console input
|
| 121 |
-
try:
|
| 122 |
-
creds = flow.run_local_server(port=0, open_browser=True)
|
| 123 |
-
except Exception:
|
| 124 |
-
creds = flow.run_console()
|
| 125 |
-
|
| 126 |
-
token_data = {
|
| 127 |
-
"access_token": creds.token,
|
| 128 |
-
"refresh_token": creds.refresh_token,
|
| 129 |
-
"expires_at": creds.expiry.timestamp() if creds.expiry else time.time() + 3600,
|
| 130 |
-
}
|
| 131 |
-
_save_token(token_data)
|
| 132 |
-
log("
|
| 133 |
-
return True, "Logged in successfully
|
| 134 |
-
except Exception as e:
|
| 135 |
-
return False, f"Login failed: {e}"
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
#
|
| 139 |
-
|
| 140 |
-
def gemini_generate_oauth(prompt: str, model: str = "gemini-2.0-flash") -> str:
|
| 141 |
-
"""Call Gemini API using the stored OAuth token (no API key)."""
|
| 142 |
-
token = get_valid_token()
|
| 143 |
-
if not token:
|
| 144 |
-
raise RuntimeError("Not logged in to Google. Please sign in via Settings.")
|
| 145 |
-
try:
|
| 146 |
-
import requests
|
| 147 |
-
url = (f"https://generativelanguage.googleapis.com/v1beta/models/"
|
| 148 |
-
f"{model}:generateContent")
|
| 149 |
-
headers = {
|
| 150 |
-
"Authorization": f"Bearer {token}",
|
| 151 |
-
"Content-Type": "application/json",
|
| 152 |
-
}
|
| 153 |
-
body = {
|
| 154 |
-
"contents": [{"parts": [{"text": prompt}]}],
|
| 155 |
-
"generationConfig": {"temperature": 0.2, "maxOutputTokens": 1024},
|
| 156 |
-
}
|
| 157 |
-
r = requests.post(url, headers=headers, json=body, timeout=60)
|
| 158 |
-
r.raise_for_status()
|
| 159 |
-
candidates = r.json().get("candidates", [])
|
| 160 |
-
if candidates:
|
| 161 |
-
parts = candidates[0].get("content", {}).get("parts", [])
|
| 162 |
-
if parts:
|
| 163 |
-
return parts[0].get("text", "").strip()
|
| 164 |
-
return "[No response from Gemini]"
|
| 165 |
-
except Exception as e:
|
| 166 |
-
raise RuntimeError(f"Gemini OAuth call failed: {e}")
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
#
|
| 170 |
-
|
| 171 |
-
def validate_google_login() -> Tuple[bool, str]:
|
| 172 |
-
"""Test if the stored Google token works with Gemini."""
|
| 173 |
-
token = get_valid_token()
|
| 174 |
-
if not token:
|
| 175 |
-
return False, "Not signed in. Click 'Sign in with Google'."
|
| 176 |
-
try:
|
| 177 |
-
result = gemini_generate_oauth("Reply with the single word: OK", model="gemini-2.0-flash")
|
| 178 |
-
if "OK" in result or len(result) > 0:
|
| 179 |
-
return True, "Google login active
|
| 180 |
-
return True, "Google login active
|
| 181 |
-
except Exception as e:
|
| 182 |
-
return False, f"Token expired or invalid: {e}"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pipeline/google_login.py -- Google OAuth login for Gemini API access.
|
| 3 |
+
|
| 4 |
+
Uses google-auth-oauthlib InstalledAppFlow to authenticate via browser.
|
| 5 |
+
After login, the access token is used directly with the Generative Language REST API
|
| 6 |
+
so the user NEVER needs to touch an API key manually.
|
| 7 |
+
|
| 8 |
+
Credentials are stored in storage/google_token.json and auto-refreshed.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
import json, time, threading
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Optional, Tuple
|
| 14 |
+
|
| 15 |
+
# Where we persist the user's OAuth token
|
| 16 |
+
_TOKEN_FILE = Path(__file__).parent.parent / "storage" / "google_token.json"
|
| 17 |
+
|
| 18 |
+
# Gemini generative language scope
|
| 19 |
+
_SCOPES = ["https://www.googleapis.com/auth/generative-language"]
|
| 20 |
+
|
| 21 |
+
# -- Bundled OAuth client credentials -----------------------------------------
|
| 22 |
+
# These are "Desktop app" / "Installed app" OAuth 2.0 credentials.
|
| 23 |
+
# They are intentionally public-facing (like VS Code's GitHub OAuth client).
|
| 24 |
+
# They allow users to log in with Google; they cannot access anything beyond
|
| 25 |
+
# what the user explicitly authorises. No secrets are exposed.
|
| 26 |
+
_CLIENT_CONFIG = {
|
| 27 |
+
"installed": {
|
| 28 |
+
"client_id": "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com",
|
| 29 |
+
"client_secret": "d-FL95Q19q7MQmFpd7hHD0Ty",
|
| 30 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 31 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 32 |
+
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"],
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# -- Core OAuth helpers --------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
def _load_token() -> Optional[dict]:
|
| 40 |
+
if _TOKEN_FILE.exists():
|
| 41 |
+
try:
|
| 42 |
+
return json.loads(_TOKEN_FILE.read_text(encoding="utf-8"))
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _save_token(token_data: dict):
|
| 49 |
+
_TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
_TOKEN_FILE.write_text(json.dumps(token_data, indent=2), encoding="utf-8")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _refresh_token(token_data: dict) -> Tuple[bool, dict]:
|
| 54 |
+
"""Use the refresh_token to get a new access_token."""
|
| 55 |
+
try:
|
| 56 |
+
import requests
|
| 57 |
+
r = requests.post(
|
| 58 |
+
_CLIENT_CONFIG["installed"]["token_uri"],
|
| 59 |
+
data={
|
| 60 |
+
"client_id": _CLIENT_CONFIG["installed"]["client_id"],
|
| 61 |
+
"client_secret": _CLIENT_CONFIG["installed"]["client_secret"],
|
| 62 |
+
"refresh_token": token_data.get("refresh_token", ""),
|
| 63 |
+
"grant_type": "refresh_token",
|
| 64 |
+
},
|
| 65 |
+
timeout=15,
|
| 66 |
+
)
|
| 67 |
+
resp = r.json()
|
| 68 |
+
if "access_token" in resp:
|
| 69 |
+
token_data["access_token"] = resp["access_token"]
|
| 70 |
+
token_data["expires_at"] = time.time() + resp.get("expires_in", 3600)
|
| 71 |
+
_save_token(token_data)
|
| 72 |
+
return True, token_data
|
| 73 |
+
return False, token_data
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return False, token_data
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def get_valid_token() -> Optional[str]:
|
| 79 |
+
"""Return a valid access_token, refreshing if needed. None if not logged in."""
|
| 80 |
+
token_data = _load_token()
|
| 81 |
+
if not token_data:
|
| 82 |
+
return None
|
| 83 |
+
if time.time() > token_data.get("expires_at", 0) - 60:
|
| 84 |
+
ok, token_data = _refresh_token(token_data)
|
| 85 |
+
if not ok:
|
| 86 |
+
return None
|
| 87 |
+
return token_data.get("access_token")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def is_logged_in() -> bool:
|
| 91 |
+
return get_valid_token() is not None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def logout():
|
| 95 |
+
if _TOKEN_FILE.exists():
|
| 96 |
+
_TOKEN_FILE.unlink()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# -- Browser login flow --------------------------------------------------------
|
| 100 |
+
|
| 101 |
+
def login_with_browser(log_fn=None) -> Tuple[bool, str]:
|
| 102 |
+
"""
|
| 103 |
+
Launch Google OAuth in the default browser.
|
| 104 |
+
Blocks until auth completes or fails.
|
| 105 |
+
Returns (success, message).
|
| 106 |
+
"""
|
| 107 |
+
def log(m):
|
| 108 |
+
if log_fn: log_fn(m)
|
| 109 |
+
try:
|
| 110 |
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
| 111 |
+
except ImportError:
|
| 112 |
+
return False, (
|
| 113 |
+
"google-auth-oauthlib not installed.\n"
|
| 114 |
+
"Run: pip install google-auth-oauthlib"
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
log("Opening browser for Google login...")
|
| 119 |
+
flow = InstalledAppFlow.from_client_config(_CLIENT_CONFIG, scopes=_SCOPES)
|
| 120 |
+
# Try local server first (most reliable), fallback to console input
|
| 121 |
+
try:
|
| 122 |
+
creds = flow.run_local_server(port=0, open_browser=True)
|
| 123 |
+
except Exception:
|
| 124 |
+
creds = flow.run_console()
|
| 125 |
+
|
| 126 |
+
token_data = {
|
| 127 |
+
"access_token": creds.token,
|
| 128 |
+
"refresh_token": creds.refresh_token,
|
| 129 |
+
"expires_at": creds.expiry.timestamp() if creds.expiry else time.time() + 3600,
|
| 130 |
+
}
|
| 131 |
+
_save_token(token_data)
|
| 132 |
+
log("[OK] Google login successful -- token saved")
|
| 133 |
+
return True, "Logged in successfully [OK]"
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return False, f"Login failed: {e}"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# -- Gemini call via REST (no API key needed when using OAuth token) -----------
|
| 139 |
+
|
| 140 |
+
def gemini_generate_oauth(prompt: str, model: str = "gemini-2.0-flash") -> str:
|
| 141 |
+
"""Call Gemini API using the stored OAuth token (no API key)."""
|
| 142 |
+
token = get_valid_token()
|
| 143 |
+
if not token:
|
| 144 |
+
raise RuntimeError("Not logged in to Google. Please sign in via Settings.")
|
| 145 |
+
try:
|
| 146 |
+
import requests
|
| 147 |
+
url = (f"https://generativelanguage.googleapis.com/v1beta/models/"
|
| 148 |
+
f"{model}:generateContent")
|
| 149 |
+
headers = {
|
| 150 |
+
"Authorization": f"Bearer {token}",
|
| 151 |
+
"Content-Type": "application/json",
|
| 152 |
+
}
|
| 153 |
+
body = {
|
| 154 |
+
"contents": [{"parts": [{"text": prompt}]}],
|
| 155 |
+
"generationConfig": {"temperature": 0.2, "maxOutputTokens": 1024},
|
| 156 |
+
}
|
| 157 |
+
r = requests.post(url, headers=headers, json=body, timeout=60)
|
| 158 |
+
r.raise_for_status()
|
| 159 |
+
candidates = r.json().get("candidates", [])
|
| 160 |
+
if candidates:
|
| 161 |
+
parts = candidates[0].get("content", {}).get("parts", [])
|
| 162 |
+
if parts:
|
| 163 |
+
return parts[0].get("text", "").strip()
|
| 164 |
+
return "[No response from Gemini]"
|
| 165 |
+
except Exception as e:
|
| 166 |
+
raise RuntimeError(f"Gemini OAuth call failed: {e}")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# -- Quick validity check ------------------------------------------------------
|
| 170 |
+
|
| 171 |
+
def validate_google_login() -> Tuple[bool, str]:
|
| 172 |
+
"""Test if the stored Google token works with Gemini."""
|
| 173 |
+
token = get_valid_token()
|
| 174 |
+
if not token:
|
| 175 |
+
return False, "Not signed in. Click 'Sign in with Google'."
|
| 176 |
+
try:
|
| 177 |
+
result = gemini_generate_oauth("Reply with the single word: OK", model="gemini-2.0-flash")
|
| 178 |
+
if "OK" in result or len(result) > 0:
|
| 179 |
+
return True, "Google login active -- Gemini working [OK]"
|
| 180 |
+
return True, "Google login active [OK]"
|
| 181 |
+
except Exception as e:
|
| 182 |
+
return False, f"Token expired or invalid: {e}"
|
pipeline/key_validator.py
CHANGED
|
@@ -1,186 +1,186 @@
|
|
| 1 |
-
"""
|
| 2 |
-
pipeline/key_validator.py
|
| 3 |
-
"""
|
| 4 |
-
from __future__ import annotations
|
| 5 |
-
import sys
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
from typing import Tuple
|
| 8 |
-
|
| 9 |
-
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def validate_fmp(key: str) -> Tuple[bool, str]:
|
| 13 |
-
"""Test FMP key with a lightweight profile call."""
|
| 14 |
-
if not key or key.strip() in ("", "your_fmp_key_here"):
|
| 15 |
-
return False, "No key entered."
|
| 16 |
-
try:
|
| 17 |
-
import requests
|
| 18 |
-
r = requests.get(
|
| 19 |
-
"https://financialmodelingprep.com/api/v3/profile/AAPL",
|
| 20 |
-
params={"apikey": key.strip()},
|
| 21 |
-
timeout=10,
|
| 22 |
-
)
|
| 23 |
-
data = r.json()
|
| 24 |
-
if isinstance(data, list) and data and data[0].get("symbol"):
|
| 25 |
-
return True, f"Valid
|
| 26 |
-
if isinstance(data, dict) and "Error Message" in data:
|
| 27 |
-
return False, f"Invalid key: {data['Error Message']}"
|
| 28 |
-
return False, "Unexpected response
|
| 29 |
-
except Exception as e:
|
| 30 |
-
return False, f"Connection error: {e}"
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def validate_gemini(key: str) -> Tuple[bool, str]:
|
| 34 |
-
"""Test Gemini key with a minimal generate call."""
|
| 35 |
-
if not key or key.strip() in ("", "your_gemini_key_here"):
|
| 36 |
-
return False, "No key entered."
|
| 37 |
-
try:
|
| 38 |
-
# Try new google.genai SDK first
|
| 39 |
-
from google import genai
|
| 40 |
-
client = genai.Client(api_key=key.strip())
|
| 41 |
-
resp = client.models.generate_content(
|
| 42 |
-
model="gemini-2.0-flash",
|
| 43 |
-
contents="Reply with the single word: OK",
|
| 44 |
-
)
|
| 45 |
-
text = resp.text.strip() if resp.text else ""
|
| 46 |
-
return True, f"Valid
|
| 47 |
-
except Exception as e1:
|
| 48 |
-
# Fallback to old SDK
|
| 49 |
-
try:
|
| 50 |
-
import google.generativeai as genai_old
|
| 51 |
-
genai_old.configure(api_key=key.strip())
|
| 52 |
-
model = genai_old.GenerativeModel("gemini-1.5-flash")
|
| 53 |
-
resp = model.generate_content("Reply with the single word: OK")
|
| 54 |
-
return True, f"Valid
|
| 55 |
-
except Exception as e2:
|
| 56 |
-
msg = str(e1)
|
| 57 |
-
if "API_KEY_INVALID" in msg or "invalid" in msg.lower():
|
| 58 |
-
return False, "Invalid API key. Check and re-enter."
|
| 59 |
-
if "quota" in msg.lower():
|
| 60 |
-
return True, "Key valid but quota exceeded
|
| 61 |
-
return False, f"Error: {msg[:80]}"
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def validate_claude(key: str) -> Tuple[bool, str]:
|
| 65 |
-
"""Test Claude key with a minimal message."""
|
| 66 |
-
if not key or key.strip() in ("", "your_claude_key_here"):
|
| 67 |
-
return False, "No key entered."
|
| 68 |
-
try:
|
| 69 |
-
import anthropic
|
| 70 |
-
client = anthropic.Anthropic(api_key=key.strip())
|
| 71 |
-
msg = client.messages.create(
|
| 72 |
-
model="claude-3-5-haiku-20241022",
|
| 73 |
-
max_tokens=10,
|
| 74 |
-
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 75 |
-
)
|
| 76 |
-
text = msg.content[0].text.strip() if msg.content else ""
|
| 77 |
-
return True, f"Valid
|
| 78 |
-
except Exception as e:
|
| 79 |
-
msg = str(e)
|
| 80 |
-
if "authentication" in msg.lower() or "401" in msg or "invalid" in msg.lower():
|
| 81 |
-
return False, "Invalid API key. Check and re-enter."
|
| 82 |
-
if "quota" in msg.lower() or "credit" in msg.lower():
|
| 83 |
-
return True, "Key valid but credit exhausted."
|
| 84 |
-
return False, f"Error: {msg[:80]}"
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
def validate_openai(key: str) -> Tuple[bool, str]:
|
| 88 |
-
"""Test OpenAI key with a minimal chat completion."""
|
| 89 |
-
if not key or key.strip() in ("", "your_openai_key_here"):
|
| 90 |
-
return False, "No key entered."
|
| 91 |
-
try:
|
| 92 |
-
from openai import OpenAI
|
| 93 |
-
client = OpenAI(api_key=key.strip())
|
| 94 |
-
resp = client.chat.completions.create(
|
| 95 |
-
model="gpt-4o-mini",
|
| 96 |
-
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 97 |
-
max_tokens=5,
|
| 98 |
-
)
|
| 99 |
-
text = resp.choices[0].message.content.strip() if resp.choices else ""
|
| 100 |
-
return True, f"Valid
|
| 101 |
-
except Exception as e:
|
| 102 |
-
msg = str(e)
|
| 103 |
-
if "401" in msg or "Incorrect API key" in msg or "invalid_api_key" in msg:
|
| 104 |
-
return False, "Invalid API key. Check and re-enter."
|
| 105 |
-
if "quota" in msg.lower() or "insufficient" in msg.lower():
|
| 106 |
-
return True, "Key valid but quota/credit exhausted."
|
| 107 |
-
return False, f"Error: {msg[:80]}"
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def validate_groq(key: str) -> tuple:
|
| 111 |
-
"""Test Groq key with a minimal chat completion (free API)."""
|
| 112 |
-
if not key or key.strip() in ("", "your_groq_key_here"):
|
| 113 |
-
return False, "No key entered."
|
| 114 |
-
try:
|
| 115 |
-
from openai import OpenAI
|
| 116 |
-
client = OpenAI(
|
| 117 |
-
api_key=key.strip(),
|
| 118 |
-
base_url="https://api.groq.com/openai/v1",
|
| 119 |
-
)
|
| 120 |
-
resp = client.chat.completions.create(
|
| 121 |
-
model="llama-3.3-70b-versatile",
|
| 122 |
-
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 123 |
-
max_tokens=5,
|
| 124 |
-
)
|
| 125 |
-
text = resp.choices[0].message.content.strip() if resp.choices else ""
|
| 126 |
-
return True, f"Valid
|
| 127 |
-
except Exception as e:
|
| 128 |
-
msg = str(e)
|
| 129 |
-
if "401" in msg or "invalid_api_key" in msg.lower() or "unauthorized" in msg.lower():
|
| 130 |
-
return False, "Invalid Groq API key. Check and re-enter."
|
| 131 |
-
if "quota" in msg.lower() or "rate" in msg.lower():
|
| 132 |
-
return True, "Key valid but rate-limited
|
| 133 |
-
return False, f"Error: {msg[:80]}"
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
def validate_nvidia(key: str) -> tuple:
|
| 137 |
-
"""Test NVIDIA NIM key with a minimal chat completion."""
|
| 138 |
-
if not key or key.strip() in ("", "your_nvidia_key_here"):
|
| 139 |
-
return False, "No key entered."
|
| 140 |
-
try:
|
| 141 |
-
from openai import OpenAI
|
| 142 |
-
client = OpenAI(
|
| 143 |
-
api_key=key.strip(),
|
| 144 |
-
base_url="https://integrate.api.nvidia.com/v1",
|
| 145 |
-
)
|
| 146 |
-
resp = client.chat.completions.create(
|
| 147 |
-
model="meta/llama-3.1-405b-instruct",
|
| 148 |
-
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 149 |
-
max_tokens=5,
|
| 150 |
-
)
|
| 151 |
-
text = resp.choices[0].message.content.strip() if resp.choices else ""
|
| 152 |
-
return True, f"Valid
|
| 153 |
-
except Exception as e:
|
| 154 |
-
msg = str(e)
|
| 155 |
-
if "401" in msg or "invalid_api_key" in msg.lower() or "unauthorized" in msg.lower():
|
| 156 |
-
return False, "Invalid NVIDIA API key. Check and re-enter."
|
| 157 |
-
return False, f"Error: {msg[:80]}"
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def check_any_ai_model(gemini_key: str = "", claude_key: str = "", openai_key: str = "", groq_key: str = "", nvidia_key: str = "") -> tuple:
|
| 161 |
-
"""Quickly check if at least one AI model is usable."""
|
| 162 |
-
checks = [
|
| 163 |
-
("nvidia", nvidia_key, validate_nvidia),
|
| 164 |
-
("groq", groq_key, validate_groq),
|
| 165 |
-
("gemini", gemini_key, validate_gemini),
|
| 166 |
-
("claude", claude_key, validate_claude),
|
| 167 |
-
("openai", openai_key, validate_openai),
|
| 168 |
-
]
|
| 169 |
-
for name, key, fn in checks:
|
| 170 |
-
if key and key.strip():
|
| 171 |
-
ok, msg = fn(key)
|
| 172 |
-
if ok:
|
| 173 |
-
return True, f"{name.capitalize()}: {msg}"
|
| 174 |
-
|
| 175 |
-
return False, (
|
| 176 |
-
"No working AI model key found.\n\n"
|
| 177 |
-
"Free options (no credit card needed):\n"
|
| 178 |
-
" β’ NVIDIA NIM (Free credits)
|
| 179 |
-
" β’ Groq (Llama 3.3 70B)
|
| 180 |
-
" β’ Gemini
|
| 181 |
-
"Paid options:\n"
|
| 182 |
-
" β’ Claude
|
| 183 |
-
" β’ ChatGPT
|
| 184 |
-
"OR uncheck all AI models to run data-only analysis."
|
| 185 |
-
)
|
| 186 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pipeline/key_validator.py -- Validate API keys before running analysis.
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Tuple
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_fmp(key: str) -> Tuple[bool, str]:
|
| 13 |
+
"""Test FMP key with a lightweight profile call."""
|
| 14 |
+
if not key or key.strip() in ("", "your_fmp_key_here"):
|
| 15 |
+
return False, "No key entered."
|
| 16 |
+
try:
|
| 17 |
+
import requests
|
| 18 |
+
r = requests.get(
|
| 19 |
+
"https://financialmodelingprep.com/api/v3/profile/AAPL",
|
| 20 |
+
params={"apikey": key.strip()},
|
| 21 |
+
timeout=10,
|
| 22 |
+
)
|
| 23 |
+
data = r.json()
|
| 24 |
+
if isinstance(data, list) and data and data[0].get("symbol"):
|
| 25 |
+
return True, f"Valid [OK] (plan: {data[0].get('exchange','FMP')})"
|
| 26 |
+
if isinstance(data, dict) and "Error Message" in data:
|
| 27 |
+
return False, f"Invalid key: {data['Error Message']}"
|
| 28 |
+
return False, "Unexpected response -- key may be invalid."
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return False, f"Connection error: {e}"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def validate_gemini(key: str) -> Tuple[bool, str]:
|
| 34 |
+
"""Test Gemini key with a minimal generate call."""
|
| 35 |
+
if not key or key.strip() in ("", "your_gemini_key_here"):
|
| 36 |
+
return False, "No key entered."
|
| 37 |
+
try:
|
| 38 |
+
# Try new google.genai SDK first
|
| 39 |
+
from google import genai
|
| 40 |
+
client = genai.Client(api_key=key.strip())
|
| 41 |
+
resp = client.models.generate_content(
|
| 42 |
+
model="gemini-2.0-flash",
|
| 43 |
+
contents="Reply with the single word: OK",
|
| 44 |
+
)
|
| 45 |
+
text = resp.text.strip() if resp.text else ""
|
| 46 |
+
return True, f"Valid [OK] (response: '{text[:20]}')"
|
| 47 |
+
except Exception as e1:
|
| 48 |
+
# Fallback to old SDK
|
| 49 |
+
try:
|
| 50 |
+
import google.generativeai as genai_old
|
| 51 |
+
genai_old.configure(api_key=key.strip())
|
| 52 |
+
model = genai_old.GenerativeModel("gemini-1.5-flash")
|
| 53 |
+
resp = model.generate_content("Reply with the single word: OK")
|
| 54 |
+
return True, f"Valid [OK] (response: '{resp.text.strip()[:20]}')"
|
| 55 |
+
except Exception as e2:
|
| 56 |
+
msg = str(e1)
|
| 57 |
+
if "API_KEY_INVALID" in msg or "invalid" in msg.lower():
|
| 58 |
+
return False, "Invalid API key. Check and re-enter."
|
| 59 |
+
if "quota" in msg.lower():
|
| 60 |
+
return True, "Key valid but quota exceeded -- will still work."
|
| 61 |
+
return False, f"Error: {msg[:80]}"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def validate_claude(key: str) -> Tuple[bool, str]:
|
| 65 |
+
"""Test Claude key with a minimal message."""
|
| 66 |
+
if not key or key.strip() in ("", "your_claude_key_here"):
|
| 67 |
+
return False, "No key entered."
|
| 68 |
+
try:
|
| 69 |
+
import anthropic
|
| 70 |
+
client = anthropic.Anthropic(api_key=key.strip())
|
| 71 |
+
msg = client.messages.create(
|
| 72 |
+
model="claude-3-5-haiku-20241022",
|
| 73 |
+
max_tokens=10,
|
| 74 |
+
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 75 |
+
)
|
| 76 |
+
text = msg.content[0].text.strip() if msg.content else ""
|
| 77 |
+
return True, f"Valid [OK] (response: '{text[:20]}')"
|
| 78 |
+
except Exception as e:
|
| 79 |
+
msg = str(e)
|
| 80 |
+
if "authentication" in msg.lower() or "401" in msg or "invalid" in msg.lower():
|
| 81 |
+
return False, "Invalid API key. Check and re-enter."
|
| 82 |
+
if "quota" in msg.lower() or "credit" in msg.lower():
|
| 83 |
+
return True, "Key valid but credit exhausted."
|
| 84 |
+
return False, f"Error: {msg[:80]}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def validate_openai(key: str) -> Tuple[bool, str]:
|
| 88 |
+
"""Test OpenAI key with a minimal chat completion."""
|
| 89 |
+
if not key or key.strip() in ("", "your_openai_key_here"):
|
| 90 |
+
return False, "No key entered."
|
| 91 |
+
try:
|
| 92 |
+
from openai import OpenAI
|
| 93 |
+
client = OpenAI(api_key=key.strip())
|
| 94 |
+
resp = client.chat.completions.create(
|
| 95 |
+
model="gpt-4o-mini",
|
| 96 |
+
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 97 |
+
max_tokens=5,
|
| 98 |
+
)
|
| 99 |
+
text = resp.choices[0].message.content.strip() if resp.choices else ""
|
| 100 |
+
return True, f"Valid [OK] (response: '{text[:20]}')"
|
| 101 |
+
except Exception as e:
|
| 102 |
+
msg = str(e)
|
| 103 |
+
if "401" in msg or "Incorrect API key" in msg or "invalid_api_key" in msg:
|
| 104 |
+
return False, "Invalid API key. Check and re-enter."
|
| 105 |
+
if "quota" in msg.lower() or "insufficient" in msg.lower():
|
| 106 |
+
return True, "Key valid but quota/credit exhausted."
|
| 107 |
+
return False, f"Error: {msg[:80]}"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def validate_groq(key: str) -> tuple:
|
| 111 |
+
"""Test Groq key with a minimal chat completion (free API)."""
|
| 112 |
+
if not key or key.strip() in ("", "your_groq_key_here"):
|
| 113 |
+
return False, "No key entered."
|
| 114 |
+
try:
|
| 115 |
+
from openai import OpenAI
|
| 116 |
+
client = OpenAI(
|
| 117 |
+
api_key=key.strip(),
|
| 118 |
+
base_url="https://api.groq.com/openai/v1",
|
| 119 |
+
)
|
| 120 |
+
resp = client.chat.completions.create(
|
| 121 |
+
model="llama-3.3-70b-versatile",
|
| 122 |
+
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 123 |
+
max_tokens=5,
|
| 124 |
+
)
|
| 125 |
+
text = resp.choices[0].message.content.strip() if resp.choices else ""
|
| 126 |
+
return True, f"Valid [OK] (Llama 3.3 70B, response: '{text[:20]}')"
|
| 127 |
+
except Exception as e:
|
| 128 |
+
msg = str(e)
|
| 129 |
+
if "401" in msg or "invalid_api_key" in msg.lower() or "unauthorized" in msg.lower():
|
| 130 |
+
return False, "Invalid Groq API key. Check and re-enter."
|
| 131 |
+
if "quota" in msg.lower() or "rate" in msg.lower():
|
| 132 |
+
return True, "Key valid but rate-limited -- try again shortly."
|
| 133 |
+
return False, f"Error: {msg[:80]}"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def validate_nvidia(key: str) -> tuple:
|
| 137 |
+
"""Test NVIDIA NIM key with a minimal chat completion."""
|
| 138 |
+
if not key or key.strip() in ("", "your_nvidia_key_here"):
|
| 139 |
+
return False, "No key entered."
|
| 140 |
+
try:
|
| 141 |
+
from openai import OpenAI
|
| 142 |
+
client = OpenAI(
|
| 143 |
+
api_key=key.strip(),
|
| 144 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
| 145 |
+
)
|
| 146 |
+
resp = client.chat.completions.create(
|
| 147 |
+
model="meta/llama-3.1-405b-instruct",
|
| 148 |
+
messages=[{"role": "user", "content": "Reply with the single word: OK"}],
|
| 149 |
+
max_tokens=5,
|
| 150 |
+
)
|
| 151 |
+
text = resp.choices[0].message.content.strip() if resp.choices else ""
|
| 152 |
+
return True, f"Valid [OK] (NVIDIA NIM, response: '{text[:20]}')"
|
| 153 |
+
except Exception as e:
|
| 154 |
+
msg = str(e)
|
| 155 |
+
if "401" in msg or "invalid_api_key" in msg.lower() or "unauthorized" in msg.lower():
|
| 156 |
+
return False, "Invalid NVIDIA API key. Check and re-enter."
|
| 157 |
+
return False, f"Error: {msg[:80]}"
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def check_any_ai_model(gemini_key: str = "", claude_key: str = "", openai_key: str = "", groq_key: str = "", nvidia_key: str = "") -> tuple:
|
| 161 |
+
"""Quickly check if at least one AI model is usable."""
|
| 162 |
+
checks = [
|
| 163 |
+
("nvidia", nvidia_key, validate_nvidia),
|
| 164 |
+
("groq", groq_key, validate_groq),
|
| 165 |
+
("gemini", gemini_key, validate_gemini),
|
| 166 |
+
("claude", claude_key, validate_claude),
|
| 167 |
+
("openai", openai_key, validate_openai),
|
| 168 |
+
]
|
| 169 |
+
for name, key, fn in checks:
|
| 170 |
+
if key and key.strip():
|
| 171 |
+
ok, msg = fn(key)
|
| 172 |
+
if ok:
|
| 173 |
+
return True, f"{name.capitalize()}: {msg}"
|
| 174 |
+
|
| 175 |
+
return False, (
|
| 176 |
+
"No working AI model key found.\n\n"
|
| 177 |
+
"Free options (no credit card needed):\n"
|
| 178 |
+
" β’ NVIDIA NIM (Free credits) -> build.nvidia.com\n"
|
| 179 |
+
" β’ Groq (Llama 3.3 70B) -> console.groq.com\n"
|
| 180 |
+
" β’ Gemini -> aistudio.google.com\n\n"
|
| 181 |
+
"Paid options:\n"
|
| 182 |
+
" β’ Claude -> console.anthropic.com\n"
|
| 183 |
+
" β’ ChatGPT -> platform.openai.com/api-keys\n\n"
|
| 184 |
+
"OR uncheck all AI models to run data-only analysis."
|
| 185 |
+
)
|
| 186 |
+
|
pipeline/peer_selector.py
CHANGED
|
@@ -1,185 +1,185 @@
|
|
| 1 |
-
"""
|
| 2 |
-
pipeline/peer_selector.py
|
| 3 |
-
|
| 4 |
-
Uses FMP's peers endpoint first, then falls back to industry-based hardcoded peers.
|
| 5 |
-
"""
|
| 6 |
-
from __future__ import annotations
|
| 7 |
-
|
| 8 |
-
import sys
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
from typing import List, Dict, Optional
|
| 11 |
-
|
| 12 |
-
import requests
|
| 13 |
-
|
| 14 |
-
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 15 |
-
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
-
import config
|
| 17 |
-
from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT
|
| 18 |
-
from pipeline.resolver import CompanyMeta
|
| 19 |
-
from pipeline.fetcher import fetch_peer_snapshot, _fmp_get
|
| 20 |
-
|
| 21 |
-
# yfinance-based peer fetch (no API key needed)
|
| 22 |
-
def _yf_peers_from_industry(meta: CompanyMeta) -> list:
|
| 23 |
-
"""Return peer tickers based on industry using hardcoded maps."""
|
| 24 |
-
return [] # handled by INDIAN_PEERS / GLOBAL_PEERS maps below
|
| 25 |
-
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
INDIAN_PEERS: Dict[str, List[str]] = {
|
| 29 |
-
"IT Services": ["TCS.NS", "INFY.NS", "WIPRO.NS", "HCLTECH.NS", "TECHM.NS"],
|
| 30 |
-
"Information Technology": ["TCS.NS", "INFY.NS", "WIPRO.NS", "HCLTECH.NS", "LTIM.NS"],
|
| 31 |
-
"Banking": ["HDFCBANK.NS", "ICICIBANK.NS", "AXISBANK.NS", "SBIN.NS", "KOTAKBANK.NS"],
|
| 32 |
-
"Finance": ["BAJFINANCE.NS", "BAJAJFINSV.NS", "HDFCAMC.NS", "MUTHOOTFIN.NS"],
|
| 33 |
-
"Pharmaceuticals": ["SUNPHARMA.NS", "CIPLA.NS", "DRREDDY.NS", "DIVISLAB.NS", "AUROPHARMA.NS"],
|
| 34 |
-
"Automobile": ["MARUTI.NS", "TATAMOTORS.NS", "M&M.NS", "HEROMOTOCO.NS", "BAJAJ-AUTO.NS"],
|
| 35 |
-
"FMCG": ["HINDUNILVR.NS", "ITC.NS", "NESTLEIND.NS", "DABUR.NS", "MARICO.NS"],
|
| 36 |
-
"Cement": ["ULTRACEMCO.NS", "SHREECEM.NS", "AMBUJACEM.NS", "ACC.NS", "GRASIM.NS"],
|
| 37 |
-
"Steel": ["TATASTEEL.NS", "JSWSTEEL.NS", "SAIL.NS", "HINDALCO.NS", "VEDL.NS"],
|
| 38 |
-
"Telecom": ["BHARTIARTL.NS", "RELIANCE.NS", "IDEA.NS"],
|
| 39 |
-
"Oil & Gas": ["RELIANCE.NS", "ONGC.NS", "IOC.NS", "BPCL.NS", "HINDPETRO.NS"],
|
| 40 |
-
"Power": ["NTPC.NS", "POWERGRID.NS", "ADANIGREEN.NS", "TATAPOWER.NS", "CESC.NS"],
|
| 41 |
-
"Real Estate": ["DLF.NS", "GODREJPROP.NS", "OBEROIRLTY.NS", "PHOENIXLTD.NS"],
|
| 42 |
-
"Consumer Electronics": ["DIXON.NS", "VOLTAS.NS", "BLUESTARCO.NS", "HAVELLS.NS"],
|
| 43 |
-
"Insurance": ["SBILIFE.NS", "HDFCLIFE.NS", "ICICIPRULI.NS", "LICI.NS"],
|
| 44 |
-
"Retail": ["DMART.NS", "TRENT.NS", "SHOPPERSSTOP.NS", "VMART.NS"],
|
| 45 |
-
"Paints": ["ASIANPAINT.NS", "BERGEPAINT.NS", "KANSAINER.NS", "INDIGO.NS"],
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
GLOBAL_PEERS: Dict[str, List[str]] = {
|
| 49 |
-
"Technology": ["AAPL", "MSFT", "GOOGL", "META", "AMZN"],
|
| 50 |
-
"Semiconductors": ["NVDA", "AMD", "INTC", "QCOM", "AVGO"],
|
| 51 |
-
"Cloud": ["MSFT", "AMZN", "GOOGL", "ORCL", "CRM"],
|
| 52 |
-
"EV/Auto": ["TSLA", "GM", "F", "TM", "STLA"],
|
| 53 |
-
"Banking": ["JPM", "BAC", "WFC", "C", "GS"],
|
| 54 |
-
"Pharma": ["JNJ", "PFE", "MRK", "ABBV", "LLY"],
|
| 55 |
-
"FMCG": ["PG", "KO", "PEP", "UL", "NESN"],
|
| 56 |
-
"Oil & Gas": ["XOM", "CVX", "SHEL", "BP", "TTE"],
|
| 57 |
-
"Retail": ["WMT", "AMZN", "COST", "TGT", "HD"],
|
| 58 |
-
"Telecom": ["VZ", "T", "TMUS", "VOD", "ORAN"],
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _fmp_peers(ticker: str) -> List[str]:
|
| 63 |
-
"""Use FMP's stock-peers endpoint."""
|
| 64 |
-
data = _fmp_get(f"/v4/stock_peers", {"symbol": ticker})
|
| 65 |
-
if data and isinstance(data, list) and data[0].get("peersList"):
|
| 66 |
-
return data[0]["peersList"][:5]
|
| 67 |
-
return []
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def _hf_intelligent_peers(meta: CompanyMeta, log_fn=None) -> List[str]:
|
| 71 |
-
"""Use Hugging Face Serverless API to intelligently select granular peers."""
|
| 72 |
-
def log(msg):
|
| 73 |
-
if log_fn: log_fn(msg)
|
| 74 |
-
|
| 75 |
-
hf_key = getattr(config, "HF_API_KEY", "")
|
| 76 |
-
if not hf_key:
|
| 77 |
-
return []
|
| 78 |
-
|
| 79 |
-
log("
|
| 80 |
-
desc = meta.description if meta.description else "No description available."
|
| 81 |
-
try:
|
| 82 |
-
from huggingface_hub import InferenceClient
|
| 83 |
-
client = InferenceClient(api_key=hf_key)
|
| 84 |
-
|
| 85 |
-
prompt = (
|
| 86 |
-
f"You are a top-tier financial analyst. Given the following company, break down its exact sub-sector "
|
| 87 |
-
f"and identify its 5 closest publicly traded peers.\n"
|
| 88 |
-
f"Company Name: {meta.name}\n"
|
| 89 |
-
f"Industry: {meta.industry}\n"
|
| 90 |
-
f"Description: {desc}\n\n"
|
| 91 |
-
f"Return ONLY a valid JSON array of their Yahoo Finance ticker symbols (e.g., [\"MSFT\", \"GOOGL\"]). "
|
| 92 |
-
f"Do not include any other text, markdown, or explanation. Only the JSON array."
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
response = client.chat_completion(
|
| 96 |
-
model="meta-llama/Meta-Llama-3-8B-Instruct",
|
| 97 |
-
messages=[{"role": "user", "content": prompt}],
|
| 98 |
-
max_tokens=100,
|
| 99 |
-
temperature=0.1
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
if response and response.choices:
|
| 103 |
-
text = response.choices[0].message.content
|
| 104 |
-
|
| 105 |
-
# Extract JSON array using regex
|
| 106 |
-
import re, json
|
| 107 |
-
match = re.search(r'\[(.*?)\]', text, re.DOTALL)
|
| 108 |
-
if match:
|
| 109 |
-
arr_str = match.group(0)
|
| 110 |
-
tickers = json.loads(arr_str)
|
| 111 |
-
if isinstance(tickers, list) and all(isinstance(t, str) for t in tickers):
|
| 112 |
-
log(f"
|
| 113 |
-
return tickers
|
| 114 |
-
log(" β HF AI returned invalid format, falling back...")
|
| 115 |
-
else:
|
| 116 |
-
log(f" β HF API Error. Falling back...")
|
| 117 |
-
except Exception as e:
|
| 118 |
-
log(f" β HF AI Request Failed: {e}. Falling back...")
|
| 119 |
-
|
| 120 |
-
return []
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def select_peers(
|
| 124 |
-
meta: CompanyMeta,
|
| 125 |
-
max_peers: int = 4,
|
| 126 |
-
log_fn=None,
|
| 127 |
-
) -> List[Dict]:
|
| 128 |
-
"""
|
| 129 |
-
Select peer companies for benchmarking.
|
| 130 |
-
Returns list of peer snapshot dicts (same format as peers in the JSON schema).
|
| 131 |
-
"""
|
| 132 |
-
def log(msg):
|
| 133 |
-
if log_fn:
|
| 134 |
-
log_fn(msg)
|
| 135 |
-
|
| 136 |
-
ticker = meta.ticker
|
| 137 |
-
peers_out: List[Dict] = []
|
| 138 |
-
|
| 139 |
-
log(f"Selecting peers for {meta.name} ({meta.industry})
|
| 140 |
-
|
| 141 |
-
# 1. Try Hugging Face Intelligent Peers
|
| 142 |
-
peer_tickers = _hf_intelligent_peers(meta, log_fn)
|
| 143 |
-
|
| 144 |
-
# 2. Try FMP peers endpoint if HF fails
|
| 145 |
-
if not peer_tickers and FMP_API_KEY and meta.is_listed and ticker != "UNLISTED":
|
| 146 |
-
peer_tickers = _fmp_peers(ticker)
|
| 147 |
-
if peer_tickers:
|
| 148 |
-
log(f"
|
| 149 |
-
|
| 150 |
-
# 2. Fallback to hardcoded industry map
|
| 151 |
-
if not peer_tickers:
|
| 152 |
-
industry = meta.industry or meta.sector or ""
|
| 153 |
-
# Check Indian peers first
|
| 154 |
-
for key, tickers in INDIAN_PEERS.items():
|
| 155 |
-
if key.lower() in industry.lower() or industry.lower() in key.lower():
|
| 156 |
-
peer_tickers = [t for t in tickers if t.upper() != ticker.upper()][:max_peers]
|
| 157 |
-
log(f"
|
| 158 |
-
break
|
| 159 |
-
# Check global peers
|
| 160 |
-
if not peer_tickers:
|
| 161 |
-
for key, tickers in GLOBAL_PEERS.items():
|
| 162 |
-
if key.lower() in industry.lower() or industry.lower() in key.lower():
|
| 163 |
-
peer_tickers = [t for t in tickers if t.upper() != ticker.upper()][:max_peers]
|
| 164 |
-
log(f"
|
| 165 |
-
break
|
| 166 |
-
|
| 167 |
-
# Remove self
|
| 168 |
-
peer_tickers = [t for t in peer_tickers if t.upper() != ticker.upper()][:max_peers]
|
| 169 |
-
|
| 170 |
-
if not peer_tickers:
|
| 171 |
-
log(" β No peers found. Peer comparison section will be skipped.")
|
| 172 |
-
return []
|
| 173 |
-
|
| 174 |
-
# 3. Fetch snapshots for each peer
|
| 175 |
-
for pt in peer_tickers:
|
| 176 |
-
log(f"
|
| 177 |
-
snap = fetch_peer_snapshot(pt)
|
| 178 |
-
if snap:
|
| 179 |
-
peers_out.append(snap)
|
| 180 |
-
log(f"
|
| 181 |
-
else:
|
| 182 |
-
log(f"
|
| 183 |
-
|
| 184 |
-
log(f"
|
| 185 |
-
return peers_out
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pipeline/peer_selector.py -- Automatically select 3-5 peer companies.
|
| 3 |
+
|
| 4 |
+
Uses FMP's peers endpoint first, then falls back to industry-based hardcoded peers.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import List, Dict, Optional
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
+
import config
|
| 17 |
+
from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT
|
| 18 |
+
from pipeline.resolver import CompanyMeta
|
| 19 |
+
from pipeline.fetcher import fetch_peer_snapshot, _fmp_get
|
| 20 |
+
|
| 21 |
+
# yfinance-based peer fetch (no API key needed)
|
| 22 |
+
def _yf_peers_from_industry(meta: CompanyMeta) -> list:
|
| 23 |
+
"""Return peer tickers based on industry using hardcoded maps."""
|
| 24 |
+
return [] # handled by INDIAN_PEERS / GLOBAL_PEERS maps below
|
| 25 |
+
|
| 26 |
+
# -- Hardcoded industry -> peer tickers (Indian + Global) ----------------------
|
| 27 |
+
|
| 28 |
+
INDIAN_PEERS: Dict[str, List[str]] = {
|
| 29 |
+
"IT Services": ["TCS.NS", "INFY.NS", "WIPRO.NS", "HCLTECH.NS", "TECHM.NS"],
|
| 30 |
+
"Information Technology": ["TCS.NS", "INFY.NS", "WIPRO.NS", "HCLTECH.NS", "LTIM.NS"],
|
| 31 |
+
"Banking": ["HDFCBANK.NS", "ICICIBANK.NS", "AXISBANK.NS", "SBIN.NS", "KOTAKBANK.NS"],
|
| 32 |
+
"Finance": ["BAJFINANCE.NS", "BAJAJFINSV.NS", "HDFCAMC.NS", "MUTHOOTFIN.NS"],
|
| 33 |
+
"Pharmaceuticals": ["SUNPHARMA.NS", "CIPLA.NS", "DRREDDY.NS", "DIVISLAB.NS", "AUROPHARMA.NS"],
|
| 34 |
+
"Automobile": ["MARUTI.NS", "TATAMOTORS.NS", "M&M.NS", "HEROMOTOCO.NS", "BAJAJ-AUTO.NS"],
|
| 35 |
+
"FMCG": ["HINDUNILVR.NS", "ITC.NS", "NESTLEIND.NS", "DABUR.NS", "MARICO.NS"],
|
| 36 |
+
"Cement": ["ULTRACEMCO.NS", "SHREECEM.NS", "AMBUJACEM.NS", "ACC.NS", "GRASIM.NS"],
|
| 37 |
+
"Steel": ["TATASTEEL.NS", "JSWSTEEL.NS", "SAIL.NS", "HINDALCO.NS", "VEDL.NS"],
|
| 38 |
+
"Telecom": ["BHARTIARTL.NS", "RELIANCE.NS", "IDEA.NS"],
|
| 39 |
+
"Oil & Gas": ["RELIANCE.NS", "ONGC.NS", "IOC.NS", "BPCL.NS", "HINDPETRO.NS"],
|
| 40 |
+
"Power": ["NTPC.NS", "POWERGRID.NS", "ADANIGREEN.NS", "TATAPOWER.NS", "CESC.NS"],
|
| 41 |
+
"Real Estate": ["DLF.NS", "GODREJPROP.NS", "OBEROIRLTY.NS", "PHOENIXLTD.NS"],
|
| 42 |
+
"Consumer Electronics": ["DIXON.NS", "VOLTAS.NS", "BLUESTARCO.NS", "HAVELLS.NS"],
|
| 43 |
+
"Insurance": ["SBILIFE.NS", "HDFCLIFE.NS", "ICICIPRULI.NS", "LICI.NS"],
|
| 44 |
+
"Retail": ["DMART.NS", "TRENT.NS", "SHOPPERSSTOP.NS", "VMART.NS"],
|
| 45 |
+
"Paints": ["ASIANPAINT.NS", "BERGEPAINT.NS", "KANSAINER.NS", "INDIGO.NS"],
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
GLOBAL_PEERS: Dict[str, List[str]] = {
|
| 49 |
+
"Technology": ["AAPL", "MSFT", "GOOGL", "META", "AMZN"],
|
| 50 |
+
"Semiconductors": ["NVDA", "AMD", "INTC", "QCOM", "AVGO"],
|
| 51 |
+
"Cloud": ["MSFT", "AMZN", "GOOGL", "ORCL", "CRM"],
|
| 52 |
+
"EV/Auto": ["TSLA", "GM", "F", "TM", "STLA"],
|
| 53 |
+
"Banking": ["JPM", "BAC", "WFC", "C", "GS"],
|
| 54 |
+
"Pharma": ["JNJ", "PFE", "MRK", "ABBV", "LLY"],
|
| 55 |
+
"FMCG": ["PG", "KO", "PEP", "UL", "NESN"],
|
| 56 |
+
"Oil & Gas": ["XOM", "CVX", "SHEL", "BP", "TTE"],
|
| 57 |
+
"Retail": ["WMT", "AMZN", "COST", "TGT", "HD"],
|
| 58 |
+
"Telecom": ["VZ", "T", "TMUS", "VOD", "ORAN"],
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _fmp_peers(ticker: str) -> List[str]:
|
| 63 |
+
"""Use FMP's stock-peers endpoint."""
|
| 64 |
+
data = _fmp_get(f"/v4/stock_peers", {"symbol": ticker})
|
| 65 |
+
if data and isinstance(data, list) and data[0].get("peersList"):
|
| 66 |
+
return data[0]["peersList"][:5]
|
| 67 |
+
return []
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _hf_intelligent_peers(meta: CompanyMeta, log_fn=None) -> List[str]:
|
| 71 |
+
"""Use Hugging Face Serverless API to intelligently select granular peers."""
|
| 72 |
+
def log(msg):
|
| 73 |
+
if log_fn: log_fn(msg)
|
| 74 |
+
|
| 75 |
+
hf_key = getattr(config, "HF_API_KEY", "")
|
| 76 |
+
if not hf_key:
|
| 77 |
+
return []
|
| 78 |
+
|
| 79 |
+
log(" -> Hugging Face API key detected. Using AI for granular sector breakdown and peer selection...")
|
| 80 |
+
desc = meta.description if meta.description else "No description available."
|
| 81 |
+
try:
|
| 82 |
+
from huggingface_hub import InferenceClient
|
| 83 |
+
client = InferenceClient(api_key=hf_key)
|
| 84 |
+
|
| 85 |
+
prompt = (
|
| 86 |
+
f"You are a top-tier financial analyst. Given the following company, break down its exact sub-sector "
|
| 87 |
+
f"and identify its 5 closest publicly traded peers.\n"
|
| 88 |
+
f"Company Name: {meta.name}\n"
|
| 89 |
+
f"Industry: {meta.industry}\n"
|
| 90 |
+
f"Description: {desc}\n\n"
|
| 91 |
+
f"Return ONLY a valid JSON array of their Yahoo Finance ticker symbols (e.g., [\"MSFT\", \"GOOGL\"]). "
|
| 92 |
+
f"Do not include any other text, markdown, or explanation. Only the JSON array."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
response = client.chat_completion(
|
| 96 |
+
model="meta-llama/Meta-Llama-3-8B-Instruct",
|
| 97 |
+
messages=[{"role": "user", "content": prompt}],
|
| 98 |
+
max_tokens=100,
|
| 99 |
+
temperature=0.1
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if response and response.choices:
|
| 103 |
+
text = response.choices[0].message.content
|
| 104 |
+
|
| 105 |
+
# Extract JSON array using regex
|
| 106 |
+
import re, json
|
| 107 |
+
match = re.search(r'\[(.*?)\]', text, re.DOTALL)
|
| 108 |
+
if match:
|
| 109 |
+
arr_str = match.group(0)
|
| 110 |
+
tickers = json.loads(arr_str)
|
| 111 |
+
if isinstance(tickers, list) and all(isinstance(t, str) for t in tickers):
|
| 112 |
+
log(f" [OK] HF AI successfully identified highly specific peers: {tickers}")
|
| 113 |
+
return tickers
|
| 114 |
+
log(" β HF AI returned invalid format, falling back...")
|
| 115 |
+
else:
|
| 116 |
+
log(f" β HF API Error. Falling back...")
|
| 117 |
+
except Exception as e:
|
| 118 |
+
log(f" β HF AI Request Failed: {e}. Falling back...")
|
| 119 |
+
|
| 120 |
+
return []
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def select_peers(
|
| 124 |
+
meta: CompanyMeta,
|
| 125 |
+
max_peers: int = 4,
|
| 126 |
+
log_fn=None,
|
| 127 |
+
) -> List[Dict]:
|
| 128 |
+
"""
|
| 129 |
+
Select peer companies for benchmarking.
|
| 130 |
+
Returns list of peer snapshot dicts (same format as peers in the JSON schema).
|
| 131 |
+
"""
|
| 132 |
+
def log(msg):
|
| 133 |
+
if log_fn:
|
| 134 |
+
log_fn(msg)
|
| 135 |
+
|
| 136 |
+
ticker = meta.ticker
|
| 137 |
+
peers_out: List[Dict] = []
|
| 138 |
+
|
| 139 |
+
log(f"Selecting peers for {meta.name} ({meta.industry}) ...")
|
| 140 |
+
|
| 141 |
+
# 1. Try Hugging Face Intelligent Peers
|
| 142 |
+
peer_tickers = _hf_intelligent_peers(meta, log_fn)
|
| 143 |
+
|
| 144 |
+
# 2. Try FMP peers endpoint if HF fails
|
| 145 |
+
if not peer_tickers and FMP_API_KEY and meta.is_listed and ticker != "UNLISTED":
|
| 146 |
+
peer_tickers = _fmp_peers(ticker)
|
| 147 |
+
if peer_tickers:
|
| 148 |
+
log(f" -> FMP suggested {len(peer_tickers)} peers")
|
| 149 |
+
|
| 150 |
+
# 2. Fallback to hardcoded industry map
|
| 151 |
+
if not peer_tickers:
|
| 152 |
+
industry = meta.industry or meta.sector or ""
|
| 153 |
+
# Check Indian peers first
|
| 154 |
+
for key, tickers in INDIAN_PEERS.items():
|
| 155 |
+
if key.lower() in industry.lower() or industry.lower() in key.lower():
|
| 156 |
+
peer_tickers = [t for t in tickers if t.upper() != ticker.upper()][:max_peers]
|
| 157 |
+
log(f" -> Using hardcoded Indian peers for '{key}'")
|
| 158 |
+
break
|
| 159 |
+
# Check global peers
|
| 160 |
+
if not peer_tickers:
|
| 161 |
+
for key, tickers in GLOBAL_PEERS.items():
|
| 162 |
+
if key.lower() in industry.lower() or industry.lower() in key.lower():
|
| 163 |
+
peer_tickers = [t for t in tickers if t.upper() != ticker.upper()][:max_peers]
|
| 164 |
+
log(f" -> Using hardcoded global peers for '{key}'")
|
| 165 |
+
break
|
| 166 |
+
|
| 167 |
+
# Remove self
|
| 168 |
+
peer_tickers = [t for t in peer_tickers if t.upper() != ticker.upper()][:max_peers]
|
| 169 |
+
|
| 170 |
+
if not peer_tickers:
|
| 171 |
+
log(" β No peers found. Peer comparison section will be skipped.")
|
| 172 |
+
return []
|
| 173 |
+
|
| 174 |
+
# 3. Fetch snapshots for each peer
|
| 175 |
+
for pt in peer_tickers:
|
| 176 |
+
log(f" -> Fetching peer data: {pt} ...")
|
| 177 |
+
snap = fetch_peer_snapshot(pt)
|
| 178 |
+
if snap:
|
| 179 |
+
peers_out.append(snap)
|
| 180 |
+
log(f" [OK] {snap['name']} ({pt})")
|
| 181 |
+
else:
|
| 182 |
+
log(f" [ERR] Could not fetch {pt}")
|
| 183 |
+
|
| 184 |
+
log(f" [OK] {len(peers_out)} peers ready")
|
| 185 |
+
return peers_out
|
pipeline/resolver.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
pipeline/resolver.py
|
| 3 |
|
| 4 |
Source priority:
|
| 5 |
1. yahooquery (free, no key, excellent Indian stock support)
|
|
@@ -18,7 +18,7 @@ from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT
|
|
| 18 |
import requests
|
| 19 |
|
| 20 |
|
| 21 |
-
#
|
| 22 |
|
| 23 |
class CompanyMeta:
|
| 24 |
def __init__(self, name, ticker, exchange, currency, sector, industry,
|
|
@@ -43,7 +43,7 @@ class CompanyMeta:
|
|
| 43 |
return self.__dict__.copy()
|
| 44 |
|
| 45 |
|
| 46 |
-
#
|
| 47 |
|
| 48 |
INDIAN_TICKERS = {
|
| 49 |
# IT
|
|
@@ -163,7 +163,7 @@ def _guess_ticker(query: str) -> Optional[str]:
|
|
| 163 |
return None
|
| 164 |
|
| 165 |
|
| 166 |
-
#
|
| 167 |
|
| 168 |
def _yq_resolve(ticker: str, log_fn=None) -> Optional[CompanyMeta]:
|
| 169 |
"""Try to resolve a ticker via yahooquery. Returns CompanyMeta or None."""
|
|
@@ -179,7 +179,7 @@ def _yq_resolve(ticker: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 179 |
|
| 180 |
if isinstance(price_data, str) or isinstance(profile_data, str):
|
| 181 |
# Yahooquery sometimes returns strings like "No fundamentals data found"
|
| 182 |
-
log(f"
|
| 183 |
return None
|
| 184 |
|
| 185 |
name = price_data.get("longName") or price_data.get("shortName", "")
|
|
@@ -198,7 +198,7 @@ def _yq_resolve(ticker: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 198 |
# Fiscal year end
|
| 199 |
fy_end = "March" if currency == "INR" else "December"
|
| 200 |
|
| 201 |
-
log(f"
|
| 202 |
return CompanyMeta(
|
| 203 |
name=name,
|
| 204 |
ticker=ticker,
|
|
@@ -216,11 +216,11 @@ def _yq_resolve(ticker: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 216 |
fiscal_year_end=fy_end,
|
| 217 |
)
|
| 218 |
except Exception as e:
|
| 219 |
-
log(f"
|
| 220 |
return None
|
| 221 |
|
| 222 |
|
| 223 |
-
#
|
| 224 |
|
| 225 |
def _fmp_get(path: str, params: dict | None = None):
|
| 226 |
if not FMP_API_KEY:
|
|
@@ -242,7 +242,7 @@ def _fmp_resolve(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 242 |
if log_fn: log_fn(msg)
|
| 243 |
if not FMP_API_KEY:
|
| 244 |
return None
|
| 245 |
-
log("
|
| 246 |
# Direct profile
|
| 247 |
profile = _fmp_get(f"/v3/profile/{query.upper()}")
|
| 248 |
if not (profile and isinstance(profile, list) and profile[0].get("symbol")):
|
|
@@ -258,7 +258,7 @@ def _fmp_resolve(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 258 |
return None
|
| 259 |
exchange = p.get("exchange", "") or p.get("exchangeShortName", "")
|
| 260 |
exchange_map = {"NSE":"NSE (India)","BSE":"BSE (India)","NASDAQ":"NASDAQ (USA)","NYSE":"NYSE (USA)"}
|
| 261 |
-
log(f"
|
| 262 |
return CompanyMeta(
|
| 263 |
name=p.get("companyName",""),
|
| 264 |
ticker=p.get("symbol",""),
|
|
@@ -277,7 +277,7 @@ def _fmp_resolve(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 277 |
)
|
| 278 |
|
| 279 |
|
| 280 |
-
#
|
| 281 |
|
| 282 |
def _yq_search(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
| 283 |
"""Use yahooquery's search to find a ticker from a company name."""
|
|
@@ -285,7 +285,7 @@ def _yq_search(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 285 |
if log_fn: log_fn(msg)
|
| 286 |
try:
|
| 287 |
import yahooquery as yq
|
| 288 |
-
log(f"
|
| 289 |
results = yq.search(query)
|
| 290 |
quotes = results.get("quotes", [])
|
| 291 |
if not quotes:
|
|
@@ -295,37 +295,37 @@ def _yq_search(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
|
| 295 |
symbol = q.get("symbol", "")
|
| 296 |
qtype = q.get("quoteType", "")
|
| 297 |
if qtype in ("EQUITY", "MUTUALFUND") and symbol:
|
| 298 |
-
log(f"
|
| 299 |
return _yq_resolve(symbol, log_fn)
|
| 300 |
return None
|
| 301 |
except Exception as e:
|
| 302 |
-
log(f"
|
| 303 |
return None
|
| 304 |
|
| 305 |
|
| 306 |
-
#
|
| 307 |
|
| 308 |
def resolve(query: str, log_fn=None) -> CompanyMeta:
|
| 309 |
"""
|
| 310 |
Resolve a company name or ticker to CompanyMeta.
|
| 311 |
-
Source priority: Indian map
|
| 312 |
"""
|
| 313 |
def log(msg):
|
| 314 |
if log_fn: log_fn(msg)
|
| 315 |
|
| 316 |
query = query.strip()
|
| 317 |
-
log(f"Resolving: '{query}'
|
| 318 |
|
| 319 |
-
# 1. Check Indian name map
|
| 320 |
indian_ticker = _guess_ticker(query)
|
| 321 |
if indian_ticker:
|
| 322 |
-
log(f"
|
| 323 |
meta = _yq_resolve(indian_ticker, log_fn)
|
| 324 |
if meta: return meta
|
| 325 |
|
| 326 |
# 2. Try direct yahooquery (query as-is, and with .NS suffix)
|
| 327 |
for candidate in [query.upper(), f"{query.upper()}.NS", f"{query.upper()}.BO"]:
|
| 328 |
-
log(f"
|
| 329 |
meta = _yq_resolve(candidate, log_fn)
|
| 330 |
if meta: return meta
|
| 331 |
|
|
@@ -340,7 +340,7 @@ def resolve(query: str, log_fn=None) -> CompanyMeta:
|
|
| 340 |
|
| 341 |
# 5. Unlisted fallback
|
| 342 |
log(f" β '{query}' not found in any public market database.")
|
| 343 |
-
log("
|
| 344 |
return CompanyMeta(
|
| 345 |
name=query, ticker="UNLISTED", exchange="Unlisted / Private",
|
| 346 |
currency="INR", sector="Unknown", industry="Unknown",
|
|
|
|
| 1 |
"""
|
| 2 |
+
pipeline/resolver.py -- Resolve a company name or ticker to structured metadata.
|
| 3 |
|
| 4 |
Source priority:
|
| 5 |
1. yahooquery (free, no key, excellent Indian stock support)
|
|
|
|
| 18 |
import requests
|
| 19 |
|
| 20 |
|
| 21 |
+
# -- CompanyMeta ---------------------------------------------------------------
|
| 22 |
|
| 23 |
class CompanyMeta:
|
| 24 |
def __init__(self, name, ticker, exchange, currency, sector, industry,
|
|
|
|
| 43 |
return self.__dict__.copy()
|
| 44 |
|
| 45 |
|
| 46 |
+
# -- Indian company name -> NSE ticker map -------------------------------------
|
| 47 |
|
| 48 |
INDIAN_TICKERS = {
|
| 49 |
# IT
|
|
|
|
| 163 |
return None
|
| 164 |
|
| 165 |
|
| 166 |
+
# -- yahooquery resolution -------------------------------------------------------
|
| 167 |
|
| 168 |
def _yq_resolve(ticker: str, log_fn=None) -> Optional[CompanyMeta]:
|
| 169 |
"""Try to resolve a ticker via yahooquery. Returns CompanyMeta or None."""
|
|
|
|
| 179 |
|
| 180 |
if isinstance(price_data, str) or isinstance(profile_data, str):
|
| 181 |
# Yahooquery sometimes returns strings like "No fundamentals data found"
|
| 182 |
+
log(f" [ERR] yahooquery returned no data for {ticker}")
|
| 183 |
return None
|
| 184 |
|
| 185 |
name = price_data.get("longName") or price_data.get("shortName", "")
|
|
|
|
| 198 |
# Fiscal year end
|
| 199 |
fy_end = "March" if currency == "INR" else "December"
|
| 200 |
|
| 201 |
+
log(f" [OK] yahooquery: {name} | {ticker} | {exchange_display}")
|
| 202 |
return CompanyMeta(
|
| 203 |
name=name,
|
| 204 |
ticker=ticker,
|
|
|
|
| 216 |
fiscal_year_end=fy_end,
|
| 217 |
)
|
| 218 |
except Exception as e:
|
| 219 |
+
log(f" [ERR] yahooquery failed for {ticker}: {e}")
|
| 220 |
return None
|
| 221 |
|
| 222 |
|
| 223 |
+
# -- FMP resolution ------------------------------------------------------------
|
| 224 |
|
| 225 |
def _fmp_get(path: str, params: dict | None = None):
|
| 226 |
if not FMP_API_KEY:
|
|
|
|
| 242 |
if log_fn: log_fn(msg)
|
| 243 |
if not FMP_API_KEY:
|
| 244 |
return None
|
| 245 |
+
log(" -> Searching FMP ...")
|
| 246 |
# Direct profile
|
| 247 |
profile = _fmp_get(f"/v3/profile/{query.upper()}")
|
| 248 |
if not (profile and isinstance(profile, list) and profile[0].get("symbol")):
|
|
|
|
| 258 |
return None
|
| 259 |
exchange = p.get("exchange", "") or p.get("exchangeShortName", "")
|
| 260 |
exchange_map = {"NSE":"NSE (India)","BSE":"BSE (India)","NASDAQ":"NASDAQ (USA)","NYSE":"NYSE (USA)"}
|
| 261 |
+
log(f" [OK] FMP: {p.get('companyName')} ({p.get('symbol')})")
|
| 262 |
return CompanyMeta(
|
| 263 |
name=p.get("companyName",""),
|
| 264 |
ticker=p.get("symbol",""),
|
|
|
|
| 277 |
)
|
| 278 |
|
| 279 |
|
| 280 |
+
# -- yahooquery search by company name ------------------------------------------
|
| 281 |
|
| 282 |
def _yq_search(query: str, log_fn=None) -> Optional[CompanyMeta]:
|
| 283 |
"""Use yahooquery's search to find a ticker from a company name."""
|
|
|
|
| 285 |
if log_fn: log_fn(msg)
|
| 286 |
try:
|
| 287 |
import yahooquery as yq
|
| 288 |
+
log(f" -> yahooquery search for '{query}' ...")
|
| 289 |
results = yq.search(query)
|
| 290 |
quotes = results.get("quotes", [])
|
| 291 |
if not quotes:
|
|
|
|
| 295 |
symbol = q.get("symbol", "")
|
| 296 |
qtype = q.get("quoteType", "")
|
| 297 |
if qtype in ("EQUITY", "MUTUALFUND") and symbol:
|
| 298 |
+
log(f" -> Found: {q.get('longname', symbol)} ({symbol})")
|
| 299 |
return _yq_resolve(symbol, log_fn)
|
| 300 |
return None
|
| 301 |
except Exception as e:
|
| 302 |
+
log(f" [ERR] yahooquery search failed: {e}")
|
| 303 |
return None
|
| 304 |
|
| 305 |
|
| 306 |
+
# -- Public resolve() ----------------------------------------------------------
|
| 307 |
|
| 308 |
def resolve(query: str, log_fn=None) -> CompanyMeta:
|
| 309 |
"""
|
| 310 |
Resolve a company name or ticker to CompanyMeta.
|
| 311 |
+
Source priority: Indian map -> yahooquery direct -> yahooquery search -> FMP -> unlisted
|
| 312 |
"""
|
| 313 |
def log(msg):
|
| 314 |
if log_fn: log_fn(msg)
|
| 315 |
|
| 316 |
query = query.strip()
|
| 317 |
+
log(f"Resolving: '{query}' ...")
|
| 318 |
|
| 319 |
+
# 1. Check Indian name map -> resolve via yahooquery
|
| 320 |
indian_ticker = _guess_ticker(query)
|
| 321 |
if indian_ticker:
|
| 322 |
+
log(f" [OK] Matches known Indian map -> {indian_ticker}")
|
| 323 |
meta = _yq_resolve(indian_ticker, log_fn)
|
| 324 |
if meta: return meta
|
| 325 |
|
| 326 |
# 2. Try direct yahooquery (query as-is, and with .NS suffix)
|
| 327 |
for candidate in [query.upper(), f"{query.upper()}.NS", f"{query.upper()}.BO"]:
|
| 328 |
+
log(f" -> Trying direct ticker: {candidate}")
|
| 329 |
meta = _yq_resolve(candidate, log_fn)
|
| 330 |
if meta: return meta
|
| 331 |
|
|
|
|
| 340 |
|
| 341 |
# 5. Unlisted fallback
|
| 342 |
log(f" β '{query}' not found in any public market database.")
|
| 343 |
+
log(" -> Treating as unlisted / private company.")
|
| 344 |
return CompanyMeta(
|
| 345 |
name=query, ticker="UNLISTED", exchange="Unlisted / Private",
|
| 346 |
currency="INR", sector="Unknown", industry="Unknown",
|
web_app/app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
web_app/app.py
|
| 3 |
|
| 4 |
Provides a rich dark UI dashboard to scrape, compute, analyze and download reports
|
| 5 |
for Excel, Word, and PowerPoint formats using user-supplied LLM credentials.
|
|
@@ -118,53 +118,53 @@ st.markdown("""
|
|
| 118 |
</style>
|
| 119 |
""", unsafe_allow_html=True)
|
| 120 |
|
| 121 |
-
#
|
| 122 |
st.sidebar.markdown("""
|
| 123 |
<h2 style='color:#60A5FA;margin-top:0;'>π€ Connect Your AI</h2>
|
| 124 |
<p style='font-size:0.8rem;color:#9CA3AF;'>
|
| 125 |
-
Bring your own key. Keys live only in your browser session
|
| 126 |
</p>
|
| 127 |
""", unsafe_allow_html=True)
|
| 128 |
|
| 129 |
-
#
|
| 130 |
st.sidebar.markdown("""
|
| 131 |
<div style='background:rgba(16,185,129,0.08);border:1px solid rgba(16,185,129,0.25);
|
| 132 |
border-radius:8px;padding:0.6rem 0.85rem;margin-bottom:0.5rem;'>
|
| 133 |
-
<span style='font-size:0.75rem;font-weight:700;color:#34D399;letter-spacing:0.06em;'>π FREE
|
| 134 |
</div>
|
| 135 |
""", unsafe_allow_html=True)
|
| 136 |
|
| 137 |
st.sidebar.markdown("""
|
| 138 |
**NVIDIA NIM** *(Llama 3.1 405B / Nemotron)*
|
| 139 |
-
<a href='https://build.nvidia.com/explore/discover' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key
|
| 140 |
""", unsafe_allow_html=True)
|
| 141 |
nvidia_key = st.sidebar.text_input(
|
| 142 |
"NVIDIA API Key", type="password",
|
| 143 |
-
placeholder="nvapi-
|
| 144 |
value=os.environ.get("NVIDIA_API_KEY", ""),
|
| 145 |
help="Free credits available. Sign up at build.nvidia.com.",
|
| 146 |
key="inp_nvidia"
|
| 147 |
)
|
| 148 |
|
| 149 |
st.sidebar.markdown("""
|
| 150 |
-
**Groq** *(Llama 3.3 70B
|
| 151 |
-
<a href='https://console.groq.com/keys' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key
|
| 152 |
""", unsafe_allow_html=True)
|
| 153 |
groq_key = st.sidebar.text_input(
|
| 154 |
"Groq API Key", type="password",
|
| 155 |
-
placeholder="gsk_
|
| 156 |
value=os.environ.get("GROQ_API_KEY", ""),
|
| 157 |
-
help="100% free. Sign up at console.groq.com
|
| 158 |
key="inp_groq"
|
| 159 |
)
|
| 160 |
|
| 161 |
st.sidebar.markdown("""
|
| 162 |
-
**Google Gemini** *(Gemini 2.0 Flash
|
| 163 |
-
<a href='https://aistudio.google.com/app/apikey' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key
|
| 164 |
""", unsafe_allow_html=True)
|
| 165 |
gemini_key = st.sidebar.text_input(
|
| 166 |
"Gemini API Key", type="password",
|
| 167 |
-
placeholder="AIza
|
| 168 |
value=os.environ.get("GEMINI_API_KEY", ""),
|
| 169 |
help="Free tier: 15 requests/min, 1M tokens/day. No billing needed.",
|
| 170 |
key="inp_gemini"
|
|
@@ -172,7 +172,7 @@ gemini_key = st.sidebar.text_input(
|
|
| 172 |
|
| 173 |
st.sidebar.markdown("""
|
| 174 |
**Hugging Face** *(Serverless API)*
|
| 175 |
-
<a href='https://huggingface.co/settings/tokens' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key
|
| 176 |
""", unsafe_allow_html=True)
|
| 177 |
|
| 178 |
_env_hf = os.environ.get("HF_API_KEY", "")
|
|
@@ -182,33 +182,33 @@ if _env_hf:
|
|
| 182 |
else:
|
| 183 |
hf_key = st.sidebar.text_input(
|
| 184 |
"Hugging Face API Key", type="password",
|
| 185 |
-
placeholder="hf_
|
| 186 |
help="Used for intelligent peer selection and DeepSeek analysis.",
|
| 187 |
key="inp_hf"
|
| 188 |
)
|
| 189 |
|
| 190 |
-
#
|
| 191 |
st.sidebar.markdown("""
|
| 192 |
<div style='background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.25);
|
| 193 |
border-radius:8px;padding:0.6rem 0.85rem;margin:0.5rem 0;'>
|
| 194 |
-
<span style='font-size:0.75rem;font-weight:700;color:#818CF8;letter-spacing:0.06em;'>π³ OPTIONAL
|
| 195 |
</div>
|
| 196 |
""", unsafe_allow_html=True)
|
| 197 |
|
| 198 |
-
with st.sidebar.expander("Claude (Anthropic)
|
| 199 |
-
st.markdown("<a href='https://console.anthropic.com/' target='_blank' style='font-size:0.75rem;color:#818CF8;'>Get key
|
| 200 |
claude_key = st.text_input(
|
| 201 |
"Claude API Key", type="password",
|
| 202 |
-
placeholder="sk-ant-
|
| 203 |
value=os.environ.get("CLAUDE_API_KEY", ""),
|
| 204 |
key="inp_claude"
|
| 205 |
)
|
| 206 |
|
| 207 |
-
with st.sidebar.expander("ChatGPT (OpenAI)
|
| 208 |
-
st.markdown("<a href='https://platform.openai.com/api-keys' target='_blank' style='font-size:0.75rem;color:#818CF8;'>Get key
|
| 209 |
openai_key = st.text_input(
|
| 210 |
"OpenAI API Key", type="password",
|
| 211 |
-
placeholder="sk-proj-
|
| 212 |
value=os.environ.get("OPENAI_API_KEY", ""),
|
| 213 |
key="inp_openai"
|
| 214 |
)
|
|
@@ -217,14 +217,14 @@ st.sidebar.markdown("---")
|
|
| 217 |
st.sidebar.markdown("<h3 style='color:#34D399;'>π€ User Profile</h3>", unsafe_allow_html=True)
|
| 218 |
username = st.sidebar.text_input("Username / Email", value="", placeholder="name@company.com", help="Mandatory for audit trail")
|
| 219 |
|
| 220 |
-
#
|
| 221 |
st.markdown("<h1 class='dashboard-title'>π Financial Statement Analyzer</h1>", unsafe_allow_html=True)
|
| 222 |
st.markdown("<p class='dashboard-subtitle'>Multi-model AI insights scraper and report compilation portal</p>", unsafe_allow_html=True)
|
| 223 |
|
| 224 |
st.markdown("<div class='glass-card'>", unsafe_allow_html=True)
|
| 225 |
st.subheader("Analysis Parameters")
|
| 226 |
|
| 227 |
-
#
|
| 228 |
search_col1, search_col2 = st.columns([3, 1])
|
| 229 |
with search_col1:
|
| 230 |
search_query = st.text_input("Search Company Name or Ticker", placeholder="e.g. TCS, Reliance, AAPL, MSFT")
|
|
@@ -266,15 +266,15 @@ chk_excel = st.checkbox("Excel Analysis Workbook (.xlsx)", value=True)
|
|
| 266 |
chk_word = st.checkbox("Word Summary Report (.docx)", value=True)
|
| 267 |
chk_pptx = st.checkbox("PowerPoint Pitch Deck (.pptx)", value=True)
|
| 268 |
|
| 269 |
-
#
|
| 270 |
st.markdown("<b>AI Engines:</b>", unsafe_allow_html=True)
|
| 271 |
|
| 272 |
-
_hint = "<span style='font-size:0.72rem;color:#9CA3AF;'>(add key in sidebar
|
| 273 |
|
| 274 |
engines = []
|
| 275 |
|
| 276 |
if st.checkbox(
|
| 277 |
-
"π NVIDIA NIM
|
| 278 |
value=bool(nvidia_key),
|
| 279 |
disabled=not nvidia_key,
|
| 280 |
help="Free credits. Get key at build.nvidia.com"
|
|
@@ -282,7 +282,7 @@ if st.checkbox(
|
|
| 282 |
engines.append("nvidia")
|
| 283 |
|
| 284 |
if st.checkbox(
|
| 285 |
-
"π Groq
|
| 286 |
value=bool(groq_key),
|
| 287 |
disabled=not groq_key,
|
| 288 |
help="Free. Get key at console.groq.com"
|
|
@@ -290,7 +290,7 @@ if st.checkbox(
|
|
| 290 |
engines.append("groq")
|
| 291 |
|
| 292 |
if st.checkbox(
|
| 293 |
-
"π Hugging Face
|
| 294 |
value=bool(hf_key),
|
| 295 |
disabled=not hf_key,
|
| 296 |
help="Free via Hugging Face Inference API"
|
|
@@ -314,7 +314,7 @@ if st.checkbox(
|
|
| 314 |
engines.append("claude")
|
| 315 |
|
| 316 |
if st.checkbox(
|
| 317 |
-
"π³ ChatGPT
|
| 318 |
value=False,
|
| 319 |
disabled=not openai_key,
|
| 320 |
help="Paid. Add key in sidebar to enable."
|
|
@@ -333,7 +333,7 @@ status_container = st.empty()
|
|
| 333 |
metrics_container = st.empty()
|
| 334 |
download_container = st.empty()
|
| 335 |
|
| 336 |
-
#
|
| 337 |
if start_btn:
|
| 338 |
if not username or "@" not in username:
|
| 339 |
st.error("Please enter a valid email address in the User Profile section before analyzing.")
|
|
@@ -406,35 +406,35 @@ if start_btn:
|
|
| 406 |
|
| 407 |
# 1. Resolve Company Info
|
| 408 |
progress_bar.progress(14, text="[1/7] Resolving company metadata...")
|
| 409 |
-
log_fn("\n[1/7] Resolving company metadata
|
| 410 |
meta = resolve(ticker_input, log_fn=log_fn)
|
| 411 |
-
log_fn(f"
|
| 412 |
|
| 413 |
# 2. Fetch Statements
|
| 414 |
progress_bar.progress(28, text="[2/7] Scrape financial statements...")
|
| 415 |
-
log_fn("\n[2/7] Scrape financial statements
|
| 416 |
fin_data = fetch_all(meta, force_refresh=force_refresh, log_fn=log_fn)
|
| 417 |
|
| 418 |
# 3. Peers Comparison Selection
|
| 419 |
progress_bar.progress(42, text="[3/7] Benchmarking peer selection...")
|
| 420 |
-
log_fn("\n[3/7] Benchmarking peer selection
|
| 421 |
fin_data["peers"] = select_peers(meta, log_fn=log_fn)
|
| 422 |
|
| 423 |
# 4. Math ratios calculations
|
| 424 |
progress_bar.progress(57, text="[4/7] Computing financial ratios...")
|
| 425 |
-
log_fn("\n[4/7] Computing financial ratios & DuPont decomposition
|
| 426 |
fin_data = calculate(fin_data, meta.to_dict())
|
| 427 |
-
log_fn("
|
| 428 |
|
| 429 |
# 5. AI Synthesis Narrative
|
| 430 |
progress_bar.progress(71, text="[5/7] Requesting AI Model narrative...")
|
| 431 |
-
log_fn("\n[5/7] Requesting AI Model narrative generation
|
| 432 |
narrative = generate_narrative(fin_data, meta.to_dict(), engines, log_fn=log_fn)
|
| 433 |
fin_data.update(narrative)
|
| 434 |
|
| 435 |
# 6. Generate outputs
|
| 436 |
progress_bar.progress(85, text="[6/7] Building output report files...")
|
| 437 |
-
log_fn("\n[6/7] Building output report files
|
| 438 |
fin_data["company"] = {
|
| 439 |
"name": meta.name, "ticker": meta.ticker, "exchange": meta.exchange,
|
| 440 |
"currency": fin_data.get("currency", meta.currency),
|
|
@@ -466,31 +466,31 @@ if start_btn:
|
|
| 466 |
build_workbook(fin_data, str(xlsx_path))
|
| 467 |
with open(xlsx_path, "rb") as f:
|
| 468 |
excel_bytes = f.read()
|
| 469 |
-
log_fn(f"
|
| 470 |
|
| 471 |
if chk_word:
|
| 472 |
docx_path = out_dir / f"{ticker_safe}_financial_analysis_{timestamp_suffix}.docx"
|
| 473 |
build_document(fin_data, str(docx_path))
|
| 474 |
with open(docx_path, "rb") as f:
|
| 475 |
word_bytes = f.read()
|
| 476 |
-
log_fn(f"
|
| 477 |
|
| 478 |
if chk_pptx:
|
| 479 |
pptx_path = out_dir / f"{ticker_safe}_financial_analysis_{timestamp_suffix}.pptx"
|
| 480 |
build_presentation(fin_data, str(pptx_path))
|
| 481 |
with open(pptx_path, "rb") as f:
|
| 482 |
pptx_bytes = f.read()
|
| 483 |
-
log_fn(f"
|
| 484 |
|
| 485 |
progress_bar.progress(100, text="[7/7] Financial analysis process complete!")
|
| 486 |
log_fn(f"\n[7/7] β
Financial analysis process complete!")
|
| 487 |
status_box.update(state="complete", expanded=False)
|
| 488 |
|
| 489 |
-
#
|
| 490 |
st.toast('Analysis successfully completed!', icon='π')
|
| 491 |
with metrics_container.container():
|
| 492 |
st.markdown("### π Quick Insights", unsafe_allow_html=True)
|
| 493 |
-
mc1, mc2, mc3 = st.columns(
|
| 494 |
mc1.metric("Company", meta.name, meta.ticker)
|
| 495 |
|
| 496 |
# Format Price
|
|
@@ -509,9 +509,32 @@ if start_btn:
|
|
| 509 |
else:
|
| 510 |
mc_str = f"{fin_data.get('currency', '')} {mc_val/1e6:,.2f} Million"
|
| 511 |
mc3.metric("Market Cap", mc_str)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
st.markdown("<br>", unsafe_allow_html=True)
|
| 513 |
|
| 514 |
-
#
|
| 515 |
with download_container.container():
|
| 516 |
st.success("Download ready!")
|
| 517 |
dl_col1, dl_col2, dl_col3, dl_col4 = st.columns(4)
|
|
@@ -593,7 +616,7 @@ if start_btn:
|
|
| 593 |
except:
|
| 594 |
pass
|
| 595 |
|
| 596 |
-
#
|
| 597 |
st.markdown("---")
|
| 598 |
st.markdown("<h3 style='color:#60A5FA;margin-top:0;'>π Query Audit Trail & History</h3>", unsafe_allow_html=True)
|
| 599 |
st.markdown("<p style='font-size:0.85rem;color:#9CA3AF;'>Past analysis runs requested by team members.</p>", unsafe_allow_html=True)
|
|
|
|
| 1 |
"""
|
| 2 |
+
web_app/app.py -- Cloud-hosted Streamlit Portal for Financial Analysis.
|
| 3 |
|
| 4 |
Provides a rich dark UI dashboard to scrape, compute, analyze and download reports
|
| 5 |
for Excel, Word, and PowerPoint formats using user-supplied LLM credentials.
|
|
|
|
| 118 |
</style>
|
| 119 |
""", unsafe_allow_html=True)
|
| 120 |
|
| 121 |
+
# -- Sidebar -- Connect Your AI ------------------------------------------
|
| 122 |
st.sidebar.markdown("""
|
| 123 |
<h2 style='color:#60A5FA;margin-top:0;'>π€ Connect Your AI</h2>
|
| 124 |
<p style='font-size:0.8rem;color:#9CA3AF;'>
|
| 125 |
+
Bring your own key. Keys live only in your browser session -- never stored on the server.
|
| 126 |
</p>
|
| 127 |
""", unsafe_allow_html=True)
|
| 128 |
|
| 129 |
+
# -- FREE OPTIONS -------------------------------------------------------
|
| 130 |
st.sidebar.markdown("""
|
| 131 |
<div style='background:rgba(16,185,129,0.08);border:1px solid rgba(16,185,129,0.25);
|
| 132 |
border-radius:8px;padding:0.6rem 0.85rem;margin-bottom:0.5rem;'>
|
| 133 |
+
<span style='font-size:0.75rem;font-weight:700;color:#34D399;letter-spacing:0.06em;'>π FREE -- NO CREDIT CARD</span>
|
| 134 |
</div>
|
| 135 |
""", unsafe_allow_html=True)
|
| 136 |
|
| 137 |
st.sidebar.markdown("""
|
| 138 |
**NVIDIA NIM** *(Llama 3.1 405B / Nemotron)*
|
| 139 |
+
<a href='https://build.nvidia.com/explore/discover' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key -> build.nvidia.com</a>
|
| 140 |
""", unsafe_allow_html=True)
|
| 141 |
nvidia_key = st.sidebar.text_input(
|
| 142 |
"NVIDIA API Key", type="password",
|
| 143 |
+
placeholder="nvapi-...",
|
| 144 |
value=os.environ.get("NVIDIA_API_KEY", ""),
|
| 145 |
help="Free credits available. Sign up at build.nvidia.com.",
|
| 146 |
key="inp_nvidia"
|
| 147 |
)
|
| 148 |
|
| 149 |
st.sidebar.markdown("""
|
| 150 |
+
**Groq** *(Llama 3.3 70B -- fast & free)*
|
| 151 |
+
<a href='https://console.groq.com/keys' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key -> console.groq.com</a>
|
| 152 |
""", unsafe_allow_html=True)
|
| 153 |
groq_key = st.sidebar.text_input(
|
| 154 |
"Groq API Key", type="password",
|
| 155 |
+
placeholder="gsk_...",
|
| 156 |
value=os.environ.get("GROQ_API_KEY", ""),
|
| 157 |
+
help="100% free. Sign up at console.groq.com -> API Keys. No credit card.",
|
| 158 |
key="inp_groq"
|
| 159 |
)
|
| 160 |
|
| 161 |
st.sidebar.markdown("""
|
| 162 |
+
**Google Gemini** *(Gemini 2.0 Flash -- free tier)*
|
| 163 |
+
<a href='https://aistudio.google.com/app/apikey' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key -> aistudio.google.com</a>
|
| 164 |
""", unsafe_allow_html=True)
|
| 165 |
gemini_key = st.sidebar.text_input(
|
| 166 |
"Gemini API Key", type="password",
|
| 167 |
+
placeholder="AIza...",
|
| 168 |
value=os.environ.get("GEMINI_API_KEY", ""),
|
| 169 |
help="Free tier: 15 requests/min, 1M tokens/day. No billing needed.",
|
| 170 |
key="inp_gemini"
|
|
|
|
| 172 |
|
| 173 |
st.sidebar.markdown("""
|
| 174 |
**Hugging Face** *(Serverless API)*
|
| 175 |
+
<a href='https://huggingface.co/settings/tokens' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key -> huggingface.co</a>
|
| 176 |
""", unsafe_allow_html=True)
|
| 177 |
|
| 178 |
_env_hf = os.environ.get("HF_API_KEY", "")
|
|
|
|
| 182 |
else:
|
| 183 |
hf_key = st.sidebar.text_input(
|
| 184 |
"Hugging Face API Key", type="password",
|
| 185 |
+
placeholder="hf_...",
|
| 186 |
help="Used for intelligent peer selection and DeepSeek analysis.",
|
| 187 |
key="inp_hf"
|
| 188 |
)
|
| 189 |
|
| 190 |
+
# -- PAID OPTIONS -------------------------------------------------------
|
| 191 |
st.sidebar.markdown("""
|
| 192 |
<div style='background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.25);
|
| 193 |
border-radius:8px;padding:0.6rem 0.85rem;margin:0.5rem 0;'>
|
| 194 |
+
<span style='font-size:0.75rem;font-weight:700;color:#818CF8;letter-spacing:0.06em;'>π³ OPTIONAL -- PAID APIS</span>
|
| 195 |
</div>
|
| 196 |
""", unsafe_allow_html=True)
|
| 197 |
|
| 198 |
+
with st.sidebar.expander("Claude (Anthropic) -- paid", expanded=False):
|
| 199 |
+
st.markdown("<a href='https://console.anthropic.com/' target='_blank' style='font-size:0.75rem;color:#818CF8;'>Get key -> console.anthropic.com</a>", unsafe_allow_html=True)
|
| 200 |
claude_key = st.text_input(
|
| 201 |
"Claude API Key", type="password",
|
| 202 |
+
placeholder="sk-ant-...",
|
| 203 |
value=os.environ.get("CLAUDE_API_KEY", ""),
|
| 204 |
key="inp_claude"
|
| 205 |
)
|
| 206 |
|
| 207 |
+
with st.sidebar.expander("ChatGPT (OpenAI) -- paid", expanded=False):
|
| 208 |
+
st.markdown("<a href='https://platform.openai.com/api-keys' target='_blank' style='font-size:0.75rem;color:#818CF8;'>Get key -> platform.openai.com</a>", unsafe_allow_html=True)
|
| 209 |
openai_key = st.text_input(
|
| 210 |
"OpenAI API Key", type="password",
|
| 211 |
+
placeholder="sk-proj-...",
|
| 212 |
value=os.environ.get("OPENAI_API_KEY", ""),
|
| 213 |
key="inp_openai"
|
| 214 |
)
|
|
|
|
| 217 |
st.sidebar.markdown("<h3 style='color:#34D399;'>π€ User Profile</h3>", unsafe_allow_html=True)
|
| 218 |
username = st.sidebar.text_input("Username / Email", value="", placeholder="name@company.com", help="Mandatory for audit trail")
|
| 219 |
|
| 220 |
+
# -- Main Dashboard Layout ----------------------------------------------
|
| 221 |
st.markdown("<h1 class='dashboard-title'>π Financial Statement Analyzer</h1>", unsafe_allow_html=True)
|
| 222 |
st.markdown("<p class='dashboard-subtitle'>Multi-model AI insights scraper and report compilation portal</p>", unsafe_allow_html=True)
|
| 223 |
|
| 224 |
st.markdown("<div class='glass-card'>", unsafe_allow_html=True)
|
| 225 |
st.subheader("Analysis Parameters")
|
| 226 |
|
| 227 |
+
# -- Ticker Search & Suggestion Logic --
|
| 228 |
search_col1, search_col2 = st.columns([3, 1])
|
| 229 |
with search_col1:
|
| 230 |
search_query = st.text_input("Search Company Name or Ticker", placeholder="e.g. TCS, Reliance, AAPL, MSFT")
|
|
|
|
| 266 |
chk_word = st.checkbox("Word Summary Report (.docx)", value=True)
|
| 267 |
chk_pptx = st.checkbox("PowerPoint Pitch Deck (.pptx)", value=True)
|
| 268 |
|
| 269 |
+
# -- AI Engine selection -- auto-disable if key not supplied
|
| 270 |
st.markdown("<b>AI Engines:</b>", unsafe_allow_html=True)
|
| 271 |
|
| 272 |
+
_hint = "<span style='font-size:0.72rem;color:#9CA3AF;'>(add key in sidebar ->)</span>"
|
| 273 |
|
| 274 |
engines = []
|
| 275 |
|
| 276 |
if st.checkbox(
|
| 277 |
+
"π NVIDIA NIM -- Llama 3.1 405B",
|
| 278 |
value=bool(nvidia_key),
|
| 279 |
disabled=not nvidia_key,
|
| 280 |
help="Free credits. Get key at build.nvidia.com"
|
|
|
|
| 282 |
engines.append("nvidia")
|
| 283 |
|
| 284 |
if st.checkbox(
|
| 285 |
+
"π Groq -- Llama 3.3 70B",
|
| 286 |
value=bool(groq_key),
|
| 287 |
disabled=not groq_key,
|
| 288 |
help="Free. Get key at console.groq.com"
|
|
|
|
| 290 |
engines.append("groq")
|
| 291 |
|
| 292 |
if st.checkbox(
|
| 293 |
+
"π Hugging Face -- DeepSeek-R1",
|
| 294 |
value=bool(hf_key),
|
| 295 |
disabled=not hf_key,
|
| 296 |
help="Free via Hugging Face Inference API"
|
|
|
|
| 314 |
engines.append("claude")
|
| 315 |
|
| 316 |
if st.checkbox(
|
| 317 |
+
"π³ ChatGPT -- GPT-4o mini (OpenAI)",
|
| 318 |
value=False,
|
| 319 |
disabled=not openai_key,
|
| 320 |
help="Paid. Add key in sidebar to enable."
|
|
|
|
| 333 |
metrics_container = st.empty()
|
| 334 |
download_container = st.empty()
|
| 335 |
|
| 336 |
+
# -- Analysis Runner ---------------------------------------------------
|
| 337 |
if start_btn:
|
| 338 |
if not username or "@" not in username:
|
| 339 |
st.error("Please enter a valid email address in the User Profile section before analyzing.")
|
|
|
|
| 406 |
|
| 407 |
# 1. Resolve Company Info
|
| 408 |
progress_bar.progress(14, text="[1/7] Resolving company metadata...")
|
| 409 |
+
log_fn("\n[1/7] Resolving company metadata ...")
|
| 410 |
meta = resolve(ticker_input, log_fn=log_fn)
|
| 411 |
+
log_fn(f" [OK] {meta.name} | {meta.ticker} | {meta.exchange}")
|
| 412 |
|
| 413 |
# 2. Fetch Statements
|
| 414 |
progress_bar.progress(28, text="[2/7] Scrape financial statements...")
|
| 415 |
+
log_fn("\n[2/7] Scrape financial statements ...")
|
| 416 |
fin_data = fetch_all(meta, force_refresh=force_refresh, log_fn=log_fn)
|
| 417 |
|
| 418 |
# 3. Peers Comparison Selection
|
| 419 |
progress_bar.progress(42, text="[3/7] Benchmarking peer selection...")
|
| 420 |
+
log_fn("\n[3/7] Benchmarking peer selection ...")
|
| 421 |
fin_data["peers"] = select_peers(meta, log_fn=log_fn)
|
| 422 |
|
| 423 |
# 4. Math ratios calculations
|
| 424 |
progress_bar.progress(57, text="[4/7] Computing financial ratios...")
|
| 425 |
+
log_fn("\n[4/7] Computing financial ratios & DuPont decomposition ...")
|
| 426 |
fin_data = calculate(fin_data, meta.to_dict())
|
| 427 |
+
log_fn(" [OK] Completed ratio math computations")
|
| 428 |
|
| 429 |
# 5. AI Synthesis Narrative
|
| 430 |
progress_bar.progress(71, text="[5/7] Requesting AI Model narrative...")
|
| 431 |
+
log_fn("\n[5/7] Requesting AI Model narrative generation ...")
|
| 432 |
narrative = generate_narrative(fin_data, meta.to_dict(), engines, log_fn=log_fn)
|
| 433 |
fin_data.update(narrative)
|
| 434 |
|
| 435 |
# 6. Generate outputs
|
| 436 |
progress_bar.progress(85, text="[6/7] Building output report files...")
|
| 437 |
+
log_fn("\n[6/7] Building output report files ...")
|
| 438 |
fin_data["company"] = {
|
| 439 |
"name": meta.name, "ticker": meta.ticker, "exchange": meta.exchange,
|
| 440 |
"currency": fin_data.get("currency", meta.currency),
|
|
|
|
| 466 |
build_workbook(fin_data, str(xlsx_path))
|
| 467 |
with open(xlsx_path, "rb") as f:
|
| 468 |
excel_bytes = f.read()
|
| 469 |
+
log_fn(f" [OK] Created Excel analysis: {xlsx_path.name}")
|
| 470 |
|
| 471 |
if chk_word:
|
| 472 |
docx_path = out_dir / f"{ticker_safe}_financial_analysis_{timestamp_suffix}.docx"
|
| 473 |
build_document(fin_data, str(docx_path))
|
| 474 |
with open(docx_path, "rb") as f:
|
| 475 |
word_bytes = f.read()
|
| 476 |
+
log_fn(f" [OK] Created Word summary: {docx_path.name}")
|
| 477 |
|
| 478 |
if chk_pptx:
|
| 479 |
pptx_path = out_dir / f"{ticker_safe}_financial_analysis_{timestamp_suffix}.pptx"
|
| 480 |
build_presentation(fin_data, str(pptx_path))
|
| 481 |
with open(pptx_path, "rb") as f:
|
| 482 |
pptx_bytes = f.read()
|
| 483 |
+
log_fn(f" [OK] Created PowerPoint Presentation: {pptx_path.name}")
|
| 484 |
|
| 485 |
progress_bar.progress(100, text="[7/7] Financial analysis process complete!")
|
| 486 |
log_fn(f"\n[7/7] β
Financial analysis process complete!")
|
| 487 |
status_box.update(state="complete", expanded=False)
|
| 488 |
|
| 489 |
+
# -- Display Success Metrics
|
| 490 |
st.toast('Analysis successfully completed!', icon='π')
|
| 491 |
with metrics_container.container():
|
| 492 |
st.markdown("### π Quick Insights", unsafe_allow_html=True)
|
| 493 |
+
mc1, mc2, mc3, mc4 = st.columns(4)
|
| 494 |
mc1.metric("Company", meta.name, meta.ticker)
|
| 495 |
|
| 496 |
# Format Price
|
|
|
|
| 509 |
else:
|
| 510 |
mc_str = f"{fin_data.get('currency', '')} {mc_val/1e6:,.2f} Million"
|
| 511 |
mc3.metric("Market Cap", mc_str)
|
| 512 |
+
|
| 513 |
+
# Data quality badge
|
| 514 |
+
dq = fin_data.get("data_quality", 0)
|
| 515 |
+
if dq >= 80:
|
| 516 |
+
dq_color, dq_label = "#22c55e", "Excellent"
|
| 517 |
+
elif dq >= 55:
|
| 518 |
+
dq_color, dq_label = "#f59e0b", "Partial"
|
| 519 |
+
else:
|
| 520 |
+
dq_color, dq_label = "#ef4444", "Low"
|
| 521 |
+
mc4.markdown(
|
| 522 |
+
f"""<div style='background:rgba(255,255,255,0.05);border-radius:12px;
|
| 523 |
+
padding:14px 12px;text-align:center;border:1px solid rgba(255,255,255,0.1)'>
|
| 524 |
+
<div style='font-size:0.75rem;color:#9CA3AF;margin-bottom:4px'>Data Quality</div>
|
| 525 |
+
<div style='font-size:1.6rem;font-weight:700;color:{dq_color}'>{dq}%</div>
|
| 526 |
+
<div style='font-size:0.75rem;color:{dq_color}'>{dq_label}</div>
|
| 527 |
+
</div>""",
|
| 528 |
+
unsafe_allow_html=True
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# Source attribution
|
| 532 |
+
src = fin_data.get("source", "")
|
| 533 |
+
if src:
|
| 534 |
+
st.caption(f"Data sources: {src}")
|
| 535 |
st.markdown("<br>", unsafe_allow_html=True)
|
| 536 |
|
| 537 |
+
# -- Generate download buttons in UI
|
| 538 |
with download_container.container():
|
| 539 |
st.success("Download ready!")
|
| 540 |
dl_col1, dl_col2, dl_col3, dl_col4 = st.columns(4)
|
|
|
|
| 616 |
except:
|
| 617 |
pass
|
| 618 |
|
| 619 |
+
# -- Audit History Panel Table -------------------------------------------
|
| 620 |
st.markdown("---")
|
| 621 |
st.markdown("<h3 style='color:#60A5FA;margin-top:0;'>π Query Audit Trail & History</h3>", unsafe_allow_html=True)
|
| 622 |
st.markdown("<p style='font-size:0.85rem;color:#9CA3AF;'>Past analysis runs requested by team members.</p>", unsafe_allow_html=True)
|