diff --git "a/pipeline/fetcher.py" "b/pipeline/fetcher.py" --- "a/pipeline/fetcher.py" +++ "b/pipeline/fetcher.py" @@ -1,838 +1,1222 @@ -""" -pipeline/fetcher.py — Fetch 5-year financials. -Priority: yfinance (free, Indian stocks) -> FMP -> screener.in -""" -from __future__ import annotations -import sys, re, json, datetime -from pathlib import Path -from typing import Optional, List, Dict, Any - -import requests -from bs4 import BeautifulSoup - -sys.path.insert(0, str(Path(__file__).parent.parent)) -from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT, DEFAULT_YEARS -from storage.cache import get_cached, set_cache -from pipeline.resolver import CompanyMeta - -HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"} - - -# ── Helpers ─────────────────────────────────────────────────────────────────── - -def _s(v, default=None): - if v is None or (isinstance(v, float) and v != v): return default - return v - - -def _row(df, *keys): - """Get a row from a yfinance DataFrame by trying multiple key names.""" - for k in keys: - if k in df.index: - return df.loc[k].tolist() - return [None] * len(df.columns) - - -# ── yahooquery fetcher (primary for Indian + global) ───────────────────────── - -def _fetch_yahooquery(ticker: str, years: int, log_fn=None) -> Optional[Dict]: - """Fetch financial statements via yahooquery. Returns normalized dict or None.""" - def log(m): - if log_fn: log_fn(m) - try: - import yahooquery as yq - import pandas as pd - import math - - log(f" -> yahooquery: fetching {ticker} ...") - t = yq.Ticker(ticker) - - inc_df = t.income_statement(frequency='annual') - bs_df = t.balance_sheet(frequency='annual') - cf_df = t.cash_flow(frequency='annual') - - if inc_df is None or isinstance(inc_df, str) or inc_df.empty: - log(" [ERR] yahooquery returned empty income statement") - return None - - # ── Filter to clean annual rows only (periodType == '12M') ── - def clean_df(df): - if df is None or isinstance(df, str) or df.empty: - return pd.DataFrame() - df = df.reset_index() - if 'asOfDate' not in df.columns: - return df - df = df.dropna(subset=['asOfDate']) - df['asOfDate'] = pd.to_datetime(df['asOfDate']) - # Keep only 12M (full annual) rows, not TTM or quarterly - if 'periodType' in df.columns: - annual = df[df['periodType'] == '12M'] - if not annual.empty: - df = annual - df = df.sort_values('asOfDate') - # Deduplicate: keep last row per year-month (safety net) - df['ym'] = df['asOfDate'].dt.to_period('M') - df = df.drop_duplicates(subset=['ym'], keep='last').drop(columns=['ym']) - return df.reset_index(drop=True) - - inc = clean_df(inc_df) - bs = clean_df(bs_df) - cf = clean_df(cf_df) - - if inc.empty: - log(" [ERR] yahooquery: no usable annual rows after filtering") - return None - - # Take the most recent `years` rows (oldest→newest) - inc = inc.tail(years) - bs = bs.tail(years) if not bs.empty else pd.DataFrame() - cf = cf.tail(years) if not cf.empty else pd.DataFrame() - - # Year labels - year_labels = [d.strftime('%Y/%m') for d in inc['asOfDate']] - n = len(year_labels) - - # Determine currency and scaling - currency = "INR" - if 'currencyCode' in inc.columns: - cur_vals = inc['currencyCode'].dropna().unique() - if len(cur_vals) > 0: - currency = str(cur_vals[-1]) - - if currency == "INR": - scale = 1e7 # raw INR -> Crores - units = "Crores" - units_label = "INR Crores (₹ Cr)" - else: - scale = 1e6 - units = "Millions" - units_label = f"{currency} Millions" - - def gcol(df, *keys): - """Get column values (oldest→newest list of length n), scaled.""" - for k in keys: - if k in df.columns: - vals = df[k].tolist() - result = [] - for v in vals: - if v is None or (isinstance(v, float) and math.isnan(v)): - result.append(None) - else: - result.append(round(float(v) / scale, 2)) - # Pad or trim to n - while len(result) < n: result.append(None) - return result[:n] - return [None] * n - - def gcol_raw(df, *keys): - """Get column values without scaling.""" - for k in keys: - if k in df.columns: - vals = df[k].tolist() - result = [] - for v in vals: - if v is None or (isinstance(v, float) and math.isnan(v)): - result.append(None) - else: - result.append(float(v)) - while len(result) < n: result.append(None) - return result[:n] - return [None] * n - - income = { - "revenue": gcol(inc, "TotalRevenue", "OperatingRevenue"), - "cost_of_revenue": gcol(inc, "CostOfRevenue", "ReconciledCostOfRevenue"), - "gross_profit": gcol(inc, "GrossProfit"), - "operating_expenses": gcol(inc, "OperatingExpense", "TotalExpenses"), - "operating_income": gcol(inc, "OperatingIncome", "EBIT"), - "ebitda": gcol(inc, "EBITDA", "NormalizedEBITDA"), - "depreciation_amort": gcol(inc, "ReconciledDepreciation", "DepreciationAndAmortizationInIncomeStatement"), - "interest_expense": gcol(inc, "InterestExpenseNonOperating", "InterestExpense"), - "pretax_income": gcol(inc, "PretaxIncome"), - "tax_expense": gcol(inc, "TaxProvision"), - "net_income": gcol(inc, "NetIncome", "NetIncomeCommonStockholders"), - "diluted_eps": gcol_raw(inc, "DilutedEPS", "BasicEPS"), - "diluted_shares": gcol_raw(inc, "DilutedAverageShares", "BasicAverageShares"), - } - - balance = { - "cash_and_equivalents": gcol(bs, "CashAndCashEquivalents", "CashFinancial"), - "short_term_investments": gcol(bs, "OtherShortTermInvestments", "InvestmentsAndAdvances"), - "receivables": gcol(bs, "AccountsReceivable", "Receivables"), - "inventory": gcol(bs, "Inventory"), - "other_current_assets": gcol(bs, "OtherCurrentAssets"), - "total_current_assets": gcol(bs, "CurrentAssets"), - "ppe_net": gcol(bs, "NetPPE"), - "goodwill": gcol(bs, "Goodwill"), - "intangibles": gcol(bs, "OtherIntangibleAssets"), - "other_long_term_assets": gcol(bs, "OtherNonCurrentAssets"), - "total_assets": gcol(bs, "TotalAssets"), - "accounts_payable": gcol(bs, "AccountsPayable", "Payables"), - "short_term_debt": gcol(bs, "CurrentDebt", "CurrentDebtAndCapitalLeaseObligation"), - "other_current_liabilities": gcol(bs, "OtherCurrentLiabilities"), - "total_current_liabilities": gcol(bs, "CurrentLiabilities"), - "long_term_debt": gcol(bs, "LongTermDebt", "LongTermDebtAndCapitalLeaseObligation"), - "other_long_term_liabilities":gcol(bs, "OtherNonCurrentLiabilities"), - "total_liabilities": gcol(bs, "TotalLiabilitiesNetMinorityInterest", "TotalLiabilities"), - "total_equity": gcol(bs, "StockholdersEquity", "CommonStockEquity"), - "total_liab_and_equity": gcol(bs, "TotalAssets"), - } - - cfo = gcol(cf, "OperatingCashFlow", "CashFlowFromContinuingOperatingActivities") - cap = gcol(cf, "CapitalExpenditure") - fcf = gcol(cf, "FreeCashFlow") - # Compute FCF from CFO - CapEx if missing - for i in range(n): - if fcf[i] is None and cfo[i] is not None and cap[i] is not None: - fcf[i] = round(cfo[i] + cap[i], 2) # CapEx is negative in yahooquery - - cashflow = { - "net_income": gcol(cf, "NetIncomeFromContinuingOperations", "NetIncome"), - "depreciation_amort": gcol(cf, "DepreciationAndAmortization", "Depreciation"), - "stock_based_comp": gcol(cf, "StockBasedCompensation"), - "working_capital_changes": gcol(cf, "ChangeInWorkingCapital"), - "other_operating": [None] * n, - "cash_from_operations": cfo, - "capex": cap, - "acquisitions": gcol(cf, "PurchaseOfBusiness", "AcquisitionOfBusiness"), - "cash_from_investing": gcol(cf, "InvestingCashFlow", "CashFlowFromContinuingInvestingActivities"), - "debt_issuance_repayment": gcol(cf, "NetLongTermDebtIssuance", "NetIssuancePaymentsOfDebt"), - "stock_buybacks": gcol(cf, "NetCommonStockIssuance", "RepurchaseOfCapitalStock"), - "dividends_paid": gcol(cf, "CashDividendsPaid", "DividendsPaid"), - "cash_from_financing": gcol(cf, "FinancingCashFlow", "CashFlowFromContinuingFinancingActivities"), - "net_change_in_cash": gcol(cf, "ChangesInCash", "ChangeInCashSupplementalAsReported"), - "free_cash_flow": fcf, - } - - # Valuation snapshot - val_snap = {} - try: - fd = t.financial_data.get(ticker, {}) - if isinstance(fd, dict): - val_snap["target_mean_price"] = fd.get("targetMeanPrice") - val_snap["target_high_price"] = fd.get("targetHighPrice") - val_snap["target_low_price"] = fd.get("targetLowPrice") - val_snap["wacc_estimate"] = 0.10 - - sd = t.summary_detail.get(ticker, {}) - if isinstance(sd, dict): - val_snap["pe_ttm"] = sd.get("trailingPE") - val_snap["dividend_yield"] = sd.get("dividendYield") - except Exception: - pass - - log(f" [OK] yahooquery data ready ({n} years, {currency}, in {units})") - - return { - "years": year_labels, - "income_statement": income, - "balance_sheet": balance, - "cash_flow": cashflow, - "currency": currency, - "units": units, - "units_label": units_label, - "scale": scale, - "source": "Yahoo Finance (yahooquery)", - "valuation_snapshot": val_snap, - } - - except Exception as e: - import traceback - log(f" [ERR] yahooquery error: {e}\n{traceback.format_exc()}") - return None - - -# Keep a stub for backward compatibility (if anything still calls _fetch_yfinance) -def _fetch_yfinance(ticker: str, years: int, log_fn=None) -> Optional[Dict]: - return _fetch_yahooquery(ticker, years, log_fn) - - -# ── FMP fetcher (secondary for global) ─────────────────────────────────────── - -def _fmp_get(path, params=None): - if not FMP_API_KEY: return None - p = {"apikey": FMP_API_KEY} - if params: p.update(params) - try: - r = requests.get(f"{FMP_BASE}{path}", params=p, timeout=REQUEST_TIMEOUT, headers=HEADERS) - r.raise_for_status() - return r.json() - except Exception: - return None - - -def _normalise_fmp(raw, years): - inc = list(reversed(raw.get("income", [])))[:years] - bal = list(reversed(raw.get("balance", [])))[:years] - cf = list(reversed(raw.get("cashflow", [])))[:years] - - def col(lst, key): - return [_s(d.get(key)) for d in lst] - - year_labels = [d.get("calendarYear", str(d.get("date",""))[:4]) for d in inc] - income = { - "revenue": col(inc, "revenue"), - "cost_of_revenue": col(inc, "costOfRevenue"), - "gross_profit": col(inc, "grossProfit"), - "operating_expenses": col(inc, "operatingExpenses"), - "operating_income": col(inc, "operatingIncome"), - "ebitda": col(inc, "ebitda"), - "depreciation_amort": col(inc, "depreciationAndAmortization"), - "interest_expense": col(inc, "interestExpense"), - "pretax_income": col(inc, "incomeBeforeTax"), - "tax_expense": col(inc, "incomeTaxExpense"), - "net_income": col(inc, "netIncome"), - "diluted_eps": col(inc, "epsdiluted"), - "diluted_shares": col(inc, "weightedAverageShsOutDil"), - } - balance = { - "cash_and_equivalents": col(bal, "cashAndCashEquivalents"), - "short_term_investments": col(bal, "shortTermInvestments"), - "receivables": col(bal, "netReceivables"), - "inventory": col(bal, "inventory"), - "other_current_assets": col(bal, "otherCurrentAssets"), - "total_current_assets": col(bal, "totalCurrentAssets"), - "ppe_net": col(bal, "propertyPlantEquipmentNet"), - "goodwill": col(bal, "goodwill"), - "intangibles": col(bal, "intangibleAssets"), - "other_long_term_assets": col(bal, "otherNonCurrentAssets"), - "total_assets": col(bal, "totalAssets"), - "accounts_payable": col(bal, "accountPayables"), - "short_term_debt": col(bal, "shortTermDebt"), - "other_current_liabilities": col(bal, "otherCurrentLiabilities"), - "total_current_liabilities": col(bal, "totalCurrentLiabilities"), - "long_term_debt": col(bal, "longTermDebt"), - "other_long_term_liabilities":col(bal, "otherNonCurrentLiabilities"), - "total_liabilities": col(bal, "totalLiabilities"), - "total_equity": col(bal, "totalStockholdersEquity"), - "total_liab_and_equity": col(bal, "totalLiabilitiesAndStockholdersEquity"), - } - cashflow = { - "net_income": col(cf, "netIncome"), - "depreciation_amort": col(cf, "depreciationAndAmortization"), - "stock_based_comp": col(cf, "stockBasedCompensation"), - "working_capital_changes": col(cf, "changeInWorkingCapital"), - "other_operating": col(cf, "otherWorkingCapital"), - "cash_from_operations": col(cf, "netCashProvidedByOperatingActivities"), - "capex": col(cf, "capitalExpenditure"), - "acquisitions": col(cf, "acquisitionsNet"), - "cash_from_investing": col(cf, "netCashUsedForInvestingActivites"), - "debt_issuance_repayment": col(cf, "debtRepayment"), - "stock_buybacks": col(cf, "commonStockRepurchased"), - "dividends_paid": col(cf, "dividendsPaid"), - "cash_from_financing": col(cf, "netCashUsedProvidedByFinancingActivities"), - "net_change_in_cash": col(cf, "netChangeInCash"), - "free_cash_flow": col(cf, "freeCashFlow"), - } - return { - "years": year_labels, "income_statement": income, - "balance_sheet": balance, "cash_flow": cashflow, - "currency": "USD", "units": "millions", - "source": "FMP API", - "valuation_snapshot": {}, - } - - -def _fetch_fmp(ticker, years, log_fn=None): - def log(m): - if log_fn: log_fn(m) - if not FMP_API_KEY: - return None - log(" -> FMP: fetching statements ...") - lim = years + 1 - raw = { - "income": _fmp_get(f"/v3/income-statement/{ticker}", {"limit": lim, "period": "annual"}) or [], - "balance": _fmp_get(f"/v3/balance-sheet-statement/{ticker}", {"limit": lim, "period": "annual"}) or [], - "cashflow": _fmp_get(f"/v3/cash-flow-statement/{ticker}", {"limit": lim, "period": "annual"}) or [], - } - if not raw["income"]: - log(" [ERR] FMP returned no data") - return None - log(" [OK] FMP data ready") - data = _normalise_fmp(raw, years) - # Add valuation - rtm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0] - km = (_fmp_get(f"/v3/key-metrics-ttm/{ticker}") or [{}])[0] - data["valuation_snapshot"] = { - "pe_ttm": _s(rtm.get("peRatioTTM")), - "pb": _s(rtm.get("priceToBookRatioTTM")), - "ps": _s(rtm.get("priceToSalesRatioTTM")), - "ev_ebitda": _s(km.get("enterpriseValueOverEBITDATTM")), - "ev_revenue": _s(km.get("evToSalesTTM")), - "fcf_yield": _s(km.get("freeCashFlowYieldTTM")), - "dividend_yield": _s(rtm.get("dividendYieldTTM")), - } - return data - - -# ── screener.in (Indian fallback) ──────────────────────────────────────────── - -def _scrape_screener(ticker: str, log_fn=None) -> Optional[Dict]: - def log(m): - if log_fn: log_fn(m) - # Ticker usually like RELIANCE.NS, extract RELIANCE - base_ticker = ticker.split(".")[0].upper() - for url in [f"https://www.screener.in/company/{base_ticker}/consolidated/", - f"https://www.screener.in/company/{base_ticker}/"]: - try: - log(f" -> screener.in: {url}") - r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS) - if r.status_code == 200: - soup = BeautifulSoup(r.text, "lxml") - sections = {} - for sec_id, key in [("profit-loss","income"),("balance-sheet","balance"), - ("cash-flow","cashflow")]: - sec = soup.find("section", {"id": sec_id}) - if sec: - table = sec.find("table") - if table: - result = {} - for row in table.find_all("tr"): - cells = row.find_all(["td","th"]) - if len(cells) < 2: continue - label = cells[0].get_text(strip=True) - vals = [] - for c in cells[1:]: - t2 = c.get_text(strip=True).replace(",","").replace("+","") - try: vals.append(float(t2)) - except: vals.append(None) - if label: result[label] = vals - sections[key] = result - if "years" not in sections: - hdr = table.find("tr") - if hdr: - sections["years"] = [c.get_text(strip=True) - for c in hdr.find_all(["th","td"])[1:]] - if sections: - sections["source_url"] = url - log(" [OK] screener.in scraped") - return sections - except Exception as e: - log(f" [ERR] screener.in error: {e}") - return None - - -def _normalise_screener(raw, years): - yr = raw.get("years", [])[:years] - n = len(yr) - inc = raw.get("income", {}) - bal = raw.get("balance", {}) - cf = raw.get("cashflow", {}) - - def row(*keys): - for k in keys: - if k in inc: return inc[k][:n] - if k in bal: return bal[k][:n] - if k in cf: return cf[k][:n] - return [None]*n - - income = { - "revenue": row("Revenue","Net Sales","Sales"), - "cost_of_revenue": row("Expenses","Cost of Goods Sold"), - "gross_profit": row("Gross Profit"), - "operating_expenses": [None]*n, - "operating_income": row("Operating Profit","EBIT","PBDIT"), - "ebitda": row("PBDIT","EBITDA"), - "depreciation_amort": row("Depreciation"), - "interest_expense": row("Interest"), - "pretax_income": row("Profit before tax","PBT"), - "tax_expense": row("Tax"), - "net_income": row("Net Profit","PAT"), - "diluted_eps": row("EPS in Rs"), - "diluted_shares": [None]*n, - } - balance = { - "cash_and_equivalents": row("Cash Equivalents"), - "short_term_investments": [None]*n, - "receivables": [None]*n, - "inventory": [None]*n, - "other_current_assets": [None]*n, - "total_current_assets": row("Current Assets"), - "ppe_net": row("Fixed Assets"), - "goodwill": [None]*n, - "intangibles": [None]*n, - "other_long_term_assets": [None]*n, - "total_assets": row("Total Assets","Balance Sheet Size"), - "accounts_payable": [None]*n, - "short_term_debt": row("Short Term Borrowing"), - "other_current_liabilities": [None]*n, - "total_current_liabilities": row("Current Liabilities"), - "long_term_debt": row("Borrowings","Long Term Borrowing"), - "other_long_term_liabilities":[None]*n, - "total_liabilities": row("Total Liabilities"), - "total_equity": row("Equity Capital","Total Equity"), - "total_liab_and_equity": row("Total Assets","Balance Sheet Size"), - } - cfo_vals = row("Cash from Operating Activity","Cash from Operations") - cap_vals = row("Fixed Assets Purchased","Capital Expenditure") - fcf_vals = [(c - abs(x)) if c is not None and x is not None else None - for c, x in zip(cfo_vals, cap_vals)] - cashflow = { - "net_income": income["net_income"], - "depreciation_amort": income["depreciation_amort"], - "stock_based_comp": [None]*n, - "working_capital_changes": [None]*n, - "other_operating": [None]*n, - "cash_from_operations": cfo_vals, - "capex": cap_vals, - "acquisitions": [None]*n, - "cash_from_investing": row("Cash from Investing Activity"), - "debt_issuance_repayment": [None]*n, - "stock_buybacks": [None]*n, - "dividends_paid": row("Dividend Amount"), - "cash_from_financing": row("Cash from Financing Activity"), - "net_change_in_cash": row("Net Cash Flow"), - "free_cash_flow": fcf_vals, - } - return { - "years": yr, "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow, - "currency": "INR", "units": "crores", - "source": f"screener.in ({raw.get('source_url','')})", - "valuation_snapshot": {}, - } - -# ── stockanalysis.com (Global fallback for >4 years) ────────────────────────── - -def _scrape_stockanalysis(ticker: str, years: int, log_fn=None) -> Optional[Dict]: - def log(m): - if log_fn: log_fn(m) - base_ticker = ticker.split(".")[0].lower() - - urls = { - "income": f"https://stockanalysis.com/stocks/{base_ticker}/financials/", - "balance": f"https://stockanalysis.com/stocks/{base_ticker}/financials/balance-sheet/", - "cashflow": f"https://stockanalysis.com/stocks/{base_ticker}/financials/cash-flow-statement/" - } - - raw = {} - try: - for key, url in urls.items(): - log(f" -> stockanalysis.com: {url}") - r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS) - if r.status_code != 200: - log(f" [ERR] stockanalysis.com returned {r.status_code} for {key}") - return None - soup = BeautifulSoup(r.text, "lxml") - table = soup.find("table") - if not table: return None - - # Parse headers (Skip TTM, take `years` count) - thead = table.find("thead") - ths = thead.find("tr").find_all("th") - # Index 0 is "Fiscal Year", Index 1 is "TTM" (usually). Index 2+ are the years. - if len(ths) < 3: return None - - # Only need to extract year labels once - if "years" not in raw: - # Get the years newest to oldest, then reverse to oldest to newest - year_labels = [th.get_text(strip=True) for th in ths[2:2+years]] - raw["years"] = list(reversed(year_labels)) - - data_rows = {} - tbody = table.find("tbody") - for tr in tbody.find_all("tr"): - tds = tr.find_all("td") - if len(tds) < 3: continue - label = tds[0].get_text(strip=True) - vals = [] - for td in tds[2:2+years]: - text = td.get_text(strip=True).replace(",", "") - if text == "-" or text == "": - vals.append(None) - else: - try: vals.append(float(text)) - except: vals.append(None) - data_rows[label] = list(reversed(vals)) - raw[key] = data_rows - - except Exception as e: - log(f" [ERR] stockanalysis error: {e}") - return None - - n = len(raw.get("years", [])) - if n == 0: return None - - def row(sec, *keys): - for k in keys: - if k in raw[sec]: return raw[sec][k] - return [None]*n - - income = { - "revenue": row("income", "Revenue"), - "cost_of_revenue": row("income", "Cost of Revenue"), - "gross_profit": row("income", "Gross Profit"), - "operating_expenses": row("income", "Operating Expenses"), - "operating_income": row("income", "Operating Income"), - "ebitda": row("income", "EBITDA"), - "depreciation_amort": row("income", "Depreciation & Amortization"), - "interest_expense": row("income", "Interest Expense / Income"), - "pretax_income": row("income", "Pretax Income"), - "tax_expense": row("income", "Income Tax"), - "net_income": row("income", "Net Income"), - "diluted_eps": row("income", "EPS (Diluted)"), - "diluted_shares": row("income", "Shares Outstanding (Diluted)"), - } - balance = { - "cash_and_equivalents": row("balance", "Cash & Equivalents"), - "short_term_investments": row("balance", "Short-Term Investments"), - "receivables": row("balance", "Accounts Receivable"), - "inventory": row("balance", "Inventory"), - "other_current_assets": row("balance", "Other Current Assets"), - "total_current_assets": row("balance", "Total Current Assets"), - "ppe_net": row("balance", "Property, Plant & Equipment"), - "goodwill": row("balance", "Goodwill and Intangibles", "Goodwill"), - "intangibles": [None]*n, - "other_long_term_assets": row("balance", "Other Long-Term Assets"), - "total_assets": row("balance", "Total Assets"), - "accounts_payable": row("balance", "Accounts Payable"), - "short_term_debt": row("balance", "Current Debt"), - "other_current_liabilities": row("balance", "Other Current Liabilities"), - "total_current_liabilities": row("balance", "Total Current Liabilities"), - "long_term_debt": row("balance", "Long-Term Debt"), - "other_long_term_liabilities":row("balance", "Other Long-Term Liabilities"), - "total_liabilities": row("balance", "Total Liabilities"), - "total_equity": row("balance", "Shareholders' Equity"), - "total_liab_and_equity": row("balance", "Total Liabilities and Equity"), - } - cashflow = { - "net_income": row("cashflow", "Net Income"), - "depreciation_amort": row("cashflow", "Depreciation & Amortization"), - "stock_based_comp": row("cashflow", "Share-Based Compensation"), - "working_capital_changes": [None]*n, - "other_operating": row("cashflow", "Other Operating Activities"), - "cash_from_operations": row("cashflow", "Operating Cash Flow"), - "capex": row("cashflow", "Capital Expenditures"), - "acquisitions": row("cashflow", "Acquisitions"), - "cash_from_investing": row("cashflow", "Investing Cash Flow"), - "debt_issuance_repayment": row("cashflow", "Net Debt Issued/Paid"), - "stock_buybacks": row("cashflow", "Common Stock Issued/Repurchased", "Stock Repurchases"), - "dividends_paid": row("cashflow", "Dividends Paid"), - "cash_from_financing": row("cashflow", "Financing Cash Flow"), - "net_change_in_cash": row("cashflow", "Net Change in Cash"), - "free_cash_flow": row("cashflow", "Free Cash Flow"), - } - return { - "years": raw["years"], "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow, - "currency": "USD", "units": "millions", - "source": "stockanalysis.com", - "valuation_snapshot": {}, - } - -# ── Peer snapshot ───────────────────────────────────────────────────────────── - -def fetch_peer_snapshot(ticker: str) -> Optional[Dict]: - try: - import yahooquery as yq - t = yq.Ticker(ticker) - price_data = t.price.get(ticker, {}) - profile_data = t.summary_profile.get(ticker, {}) - key_stats = t.key_stats.get(ticker, {}) - fin_data = t.financial_data.get(ticker, {}) - summary_det = t.summary_detail.get(ticker, {}) - - name = price_data.get("longName") or price_data.get("shortName", "") - if not name: - return None - - # Try to get latest revenue from income statement - rev = None - try: - inc = t.income_statement(frequency='annual') - if inc is not None and not isinstance(inc, str) and not inc.empty: - annual_inc = inc[inc.get('periodType', '') == '12M'] if 'periodType' in inc.columns else inc - rev_col = annual_inc['TotalRevenue'].dropna() if 'TotalRevenue' in annual_inc.columns else None - if rev_col is not None and not rev_col.empty: - rev = float(rev_col.iloc[-1]) - except Exception: - pass - - ratios_ttm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0] - - return { - "name": name, - "ticker": ticker, - "rationale": f"Industry peer ({profile_data.get('industry', '')})", - "latest_year": "", - "currency": price_data.get("currency", "INR"), - "units": "actuals", - "revenue": _s(rev), - "gross_margin": _s(fin_data.get("grossMargins")), - "operating_margin": _s(fin_data.get("operatingMargins")), - "net_margin": _s(fin_data.get("profitMargins")), - "roe": _s(fin_data.get("returnOnEquity")), - "roic": _s(ratios_ttm.get("returnOnCapitalEmployedTTM")), - "debt_to_equity": _s(key_stats.get("debtToEquity")), - "current_ratio": _s(fin_data.get("currentRatio")), - "fcf_margin": None, - "revenue_growth_3y_cagr": _s(fin_data.get("revenueGrowth")), - "pe_ttm": _s(summary_det.get("trailingPE")), - "ev_ebitda": _s(key_stats.get("enterpriseToEbitda")), - } - except Exception: - return None - - -def fetch_valuation(ticker: str) -> Dict: - try: - import yahooquery as yq - t = yq.Ticker(ticker) - key_stats = t.key_stats.get(ticker, {}) - summary_det = t.summary_detail.get(ticker, {}) - fin_data = t.financial_data.get(ticker, {}) - return { - "pe_ttm": _s(summary_det.get("trailingPE")), - "pb": _s(key_stats.get("priceToBook")), - "ps": _s(key_stats.get("priceToSalesTrailing12Months")), - "ev_ebitda": _s(key_stats.get("enterpriseToEbitda")), - "ev_revenue": _s(key_stats.get("enterpriseToRevenue")), - "fcf_yield": None, - "dividend_yield": _s(summary_det.get("dividendYield")), - } - except Exception: - return {} - -def _scrape_edgar_10k(ticker: str, log_fn=None) -> str: - """Fetch the latest 10-K for a US company from SEC EDGAR and extract a chunk of text.""" - headers = {"User-Agent": "FinancialAnalyzer/1.0 (contact@example.com)"} - try: - if log_fn: log_fn(f" -> Looking up SEC CIK for {ticker}...") - r = requests.get("https://www.sec.gov/files/company_tickers.json", headers=headers, timeout=10) - tickers = r.json() - cik = None - for k, v in tickers.items(): - if v["ticker"].upper() == ticker.upper(): - cik = str(v["cik_str"]).zfill(10) - break - - if not cik: - if log_fn: log_fn(" [ERR] CIK not found in SEC database.") - return "" - - if log_fn: log_fn(f" -> Found CIK {cik}. Fetching recent filings...") - sub_r = requests.get(f"https://data.sec.gov/submissions/CIK{cik}.json", headers=headers, timeout=10) - data = sub_r.json() - filings = data.get("filings", {}).get("recent", {}) - - form_types = filings.get("form", []) - accessions = filings.get("accessionNumber", []) - primary_docs = filings.get("primaryDocument", []) - - idx = -1 - for i, form in enumerate(form_types): - if form == "10-K": - idx = i - break - - if idx == -1: - if log_fn: log_fn(" [ERR] No 10-K found in recent filings.") - return "" - - acc_num = accessions[idx] - acc_num_no_dash = acc_num.replace("-", "") - doc = primary_docs[idx] - - url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{acc_num_no_dash}/{doc}" - if log_fn: log_fn(f" -> Downloading 10-K from {url}...") - - doc_r = requests.get(url, headers=headers, timeout=20) - from bs4 import BeautifulSoup - soup = BeautifulSoup(doc_r.content, "lxml") - - text = soup.get_text(separator="\n", strip=True) - import re - match = re.search(r'(?i)Item\s+7\.\s*Management[’\']s\s+Discussion', text) - if match: - start = match.start() - extract = text[start:start+40000] - else: - extract = text[len(text)//4 : len(text)//4 + 40000] - - if log_fn: log_fn(" [OK] 10-K text extracted successfully.") - return extract - except Exception as e: - if log_fn: log_fn(f" [ERR] Failed to scrape EDGAR: {str(e)[:80]}") - return "" - - -# ── Main Fetcher ────────────────────────────────────────────────────────────── - -def fetch_all(meta: CompanyMeta, years: int = DEFAULT_YEARS, - force_refresh: bool = False, log_fn=None) -> Dict: - def log(m): - if log_fn: log_fn(m) - - if not meta.is_listed: - msg = (f"'{meta.name}' is unlisted/private. Public data not available. " - "Try the exact BSE/NSE ticker.") - log(f" ⚠ {msg}") - return {"warnings": [msg], "years": [], "income_statement": {}, - "balance_sheet": {}, "cash_flow": {}} - - ticker = meta.ticker - cache_key = f"full_{years}yr" - if not force_refresh: - cached = get_cached(ticker, cache_key) - if cached: - log(f" [OK] Loaded cached data for {ticker}") - return cached - - warnings = [] - result = None - - # Re-prioritized Fetching Logic: - - # 1. Indian Stocks: Try screener.in first (up to 10+ years of data) - if meta.currency == "INR": - log(" -> Indian Stock detected. Prioritizing screener.in ...") - scraped = _scrape_screener(ticker, log_fn) - if scraped: - result = _normalise_screener(scraped, years) - warnings.append("Data sourced from screener.in. Verify against company filings.") - - # Fallback to yfinance if screener fails or yields nothing - if not result or not result.get("years"): - log(" -> screener.in failed. Falling back to yahooquery ...") - result = _fetch_yahooquery(ticker, years, log_fn) - if result and len(result.get("years", [])) < years: - warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.") - - # 2. Global/US Stocks - else: - # If requesting > 4 years, try stockanalysis.com first because yahooquery limits to 4 years - if years > 4: - log(" -> Horizon > 4 years requested. Prioritizing stockanalysis.com for global stock ...") - result = _scrape_stockanalysis(ticker, years, log_fn) - if result: - warnings.append("Data sourced from stockanalysis.com. Verify against company filings.") - - # Fallback to yahooquery - if not result or not result.get("years"): - log(" -> Trying yahooquery ...") - result = _fetch_yahooquery(ticker, years, log_fn) - if result and len(result.get("years", [])) < years: - warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.") - - # Fallback to FMP - if (not result or not result.get("years")) and FMP_API_KEY: - result = _fetch_fmp(ticker, years, log_fn) - - # 3. Final validation - if not result or not result.get("years"): - msg = (f"Could not fetch data for '{meta.name}' ({ticker}). " - "Check ticker, or the company may have limited public data coverage.") - log(f" ⚠ {msg}") - return {"warnings": [msg], "years": [], "income_statement": {}, - "balance_sheet": {}, "cash_flow": {}} - - # 4. Optional Annual Report Scrape (for context) - if meta.currency != "INR": - ar_context = _scrape_edgar_10k(ticker, log_fn) - if ar_context: - result["annual_report_context"] = ar_context - warnings.append("AI analysis enhanced with raw MD&A excerpts from SEC EDGAR 10-K.") - - result["warnings"] = warnings - result.setdefault("currency", meta.currency) - set_cache(ticker, cache_key, result) - log(" [OK] Data cached for 7 days") - return result +""" +pipeline/fetcher.py — Robust financial data pipeline. +5-layer waterfall: screener.in -> yahooquery -> moneycontrol -> FMP -> stockanalysis +All sources run; results are merged field-by-field to maximise data coverage. +Never crashes — every fetcher is fully exception-guarded. +""" +from __future__ import annotations +import sys, re, json, math, datetime +from pathlib import Path +from typing import Optional, List, Dict, Any + +import requests +from bs4 import BeautifulSoup + +sys.path.insert(0, str(Path(__file__).parent.parent)) +from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT, DEFAULT_YEARS +from storage.cache import get_cached, set_cache +from pipeline.resolver import CompanyMeta + +HEADERS = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + "Accept-Language": "en-US,en;q=0.9", + "Accept": "text/html,application/xhtml+xml", +} +MC_HEADERS = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + "Referer": "https://www.moneycontrol.com/", +} + + +# ── Helpers ──────────────────────────────────────────────────────────────────── + +def _s(v, default=None): + if v is None or (isinstance(v, float) and v != v): return default + return v + + +def _safe_float(s): + """Parse a string like '1,23,456.78' or '(1234)' into float or None.""" + if s is None: return None + s = str(s).strip().replace(",", "").replace(" ", "") + if not s or s in ("-", "--", "N/A", "NA"): return None + negative = s.startswith("(") and s.endswith(")") + s = s.strip("()") + try: + v = float(s) + return -v if negative else v + except Exception: + return None + + +def _nonnull_count(lst): + return sum(1 for v in lst if v is not None) + + +# ── Sector Detection ─────────────────────────────────────────────────────────── + +INSURANCE_SIGNALS = {"Premium Earned", "Net Premium", "Gross Premium", "Claims Incurred", + "Policyholder", "Reinsurance", "Actuarial"} +BANKING_SIGNALS = {"Interest Earned", "Interest Expended", "Net Interest Income", + "NIM", "CASA", "Advances", "Deposits", "Provisions and Contingencies"} +NBFC_SIGNALS = {"Interest Income", "Finance Cost", "Net Interest Margin", + "Loan Portfolio", "AUM", "NPA"} + +def _detect_sector(keys: set) -> str: + """Returns 'insurance', 'banking', 'nbfc', or 'default'.""" + if keys & INSURANCE_SIGNALS: return "insurance" + if keys & BANKING_SIGNALS: return "banking" + if keys & NBFC_SIGNALS: return "nbfc" + return "default" + + +# ── Sector-aware key maps ────────────────────────────────────────────────────── + +REVENUE_KEYS = { + "insurance": ["Premium Earned", "Net Premium", "Gross Premium", "Total Income", + "Net Earned Premium", "Premiums"], + "banking": ["Interest Earned", "Net Interest Income", "Total Interest Income", + "Revenue from operations", "Total Income"], + "nbfc": ["Interest Income", "Revenue From Operations", "Total Income"], + "default": ["Revenue", "Net Sales", "Sales", "Net Revenue", "Total Revenue", + "Revenue From Operations", "Total Operating Revenues", + "Revenue from operations", "Net Revenue from Operations"], +} +COST_KEYS = { + "insurance": ["Claims Incurred", "Benefits and Claims", "Net Claims Incurred", + "Expenses", "Total Expenses"], + "banking": ["Interest Expended", "Total Interest Expended", "Expenses"], + "nbfc": ["Finance Costs", "Interest Expense", "Expenses"], + "default": ["Expenses", "Cost of Goods Sold", "Total Expenses", + "Cost Of Materials Consumed", "Cost of Revenue"], +} +NET_INCOME_KEYS = { + "insurance": ["Net Profit", "Profit After Tax", "PAT", "Surplus", "Net Surplus", + "Profit for the year", "Net Profit after minority interest"], + "banking": ["Net Profit", "PAT", "Profit After Tax", "Net Profit after tax"], + "nbfc": ["Net Profit", "PAT", "Profit After Tax"], + "default": ["Net Profit", "PAT", "Net Profit after tax", "Profit after tax", + "Net Profit/Loss For The Period", "Profit for the Year"], +} +OPERATING_INCOME_KEYS = { + "insurance": ["Operating Profit", "EBIT", "Profit Before Tax"], + "banking": ["Operating Profit", "PBDT", "EBIT"], + "nbfc": ["Operating Profit", "EBIT", "PBDT"], + "default": ["Operating Profit", "EBIT", "PBDIT", + "Profit/Loss Before Exceptional Items", + "Profit/Loss Before Tax"], +} + + +# ── Data quality validator ──────────────────────────────────────────���───────── + +def _validate_data_quality(result: Dict, years: int) -> int: + """Returns a 0-100 data quality score based on field coverage.""" + if not result or not result.get("years"): + return 0 + n = max(len(result.get("years", [])), 1) + inc = result.get("income_statement", {}) + bal = result.get("balance_sheet", {}) + cf = result.get("cash_flow", {}) + + rev_score = (_nonnull_count(inc.get("revenue", [])) / n) * 35 + ni_score = (_nonnull_count(inc.get("net_income", [])) / n) * 25 + ta_score = (_nonnull_count(bal.get("total_assets", [])) / n) * 20 + cfo_score = (_nonnull_count(cf.get("cash_from_operations", [])) / n) * 20 + + return min(100, int(rev_score + ni_score + ta_score + cfo_score)) + + +# ── Intelligent field-by-field merge ───────────────────────────────────────── + +def _merge_financial_data(sources: List[Dict], log_fn=None) -> Optional[Dict]: + """ + Takes a list of result dicts from different sources (highest priority first). + For each data field, picks the source with the most non-None values. + Returns a single merged result dict. + """ + def log(m): + if log_fn: log_fn(m) + + # Filter out None/empty sources + valid = [s for s in sources if s and s.get("years")] + if not valid: + return None + + # Use the longest year axis as the master timeline + master = max(valid, key=lambda s: len(s.get("years", []))) + merged = { + "years": master["years"], + "currency": master.get("currency", "INR"), + "units": master.get("units", "Crores"), + "units_label": master.get("units_label", "INR Crores"), + "scale": master.get("scale", 1e7), + "source": master.get("source", "Multi-source"), + "income_statement": {}, + "balance_sheet": {}, + "cash_flow": {}, + "valuation_snapshot": {}, + } + + n = len(merged["years"]) + + def best_field(section_key, field_key): + """Return the list with the most non-None values across all valid sources.""" + best_list = [None] * n + best_count = -1 + for src in valid: + candidate = src.get(section_key, {}).get(field_key, []) + # Align length + if len(candidate) > n: + candidate = candidate[-n:] + elif len(candidate) < n: + candidate = [None] * (n - len(candidate)) + candidate + count = _nonnull_count(candidate) + if count > best_count: + best_count = count + best_list = candidate + return best_list + + for field in ["revenue", "cost_of_revenue", "gross_profit", "operating_expenses", + "operating_income", "ebitda", "depreciation_amort", "interest_expense", + "pretax_income", "tax_expense", "net_income", "diluted_eps", "diluted_shares"]: + merged["income_statement"][field] = best_field("income_statement", field) + + for field in ["cash_and_equivalents", "short_term_investments", "receivables", + "inventory", "other_current_assets", "total_current_assets", "ppe_net", + "goodwill", "intangibles", "other_long_term_assets", "total_assets", + "accounts_payable", "short_term_debt", "other_current_liabilities", + "total_current_liabilities", "long_term_debt", "other_long_term_liabilities", + "total_liabilities", "total_equity", "total_liab_and_equity"]: + merged["balance_sheet"][field] = best_field("balance_sheet", field) + + for field in ["net_income", "depreciation_amort", "stock_based_comp", + "working_capital_changes", "other_operating", "cash_from_operations", + "capex", "acquisitions", "cash_from_investing", "debt_issuance_repayment", + "stock_buybacks", "dividends_paid", "cash_from_financing", + "net_change_in_cash", "free_cash_flow"]: + merged["cash_flow"][field] = best_field("cash_flow", field) + + # Valuation: take the first available + for src in valid: + vs = src.get("valuation_snapshot", {}) + if vs: + merged["valuation_snapshot"] = vs + break + + # Derive gross_profit if missing + if all(v is None for v in merged["income_statement"]["gross_profit"]): + rev = merged["income_statement"]["revenue"] + cog = merged["income_statement"]["cost_of_revenue"] + merged["income_statement"]["gross_profit"] = [ + round(r - c, 2) if r is not None and c is not None else None + for r, c in zip(rev, cog) + ] + + # Derive FCF if missing + fcf = merged["cash_flow"]["free_cash_flow"] + cfo = merged["cash_flow"]["cash_from_operations"] + cap = merged["cash_flow"]["capex"] + merged["cash_flow"]["free_cash_flow"] = [ + fcf[i] if fcf[i] is not None + else (round(cfo[i] + cap[i], 2) if cfo[i] is not None and cap[i] is not None else None) + for i in range(n) + ] + + # Collect all source names + source_names = list(dict.fromkeys([s.get("source", "") for s in valid if s.get("source")])) + merged["source"] = " + ".join(source_names) if source_names else "Multi-source" + + log(f" [OK] Merged {len(valid)} source(s): {merged['source']}") + return merged + + +# ── SOURCE 1: yahooquery ────────────────────────────────────────────────────── + +def _fetch_yahooquery(ticker: str, years: int, log_fn=None) -> Optional[Dict]: + """Fetch financial statements via yahooquery.""" + def log(m): + if log_fn: log_fn(m) + try: + import yahooquery as yq + import pandas as pd + + log(f" -> [yahooquery] fetching {ticker} ...") + t = yq.Ticker(ticker) + + inc_df = t.income_statement(frequency='annual') + bs_df = t.balance_sheet(frequency='annual') + cf_df = t.cash_flow(frequency='annual') + + if inc_df is None or isinstance(inc_df, str) or inc_df.empty: + log(" [ERR] yahooquery: empty income statement") + return None + + def clean_df(df): + if df is None or isinstance(df, str) or df.empty: + return pd.DataFrame() + df = df.reset_index() + if 'asOfDate' not in df.columns: return df + df = df.dropna(subset=['asOfDate']) + df['asOfDate'] = pd.to_datetime(df['asOfDate']) + if 'periodType' in df.columns: + annual = df[df['periodType'] == '12M'] + if not annual.empty: df = annual + df = df.sort_values('asOfDate') + df['ym'] = df['asOfDate'].dt.to_period('M') + df = df.drop_duplicates(subset=['ym'], keep='last').drop(columns=['ym']) + return df.reset_index(drop=True) + + inc = clean_df(inc_df).tail(years) + bs = clean_df(bs_df).tail(years) if not clean_df(bs_df).empty else pd.DataFrame() + cf = clean_df(cf_df).tail(years) if not clean_df(cf_df).empty else pd.DataFrame() + + if inc.empty: + log(" [ERR] yahooquery: no annual rows after filtering") + return None + + year_labels = [d.strftime('%Y/%m') for d in inc['asOfDate']] + n = len(year_labels) + + currency = "INR" + if 'currencyCode' in inc.columns: + cur_vals = inc['currencyCode'].dropna().unique() + if len(cur_vals) > 0: currency = str(cur_vals[-1]) + + if currency == "INR": + scale, units, units_label = 1e7, "Crores", "INR Crores (Rs. Cr)" + else: + scale, units, units_label = 1e6, "Millions", f"{currency} Millions" + + def gcol(df, *keys): + for k in keys: + if not df.empty and k in df.columns: + vals = df[k].tolist() + result = [None if v is None or (isinstance(v, float) and math.isnan(v)) + else round(float(v) / scale, 2) for v in vals] + while len(result) < n: result.append(None) + return result[:n] + return [None] * n + + def gcol_raw(df, *keys): + for k in keys: + if not df.empty and k in df.columns: + vals = df[k].tolist() + result = [None if v is None or (isinstance(v, float) and math.isnan(v)) + else float(v) for v in vals] + while len(result) < n: result.append(None) + return result[:n] + return [None] * n + + cfo = gcol(cf, "OperatingCashFlow", "CashFlowFromContinuingOperatingActivities") + cap = gcol(cf, "CapitalExpenditure") + fcf = gcol(cf, "FreeCashFlow") + for i in range(n): + if fcf[i] is None and cfo[i] is not None and cap[i] is not None: + fcf[i] = round(cfo[i] + cap[i], 2) + + val_snap = {} + try: + fd = t.financial_data.get(ticker, {}) + if isinstance(fd, dict): + val_snap.update({ + "target_mean_price": fd.get("targetMeanPrice"), + "target_high_price": fd.get("targetHighPrice"), + "target_low_price": fd.get("targetLowPrice"), + "wacc_estimate": 0.10, + }) + sd = t.summary_detail.get(ticker, {}) + if isinstance(sd, dict): + val_snap["pe_ttm"] = sd.get("trailingPE") + val_snap["dividend_yield"] = sd.get("dividendYield") + except Exception: + pass + + log(f" [OK] yahooquery: {n} years, {currency}, {units}") + return { + "years": year_labels, + "income_statement": { + "revenue": gcol(inc, "TotalRevenue", "OperatingRevenue"), + "cost_of_revenue": gcol(inc, "CostOfRevenue", "ReconciledCostOfRevenue"), + "gross_profit": gcol(inc, "GrossProfit"), + "operating_expenses": gcol(inc, "OperatingExpense", "TotalExpenses"), + "operating_income": gcol(inc, "OperatingIncome", "EBIT"), + "ebitda": gcol(inc, "EBITDA", "NormalizedEBITDA"), + "depreciation_amort": gcol(inc, "ReconciledDepreciation", + "DepreciationAndAmortizationInIncomeStatement"), + "interest_expense": gcol(inc, "InterestExpenseNonOperating", "InterestExpense"), + "pretax_income": gcol(inc, "PretaxIncome"), + "tax_expense": gcol(inc, "TaxProvision"), + "net_income": gcol(inc, "NetIncome", "NetIncomeCommonStockholders"), + "diluted_eps": gcol_raw(inc, "DilutedEPS", "BasicEPS"), + "diluted_shares": gcol_raw(inc, "DilutedAverageShares", "BasicAverageShares"), + }, + "balance_sheet": { + "cash_and_equivalents": gcol(bs, "CashAndCashEquivalents", "CashFinancial"), + "short_term_investments": gcol(bs, "OtherShortTermInvestments", "InvestmentsAndAdvances"), + "receivables": gcol(bs, "AccountsReceivable", "Receivables"), + "inventory": gcol(bs, "Inventory"), + "other_current_assets": gcol(bs, "OtherCurrentAssets"), + "total_current_assets": gcol(bs, "CurrentAssets"), + "ppe_net": gcol(bs, "NetPPE"), + "goodwill": gcol(bs, "Goodwill"), + "intangibles": gcol(bs, "OtherIntangibleAssets"), + "other_long_term_assets": gcol(bs, "OtherNonCurrentAssets"), + "total_assets": gcol(bs, "TotalAssets"), + "accounts_payable": gcol(bs, "AccountsPayable", "Payables"), + "short_term_debt": gcol(bs, "CurrentDebt", "CurrentDebtAndCapitalLeaseObligation"), + "other_current_liabilities": gcol(bs, "OtherCurrentLiabilities"), + "total_current_liabilities": gcol(bs, "CurrentLiabilities"), + "long_term_debt": gcol(bs, "LongTermDebt", "LongTermDebtAndCapitalLeaseObligation"), + "other_long_term_liabilities": gcol(bs, "OtherNonCurrentLiabilities"), + "total_liabilities": gcol(bs, "TotalLiabilitiesNetMinorityInterest", "TotalLiabilities"), + "total_equity": gcol(bs, "StockholdersEquity", "CommonStockEquity"), + "total_liab_and_equity": gcol(bs, "TotalAssets"), + }, + "cash_flow": { + "net_income": gcol(cf, "NetIncomeFromContinuingOperations", "NetIncome"), + "depreciation_amort": gcol(cf, "DepreciationAndAmortization", "Depreciation"), + "stock_based_comp": gcol(cf, "StockBasedCompensation"), + "working_capital_changes": gcol(cf, "ChangeInWorkingCapital"), + "other_operating": [None] * n, + "cash_from_operations": cfo, + "capex": cap, + "acquisitions": gcol(cf, "PurchaseOfBusiness", "AcquisitionOfBusiness"), + "cash_from_investing": gcol(cf, "InvestingCashFlow", + "CashFlowFromContinuingInvestingActivities"), + "debt_issuance_repayment": gcol(cf, "NetLongTermDebtIssuance", "NetIssuancePaymentsOfDebt"), + "stock_buybacks": gcol(cf, "NetCommonStockIssuance", "RepurchaseOfCapitalStock"), + "dividends_paid": gcol(cf, "CashDividendsPaid", "DividendsPaid"), + "cash_from_financing": gcol(cf, "FinancingCashFlow", + "CashFlowFromContinuingFinancingActivities"), + "net_change_in_cash": gcol(cf, "ChangesInCash", + "ChangeInCashSupplementalAsReported"), + "free_cash_flow": fcf, + }, + "currency": currency, "units": units, "units_label": units_label, + "scale": scale, "source": "Yahoo Finance (yahooquery)", + "valuation_snapshot": val_snap, + } + except Exception as e: + import traceback + if log_fn: log_fn(f" [ERR] yahooquery: {e}\n{traceback.format_exc()[:300]}") + return None + + +# Keep backward-compat stub +def _fetch_yfinance(ticker, years, log_fn=None): + return _fetch_yahooquery(ticker, years, log_fn) + + +# ── SOURCE 2: screener.in ───────────────────────────────────────────────────── + +def _scrape_screener(ticker: str, log_fn=None) -> Optional[Dict]: + def log(m): + if log_fn: log_fn(m) + base_ticker = ticker.split(".")[0].upper() + for url in [f"https://www.screener.in/company/{base_ticker}/consolidated/", + f"https://www.screener.in/company/{base_ticker}/"]: + try: + log(f" -> [screener.in] {url}") + r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS) + if r.status_code != 200: continue + soup = BeautifulSoup(r.text, "lxml") + sections = {} + for sec_id, key in [("profit-loss", "income"), ("balance-sheet", "balance"), + ("cash-flow", "cashflow")]: + sec = soup.find("section", {"id": sec_id}) + if sec: + table = sec.find("table") + if table: + result = {} + for row in table.find_all("tr"): + cells = row.find_all(["td", "th"]) + if len(cells) < 2: continue + label = cells[0].get_text(strip=True) + vals = [] + for c in cells[1:]: + t2 = c.get_text(strip=True).replace(",", "").replace("+", "") + try: vals.append(float(t2)) + except: vals.append(None) + if label: result[label] = vals + sections[key] = result + if "years" not in sections: + hdr = table.find("tr") + if hdr: + sections["years"] = [c.get_text(strip=True) + for c in hdr.find_all(["th", "td"])[1:]] + if sections: + sections["source_url"] = url + log(" [OK] screener.in scraped") + return sections + except Exception as e: + log(f" [ERR] screener.in: {e}") + return None + + +def _normalise_screener(raw: Dict, years: int) -> Optional[Dict]: + yr = raw.get("years", [])[:years] + n = len(yr) + if n == 0: return None + inc = raw.get("income", {}) + bal = raw.get("balance", {}) + cf = raw.get("cashflow", {}) + + # Detect sector from row names + all_keys = set(inc.keys()) | set(bal.keys()) | set(cf.keys()) + sector = _detect_sector(all_keys) + + def row(*keys): + for k in keys: + if k in inc: return inc[k][:n] + if k in bal: return bal[k][:n] + if k in cf: return cf[k][:n] + kp = k + "+" + if kp in inc: return inc[kp][:n] + if kp in bal: return bal[kp][:n] + if kp in cf: return cf[kp][:n] + return [None] * n + + revenue = row(*REVENUE_KEYS.get(sector, REVENUE_KEYS["default"])) + cost = row(*COST_KEYS.get(sector, COST_KEYS["default"])) + net_inc = row(*NET_INCOME_KEYS.get(sector, NET_INCOME_KEYS["default"])) + op_income = row(*OPERATING_INCOME_KEYS.get(sector, OPERATING_INCOME_KEYS["default"])) + + gross = [round(r - c, 2) if r is not None and c is not None else None + for r, c in zip(revenue, cost)] + + cfo_vals = row("Cash from Operating Activity", "Cash from Operations", + "Operating Cash Flow", "Net Cash from Operating Activities") + cap_vals = row("Fixed Assets Purchased", "Capital Expenditure", + "Purchase of Fixed Assets", "Capex") + fcf_vals = [round(c - abs(x), 2) if c is not None and x is not None else None + for c, x in zip(cfo_vals, cap_vals)] + # Also try direct FCF row + direct_fcf = row("Free Cash Flow") + fcf_vals = [d if d is not None else f for d, f in zip(direct_fcf, fcf_vals)] + + return { + "years": yr, + "income_statement": { + "revenue": revenue, + "cost_of_revenue": cost, + "gross_profit": gross, + "operating_expenses": [None] * n, + "operating_income": op_income, + "ebitda": row("PBDIT", "EBITDA", "Operating Profit"), + "depreciation_amort": row("Depreciation"), + "interest_expense": row("Interest", "Finance Cost", "Finance Costs", + "Interest Expended"), + "pretax_income": row("Profit before tax", "PBT", "Profit Before Tax"), + "tax_expense": row("Tax", "Income Tax", "Tax Expenses"), + "net_income": net_inc, + "diluted_eps": row("EPS in Rs", "EPS", "Basic EPS", "Diluted EPS"), + "diluted_shares": [None] * n, + }, + "balance_sheet": { + "cash_and_equivalents": row("Cash Equivalents", "Cash and Bank Balances"), + "short_term_investments": row("Short Term Investments", "Investments"), + "receivables": row("Receivables", "Trade Receivables", "Debtors"), + "inventory": row("Inventory", "Inventories"), + "other_current_assets": row("Other Current Assets"), + "total_current_assets": row("Current Assets"), + "ppe_net": row("Fixed Assets", "Net Block", "PPE"), + "goodwill": row("Goodwill"), + "intangibles": row("Intangible Assets"), + "other_long_term_assets": row("Other Assets", "Other Non-Current Assets"), + "total_assets": row("Total Assets", "Balance Sheet Size"), + "accounts_payable": row("Trade Payables", "Creditors", "Accounts Payable"), + "short_term_debt": row("Short Term Borrowing", "Current Borrowings"), + "other_current_liabilities": row("Other Current Liabilities"), + "total_current_liabilities": row("Current Liabilities"), + "long_term_debt": row("Borrowings", "Long Term Borrowing", + "Non-Current Borrowings"), + "other_long_term_liabilities": row("Other Liabilities", "Other Non-Current Liabilities"), + "total_liabilities": row("Total Liabilities"), + "total_equity": row("Equity Capital", "Total Equity", + "Shareholders Equity", "Net Worth"), + "total_liab_and_equity": row("Total Assets", "Balance Sheet Size"), + }, + "cash_flow": { + "net_income": net_inc, + "depreciation_amort": row("Depreciation"), + "stock_based_comp": [None] * n, + "working_capital_changes": [None] * n, + "other_operating": [None] * n, + "cash_from_operations": cfo_vals, + "capex": cap_vals, + "acquisitions": [None] * n, + "cash_from_investing": row("Cash from Investing Activity", + "Net Cash from Investing Activities"), + "debt_issuance_repayment": [None] * n, + "stock_buybacks": [None] * n, + "dividends_paid": row("Dividend Amount", "Dividends Paid"), + "cash_from_financing": row("Cash from Financing Activity", + "Net Cash from Financing Activities"), + "net_change_in_cash": row("Net Cash Flow"), + "free_cash_flow": fcf_vals, + }, + "currency": "INR", "units": "Crores", + "units_label": "INR Crores (Rs. Cr)", "scale": 1, + "source": f"screener.in ({raw.get('source_url', '')})", + "valuation_snapshot": {}, + "_sector": sector, + } + + +# ── SOURCE 3: moneycontrol.com ──────────────────────────────────────────────── + +def _get_moneycontrol_id(ticker: str, log_fn=None) -> Optional[str]: + """Use moneycontrol autocomplete API to find their internal sc_id.""" + def log(m): + if log_fn: log_fn(m) + try: + base = ticker.split(".")[0].upper() + url = (f"https://www.moneycontrol.com/mccode/common/autosuggestion_solr.php" + f"?classic=true&query={base}&type=1&format=json&callback=suggest") + r = requests.get(url, headers=MC_HEADERS, timeout=8) + if not r.ok: return None + # Response is JSONP: suggest([...]) + text = r.text.strip() + if text.startswith("suggest("): + text = text[8:] + if text.endswith(")"): + text = text[:-1] + items = json.loads(text) + if not items: return None + # Find the item whose NSE ticker matches + for item in items: + name_html = item.get("pdt_dis_nm", "") + # sc_id is the moneycontrol internal ID + sc_id = item.get("sc_id", "") + # Check if NSE ticker matches + if base in name_html: + log(f" [OK] moneycontrol sc_id: {sc_id}") + return sc_id + # Fallback: return first result's sc_id + sc_id = items[0].get("sc_id", "") + log(f" [OK] moneycontrol sc_id (first match): {sc_id}") + return sc_id + except Exception as e: + if log_fn: log_fn(f" [ERR] moneycontrol ID lookup: {e}") + return None + + +def _scrape_mc_table(url: str) -> Optional[Dict[str, List]]: + """Scrape a moneycontrol financial page and return {label: [values...]}.""" + try: + r = requests.get(url, headers=MC_HEADERS, timeout=12) + if not r.ok: return None + soup = BeautifulSoup(r.text, "lxml") + tables = soup.find_all("table") + # The data table is index 1 (index 0 is nav/metadata) + tbl = None + for t in tables: + rows = t.find_all("tr") + if len(rows) > 5: + tbl = t + break + if not tbl: return None + rows = tbl.find_all("tr") + result = {"__years__": []} + for i, row in enumerate(rows): + cells = row.find_all(["td", "th"]) + if not cells: continue + label = cells[0].get_text(strip=True) + vals = [c.get_text(strip=True) for c in cells[1:]] + if i == 0: + # year header row + result["__years__"] = [v for v in vals if v and v != ""] + else: + result[label] = [_safe_float(v) for v in vals] + return result + except Exception: + return None + + +def _scrape_moneycontrol(ticker: str, years: int, log_fn=None) -> Optional[Dict]: + """Fetch data from moneycontrol.com for Indian stocks.""" + def log(m): + if log_fn: log_fn(m) + try: + sc_id = _get_moneycontrol_id(ticker, log_fn) + if not sc_id: + log(" [ERR] moneycontrol: could not find sc_id") + return None + + # We need the company slug. Derive it from the search result link + base = ticker.split(".")[0].upper() + url_base = (f"https://www.moneycontrol.com/mccode/common/autosuggestion_solr.php" + f"?classic=true&query={base}&type=1&format=json&callback=suggest") + r = requests.get(url_base, headers=MC_HEADERS, timeout=8) + text = r.text.strip() + if text.startswith("suggest("): text = text[8:] + if text.endswith(")"): text = text[:-1] + items = json.loads(text) + + link = None + for item in items: + if item.get("sc_id") == sc_id: + link = item.get("link_src", "") + break + + if not link: + log(" [ERR] moneycontrol: no link found") + return None + + # link is like: https://www.moneycontrol.com/india/stockpricequote/sector/companyname/SCID + # Construct financial page URLs + parts = link.rstrip("/").split("/") + # e.g. ['https:', '', 'www.moneycontrol.com', 'india', 'stockpricequote', 'sector', 'companyslug', 'SCID'] + if len(parts) < 8: + log(" [ERR] moneycontrol: unexpected URL structure") + return None + sector_slug = parts[5] + company_slug = parts[6] + mc_id = parts[7] + + fin_base = f"https://www.moneycontrol.com/financials/{company_slug}" + + log(f" -> [moneycontrol] fetching P&L, BS, CF for {company_slug}...") + pl_data = _scrape_mc_table(f"{fin_base}/profit-lossVI/{mc_id}#{mc_id}") + bs_data = _scrape_mc_table(f"{fin_base}/balance-sheetVI/{mc_id}#{mc_id}") + cf_data = _scrape_mc_table(f"{fin_base}/cash-flowVI/{mc_id}#{mc_id}") + + if not pl_data: + log(" [ERR] moneycontrol: P&L scrape failed") + return None + + yr_raw = pl_data.get("__years__", []) + # year labels like "Mar 25", "Mar 24" — reverse to oldest first, take `years` + yr = list(reversed(yr_raw[:years])) + n = len(yr) + if n == 0: return None + + bs_data = bs_data or {} + cf_data = cf_data or {} + + def pl(label): + """Get reversed (oldest first) values from P&L.""" + v = pl_data.get(label, []) or [] + return list(reversed(v[:years]))[:n] + [None] * max(0, n - len(v)) + + def bs(label): + v = bs_data.get(label, []) or [] + return list(reversed(v[:years]))[:n] + [None] * max(0, n - len(v)) + + def cf(label): + v = cf_data.get(label, []) or [] + return list(reversed(v[:years]))[:n] + [None] * max(0, n - len(v)) + + revenue = pl("Total Operating Revenues") or pl("Revenue From Operations [Net]") or pl("Total Revenue") + net_inc = pl("Profit/Loss For The Period") or pl("Net Profit") or pl("PAT") + pretax = pl("Profit/Loss Before Tax") + dep = pl("Depreciation And Amortisation Expenses") + interest = pl("Finance Costs") or pl("Interest") + total_exp = pl("Total Expenses") + + cfo_vals = cf("Net Cash From Operating Activities") or cf("Cash From Operating Activity") + cap_vals = cf("Net Cash Used In Investing Activities (Capex)") + fcf_vals = cf("Free Cash Flow") + + log(f" [OK] moneycontrol: {n} years") + return { + "years": yr, + "income_statement": { + "revenue": revenue, + "cost_of_revenue": total_exp, + "gross_profit": [round(r - c, 2) if r is not None and c is not None else None + for r, c in zip(revenue or [None]*n, total_exp or [None]*n)], + "operating_expenses": total_exp, + "operating_income": pl("Profit/Loss Before Exceptional Items") or pretax, + "ebitda": [round(p + d + i, 2) + if p is not None and d is not None and i is not None else None + for p, d, i in zip(pretax or [None]*n, + dep or [None]*n, interest or [None]*n)], + "depreciation_amort": dep, + "interest_expense": interest, + "pretax_income": pretax, + "tax_expense": pl("Current Tax") or pl("Tax Expense"), + "net_income": net_inc, + "diluted_eps": pl("EPS") or pl("Diluted EPS"), + "diluted_shares": [None] * n, + }, + "balance_sheet": { + "cash_and_equivalents": bs("Cash And Cash Equivalents") or bs("Cash and Cash Equivalents"), + "short_term_investments": bs("Short Term Investments") or bs("Current Investments"), + "receivables": bs("Trade Receivables") or bs("Debtors"), + "inventory": bs("Inventories"), + "other_current_assets": bs("Other Current Assets"), + "total_current_assets": bs("Total Current Assets"), + "ppe_net": bs("Tangible Assets") or bs("Net Block"), + "goodwill": bs("Goodwill") or bs("Goodwill On Consolidation"), + "intangibles": bs("Intangible Assets"), + "other_long_term_assets": bs("Other Non-Current Assets"), + "total_assets": bs("Total Assets"), + "accounts_payable": bs("Trade Payables"), + "short_term_debt": bs("Short Term Borrowings") or bs("Current Maturities"), + "other_current_liabilities": bs("Other Current Liabilities"), + "total_current_liabilities": bs("Total Current Liabilities"), + "long_term_debt": bs("Long Term Borrowings") or bs("Borrowings"), + "other_long_term_liabilities": bs("Other Long Term Liabilities"), + "total_liabilities": bs("Total Capital And Liabilities"), + "total_equity": bs("Total Shareholders Funds") or bs("Shareholders Fund"), + "total_liab_and_equity": bs("Total Assets"), + }, + "cash_flow": { + "net_income": net_inc, + "depreciation_amort": dep, + "stock_based_comp": [None] * n, + "working_capital_changes": [None] * n, + "other_operating": [None] * n, + "cash_from_operations": cfo_vals, + "capex": cap_vals, + "acquisitions": [None] * n, + "cash_from_investing": cf("Net Cash Used In Investing Activities"), + "debt_issuance_repayment": [None] * n, + "stock_buybacks": [None] * n, + "dividends_paid": cf("Dividend Paid"), + "cash_from_financing": cf("Net Cash Used From Financing Activities"), + "net_change_in_cash": cf("Net Inc/Dec In Cash And Cash Equivalents"), + "free_cash_flow": fcf_vals, + }, + "currency": "INR", "units": "Crores", + "units_label": "INR Crores (Rs. Cr)", "scale": 1, + "source": "moneycontrol.com", + "valuation_snapshot": {}, + } + except Exception as e: + import traceback + if log_fn: log_fn(f" [ERR] moneycontrol: {e}\n{traceback.format_exc()[:300]}") + return None + + +# ── SOURCE 4: FMP (global) ───────────────────────────────────────────────────── + +def _fmp_get(path, params=None): + if not FMP_API_KEY: return None + p = {"apikey": FMP_API_KEY} + if params: p.update(params) + try: + r = requests.get(f"{FMP_BASE}{path}", params=p, timeout=REQUEST_TIMEOUT, headers=HEADERS) + r.raise_for_status() + return r.json() + except Exception: + return None + + +def _fetch_fmp(ticker: str, years: int, log_fn=None) -> Optional[Dict]: + def log(m): + if log_fn: log_fn(m) + if not FMP_API_KEY: return None + log(" -> [FMP] fetching ...") + lim = years + 1 + raw = { + "income": _fmp_get(f"/v3/income-statement/{ticker}", {"limit": lim, "period": "annual"}) or [], + "balance": _fmp_get(f"/v3/balance-sheet-statement/{ticker}", {"limit": lim, "period": "annual"}) or [], + "cashflow": _fmp_get(f"/v3/cash-flow-statement/{ticker}", {"limit": lim, "period": "annual"}) or [], + } + if not raw["income"]: + log(" [ERR] FMP returned no data") + return None + + inc = list(reversed(raw["income"]))[:years] + bal = list(reversed(raw["balance"]))[:years] + cf = list(reversed(raw["cashflow"]))[:years] + + def col(lst, key): return [_s(d.get(key)) for d in lst] + yr = [d.get("calendarYear", str(d.get("date",""))[:4]) for d in inc] + n = len(yr) + + rtm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0] + km = (_fmp_get(f"/v3/key-metrics-ttm/{ticker}") or [{}])[0] + + log(f" [OK] FMP: {n} years") + return { + "years": yr, + "income_statement": { + "revenue": col(inc, "revenue"), + "cost_of_revenue": col(inc, "costOfRevenue"), + "gross_profit": col(inc, "grossProfit"), + "operating_expenses": col(inc, "operatingExpenses"), + "operating_income": col(inc, "operatingIncome"), + "ebitda": col(inc, "ebitda"), + "depreciation_amort": col(inc, "depreciationAndAmortization"), + "interest_expense": col(inc, "interestExpense"), + "pretax_income": col(inc, "incomeBeforeTax"), + "tax_expense": col(inc, "incomeTaxExpense"), + "net_income": col(inc, "netIncome"), + "diluted_eps": col(inc, "epsdiluted"), + "diluted_shares": col(inc, "weightedAverageShsOutDil"), + }, + "balance_sheet": { + "cash_and_equivalents": col(bal, "cashAndCashEquivalents"), + "short_term_investments": col(bal, "shortTermInvestments"), + "receivables": col(bal, "netReceivables"), + "inventory": col(bal, "inventory"), + "other_current_assets": col(bal, "otherCurrentAssets"), + "total_current_assets": col(bal, "totalCurrentAssets"), + "ppe_net": col(bal, "propertyPlantEquipmentNet"), + "goodwill": col(bal, "goodwill"), + "intangibles": col(bal, "intangibleAssets"), + "other_long_term_assets": col(bal, "otherNonCurrentAssets"), + "total_assets": col(bal, "totalAssets"), + "accounts_payable": col(bal, "accountPayables"), + "short_term_debt": col(bal, "shortTermDebt"), + "other_current_liabilities": col(bal, "otherCurrentLiabilities"), + "total_current_liabilities": col(bal, "totalCurrentLiabilities"), + "long_term_debt": col(bal, "longTermDebt"), + "other_long_term_liabilities": col(bal, "otherNonCurrentLiabilities"), + "total_liabilities": col(bal, "totalLiabilities"), + "total_equity": col(bal, "totalStockholdersEquity"), + "total_liab_and_equity": col(bal, "totalLiabilitiesAndStockholdersEquity"), + }, + "cash_flow": { + "net_income": col(cf, "netIncome"), + "depreciation_amort": col(cf, "depreciationAndAmortization"), + "stock_based_comp": col(cf, "stockBasedCompensation"), + "working_capital_changes": col(cf, "changeInWorkingCapital"), + "other_operating": col(cf, "otherWorkingCapital"), + "cash_from_operations": col(cf, "netCashProvidedByOperatingActivities"), + "capex": col(cf, "capitalExpenditure"), + "acquisitions": col(cf, "acquisitionsNet"), + "cash_from_investing": col(cf, "netCashUsedForInvestingActivites"), + "debt_issuance_repayment": col(cf, "debtRepayment"), + "stock_buybacks": col(cf, "commonStockRepurchased"), + "dividends_paid": col(cf, "dividendsPaid"), + "cash_from_financing": col(cf, "netCashUsedProvidedByFinancingActivities"), + "net_change_in_cash": col(cf, "netChangeInCash"), + "free_cash_flow": col(cf, "freeCashFlow"), + }, + "currency": "USD", "units": "Millions", "units_label": "USD Millions", + "scale": 1, "source": "FMP API", + "valuation_snapshot": { + "pe_ttm": _s(rtm.get("peRatioTTM")), + "pb": _s(rtm.get("priceToBookRatioTTM")), + "ev_ebitda": _s(km.get("enterpriseValueOverEBITDATTM")), + "dividend_yield": _s(rtm.get("dividendYieldTTM")), + }, + } + + +# ── SOURCE 5: stockanalysis.com (global extended history) ───────────────────── + +def _scrape_stockanalysis(ticker: str, years: int, log_fn=None) -> Optional[Dict]: + def log(m): + if log_fn: log_fn(m) + base_ticker = ticker.split(".")[0].lower() + urls = { + "income": f"https://stockanalysis.com/stocks/{base_ticker}/financials/", + "balance": f"https://stockanalysis.com/stocks/{base_ticker}/financials/balance-sheet/", + "cashflow":f"https://stockanalysis.com/stocks/{base_ticker}/financials/cash-flow-statement/", + } + raw = {} + try: + for key, url in urls.items(): + log(f" -> [stockanalysis] {url}") + r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS) + if r.status_code != 200: return None + soup = BeautifulSoup(r.text, "lxml") + table = soup.find("table") + if not table: return None + thead = table.find("thead") + ths = thead.find("tr").find_all("th") if thead else [] + if len(ths) < 3: return None + if "years" not in raw: + raw["years"] = list(reversed([th.get_text(strip=True) for th in ths[2:2+years]])) + data_rows = {} + tbody = table.find("tbody") + for tr in (tbody.find_all("tr") if tbody else []): + tds = tr.find_all("td") + if len(tds) < 3: continue + label = tds[0].get_text(strip=True) + vals = [] + for td in tds[2:2+years]: + text = td.get_text(strip=True).replace(",", "") + vals.append(None if text in ("-", "") else _safe_float(text)) + data_rows[label] = list(reversed(vals)) + raw[key] = data_rows + except Exception as e: + log(f" [ERR] stockanalysis: {e}") + return None + + n = len(raw.get("years", [])) + if n == 0: return None + + def row(sec, *keys): + for k in keys: + if k in raw.get(sec, {}): return raw[sec][k] + return [None] * n + + log(f" [OK] stockanalysis: {n} years") + return { + "years": raw["years"], + "income_statement": { + "revenue": row("income", "Revenue"), + "cost_of_revenue": row("income", "Cost of Revenue"), + "gross_profit": row("income", "Gross Profit"), + "operating_expenses": row("income", "Operating Expenses"), + "operating_income": row("income", "Operating Income"), + "ebitda": row("income", "EBITDA"), + "depreciation_amort": row("income", "Depreciation & Amortization"), + "interest_expense": row("income", "Interest Expense / Income"), + "pretax_income": row("income", "Pretax Income"), + "tax_expense": row("income", "Income Tax"), + "net_income": row("income", "Net Income"), + "diluted_eps": row("income", "EPS (Diluted)"), + "diluted_shares": row("income", "Shares Outstanding (Diluted)"), + }, + "balance_sheet": { + "cash_and_equivalents": row("balance", "Cash & Equivalents"), + "short_term_investments": row("balance", "Short-Term Investments"), + "receivables": row("balance", "Accounts Receivable"), + "inventory": row("balance", "Inventory"), + "other_current_assets": row("balance", "Other Current Assets"), + "total_current_assets": row("balance", "Total Current Assets"), + "ppe_net": row("balance", "Property, Plant & Equipment"), + "goodwill": row("balance", "Goodwill and Intangibles", "Goodwill"), + "intangibles": [None] * n, + "other_long_term_assets": row("balance", "Other Long-Term Assets"), + "total_assets": row("balance", "Total Assets"), + "accounts_payable": row("balance", "Accounts Payable"), + "short_term_debt": row("balance", "Current Debt"), + "other_current_liabilities": row("balance", "Other Current Liabilities"), + "total_current_liabilities": row("balance", "Total Current Liabilities"), + "long_term_debt": row("balance", "Long-Term Debt"), + "other_long_term_liabilities": row("balance", "Other Long-Term Liabilities"), + "total_liabilities": row("balance", "Total Liabilities"), + "total_equity": row("balance", "Shareholders' Equity"), + "total_liab_and_equity": row("balance", "Total Liabilities and Equity"), + }, + "cash_flow": { + "net_income": row("cashflow", "Net Income"), + "depreciation_amort": row("cashflow", "Depreciation & Amortization"), + "stock_based_comp": row("cashflow", "Share-Based Compensation"), + "working_capital_changes": [None] * n, + "other_operating": row("cashflow", "Other Operating Activities"), + "cash_from_operations": row("cashflow", "Operating Cash Flow"), + "capex": row("cashflow", "Capital Expenditures"), + "acquisitions": row("cashflow", "Acquisitions"), + "cash_from_investing": row("cashflow", "Investing Cash Flow"), + "debt_issuance_repayment": row("cashflow", "Net Debt Issued/Paid"), + "stock_buybacks": row("cashflow", "Common Stock Issued/Repurchased", "Stock Repurchases"), + "dividends_paid": row("cashflow", "Dividends Paid"), + "cash_from_financing": row("cashflow", "Financing Cash Flow"), + "net_change_in_cash": row("cashflow", "Net Change in Cash"), + "free_cash_flow": row("cashflow", "Free Cash Flow"), + }, + "currency": "USD", "units": "Millions", "units_label": "USD Millions", + "scale": 1, "source": "stockanalysis.com", "valuation_snapshot": {}, + } + + +# ── Peer snapshot & valuation helpers ───────────────────────────────────────── + +def fetch_peer_snapshot(ticker: str) -> Optional[Dict]: + try: + import yahooquery as yq + t = yq.Ticker(ticker) + price_data = t.price.get(ticker, {}) + profile_data = t.summary_profile.get(ticker, {}) + key_stats = t.key_stats.get(ticker, {}) + fin_data = t.financial_data.get(ticker, {}) + summary_det = t.summary_detail.get(ticker, {}) + name = price_data.get("longName") or price_data.get("shortName", "") + if not name: return None + rev = None + try: + inc = t.income_statement(frequency='annual') + if inc is not None and not isinstance(inc, str) and not inc.empty: + if 'periodType' in inc.columns: + inc = inc[inc['periodType'] == '12M'] + rev_col = inc['TotalRevenue'].dropna() if 'TotalRevenue' in inc.columns else None + if rev_col is not None and not rev_col.empty: + rev = float(rev_col.iloc[-1]) + except Exception: + pass + rtm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0] + return { + "name": name, "ticker": ticker, + "rationale": f"Industry peer ({profile_data.get('industry', '')})", + "latest_year": "", "currency": price_data.get("currency", "INR"), + "units": "actuals", "revenue": _s(rev), + "gross_margin": _s(fin_data.get("grossMargins")), + "operating_margin": _s(fin_data.get("operatingMargins")), + "net_margin": _s(fin_data.get("profitMargins")), + "roe": _s(fin_data.get("returnOnEquity")), + "roic": _s(rtm.get("returnOnCapitalEmployedTTM")), + "debt_to_equity": _s(key_stats.get("debtToEquity")), + "current_ratio": _s(fin_data.get("currentRatio")), + "fcf_margin": None, + "revenue_growth_3y_cagr": _s(fin_data.get("revenueGrowth")), + "pe_ttm": _s(summary_det.get("trailingPE")), + "ev_ebitda": _s(key_stats.get("enterpriseToEbitda")), + } + except Exception: + return None + + +def fetch_valuation(ticker: str) -> Dict: + try: + import yahooquery as yq + t = yq.Ticker(ticker) + key_stats = t.key_stats.get(ticker, {}) + summary_det = t.summary_detail.get(ticker, {}) + return { + "pe_ttm": _s(summary_det.get("trailingPE")), + "pb": _s(key_stats.get("priceToBook")), + "ps": _s(key_stats.get("priceToSalesTrailing12Months")), + "ev_ebitda": _s(key_stats.get("enterpriseToEbitda")), + "ev_revenue": _s(key_stats.get("enterpriseToRevenue")), + "fcf_yield": None, + "dividend_yield": _s(summary_det.get("dividendYield")), + } + except Exception: + return {} + + +# ── EDGAR 10-K scraper (US only) ─────────────────────────────────────────────── + +def _scrape_edgar_10k(ticker: str, log_fn=None) -> str: + headers = {"User-Agent": "FinancialAnalyzer/1.0 (contact@example.com)"} + try: + if log_fn: log_fn(f" -> Looking up SEC CIK for {ticker}...") + r = requests.get("https://www.sec.gov/files/company_tickers.json", headers=headers, timeout=10) + tickers = r.json() + cik = None + for k, v in tickers.items(): + if v["ticker"].upper() == ticker.upper(): + cik = str(v["cik_str"]).zfill(10) + break + if not cik: + if log_fn: log_fn(" [ERR] CIK not found in SEC database.") + return "" + if log_fn: log_fn(f" -> Found CIK {cik}. Fetching recent filings...") + sub_r = requests.get(f"https://data.sec.gov/submissions/CIK{cik}.json", headers=headers, timeout=10) + data = sub_r.json() + filings = data.get("filings", {}).get("recent", {}) + form_types, accessions, primary_docs = ( + filings.get("form", []), filings.get("accessionNumber", []), + filings.get("primaryDocument", []) + ) + idx = next((i for i, f in enumerate(form_types) if f == "10-K"), -1) + if idx == -1: + if log_fn: log_fn(" [ERR] No 10-K found in recent filings.") + return "" + acc_num = accessions[idx].replace("-", "") + doc = primary_docs[idx] + url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{acc_num}/{doc}" + if log_fn: log_fn(f" -> Downloading 10-K from {url}...") + doc_r = requests.get(url, headers=headers, timeout=20) + soup = BeautifulSoup(doc_r.content, "lxml") + text = soup.get_text(separator="\n", strip=True) + match = re.search(r'(?i)Item\s+7\.\s*Management[\'\u2019]s\s+Discussion', text) + start = match.start() if match else len(text) // 4 + extract = text[start:start + 40000] + if log_fn: log_fn(" [OK] 10-K text extracted successfully.") + return extract + except Exception as e: + if log_fn: log_fn(f" [ERR] Failed to scrape EDGAR: {str(e)[:80]}") + return "" + + +# ── MAIN ORCHESTRATOR ───────────────────────────────────────────────────────── + +def fetch_all(meta: CompanyMeta, years: int = DEFAULT_YEARS, + force_refresh: bool = False, log_fn=None) -> Dict: + def log(m): + if log_fn: log_fn(m) + + if not meta.is_listed: + msg = (f"'{meta.name}' is unlisted/private. Public data not available. " + "Try the exact BSE/NSE ticker.") + log(f" [WARN] {msg}") + return {"warnings": [msg], "years": [], "income_statement": {}, + "balance_sheet": {}, "cash_flow": {}, "data_quality": 0} + + ticker = meta.ticker + cache_key = f"full_{years}yr" + if not force_refresh: + cached = get_cached(ticker, cache_key) + if cached: + log(f" [OK] Loaded cached data for {ticker}") + return cached + + warnings = [] + sources = [] + + is_indian = (meta.currency == "INR") + + if is_indian: + log(" -> Indian stock detected — running all Indian sources ...") + + # Source 1: screener.in + scraped = _scrape_screener(ticker, log_fn) + if scraped: + norm = _normalise_screener(scraped, years) + if norm and norm.get("years"): + sector = norm.get("_sector", "default") + log(f" [OK] screener.in: {len(norm['years'])} years (sector: {sector})") + sources.append(norm) + warnings.append(f"screener.in: {len(norm['years'])} years of data.") + + # Source 2: yahooquery + yq_data = _fetch_yahooquery(ticker, years, log_fn) + if yq_data and yq_data.get("years"): + sources.append(yq_data) + + # Source 3: moneycontrol.com + mc_data = _scrape_moneycontrol(ticker, years, log_fn) + if mc_data and mc_data.get("years"): + sources.append(mc_data) + warnings.append("moneycontrol.com data included in merge.") + + else: + log(" -> Global stock detected — running yahooquery + FMP + stockanalysis ...") + + # Source 1: yahooquery + yq_data = _fetch_yahooquery(ticker, years, log_fn) + if yq_data and yq_data.get("years"): + sources.append(yq_data) + + # Source 2: stockanalysis.com (better historical depth) + if years > 3: + sa_data = _scrape_stockanalysis(ticker, years, log_fn) + if sa_data and sa_data.get("years"): + sources.append(sa_data) + warnings.append("stockanalysis.com data included in merge.") + + # Source 3: FMP (if key provided) + if FMP_API_KEY: + fmp_data = _fetch_fmp(ticker, years, log_fn) + if fmp_data and fmp_data.get("years"): + sources.append(fmp_data) + + # ── Merge all sources field-by-field ────────────────────────────────────── + result = _merge_financial_data(sources, log_fn) + + if not result or not result.get("years"): + msg = (f"Could not fetch data for '{meta.name}' ({ticker}). " + f"Tried {len(sources)} source(s). " + "The company may have limited public data coverage.") + log(f" [ERR] {msg}") + return {"warnings": [msg], "years": [], "income_statement": {}, + "balance_sheet": {}, "cash_flow": {}, "data_quality": 0} + + # ── Data quality score ──────────────────────────────────────────────────── + quality = _validate_data_quality(result, years) + result["data_quality"] = quality + log(f" [OK] Data quality score: {quality}/100 (sources: {len(sources)})") + + # ── Optional EDGAR 10-K context for US stocks ───────────────────────────── + if not is_indian: + ar_context = _scrape_edgar_10k(ticker, log_fn) + if ar_context: + result["annual_report_context"] = ar_context + warnings.append("AI analysis enhanced with MD&A excerpts from SEC EDGAR 10-K.") + + result["warnings"] = warnings + result.setdefault("currency", meta.currency) + set_cache(ticker, cache_key, result) + log(" [OK] Data cached for 7 days") + return result