Community Information
-
Code for fundamental analysis - just change the list of symbols to get your stocks
i am stuck and cant work more on it from tqdm import tqdm import yfinance as yf import pandas as pd import os import time from datetime import datetime import logging logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") folder = "financial\_statements\_combined" os.makedirs(folder, exist\_ok=True) symbols = \["RELIANCE.NS", "TCS.NS", "INFY.NS"\] # Example subset for testing timestamp = datetime.now().strftime("%Y%m%d\_%H%M%S") def safe\_fetch(data): return data if isinstance(data, pd.DataFrame) else pd.DataFrame() def get\_value(data, keys, latest=True): for key in keys: if key in data.index: return data\[key\].iloc\[0\] if latest else data\[key\] return None def calculate\_metrics(balance\_sheet\_annual, income\_statement\_annual, cash\_flow\_annual): try: equity = get\_value(balance\_sheet\_annual, \['Total Stockholder Equity', 'Total Equity', "Stockholders' Equity"\]) total\_assets = get\_value(balance\_sheet\_annual, \['Total Assets'\]) tangible\_assets = get\_value(balance\_sheet\_annual, \['Tangible Assets'\]) non\_current\_assets = get\_value(balance\_sheet\_annual, \['Total Non Current Assets'\]) current\_assets = get\_value(balance\_sheet\_annual, \['Total Current Assets'\]) debt = get\_value(balance\_sheet\_annual, \['Total Liabilities Net Minority Interest', 'Total Liabilities'\]) net\_income = get\_value(income\_statement\_annual, \['Net Income', 'Net Income Applicable To Common Shares'\]) ebit = get\_value(income\_statement\_annual, \['EBIT', 'Operating Income'\]) revenue = get\_value(income\_statement\_annual, \['Total Revenue', 'Revenue'\]) \# Use Total Assets if available, else fallback to Tangible Assets assets = total\_assets if total\_assets is not None else tangible\_assets if equity is None or assets is None or net\_income is None or ebit is None: logging.warning("Missing key financial values for metrics") return {} roe = net\_income / equity if equity else None roce = ebit / assets if assets else None profit\_margin = net\_income / revenue if revenue else None debt\_to\_equity = debt / equity if equity else None return { "ROE": roe, "ROCE": roce, "Profit Margin": profit\_margin, "Debt to Equity": debt\_to\_equity, } except Exception as e: logging.warning(f"Error calculating metrics: {e}") return {} def score\_metrics(metrics): try: score = 0 if metrics.get("ROE") and metrics\["ROE"\] > 0.15: score += 1 if metrics.get("ROCE") and metrics\["ROCE"\] > 0.15: score += 1 if metrics.get("Profit Margin") and metrics\["Profit Margin"\] > 0.1: score += 1 if metrics.get("Debt to Equity") is not None and metrics\["Debt to Equity"\] < 1: score += 1 return score except Exception as e: logging.warning(f"Error scoring metrics: {e}") return 0 for symbol in tqdm(symbols, desc="Fetching Data"): try: stock = yf.Ticker(symbol) balance\_sheet\_annual = safe\_fetch(stock.balance\_sheet) income\_statement\_annual = safe\_fetch(stock.financials) cash\_flow\_annual = safe\_fetch(stock.cashflow) if balance\_sheet\_annual.empty and income\_statement\_annual.empty and cash\_flow\_annual.empty: logging.warning(f"No financial data available for {symbol}") continue metrics = calculate\_metrics(balance\_sheet\_annual, income\_statement\_annual, cash\_flow\_annual) score = score\_metrics(metrics) excel\_path = os.path.join(folder, f"{symbol}\_financials\_{timestamp}.xlsx") with pd.ExcelWriter(excel\_path) as writer: if not balance\_sheet\_annual.empty: balance\_sheet\_annual.to\_excel(writer, sheet\_name="Balance Sheet (Annual)") if not income\_statement\_annual.empty: income\_statement\_annual.to\_excel(writer, sheet\_name="Income Statement (Annual)") if not cash\_flow\_annual.empty: cash\_flow\_annual.to\_excel(writer, sheet\_name="Cash Flow (Annual)") \# Combined Metrics & Scores Sheet if metrics: metrics\_df = pd.DataFrame(\[metrics\]) metrics\_df\['Final Score'\] = score metrics\_df.to\_excel(writer, sheet\_name="Metrics & Scores", index=False) logging.info(f"Data saved for {symbol}") except Exception as e: logging.error(f"Error fetching data for {symbol}: {e}") time.sleep(2) logging.info("Data extraction complete with metrics and scores.")1
© 2025 Indiareply.com. All rights reserved.