Shivam4096 commited on
Commit
fd3c1f7
Β·
verified Β·
1 Parent(s): 02b42b3

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. pipeline/fetcher.py +838 -759
pipeline/fetcher.py CHANGED
@@ -1,759 +1,838 @@
1
- """
2
- pipeline/fetcher.py β€” Fetch 5-year financials.
3
- Priority: yfinance (free, Indian stocks) β†’ FMP β†’ screener.in
4
- """
5
- from __future__ import annotations
6
- import sys, re, json, datetime
7
- from pathlib import Path
8
- from typing import Optional, List, Dict, Any
9
-
10
- import requests
11
- from bs4 import BeautifulSoup
12
-
13
- sys.path.insert(0, str(Path(__file__).parent.parent))
14
- from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT, DEFAULT_YEARS
15
- from storage.cache import get_cached, set_cache
16
- from pipeline.resolver import CompanyMeta
17
-
18
- HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
19
-
20
-
21
- # ── Helpers ───────────────────────────────────────────────────────────────────
22
-
23
- def _s(v, default=None):
24
- if v is None or (isinstance(v, float) and v != v): return default
25
- return v
26
-
27
-
28
- def _row(df, *keys):
29
- """Get a row from a yfinance DataFrame by trying multiple key names."""
30
- for k in keys:
31
- if k in df.index:
32
- return df.loc[k].tolist()
33
- return [None] * len(df.columns)
34
-
35
-
36
- # ── yfinance fetcher (primary for Indian + global) ───────────────────────────
37
-
38
- def _fetch_yfinance(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
39
- def log(m):
40
- if log_fn: log_fn(m)
41
- try:
42
- import yfinance as yf
43
- log(f" β†’ yfinance: fetching {ticker} …")
44
- t = yf.Ticker(ticker)
45
-
46
- fin = t.financials # newest col first
47
- bs = t.balance_sheet
48
- cf = t.cashflow
49
- info = t.info
50
-
51
- if fin is None or fin.empty:
52
- log(" βœ— yfinance returned empty financials")
53
- return None
54
-
55
- # Year labels — columns are Timestamps, newest first; we want oldest→newest
56
- all_cols = list(fin.columns) # newest first
57
- use_cols = all_cols[:years] # take up to `years` newest
58
- use_cols_asc = list(reversed(use_cols)) # now oldest→newest
59
- year_labels = []
60
- for c in use_cols_asc:
61
- try:
62
- year_labels.append(f"{c.year}/{c.month:02d}")
63
- except Exception:
64
- year_labels.append(str(c)[:7])
65
-
66
- n = len(year_labels)
67
-
68
- def col(df, *keys):
69
- """Extract a row from df, return list oldest→newest, length n."""
70
- for k in keys:
71
- if df is not None and not df.empty and k in df.index:
72
- # df columns are newest first; slice to use_cols then reverse
73
- vals = []
74
- for c in use_cols_asc: # iterate oldest→newest
75
- if c in df.columns:
76
- v = df.at[k, c]
77
- if currency == "INR":
78
- scale = 1e7
79
- units = "Crores"
80
- units_label = "INR Crores (β‚Ή Cr)"
81
- else:
82
- scale = 1e6
83
- units = "Millions"
84
- units_label = f"{currency} Millions"
85
-
86
- def col(df, *keys):
87
- for k in keys:
88
- if k in df.columns:
89
- return df[k].tolist()
90
- return [None] * len(df)
91
-
92
- def sc(lst):
93
- return [round(v / scale, 2) if v is not None and not pd.isna(v) else None for v in lst]
94
-
95
- income = {
96
- "revenue": sc(col(inc, "TotalRevenue", "OperatingRevenue")),
97
- "cost_of_revenue": sc(col(inc, "CostOfRevenue", "ReconciledCostOfRevenue")),
98
- "gross_profit": sc(col(inc, "GrossProfit")),
99
- "operating_expenses": sc(col(inc, "OperatingExpense")),
100
- "operating_income": sc(col(inc, "OperatingIncome", "EBIT")),
101
- "ebitda": sc(col(inc, "EBITDA", "NormalizedEBITDA")),
102
- "depreciation_amort": sc(col(inc, "ReconciledDepreciation", "DepreciationAndAmortization")),
103
- "interest_expense": sc(col(inc, "InterestExpenseNonOperating", "InterestExpense")),
104
- "pretax_income": sc(col(inc, "PretaxIncome")),
105
- "tax_expense": sc(col(inc, "TaxProvision")),
106
- "net_income": sc(col(inc, "NetIncome", "NetIncomeCommonStockholders")),
107
- "diluted_eps": col(inc, "DilutedEPS"),
108
- "diluted_shares": col(inc, "DilutedAverageShares"),
109
- }
110
-
111
- balance = {
112
- "cash_and_equivalents": sc(col(bs, "CashAndCashEquivalents", "CashFinancial")),
113
- "short_term_investments": sc(col(bs, "OtherShortTermInvestments")),
114
- "receivables": sc(col(bs, "AccountsReceivable", "Receivables")),
115
- "inventory": sc(col(bs, "Inventory")),
116
- "other_current_assets": sc(col(bs, "OtherCurrentAssets")),
117
- "total_current_assets": sc(col(bs, "CurrentAssets")),
118
- "ppe_net": sc(col(bs, "NetPPE")),
119
- "goodwill": sc(col(bs, "Goodwill")),
120
- "intangibles": sc(col(bs, "OtherIntangibleAssets")),
121
- "other_long_term_assets": sc(col(bs, "OtherNonCurrentAssets")),
122
- "total_assets": sc(col(bs, "TotalAssets")),
123
- "accounts_payable": sc(col(bs, "AccountsPayable", "Payables")),
124
- "short_term_debt": sc(col(bs, "CurrentDebt", "CurrentDebtAndCapitalLeaseObligation")),
125
- "other_current_liabilities": sc(col(bs, "OtherCurrentLiabilities")),
126
- "total_current_liabilities": sc(col(bs, "CurrentLiabilities")),
127
- "long_term_debt": sc(col(bs, "LongTermDebt", "LongTermDebtAndCapitalLeaseObligation")),
128
- "other_long_term_liabilities":sc(col(bs, "OtherNonCurrentLiabilities")),
129
- "total_liabilities": sc(col(bs, "TotalLiabilitiesNetMinorityInterest", "TotalLiabilities")),
130
- "total_equity": sc(col(bs, "StockholdersEquity", "CommonStockEquity")),
131
- "total_liab_and_equity": sc(col(bs, "TotalAssets")),
132
- }
133
-
134
- cashflow = {
135
- "net_income": sc(col(cf, "NetIncomeFromContinuingOperations", "NetIncome")),
136
- "depreciation_amort": sc(col(cf, "DepreciationAndAmortization", "Depreciation")),
137
- "stock_based_comp": sc(col(cf, "StockBasedCompensation")),
138
- "working_capital_changes": sc(col(cf, "ChangeInWorkingCapital")),
139
- "other_operating": [None] * n,
140
- "cash_from_operations": sc(col(cf, "OperatingCashFlow", "CashFlowFromContinuingOperatingActivities")),
141
- "capex": sc(col(cf, "CapitalExpenditure", "PurchaseOfPPE")),
142
- "acquisitions": sc(col(cf, "PurchaseOfBusiness")),
143
- "cash_from_investing": sc(col(cf, "InvestingCashFlow", "CashFlowFromContinuingInvestingActivities")),
144
- "debt_issuance_repayment": sc(col(cf, "NetLongTermDebtIssuance", "NetIssuancePaymentsOfDebt")),
145
- "stock_buybacks": sc(col(cf, "NetCommonStockIssuance", "RepurchaseOfCapitalStock")),
146
- "dividends_paid": sc(col(cf, "CashDividendsPaid")),
147
- "cash_from_financing": sc(col(cf, "FinancingCashFlow", "CashFlowFromContinuingFinancingActivities")),
148
- "net_change_in_cash": sc(col(cf, "ChangesInCash", "ChangeInCashSupplementalAsReported")),
149
- "free_cash_flow": sc(col(cf, "FreeCashFlow")),
150
- }
151
-
152
- # Compute FCF if missing
153
- for i in range(n):
154
- if cashflow["free_cash_flow"][i] is None:
155
- cfo = cashflow["cash_from_operations"][i]
156
- cap = cashflow["capex"][i]
157
- if cfo is not None and cap is not None:
158
- cashflow["free_cash_flow"][i] = round(cfo + cap, 2)
159
-
160
- # Extract valuation snapshot and analyst targets
161
- val_snap = {}
162
- fd = t.financial_data
163
- if fd and ticker in fd and isinstance(fd[ticker], dict):
164
- val_snap["target_mean_price"] = fd[ticker].get("targetMeanPrice")
165
- val_snap["target_high_price"] = fd[ticker].get("targetHighPrice")
166
- val_snap["target_low_price"] = fd[ticker].get("targetLowPrice")
167
- val_snap["wacc_estimate"] = 0.10 # default fallback
168
-
169
- info = t.summary_detail
170
- if info and ticker in info and isinstance(info[ticker], dict):
171
- val_snap["pe_ttm"] = info[ticker].get("trailingPE")
172
- val_snap["dividend_yield"] = info[ticker].get("dividendYield")
173
-
174
- log(f" βœ“ yahooquery data ready ({n} years, {currency}, in {units})")
175
-
176
- return {
177
- "years": year_labels,
178
- "income_statement": income,
179
- "balance_sheet": balance,
180
- "cash_flow": cashflow,
181
- "currency": currency,
182
- "units": units,
183
- "units_label": units_label,
184
- "scale": scale,
185
- "source": "Yahoo Finance (yahooquery)",
186
- "valuation_snapshot": val_snap,
187
- }
188
- except Exception as e:
189
- import traceback
190
- if log_fn: log_fn(f" βœ— yahooquery error: {e}\n{traceback.format_exc()}")
191
- return None
192
-
193
-
194
- # ── FMP fetcher (secondary for global) ───────────────────────────────────────
195
-
196
- def _fmp_get(path, params=None):
197
- if not FMP_API_KEY: return None
198
- p = {"apikey": FMP_API_KEY}
199
- if params: p.update(params)
200
- try:
201
- r = requests.get(f"{FMP_BASE}{path}", params=p, timeout=REQUEST_TIMEOUT, headers=HEADERS)
202
- r.raise_for_status()
203
- return r.json()
204
- except Exception:
205
- return None
206
-
207
-
208
- def _normalise_fmp(raw, years):
209
- inc = list(reversed(raw.get("income", [])))[:years]
210
- bal = list(reversed(raw.get("balance", [])))[:years]
211
- cf = list(reversed(raw.get("cashflow", [])))[:years]
212
-
213
- def col(lst, key):
214
- return [_s(d.get(key)) for d in lst]
215
-
216
- year_labels = [d.get("calendarYear", str(d.get("date",""))[:4]) for d in inc]
217
- income = {
218
- "revenue": col(inc, "revenue"),
219
- "cost_of_revenue": col(inc, "costOfRevenue"),
220
- "gross_profit": col(inc, "grossProfit"),
221
- "operating_expenses": col(inc, "operatingExpenses"),
222
- "operating_income": col(inc, "operatingIncome"),
223
- "ebitda": col(inc, "ebitda"),
224
- "depreciation_amort": col(inc, "depreciationAndAmortization"),
225
- "interest_expense": col(inc, "interestExpense"),
226
- "pretax_income": col(inc, "incomeBeforeTax"),
227
- "tax_expense": col(inc, "incomeTaxExpense"),
228
- "net_income": col(inc, "netIncome"),
229
- "diluted_eps": col(inc, "epsdiluted"),
230
- "diluted_shares": col(inc, "weightedAverageShsOutDil"),
231
- }
232
- balance = {
233
- "cash_and_equivalents": col(bal, "cashAndCashEquivalents"),
234
- "short_term_investments": col(bal, "shortTermInvestments"),
235
- "receivables": col(bal, "netReceivables"),
236
- "inventory": col(bal, "inventory"),
237
- "other_current_assets": col(bal, "otherCurrentAssets"),
238
- "total_current_assets": col(bal, "totalCurrentAssets"),
239
- "ppe_net": col(bal, "propertyPlantEquipmentNet"),
240
- "goodwill": col(bal, "goodwill"),
241
- "intangibles": col(bal, "intangibleAssets"),
242
- "other_long_term_assets": col(bal, "otherNonCurrentAssets"),
243
- "total_assets": col(bal, "totalAssets"),
244
- "accounts_payable": col(bal, "accountPayables"),
245
- "short_term_debt": col(bal, "shortTermDebt"),
246
- "other_current_liabilities": col(bal, "otherCurrentLiabilities"),
247
- "total_current_liabilities": col(bal, "totalCurrentLiabilities"),
248
- "long_term_debt": col(bal, "longTermDebt"),
249
- "other_long_term_liabilities":col(bal, "otherNonCurrentLiabilities"),
250
- "total_liabilities": col(bal, "totalLiabilities"),
251
- "total_equity": col(bal, "totalStockholdersEquity"),
252
- "total_liab_and_equity": col(bal, "totalLiabilitiesAndStockholdersEquity"),
253
- }
254
- cashflow = {
255
- "net_income": col(cf, "netIncome"),
256
- "depreciation_amort": col(cf, "depreciationAndAmortization"),
257
- "stock_based_comp": col(cf, "stockBasedCompensation"),
258
- "working_capital_changes": col(cf, "changeInWorkingCapital"),
259
- "other_operating": col(cf, "otherWorkingCapital"),
260
- "cash_from_operations": col(cf, "netCashProvidedByOperatingActivities"),
261
- "capex": col(cf, "capitalExpenditure"),
262
- "acquisitions": col(cf, "acquisitionsNet"),
263
- "cash_from_investing": col(cf, "netCashUsedForInvestingActivites"),
264
- "debt_issuance_repayment": col(cf, "debtRepayment"),
265
- "stock_buybacks": col(cf, "commonStockRepurchased"),
266
- "dividends_paid": col(cf, "dividendsPaid"),
267
- "cash_from_financing": col(cf, "netCashUsedProvidedByFinancingActivities"),
268
- "net_change_in_cash": col(cf, "netChangeInCash"),
269
- "free_cash_flow": col(cf, "freeCashFlow"),
270
- }
271
- return {
272
- "years": year_labels, "income_statement": income,
273
- "balance_sheet": balance, "cash_flow": cashflow,
274
- "currency": "USD", "units": "millions",
275
- "source": "FMP API",
276
- "valuation_snapshot": {},
277
- }
278
-
279
-
280
- def _fetch_fmp(ticker, years, log_fn=None):
281
- def log(m):
282
- if log_fn: log_fn(m)
283
- if not FMP_API_KEY:
284
- return None
285
- log(" β†’ FMP: fetching statements …")
286
- lim = years + 1
287
- raw = {
288
- "income": _fmp_get(f"/v3/income-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
289
- "balance": _fmp_get(f"/v3/balance-sheet-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
290
- "cashflow": _fmp_get(f"/v3/cash-flow-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
291
- }
292
- if not raw["income"]:
293
- log(" βœ— FMP returned no data")
294
- return None
295
- log(" βœ“ FMP data ready")
296
- data = _normalise_fmp(raw, years)
297
- # Add valuation
298
- rtm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0]
299
- km = (_fmp_get(f"/v3/key-metrics-ttm/{ticker}") or [{}])[0]
300
- data["valuation_snapshot"] = {
301
- "pe_ttm": _s(rtm.get("peRatioTTM")),
302
- "pb": _s(rtm.get("priceToBookRatioTTM")),
303
- "ps": _s(rtm.get("priceToSalesRatioTTM")),
304
- "ev_ebitda": _s(km.get("enterpriseValueOverEBITDATTM")),
305
- "ev_revenue": _s(km.get("evToSalesTTM")),
306
- "fcf_yield": _s(km.get("freeCashFlowYieldTTM")),
307
- "dividend_yield": _s(rtm.get("dividendYieldTTM")),
308
- }
309
- return data
310
-
311
-
312
- # ── screener.in (Indian fallback) ────────────────────────────────────────────
313
-
314
- def _scrape_screener(ticker: str, log_fn=None) -> Optional[Dict]:
315
- def log(m):
316
- if log_fn: log_fn(m)
317
- # Ticker usually like RELIANCE.NS, extract RELIANCE
318
- base_ticker = ticker.split(".")[0].upper()
319
- for url in [f"https://www.screener.in/company/{base_ticker}/consolidated/",
320
- f"https://www.screener.in/company/{base_ticker}/"]:
321
- try:
322
- log(f" β†’ screener.in: {url}")
323
- r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS)
324
- if r.status_code == 200:
325
- soup = BeautifulSoup(r.text, "lxml")
326
- sections = {}
327
- for sec_id, key in [("profit-loss","income"),("balance-sheet","balance"),
328
- ("cash-flow","cashflow")]:
329
- sec = soup.find("section", {"id": sec_id})
330
- if sec:
331
- table = sec.find("table")
332
- if table:
333
- result = {}
334
- for row in table.find_all("tr"):
335
- cells = row.find_all(["td","th"])
336
- if len(cells) < 2: continue
337
- label = cells[0].get_text(strip=True)
338
- vals = []
339
- for c in cells[1:]:
340
- t2 = c.get_text(strip=True).replace(",","").replace("+","")
341
- try: vals.append(float(t2))
342
- except: vals.append(None)
343
- if label: result[label] = vals
344
- sections[key] = result
345
- if "years" not in sections:
346
- hdr = table.find("tr")
347
- if hdr:
348
- sections["years"] = [c.get_text(strip=True)
349
- for c in hdr.find_all(["th","td"])[1:]]
350
- if sections:
351
- sections["source_url"] = url
352
- log(" βœ“ screener.in scraped")
353
- return sections
354
- except Exception as e:
355
- log(f" βœ— screener.in error: {e}")
356
- return None
357
-
358
-
359
- def _normalise_screener(raw, years):
360
- yr = raw.get("years", [])[:years]
361
- n = len(yr)
362
- inc = raw.get("income", {})
363
- bal = raw.get("balance", {})
364
- cf = raw.get("cashflow", {})
365
-
366
- def row(*keys):
367
- for k in keys:
368
- if k in inc: return inc[k][:n]
369
- if k in bal: return bal[k][:n]
370
- if k in cf: return cf[k][:n]
371
- return [None]*n
372
-
373
- income = {
374
- "revenue": row("Revenue","Net Sales","Sales"),
375
- "cost_of_revenue": row("Expenses","Cost of Goods Sold"),
376
- "gross_profit": row("Gross Profit"),
377
- "operating_expenses": [None]*n,
378
- "operating_income": row("Operating Profit","EBIT","PBDIT"),
379
- "ebitda": row("PBDIT","EBITDA"),
380
- "depreciation_amort": row("Depreciation"),
381
- "interest_expense": row("Interest"),
382
- "pretax_income": row("Profit before tax","PBT"),
383
- "tax_expense": row("Tax"),
384
- "net_income": row("Net Profit","PAT"),
385
- "diluted_eps": row("EPS in Rs"),
386
- "diluted_shares": [None]*n,
387
- }
388
- balance = {
389
- "cash_and_equivalents": row("Cash Equivalents"),
390
- "short_term_investments": [None]*n,
391
- "receivables": [None]*n,
392
- "inventory": [None]*n,
393
- "other_current_assets": [None]*n,
394
- "total_current_assets": row("Current Assets"),
395
- "ppe_net": row("Fixed Assets"),
396
- "goodwill": [None]*n,
397
- "intangibles": [None]*n,
398
- "other_long_term_assets": [None]*n,
399
- "total_assets": row("Total Assets","Balance Sheet Size"),
400
- "accounts_payable": [None]*n,
401
- "short_term_debt": row("Short Term Borrowing"),
402
- "other_current_liabilities": [None]*n,
403
- "total_current_liabilities": row("Current Liabilities"),
404
- "long_term_debt": row("Borrowings","Long Term Borrowing"),
405
- "other_long_term_liabilities":[None]*n,
406
- "total_liabilities": row("Total Liabilities"),
407
- "total_equity": row("Equity Capital","Total Equity"),
408
- "total_liab_and_equity": row("Total Assets","Balance Sheet Size"),
409
- }
410
- cfo_vals = row("Cash from Operating Activity","Cash from Operations")
411
- cap_vals = row("Fixed Assets Purchased","Capital Expenditure")
412
- fcf_vals = [(c - abs(x)) if c is not None and x is not None else None
413
- for c, x in zip(cfo_vals, cap_vals)]
414
- cashflow = {
415
- "net_income": income["net_income"],
416
- "depreciation_amort": income["depreciation_amort"],
417
- "stock_based_comp": [None]*n,
418
- "working_capital_changes": [None]*n,
419
- "other_operating": [None]*n,
420
- "cash_from_operations": cfo_vals,
421
- "capex": cap_vals,
422
- "acquisitions": [None]*n,
423
- "cash_from_investing": row("Cash from Investing Activity"),
424
- "debt_issuance_repayment": [None]*n,
425
- "stock_buybacks": [None]*n,
426
- "dividends_paid": row("Dividend Amount"),
427
- "cash_from_financing": row("Cash from Financing Activity"),
428
- "net_change_in_cash": row("Net Cash Flow"),
429
- "free_cash_flow": fcf_vals,
430
- }
431
- return {
432
- "years": yr, "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow,
433
- "currency": "INR", "units": "crores",
434
- "source": f"screener.in ({raw.get('source_url','')})",
435
- "valuation_snapshot": {},
436
- }
437
-
438
- # ── stockanalysis.com (Global fallback for >4 years) ──────────────────────────
439
-
440
- def _scrape_stockanalysis(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
441
- def log(m):
442
- if log_fn: log_fn(m)
443
- base_ticker = ticker.split(".")[0].lower()
444
-
445
- urls = {
446
- "income": f"https://stockanalysis.com/stocks/{base_ticker}/financials/",
447
- "balance": f"https://stockanalysis.com/stocks/{base_ticker}/financials/balance-sheet/",
448
- "cashflow": f"https://stockanalysis.com/stocks/{base_ticker}/financials/cash-flow-statement/"
449
- }
450
-
451
- raw = {}
452
- try:
453
- for key, url in urls.items():
454
- log(f" β†’ stockanalysis.com: {url}")
455
- r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS)
456
- if r.status_code != 200:
457
- log(f" βœ— stockanalysis.com returned {r.status_code} for {key}")
458
- return None
459
- soup = BeautifulSoup(r.text, "lxml")
460
- table = soup.find("table")
461
- if not table: return None
462
-
463
- # Parse headers (Skip TTM, take `years` count)
464
- thead = table.find("thead")
465
- ths = thead.find("tr").find_all("th")
466
- # Index 0 is "Fiscal Year", Index 1 is "TTM" (usually). Index 2+ are the years.
467
- if len(ths) < 3: return None
468
-
469
- # Only need to extract year labels once
470
- if "years" not in raw:
471
- # Get the years newest to oldest, then reverse to oldest to newest
472
- year_labels = [th.get_text(strip=True) for th in ths[2:2+years]]
473
- raw["years"] = list(reversed(year_labels))
474
-
475
- data_rows = {}
476
- tbody = table.find("tbody")
477
- for tr in tbody.find_all("tr"):
478
- tds = tr.find_all("td")
479
- if len(tds) < 3: continue
480
- label = tds[0].get_text(strip=True)
481
- vals = []
482
- for td in tds[2:2+years]:
483
- text = td.get_text(strip=True).replace(",", "")
484
- if text == "-" or text == "":
485
- vals.append(None)
486
- else:
487
- try: vals.append(float(text))
488
- except: vals.append(None)
489
- data_rows[label] = list(reversed(vals))
490
- raw[key] = data_rows
491
-
492
- except Exception as e:
493
- log(f" βœ— stockanalysis error: {e}")
494
- return None
495
-
496
- n = len(raw.get("years", []))
497
- if n == 0: return None
498
-
499
- def row(sec, *keys):
500
- for k in keys:
501
- if k in raw[sec]: return raw[sec][k]
502
- return [None]*n
503
-
504
- income = {
505
- "revenue": row("income", "Revenue"),
506
- "cost_of_revenue": row("income", "Cost of Revenue"),
507
- "gross_profit": row("income", "Gross Profit"),
508
- "operating_expenses": row("income", "Operating Expenses"),
509
- "operating_income": row("income", "Operating Income"),
510
- "ebitda": row("income", "EBITDA"),
511
- "depreciation_amort": row("income", "Depreciation & Amortization"),
512
- "interest_expense": row("income", "Interest Expense / Income"),
513
- "pretax_income": row("income", "Pretax Income"),
514
- "tax_expense": row("income", "Income Tax"),
515
- "net_income": row("income", "Net Income"),
516
- "diluted_eps": row("income", "EPS (Diluted)"),
517
- "diluted_shares": row("income", "Shares Outstanding (Diluted)"),
518
- }
519
- balance = {
520
- "cash_and_equivalents": row("balance", "Cash & Equivalents"),
521
- "short_term_investments": row("balance", "Short-Term Investments"),
522
- "receivables": row("balance", "Accounts Receivable"),
523
- "inventory": row("balance", "Inventory"),
524
- "other_current_assets": row("balance", "Other Current Assets"),
525
- "total_current_assets": row("balance", "Total Current Assets"),
526
- "ppe_net": row("balance", "Property, Plant & Equipment"),
527
- "goodwill": row("balance", "Goodwill and Intangibles", "Goodwill"),
528
- "intangibles": [None]*n,
529
- "other_long_term_assets": row("balance", "Other Long-Term Assets"),
530
- "total_assets": row("balance", "Total Assets"),
531
- "accounts_payable": row("balance", "Accounts Payable"),
532
- "short_term_debt": row("balance", "Current Debt"),
533
- "other_current_liabilities": row("balance", "Other Current Liabilities"),
534
- "total_current_liabilities": row("balance", "Total Current Liabilities"),
535
- "long_term_debt": row("balance", "Long-Term Debt"),
536
- "other_long_term_liabilities":row("balance", "Other Long-Term Liabilities"),
537
- "total_liabilities": row("balance", "Total Liabilities"),
538
- "total_equity": row("balance", "Shareholders' Equity"),
539
- "total_liab_and_equity": row("balance", "Total Liabilities and Equity"),
540
- }
541
- cashflow = {
542
- "net_income": row("cashflow", "Net Income"),
543
- "depreciation_amort": row("cashflow", "Depreciation & Amortization"),
544
- "stock_based_comp": row("cashflow", "Share-Based Compensation"),
545
- "working_capital_changes": [None]*n,
546
- "other_operating": row("cashflow", "Other Operating Activities"),
547
- "cash_from_operations": row("cashflow", "Operating Cash Flow"),
548
- "capex": row("cashflow", "Capital Expenditures"),
549
- "acquisitions": row("cashflow", "Acquisitions"),
550
- "cash_from_investing": row("cashflow", "Investing Cash Flow"),
551
- "debt_issuance_repayment": row("cashflow", "Net Debt Issued/Paid"),
552
- "stock_buybacks": row("cashflow", "Common Stock Issued/Repurchased", "Stock Repurchases"),
553
- "dividends_paid": row("cashflow", "Dividends Paid"),
554
- "cash_from_financing": row("cashflow", "Financing Cash Flow"),
555
- "net_change_in_cash": row("cashflow", "Net Change in Cash"),
556
- "free_cash_flow": row("cashflow", "Free Cash Flow"),
557
- }
558
- return {
559
- "years": raw["years"], "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow,
560
- "currency": "USD", "units": "millions",
561
- "source": "stockanalysis.com",
562
- "valuation_snapshot": {},
563
- }
564
-
565
- # ── Peer snapshot ─────────────────────────────────────────────────────────────
566
-
567
- def fetch_peer_snapshot(ticker: str) -> Optional[Dict]:
568
- try:
569
- import yfinance as yf
570
- t = yf.Ticker(ticker)
571
- info = t.info
572
- if not info.get("longName"): return None
573
- fin = t.financials
574
- rev = fin.loc["Total Revenue"].iloc[0] if fin is not None and "Total Revenue" in fin.index else None
575
- ratios_ttm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0]
576
- return {
577
- "name": info.get("longName", ticker),
578
- "ticker": ticker,
579
- "rationale": f"Industry peer ({info.get('industry','')})",
580
- "latest_year": "",
581
- "currency": info.get("currency","INR"),
582
- "units": "actuals",
583
- "revenue": _s(rev),
584
- "gross_margin": _s(info.get("grossMargins")),
585
- "operating_margin": _s(info.get("operatingMargins")),
586
- "net_margin": _s(info.get("profitMargins")),
587
- "roe": _s(info.get("returnOnEquity")),
588
- "roic": _s(ratios_ttm.get("returnOnCapitalEmployedTTM")),
589
- "debt_to_equity": _s(info.get("debtToEquity")),
590
- "current_ratio": _s(info.get("currentRatio")),
591
- "fcf_margin": None,
592
- "revenue_growth_3y_cagr": _s(info.get("revenueGrowth")),
593
- "pe_ttm": _s(info.get("trailingPE")),
594
- "ev_ebitda": _s(info.get("enterpriseToEbitda")),
595
- }
596
- except Exception:
597
- return None
598
-
599
- def fetch_valuation(ticker: str) -> Dict:
600
- try:
601
- import yfinance as yf
602
- info = yf.Ticker(ticker).info
603
- return {
604
- "pe_ttm": _s(info.get("trailingPE")),
605
- "pb": _s(info.get("priceToBook")),
606
- "ps": _s(info.get("priceToSalesTrailing12Months")),
607
- "ev_ebitda": _s(info.get("enterpriseToEbitda")),
608
- "ev_revenue": _s(info.get("enterpriseToRevenue")),
609
- "fcf_yield": None,
610
- "dividend_yield": _s(info.get("dividendYield")),
611
- }
612
- except Exception:
613
- return {}
614
-
615
- def _scrape_edgar_10k(ticker: str, log_fn=None) -> str:
616
- """Fetch the latest 10-K for a US company from SEC EDGAR and extract a chunk of text."""
617
- headers = {"User-Agent": "FinancialAnalyzer/1.0 (contact@example.com)"}
618
- try:
619
- if log_fn: log_fn(f" β†’ Looking up SEC CIK for {ticker}...")
620
- r = requests.get("https://www.sec.gov/files/company_tickers.json", headers=headers, timeout=10)
621
- tickers = r.json()
622
- cik = None
623
- for k, v in tickers.items():
624
- if v["ticker"].upper() == ticker.upper():
625
- cik = str(v["cik_str"]).zfill(10)
626
- break
627
-
628
- if not cik:
629
- if log_fn: log_fn(" βœ— CIK not found in SEC database.")
630
- return ""
631
-
632
- if log_fn: log_fn(f" β†’ Found CIK {cik}. Fetching recent filings...")
633
- sub_r = requests.get(f"https://data.sec.gov/submissions/CIK{cik}.json", headers=headers, timeout=10)
634
- data = sub_r.json()
635
- filings = data.get("filings", {}).get("recent", {})
636
-
637
- form_types = filings.get("form", [])
638
- accessions = filings.get("accessionNumber", [])
639
- primary_docs = filings.get("primaryDocument", [])
640
-
641
- idx = -1
642
- for i, form in enumerate(form_types):
643
- if form == "10-K":
644
- idx = i
645
- break
646
-
647
- if idx == -1:
648
- if log_fn: log_fn(" βœ— No 10-K found in recent filings.")
649
- return ""
650
-
651
- acc_num = accessions[idx]
652
- acc_num_no_dash = acc_num.replace("-", "")
653
- doc = primary_docs[idx]
654
-
655
- url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{acc_num_no_dash}/{doc}"
656
- if log_fn: log_fn(f" β†’ Downloading 10-K from {url}...")
657
-
658
- doc_r = requests.get(url, headers=headers, timeout=20)
659
- from bs4 import BeautifulSoup
660
- soup = BeautifulSoup(doc_r.content, "lxml")
661
-
662
- text = soup.get_text(separator="\n", strip=True)
663
- import re
664
- match = re.search(r'(?i)Item\s+7\.\s*Management[’\']s\s+Discussion', text)
665
- if match:
666
- start = match.start()
667
- extract = text[start:start+40000]
668
- else:
669
- extract = text[len(text)//4 : len(text)//4 + 40000]
670
-
671
- if log_fn: log_fn(" βœ“ 10-K text extracted successfully.")
672
- return extract
673
- except Exception as e:
674
- if log_fn: log_fn(f" βœ— Failed to scrape EDGAR: {str(e)[:80]}")
675
- return ""
676
-
677
-
678
- # ── Main Fetcher ──────────────────────────────────────────────────────────────
679
-
680
- def fetch_all(meta: CompanyMeta, years: int = DEFAULT_YEARS,
681
- force_refresh: bool = False, log_fn=None) -> Dict:
682
- def log(m):
683
- if log_fn: log_fn(m)
684
-
685
- if not meta.is_listed:
686
- msg = (f"'{meta.name}' is unlisted/private. Public data not available. "
687
- "Try the exact BSE/NSE ticker.")
688
- log(f" ⚠ {msg}")
689
- return {"warnings": [msg], "years": [], "income_statement": {},
690
- "balance_sheet": {}, "cash_flow": {}}
691
-
692
- ticker = meta.ticker
693
- cache_key = f"full_{years}yr"
694
- if not force_refresh:
695
- cached = get_cached(ticker, cache_key)
696
- if cached:
697
- log(f" βœ“ Loaded cached data for {ticker}")
698
- return cached
699
-
700
- warnings = []
701
- result = None
702
-
703
- # Re-prioritized Fetching Logic:
704
-
705
- # 1. Indian Stocks: Try screener.in first (up to 10+ years of data)
706
- if meta.currency == "INR":
707
- log(" β†’ Indian Stock detected. Prioritizing screener.in ...")
708
- scraped = _scrape_screener(ticker, log_fn)
709
- if scraped:
710
- result = _normalise_screener(scraped, years)
711
- warnings.append("Data sourced from screener.in. Verify against company filings.")
712
-
713
- # Fallback to yfinance if screener fails or yields nothing
714
- if not result or not result.get("years"):
715
- log(" β†’ screener.in failed. Falling back to yahooquery ...")
716
- result = _fetch_yahooquery(ticker, years, log_fn)
717
- if result and len(result.get("years", [])) < years:
718
- warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.")
719
-
720
- # 2. Global/US Stocks
721
- else:
722
- # If requesting > 4 years, try stockanalysis.com first because yahooquery limits to 4 years
723
- if years > 4:
724
- log(" β†’ Horizon > 4 years requested. Prioritizing stockanalysis.com for global stock ...")
725
- result = _scrape_stockanalysis(ticker, years, log_fn)
726
- if result:
727
- warnings.append("Data sourced from stockanalysis.com. Verify against company filings.")
728
-
729
- # Fallback to yahooquery
730
- if not result or not result.get("years"):
731
- log(" β†’ Trying yahooquery ...")
732
- result = _fetch_yahooquery(ticker, years, log_fn)
733
- if result and len(result.get("years", [])) < years:
734
- warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.")
735
-
736
- # Fallback to FMP
737
- if (not result or not result.get("years")) and FMP_API_KEY:
738
- result = _fetch_fmp(ticker, years, log_fn)
739
-
740
- # 3. Final validation
741
- if not result or not result.get("years"):
742
- msg = (f"Could not fetch data for '{meta.name}' ({ticker}). "
743
- "Check ticker, or the company may have limited public data coverage.")
744
- log(f" ⚠ {msg}")
745
- return {"warnings": [msg], "years": [], "income_statement": {},
746
- "balance_sheet": {}, "cash_flow": {}}
747
-
748
- # 4. Optional Annual Report Scrape (for context)
749
- if meta.currency != "INR":
750
- ar_context = _scrape_edgar_10k(ticker, log_fn)
751
- if ar_context:
752
- result["annual_report_context"] = ar_context
753
- warnings.append("AI analysis enhanced with raw MD&A excerpts from SEC EDGAR 10-K.")
754
-
755
- result["warnings"] = warnings
756
- result.setdefault("currency", meta.currency)
757
- set_cache(ticker, cache_key, result)
758
- log(" βœ“ Data cached for 7 days")
759
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pipeline/fetcher.py β€” Fetch 5-year financials.
3
+ Priority: yfinance (free, Indian stocks) -> FMP -> screener.in
4
+ """
5
+ from __future__ import annotations
6
+ import sys, re, json, datetime
7
+ from pathlib import Path
8
+ from typing import Optional, List, Dict, Any
9
+
10
+ import requests
11
+ from bs4 import BeautifulSoup
12
+
13
+ sys.path.insert(0, str(Path(__file__).parent.parent))
14
+ from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT, DEFAULT_YEARS
15
+ from storage.cache import get_cached, set_cache
16
+ from pipeline.resolver import CompanyMeta
17
+
18
+ HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
19
+
20
+
21
+ # ── Helpers ───────────────────────────────────────────────────────────────────
22
+
23
+ def _s(v, default=None):
24
+ if v is None or (isinstance(v, float) and v != v): return default
25
+ return v
26
+
27
+
28
+ def _row(df, *keys):
29
+ """Get a row from a yfinance DataFrame by trying multiple key names."""
30
+ for k in keys:
31
+ if k in df.index:
32
+ return df.loc[k].tolist()
33
+ return [None] * len(df.columns)
34
+
35
+
36
+ # ── yahooquery fetcher (primary for Indian + global) ─────────────────────────
37
+
38
+ def _fetch_yahooquery(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
39
+ """Fetch financial statements via yahooquery. Returns normalized dict or None."""
40
+ def log(m):
41
+ if log_fn: log_fn(m)
42
+ try:
43
+ import yahooquery as yq
44
+ import pandas as pd
45
+ import math
46
+
47
+ log(f" -> yahooquery: fetching {ticker} ...")
48
+ t = yq.Ticker(ticker)
49
+
50
+ inc_df = t.income_statement(frequency='annual')
51
+ bs_df = t.balance_sheet(frequency='annual')
52
+ cf_df = t.cash_flow(frequency='annual')
53
+
54
+ if inc_df is None or isinstance(inc_df, str) or inc_df.empty:
55
+ log(" [ERR] yahooquery returned empty income statement")
56
+ return None
57
+
58
+ # ── Filter to clean annual rows only (periodType == '12M') ──
59
+ def clean_df(df):
60
+ if df is None or isinstance(df, str) or df.empty:
61
+ return pd.DataFrame()
62
+ df = df.reset_index()
63
+ if 'asOfDate' not in df.columns:
64
+ return df
65
+ df = df.dropna(subset=['asOfDate'])
66
+ df['asOfDate'] = pd.to_datetime(df['asOfDate'])
67
+ # Keep only 12M (full annual) rows, not TTM or quarterly
68
+ if 'periodType' in df.columns:
69
+ annual = df[df['periodType'] == '12M']
70
+ if not annual.empty:
71
+ df = annual
72
+ df = df.sort_values('asOfDate')
73
+ # Deduplicate: keep last row per year-month (safety net)
74
+ df['ym'] = df['asOfDate'].dt.to_period('M')
75
+ df = df.drop_duplicates(subset=['ym'], keep='last').drop(columns=['ym'])
76
+ return df.reset_index(drop=True)
77
+
78
+ inc = clean_df(inc_df)
79
+ bs = clean_df(bs_df)
80
+ cf = clean_df(cf_df)
81
+
82
+ if inc.empty:
83
+ log(" [ERR] yahooquery: no usable annual rows after filtering")
84
+ return None
85
+
86
+ # Take the most recent `years` rows (oldest→newest)
87
+ inc = inc.tail(years)
88
+ bs = bs.tail(years) if not bs.empty else pd.DataFrame()
89
+ cf = cf.tail(years) if not cf.empty else pd.DataFrame()
90
+
91
+ # Year labels
92
+ year_labels = [d.strftime('%Y/%m') for d in inc['asOfDate']]
93
+ n = len(year_labels)
94
+
95
+ # Determine currency and scaling
96
+ currency = "INR"
97
+ if 'currencyCode' in inc.columns:
98
+ cur_vals = inc['currencyCode'].dropna().unique()
99
+ if len(cur_vals) > 0:
100
+ currency = str(cur_vals[-1])
101
+
102
+ if currency == "INR":
103
+ scale = 1e7 # raw INR -> Crores
104
+ units = "Crores"
105
+ units_label = "INR Crores (β‚Ή Cr)"
106
+ else:
107
+ scale = 1e6
108
+ units = "Millions"
109
+ units_label = f"{currency} Millions"
110
+
111
+ def gcol(df, *keys):
112
+ """Get column values (oldest→newest list of length n), scaled."""
113
+ for k in keys:
114
+ if k in df.columns:
115
+ vals = df[k].tolist()
116
+ result = []
117
+ for v in vals:
118
+ if v is None or (isinstance(v, float) and math.isnan(v)):
119
+ result.append(None)
120
+ else:
121
+ result.append(round(float(v) / scale, 2))
122
+ # Pad or trim to n
123
+ while len(result) < n: result.append(None)
124
+ return result[:n]
125
+ return [None] * n
126
+
127
+ def gcol_raw(df, *keys):
128
+ """Get column values without scaling."""
129
+ for k in keys:
130
+ if k in df.columns:
131
+ vals = df[k].tolist()
132
+ result = []
133
+ for v in vals:
134
+ if v is None or (isinstance(v, float) and math.isnan(v)):
135
+ result.append(None)
136
+ else:
137
+ result.append(float(v))
138
+ while len(result) < n: result.append(None)
139
+ return result[:n]
140
+ return [None] * n
141
+
142
+ income = {
143
+ "revenue": gcol(inc, "TotalRevenue", "OperatingRevenue"),
144
+ "cost_of_revenue": gcol(inc, "CostOfRevenue", "ReconciledCostOfRevenue"),
145
+ "gross_profit": gcol(inc, "GrossProfit"),
146
+ "operating_expenses": gcol(inc, "OperatingExpense", "TotalExpenses"),
147
+ "operating_income": gcol(inc, "OperatingIncome", "EBIT"),
148
+ "ebitda": gcol(inc, "EBITDA", "NormalizedEBITDA"),
149
+ "depreciation_amort": gcol(inc, "ReconciledDepreciation", "DepreciationAndAmortizationInIncomeStatement"),
150
+ "interest_expense": gcol(inc, "InterestExpenseNonOperating", "InterestExpense"),
151
+ "pretax_income": gcol(inc, "PretaxIncome"),
152
+ "tax_expense": gcol(inc, "TaxProvision"),
153
+ "net_income": gcol(inc, "NetIncome", "NetIncomeCommonStockholders"),
154
+ "diluted_eps": gcol_raw(inc, "DilutedEPS", "BasicEPS"),
155
+ "diluted_shares": gcol_raw(inc, "DilutedAverageShares", "BasicAverageShares"),
156
+ }
157
+
158
+ balance = {
159
+ "cash_and_equivalents": gcol(bs, "CashAndCashEquivalents", "CashFinancial"),
160
+ "short_term_investments": gcol(bs, "OtherShortTermInvestments", "InvestmentsAndAdvances"),
161
+ "receivables": gcol(bs, "AccountsReceivable", "Receivables"),
162
+ "inventory": gcol(bs, "Inventory"),
163
+ "other_current_assets": gcol(bs, "OtherCurrentAssets"),
164
+ "total_current_assets": gcol(bs, "CurrentAssets"),
165
+ "ppe_net": gcol(bs, "NetPPE"),
166
+ "goodwill": gcol(bs, "Goodwill"),
167
+ "intangibles": gcol(bs, "OtherIntangibleAssets"),
168
+ "other_long_term_assets": gcol(bs, "OtherNonCurrentAssets"),
169
+ "total_assets": gcol(bs, "TotalAssets"),
170
+ "accounts_payable": gcol(bs, "AccountsPayable", "Payables"),
171
+ "short_term_debt": gcol(bs, "CurrentDebt", "CurrentDebtAndCapitalLeaseObligation"),
172
+ "other_current_liabilities": gcol(bs, "OtherCurrentLiabilities"),
173
+ "total_current_liabilities": gcol(bs, "CurrentLiabilities"),
174
+ "long_term_debt": gcol(bs, "LongTermDebt", "LongTermDebtAndCapitalLeaseObligation"),
175
+ "other_long_term_liabilities":gcol(bs, "OtherNonCurrentLiabilities"),
176
+ "total_liabilities": gcol(bs, "TotalLiabilitiesNetMinorityInterest", "TotalLiabilities"),
177
+ "total_equity": gcol(bs, "StockholdersEquity", "CommonStockEquity"),
178
+ "total_liab_and_equity": gcol(bs, "TotalAssets"),
179
+ }
180
+
181
+ cfo = gcol(cf, "OperatingCashFlow", "CashFlowFromContinuingOperatingActivities")
182
+ cap = gcol(cf, "CapitalExpenditure")
183
+ fcf = gcol(cf, "FreeCashFlow")
184
+ # Compute FCF from CFO - CapEx if missing
185
+ for i in range(n):
186
+ if fcf[i] is None and cfo[i] is not None and cap[i] is not None:
187
+ fcf[i] = round(cfo[i] + cap[i], 2) # CapEx is negative in yahooquery
188
+
189
+ cashflow = {
190
+ "net_income": gcol(cf, "NetIncomeFromContinuingOperations", "NetIncome"),
191
+ "depreciation_amort": gcol(cf, "DepreciationAndAmortization", "Depreciation"),
192
+ "stock_based_comp": gcol(cf, "StockBasedCompensation"),
193
+ "working_capital_changes": gcol(cf, "ChangeInWorkingCapital"),
194
+ "other_operating": [None] * n,
195
+ "cash_from_operations": cfo,
196
+ "capex": cap,
197
+ "acquisitions": gcol(cf, "PurchaseOfBusiness", "AcquisitionOfBusiness"),
198
+ "cash_from_investing": gcol(cf, "InvestingCashFlow", "CashFlowFromContinuingInvestingActivities"),
199
+ "debt_issuance_repayment": gcol(cf, "NetLongTermDebtIssuance", "NetIssuancePaymentsOfDebt"),
200
+ "stock_buybacks": gcol(cf, "NetCommonStockIssuance", "RepurchaseOfCapitalStock"),
201
+ "dividends_paid": gcol(cf, "CashDividendsPaid", "DividendsPaid"),
202
+ "cash_from_financing": gcol(cf, "FinancingCashFlow", "CashFlowFromContinuingFinancingActivities"),
203
+ "net_change_in_cash": gcol(cf, "ChangesInCash", "ChangeInCashSupplementalAsReported"),
204
+ "free_cash_flow": fcf,
205
+ }
206
+
207
+ # Valuation snapshot
208
+ val_snap = {}
209
+ try:
210
+ fd = t.financial_data.get(ticker, {})
211
+ if isinstance(fd, dict):
212
+ val_snap["target_mean_price"] = fd.get("targetMeanPrice")
213
+ val_snap["target_high_price"] = fd.get("targetHighPrice")
214
+ val_snap["target_low_price"] = fd.get("targetLowPrice")
215
+ val_snap["wacc_estimate"] = 0.10
216
+
217
+ sd = t.summary_detail.get(ticker, {})
218
+ if isinstance(sd, dict):
219
+ val_snap["pe_ttm"] = sd.get("trailingPE")
220
+ val_snap["dividend_yield"] = sd.get("dividendYield")
221
+ except Exception:
222
+ pass
223
+
224
+ log(f" [OK] yahooquery data ready ({n} years, {currency}, in {units})")
225
+
226
+ return {
227
+ "years": year_labels,
228
+ "income_statement": income,
229
+ "balance_sheet": balance,
230
+ "cash_flow": cashflow,
231
+ "currency": currency,
232
+ "units": units,
233
+ "units_label": units_label,
234
+ "scale": scale,
235
+ "source": "Yahoo Finance (yahooquery)",
236
+ "valuation_snapshot": val_snap,
237
+ }
238
+
239
+ except Exception as e:
240
+ import traceback
241
+ log(f" [ERR] yahooquery error: {e}\n{traceback.format_exc()}")
242
+ return None
243
+
244
+
245
+ # Keep a stub for backward compatibility (if anything still calls _fetch_yfinance)
246
+ def _fetch_yfinance(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
247
+ return _fetch_yahooquery(ticker, years, log_fn)
248
+
249
+
250
+ # ── FMP fetcher (secondary for global) ───────────────────────────────────────
251
+
252
+ def _fmp_get(path, params=None):
253
+ if not FMP_API_KEY: return None
254
+ p = {"apikey": FMP_API_KEY}
255
+ if params: p.update(params)
256
+ try:
257
+ r = requests.get(f"{FMP_BASE}{path}", params=p, timeout=REQUEST_TIMEOUT, headers=HEADERS)
258
+ r.raise_for_status()
259
+ return r.json()
260
+ except Exception:
261
+ return None
262
+
263
+
264
+ def _normalise_fmp(raw, years):
265
+ inc = list(reversed(raw.get("income", [])))[:years]
266
+ bal = list(reversed(raw.get("balance", [])))[:years]
267
+ cf = list(reversed(raw.get("cashflow", [])))[:years]
268
+
269
+ def col(lst, key):
270
+ return [_s(d.get(key)) for d in lst]
271
+
272
+ year_labels = [d.get("calendarYear", str(d.get("date",""))[:4]) for d in inc]
273
+ income = {
274
+ "revenue": col(inc, "revenue"),
275
+ "cost_of_revenue": col(inc, "costOfRevenue"),
276
+ "gross_profit": col(inc, "grossProfit"),
277
+ "operating_expenses": col(inc, "operatingExpenses"),
278
+ "operating_income": col(inc, "operatingIncome"),
279
+ "ebitda": col(inc, "ebitda"),
280
+ "depreciation_amort": col(inc, "depreciationAndAmortization"),
281
+ "interest_expense": col(inc, "interestExpense"),
282
+ "pretax_income": col(inc, "incomeBeforeTax"),
283
+ "tax_expense": col(inc, "incomeTaxExpense"),
284
+ "net_income": col(inc, "netIncome"),
285
+ "diluted_eps": col(inc, "epsdiluted"),
286
+ "diluted_shares": col(inc, "weightedAverageShsOutDil"),
287
+ }
288
+ balance = {
289
+ "cash_and_equivalents": col(bal, "cashAndCashEquivalents"),
290
+ "short_term_investments": col(bal, "shortTermInvestments"),
291
+ "receivables": col(bal, "netReceivables"),
292
+ "inventory": col(bal, "inventory"),
293
+ "other_current_assets": col(bal, "otherCurrentAssets"),
294
+ "total_current_assets": col(bal, "totalCurrentAssets"),
295
+ "ppe_net": col(bal, "propertyPlantEquipmentNet"),
296
+ "goodwill": col(bal, "goodwill"),
297
+ "intangibles": col(bal, "intangibleAssets"),
298
+ "other_long_term_assets": col(bal, "otherNonCurrentAssets"),
299
+ "total_assets": col(bal, "totalAssets"),
300
+ "accounts_payable": col(bal, "accountPayables"),
301
+ "short_term_debt": col(bal, "shortTermDebt"),
302
+ "other_current_liabilities": col(bal, "otherCurrentLiabilities"),
303
+ "total_current_liabilities": col(bal, "totalCurrentLiabilities"),
304
+ "long_term_debt": col(bal, "longTermDebt"),
305
+ "other_long_term_liabilities":col(bal, "otherNonCurrentLiabilities"),
306
+ "total_liabilities": col(bal, "totalLiabilities"),
307
+ "total_equity": col(bal, "totalStockholdersEquity"),
308
+ "total_liab_and_equity": col(bal, "totalLiabilitiesAndStockholdersEquity"),
309
+ }
310
+ cashflow = {
311
+ "net_income": col(cf, "netIncome"),
312
+ "depreciation_amort": col(cf, "depreciationAndAmortization"),
313
+ "stock_based_comp": col(cf, "stockBasedCompensation"),
314
+ "working_capital_changes": col(cf, "changeInWorkingCapital"),
315
+ "other_operating": col(cf, "otherWorkingCapital"),
316
+ "cash_from_operations": col(cf, "netCashProvidedByOperatingActivities"),
317
+ "capex": col(cf, "capitalExpenditure"),
318
+ "acquisitions": col(cf, "acquisitionsNet"),
319
+ "cash_from_investing": col(cf, "netCashUsedForInvestingActivites"),
320
+ "debt_issuance_repayment": col(cf, "debtRepayment"),
321
+ "stock_buybacks": col(cf, "commonStockRepurchased"),
322
+ "dividends_paid": col(cf, "dividendsPaid"),
323
+ "cash_from_financing": col(cf, "netCashUsedProvidedByFinancingActivities"),
324
+ "net_change_in_cash": col(cf, "netChangeInCash"),
325
+ "free_cash_flow": col(cf, "freeCashFlow"),
326
+ }
327
+ return {
328
+ "years": year_labels, "income_statement": income,
329
+ "balance_sheet": balance, "cash_flow": cashflow,
330
+ "currency": "USD", "units": "millions",
331
+ "source": "FMP API",
332
+ "valuation_snapshot": {},
333
+ }
334
+
335
+
336
+ def _fetch_fmp(ticker, years, log_fn=None):
337
+ def log(m):
338
+ if log_fn: log_fn(m)
339
+ if not FMP_API_KEY:
340
+ return None
341
+ log(" -> FMP: fetching statements ...")
342
+ lim = years + 1
343
+ raw = {
344
+ "income": _fmp_get(f"/v3/income-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
345
+ "balance": _fmp_get(f"/v3/balance-sheet-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
346
+ "cashflow": _fmp_get(f"/v3/cash-flow-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
347
+ }
348
+ if not raw["income"]:
349
+ log(" [ERR] FMP returned no data")
350
+ return None
351
+ log(" [OK] FMP data ready")
352
+ data = _normalise_fmp(raw, years)
353
+ # Add valuation
354
+ rtm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0]
355
+ km = (_fmp_get(f"/v3/key-metrics-ttm/{ticker}") or [{}])[0]
356
+ data["valuation_snapshot"] = {
357
+ "pe_ttm": _s(rtm.get("peRatioTTM")),
358
+ "pb": _s(rtm.get("priceToBookRatioTTM")),
359
+ "ps": _s(rtm.get("priceToSalesRatioTTM")),
360
+ "ev_ebitda": _s(km.get("enterpriseValueOverEBITDATTM")),
361
+ "ev_revenue": _s(km.get("evToSalesTTM")),
362
+ "fcf_yield": _s(km.get("freeCashFlowYieldTTM")),
363
+ "dividend_yield": _s(rtm.get("dividendYieldTTM")),
364
+ }
365
+ return data
366
+
367
+
368
+ # ── screener.in (Indian fallback) ────────────────────────────────────────────
369
+
370
+ def _scrape_screener(ticker: str, log_fn=None) -> Optional[Dict]:
371
+ def log(m):
372
+ if log_fn: log_fn(m)
373
+ # Ticker usually like RELIANCE.NS, extract RELIANCE
374
+ base_ticker = ticker.split(".")[0].upper()
375
+ for url in [f"https://www.screener.in/company/{base_ticker}/consolidated/",
376
+ f"https://www.screener.in/company/{base_ticker}/"]:
377
+ try:
378
+ log(f" -> screener.in: {url}")
379
+ r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS)
380
+ if r.status_code == 200:
381
+ soup = BeautifulSoup(r.text, "lxml")
382
+ sections = {}
383
+ for sec_id, key in [("profit-loss","income"),("balance-sheet","balance"),
384
+ ("cash-flow","cashflow")]:
385
+ sec = soup.find("section", {"id": sec_id})
386
+ if sec:
387
+ table = sec.find("table")
388
+ if table:
389
+ result = {}
390
+ for row in table.find_all("tr"):
391
+ cells = row.find_all(["td","th"])
392
+ if len(cells) < 2: continue
393
+ label = cells[0].get_text(strip=True)
394
+ vals = []
395
+ for c in cells[1:]:
396
+ t2 = c.get_text(strip=True).replace(",","").replace("+","")
397
+ try: vals.append(float(t2))
398
+ except: vals.append(None)
399
+ if label: result[label] = vals
400
+ sections[key] = result
401
+ if "years" not in sections:
402
+ hdr = table.find("tr")
403
+ if hdr:
404
+ sections["years"] = [c.get_text(strip=True)
405
+ for c in hdr.find_all(["th","td"])[1:]]
406
+ if sections:
407
+ sections["source_url"] = url
408
+ log(" [OK] screener.in scraped")
409
+ return sections
410
+ except Exception as e:
411
+ log(f" [ERR] screener.in error: {e}")
412
+ return None
413
+
414
+
415
+ def _normalise_screener(raw, years):
416
+ yr = raw.get("years", [])[:years]
417
+ n = len(yr)
418
+ inc = raw.get("income", {})
419
+ bal = raw.get("balance", {})
420
+ cf = raw.get("cashflow", {})
421
+
422
+ def row(*keys):
423
+ for k in keys:
424
+ if k in inc: return inc[k][:n]
425
+ if k in bal: return bal[k][:n]
426
+ if k in cf: return cf[k][:n]
427
+ return [None]*n
428
+
429
+ income = {
430
+ "revenue": row("Revenue","Net Sales","Sales"),
431
+ "cost_of_revenue": row("Expenses","Cost of Goods Sold"),
432
+ "gross_profit": row("Gross Profit"),
433
+ "operating_expenses": [None]*n,
434
+ "operating_income": row("Operating Profit","EBIT","PBDIT"),
435
+ "ebitda": row("PBDIT","EBITDA"),
436
+ "depreciation_amort": row("Depreciation"),
437
+ "interest_expense": row("Interest"),
438
+ "pretax_income": row("Profit before tax","PBT"),
439
+ "tax_expense": row("Tax"),
440
+ "net_income": row("Net Profit","PAT"),
441
+ "diluted_eps": row("EPS in Rs"),
442
+ "diluted_shares": [None]*n,
443
+ }
444
+ balance = {
445
+ "cash_and_equivalents": row("Cash Equivalents"),
446
+ "short_term_investments": [None]*n,
447
+ "receivables": [None]*n,
448
+ "inventory": [None]*n,
449
+ "other_current_assets": [None]*n,
450
+ "total_current_assets": row("Current Assets"),
451
+ "ppe_net": row("Fixed Assets"),
452
+ "goodwill": [None]*n,
453
+ "intangibles": [None]*n,
454
+ "other_long_term_assets": [None]*n,
455
+ "total_assets": row("Total Assets","Balance Sheet Size"),
456
+ "accounts_payable": [None]*n,
457
+ "short_term_debt": row("Short Term Borrowing"),
458
+ "other_current_liabilities": [None]*n,
459
+ "total_current_liabilities": row("Current Liabilities"),
460
+ "long_term_debt": row("Borrowings","Long Term Borrowing"),
461
+ "other_long_term_liabilities":[None]*n,
462
+ "total_liabilities": row("Total Liabilities"),
463
+ "total_equity": row("Equity Capital","Total Equity"),
464
+ "total_liab_and_equity": row("Total Assets","Balance Sheet Size"),
465
+ }
466
+ cfo_vals = row("Cash from Operating Activity","Cash from Operations")
467
+ cap_vals = row("Fixed Assets Purchased","Capital Expenditure")
468
+ fcf_vals = [(c - abs(x)) if c is not None and x is not None else None
469
+ for c, x in zip(cfo_vals, cap_vals)]
470
+ cashflow = {
471
+ "net_income": income["net_income"],
472
+ "depreciation_amort": income["depreciation_amort"],
473
+ "stock_based_comp": [None]*n,
474
+ "working_capital_changes": [None]*n,
475
+ "other_operating": [None]*n,
476
+ "cash_from_operations": cfo_vals,
477
+ "capex": cap_vals,
478
+ "acquisitions": [None]*n,
479
+ "cash_from_investing": row("Cash from Investing Activity"),
480
+ "debt_issuance_repayment": [None]*n,
481
+ "stock_buybacks": [None]*n,
482
+ "dividends_paid": row("Dividend Amount"),
483
+ "cash_from_financing": row("Cash from Financing Activity"),
484
+ "net_change_in_cash": row("Net Cash Flow"),
485
+ "free_cash_flow": fcf_vals,
486
+ }
487
+ return {
488
+ "years": yr, "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow,
489
+ "currency": "INR", "units": "crores",
490
+ "source": f"screener.in ({raw.get('source_url','')})",
491
+ "valuation_snapshot": {},
492
+ }
493
+
494
+ # ── stockanalysis.com (Global fallback for >4 years) ──────────────────────────
495
+
496
+ def _scrape_stockanalysis(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
497
+ def log(m):
498
+ if log_fn: log_fn(m)
499
+ base_ticker = ticker.split(".")[0].lower()
500
+
501
+ urls = {
502
+ "income": f"https://stockanalysis.com/stocks/{base_ticker}/financials/",
503
+ "balance": f"https://stockanalysis.com/stocks/{base_ticker}/financials/balance-sheet/",
504
+ "cashflow": f"https://stockanalysis.com/stocks/{base_ticker}/financials/cash-flow-statement/"
505
+ }
506
+
507
+ raw = {}
508
+ try:
509
+ for key, url in urls.items():
510
+ log(f" -> stockanalysis.com: {url}")
511
+ r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS)
512
+ if r.status_code != 200:
513
+ log(f" [ERR] stockanalysis.com returned {r.status_code} for {key}")
514
+ return None
515
+ soup = BeautifulSoup(r.text, "lxml")
516
+ table = soup.find("table")
517
+ if not table: return None
518
+
519
+ # Parse headers (Skip TTM, take `years` count)
520
+ thead = table.find("thead")
521
+ ths = thead.find("tr").find_all("th")
522
+ # Index 0 is "Fiscal Year", Index 1 is "TTM" (usually). Index 2+ are the years.
523
+ if len(ths) < 3: return None
524
+
525
+ # Only need to extract year labels once
526
+ if "years" not in raw:
527
+ # Get the years newest to oldest, then reverse to oldest to newest
528
+ year_labels = [th.get_text(strip=True) for th in ths[2:2+years]]
529
+ raw["years"] = list(reversed(year_labels))
530
+
531
+ data_rows = {}
532
+ tbody = table.find("tbody")
533
+ for tr in tbody.find_all("tr"):
534
+ tds = tr.find_all("td")
535
+ if len(tds) < 3: continue
536
+ label = tds[0].get_text(strip=True)
537
+ vals = []
538
+ for td in tds[2:2+years]:
539
+ text = td.get_text(strip=True).replace(",", "")
540
+ if text == "-" or text == "":
541
+ vals.append(None)
542
+ else:
543
+ try: vals.append(float(text))
544
+ except: vals.append(None)
545
+ data_rows[label] = list(reversed(vals))
546
+ raw[key] = data_rows
547
+
548
+ except Exception as e:
549
+ log(f" [ERR] stockanalysis error: {e}")
550
+ return None
551
+
552
+ n = len(raw.get("years", []))
553
+ if n == 0: return None
554
+
555
+ def row(sec, *keys):
556
+ for k in keys:
557
+ if k in raw[sec]: return raw[sec][k]
558
+ return [None]*n
559
+
560
+ income = {
561
+ "revenue": row("income", "Revenue"),
562
+ "cost_of_revenue": row("income", "Cost of Revenue"),
563
+ "gross_profit": row("income", "Gross Profit"),
564
+ "operating_expenses": row("income", "Operating Expenses"),
565
+ "operating_income": row("income", "Operating Income"),
566
+ "ebitda": row("income", "EBITDA"),
567
+ "depreciation_amort": row("income", "Depreciation & Amortization"),
568
+ "interest_expense": row("income", "Interest Expense / Income"),
569
+ "pretax_income": row("income", "Pretax Income"),
570
+ "tax_expense": row("income", "Income Tax"),
571
+ "net_income": row("income", "Net Income"),
572
+ "diluted_eps": row("income", "EPS (Diluted)"),
573
+ "diluted_shares": row("income", "Shares Outstanding (Diluted)"),
574
+ }
575
+ balance = {
576
+ "cash_and_equivalents": row("balance", "Cash & Equivalents"),
577
+ "short_term_investments": row("balance", "Short-Term Investments"),
578
+ "receivables": row("balance", "Accounts Receivable"),
579
+ "inventory": row("balance", "Inventory"),
580
+ "other_current_assets": row("balance", "Other Current Assets"),
581
+ "total_current_assets": row("balance", "Total Current Assets"),
582
+ "ppe_net": row("balance", "Property, Plant & Equipment"),
583
+ "goodwill": row("balance", "Goodwill and Intangibles", "Goodwill"),
584
+ "intangibles": [None]*n,
585
+ "other_long_term_assets": row("balance", "Other Long-Term Assets"),
586
+ "total_assets": row("balance", "Total Assets"),
587
+ "accounts_payable": row("balance", "Accounts Payable"),
588
+ "short_term_debt": row("balance", "Current Debt"),
589
+ "other_current_liabilities": row("balance", "Other Current Liabilities"),
590
+ "total_current_liabilities": row("balance", "Total Current Liabilities"),
591
+ "long_term_debt": row("balance", "Long-Term Debt"),
592
+ "other_long_term_liabilities":row("balance", "Other Long-Term Liabilities"),
593
+ "total_liabilities": row("balance", "Total Liabilities"),
594
+ "total_equity": row("balance", "Shareholders' Equity"),
595
+ "total_liab_and_equity": row("balance", "Total Liabilities and Equity"),
596
+ }
597
+ cashflow = {
598
+ "net_income": row("cashflow", "Net Income"),
599
+ "depreciation_amort": row("cashflow", "Depreciation & Amortization"),
600
+ "stock_based_comp": row("cashflow", "Share-Based Compensation"),
601
+ "working_capital_changes": [None]*n,
602
+ "other_operating": row("cashflow", "Other Operating Activities"),
603
+ "cash_from_operations": row("cashflow", "Operating Cash Flow"),
604
+ "capex": row("cashflow", "Capital Expenditures"),
605
+ "acquisitions": row("cashflow", "Acquisitions"),
606
+ "cash_from_investing": row("cashflow", "Investing Cash Flow"),
607
+ "debt_issuance_repayment": row("cashflow", "Net Debt Issued/Paid"),
608
+ "stock_buybacks": row("cashflow", "Common Stock Issued/Repurchased", "Stock Repurchases"),
609
+ "dividends_paid": row("cashflow", "Dividends Paid"),
610
+ "cash_from_financing": row("cashflow", "Financing Cash Flow"),
611
+ "net_change_in_cash": row("cashflow", "Net Change in Cash"),
612
+ "free_cash_flow": row("cashflow", "Free Cash Flow"),
613
+ }
614
+ return {
615
+ "years": raw["years"], "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow,
616
+ "currency": "USD", "units": "millions",
617
+ "source": "stockanalysis.com",
618
+ "valuation_snapshot": {},
619
+ }
620
+
621
+ # ── Peer snapshot ─────────────────────────────────────────────────────────────
622
+
623
+ def fetch_peer_snapshot(ticker: str) -> Optional[Dict]:
624
+ try:
625
+ import yahooquery as yq
626
+ t = yq.Ticker(ticker)
627
+ price_data = t.price.get(ticker, {})
628
+ profile_data = t.summary_profile.get(ticker, {})
629
+ key_stats = t.key_stats.get(ticker, {})
630
+ fin_data = t.financial_data.get(ticker, {})
631
+ summary_det = t.summary_detail.get(ticker, {})
632
+
633
+ name = price_data.get("longName") or price_data.get("shortName", "")
634
+ if not name:
635
+ return None
636
+
637
+ # Try to get latest revenue from income statement
638
+ rev = None
639
+ try:
640
+ inc = t.income_statement(frequency='annual')
641
+ if inc is not None and not isinstance(inc, str) and not inc.empty:
642
+ annual_inc = inc[inc.get('periodType', '') == '12M'] if 'periodType' in inc.columns else inc
643
+ rev_col = annual_inc['TotalRevenue'].dropna() if 'TotalRevenue' in annual_inc.columns else None
644
+ if rev_col is not None and not rev_col.empty:
645
+ rev = float(rev_col.iloc[-1])
646
+ except Exception:
647
+ pass
648
+
649
+ ratios_ttm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0]
650
+
651
+ return {
652
+ "name": name,
653
+ "ticker": ticker,
654
+ "rationale": f"Industry peer ({profile_data.get('industry', '')})",
655
+ "latest_year": "",
656
+ "currency": price_data.get("currency", "INR"),
657
+ "units": "actuals",
658
+ "revenue": _s(rev),
659
+ "gross_margin": _s(fin_data.get("grossMargins")),
660
+ "operating_margin": _s(fin_data.get("operatingMargins")),
661
+ "net_margin": _s(fin_data.get("profitMargins")),
662
+ "roe": _s(fin_data.get("returnOnEquity")),
663
+ "roic": _s(ratios_ttm.get("returnOnCapitalEmployedTTM")),
664
+ "debt_to_equity": _s(key_stats.get("debtToEquity")),
665
+ "current_ratio": _s(fin_data.get("currentRatio")),
666
+ "fcf_margin": None,
667
+ "revenue_growth_3y_cagr": _s(fin_data.get("revenueGrowth")),
668
+ "pe_ttm": _s(summary_det.get("trailingPE")),
669
+ "ev_ebitda": _s(key_stats.get("enterpriseToEbitda")),
670
+ }
671
+ except Exception:
672
+ return None
673
+
674
+
675
+ def fetch_valuation(ticker: str) -> Dict:
676
+ try:
677
+ import yahooquery as yq
678
+ t = yq.Ticker(ticker)
679
+ key_stats = t.key_stats.get(ticker, {})
680
+ summary_det = t.summary_detail.get(ticker, {})
681
+ fin_data = t.financial_data.get(ticker, {})
682
+ return {
683
+ "pe_ttm": _s(summary_det.get("trailingPE")),
684
+ "pb": _s(key_stats.get("priceToBook")),
685
+ "ps": _s(key_stats.get("priceToSalesTrailing12Months")),
686
+ "ev_ebitda": _s(key_stats.get("enterpriseToEbitda")),
687
+ "ev_revenue": _s(key_stats.get("enterpriseToRevenue")),
688
+ "fcf_yield": None,
689
+ "dividend_yield": _s(summary_det.get("dividendYield")),
690
+ }
691
+ except Exception:
692
+ return {}
693
+
694
+ def _scrape_edgar_10k(ticker: str, log_fn=None) -> str:
695
+ """Fetch the latest 10-K for a US company from SEC EDGAR and extract a chunk of text."""
696
+ headers = {"User-Agent": "FinancialAnalyzer/1.0 (contact@example.com)"}
697
+ try:
698
+ if log_fn: log_fn(f" -> Looking up SEC CIK for {ticker}...")
699
+ r = requests.get("https://www.sec.gov/files/company_tickers.json", headers=headers, timeout=10)
700
+ tickers = r.json()
701
+ cik = None
702
+ for k, v in tickers.items():
703
+ if v["ticker"].upper() == ticker.upper():
704
+ cik = str(v["cik_str"]).zfill(10)
705
+ break
706
+
707
+ if not cik:
708
+ if log_fn: log_fn(" [ERR] CIK not found in SEC database.")
709
+ return ""
710
+
711
+ if log_fn: log_fn(f" -> Found CIK {cik}. Fetching recent filings...")
712
+ sub_r = requests.get(f"https://data.sec.gov/submissions/CIK{cik}.json", headers=headers, timeout=10)
713
+ data = sub_r.json()
714
+ filings = data.get("filings", {}).get("recent", {})
715
+
716
+ form_types = filings.get("form", [])
717
+ accessions = filings.get("accessionNumber", [])
718
+ primary_docs = filings.get("primaryDocument", [])
719
+
720
+ idx = -1
721
+ for i, form in enumerate(form_types):
722
+ if form == "10-K":
723
+ idx = i
724
+ break
725
+
726
+ if idx == -1:
727
+ if log_fn: log_fn(" [ERR] No 10-K found in recent filings.")
728
+ return ""
729
+
730
+ acc_num = accessions[idx]
731
+ acc_num_no_dash = acc_num.replace("-", "")
732
+ doc = primary_docs[idx]
733
+
734
+ url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{acc_num_no_dash}/{doc}"
735
+ if log_fn: log_fn(f" -> Downloading 10-K from {url}...")
736
+
737
+ doc_r = requests.get(url, headers=headers, timeout=20)
738
+ from bs4 import BeautifulSoup
739
+ soup = BeautifulSoup(doc_r.content, "lxml")
740
+
741
+ text = soup.get_text(separator="\n", strip=True)
742
+ import re
743
+ match = re.search(r'(?i)Item\s+7\.\s*Management[’\']s\s+Discussion', text)
744
+ if match:
745
+ start = match.start()
746
+ extract = text[start:start+40000]
747
+ else:
748
+ extract = text[len(text)//4 : len(text)//4 + 40000]
749
+
750
+ if log_fn: log_fn(" [OK] 10-K text extracted successfully.")
751
+ return extract
752
+ except Exception as e:
753
+ if log_fn: log_fn(f" [ERR] Failed to scrape EDGAR: {str(e)[:80]}")
754
+ return ""
755
+
756
+
757
+ # ── Main Fetcher ──────────────────────────────────────────────────────────────
758
+
759
+ def fetch_all(meta: CompanyMeta, years: int = DEFAULT_YEARS,
760
+ force_refresh: bool = False, log_fn=None) -> Dict:
761
+ def log(m):
762
+ if log_fn: log_fn(m)
763
+
764
+ if not meta.is_listed:
765
+ msg = (f"'{meta.name}' is unlisted/private. Public data not available. "
766
+ "Try the exact BSE/NSE ticker.")
767
+ log(f" ⚠ {msg}")
768
+ return {"warnings": [msg], "years": [], "income_statement": {},
769
+ "balance_sheet": {}, "cash_flow": {}}
770
+
771
+ ticker = meta.ticker
772
+ cache_key = f"full_{years}yr"
773
+ if not force_refresh:
774
+ cached = get_cached(ticker, cache_key)
775
+ if cached:
776
+ log(f" [OK] Loaded cached data for {ticker}")
777
+ return cached
778
+
779
+ warnings = []
780
+ result = None
781
+
782
+ # Re-prioritized Fetching Logic:
783
+
784
+ # 1. Indian Stocks: Try screener.in first (up to 10+ years of data)
785
+ if meta.currency == "INR":
786
+ log(" -> Indian Stock detected. Prioritizing screener.in ...")
787
+ scraped = _scrape_screener(ticker, log_fn)
788
+ if scraped:
789
+ result = _normalise_screener(scraped, years)
790
+ warnings.append("Data sourced from screener.in. Verify against company filings.")
791
+
792
+ # Fallback to yfinance if screener fails or yields nothing
793
+ if not result or not result.get("years"):
794
+ log(" -> screener.in failed. Falling back to yahooquery ...")
795
+ result = _fetch_yahooquery(ticker, years, log_fn)
796
+ if result and len(result.get("years", [])) < years:
797
+ warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.")
798
+
799
+ # 2. Global/US Stocks
800
+ else:
801
+ # If requesting > 4 years, try stockanalysis.com first because yahooquery limits to 4 years
802
+ if years > 4:
803
+ log(" -> Horizon > 4 years requested. Prioritizing stockanalysis.com for global stock ...")
804
+ result = _scrape_stockanalysis(ticker, years, log_fn)
805
+ if result:
806
+ warnings.append("Data sourced from stockanalysis.com. Verify against company filings.")
807
+
808
+ # Fallback to yahooquery
809
+ if not result or not result.get("years"):
810
+ log(" -> Trying yahooquery ...")
811
+ result = _fetch_yahooquery(ticker, years, log_fn)
812
+ if result and len(result.get("years", [])) < years:
813
+ warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.")
814
+
815
+ # Fallback to FMP
816
+ if (not result or not result.get("years")) and FMP_API_KEY:
817
+ result = _fetch_fmp(ticker, years, log_fn)
818
+
819
+ # 3. Final validation
820
+ if not result or not result.get("years"):
821
+ msg = (f"Could not fetch data for '{meta.name}' ({ticker}). "
822
+ "Check ticker, or the company may have limited public data coverage.")
823
+ log(f" ⚠ {msg}")
824
+ return {"warnings": [msg], "years": [], "income_statement": {},
825
+ "balance_sheet": {}, "cash_flow": {}}
826
+
827
+ # 4. Optional Annual Report Scrape (for context)
828
+ if meta.currency != "INR":
829
+ ar_context = _scrape_edgar_10k(ticker, log_fn)
830
+ if ar_context:
831
+ result["annual_report_context"] = ar_context
832
+ warnings.append("AI analysis enhanced with raw MD&A excerpts from SEC EDGAR 10-K.")
833
+
834
+ result["warnings"] = warnings
835
+ result.setdefault("currency", meta.currency)
836
+ set_cache(ticker, cache_key, result)
837
+ log(" [OK] Data cached for 7 days")
838
+ return result