Spaces:
Sleeping
Sleeping
| import yfinance as yf | |
| import pandas as pd | |
| from datetime import datetime, timedelta | |
| class FinanceUtils: | |
| def __init__(self): | |
| pass | |
| def get_stock_quote(self, ticker): | |
| """Get current stock quote and basic info""" | |
| try: | |
| stock = yf.Ticker(ticker) | |
| info = stock.info | |
| if not info or info.get('regularMarketPrice') is None: | |
| return f"β No stock data found for {ticker}" | |
| price = info.get('regularMarketPrice', 'N/A') | |
| prev_close = info.get('previousClose', 'N/A') | |
| change = price - prev_close if (price != 'N/A' and prev_close != 'N/A') else 'N/A' | |
| change_pct = (change / prev_close * 100) if change != 'N/A' else 'N/A' | |
| result = f"π° **Stock Quote for {ticker}**\n\n" | |
| result += f"β’ **Current Price**: ${price:.2f}\n" | |
| result += f"β’ **Previous Close**: ${prev_close:.2f}\n" | |
| if change != 'N/A': | |
| change_emoji = "π" if change >= 0 else "π" | |
| result += f"β’ **Change**: {change_emoji} ${change:.2f} ({change_pct:.2f}%)\n" | |
| result += f"β’ **Volume**: {info.get('volume', 'N/A'):,}\n" | |
| result += f"β’ **Market Cap**: ${info.get('marketCap', 0):,}\n" | |
| result += f"β’ **52W High**: ${info.get('fiftyTwoWeekHigh', 'N/A')}\n" | |
| result += f"β’ **52W Low**: ${info.get('fiftyTwoWeekLow', 'N/A')}\n\n" | |
| return result | |
| except Exception as e: | |
| return f"β Error fetching stock quote: {str(e)}" | |
| def get_financial_summary(self, ticker): | |
| """Get key financial metrics""" | |
| try: | |
| stock = yf.Ticker(ticker) | |
| info = stock.info | |
| if not info: | |
| return f"β No financial data found for {ticker}" | |
| result = f"π **Financial Summary for {ticker}**\n\n" | |
| # Revenue and Profit | |
| revenue = info.get('totalRevenue', 'N/A') | |
| if revenue != 'N/A': | |
| result += f"β’ **Revenue (TTM)**: ${revenue:,}\n" | |
| net_income = info.get('netIncomeToCommon', 'N/A') | |
| if net_income != 'N/A': | |
| result += f"β’ **Net Income**: ${net_income:,}\n" | |
| # Ratios | |
| pe_ratio = info.get('trailingPE', 'N/A') | |
| if pe_ratio != 'N/A': | |
| result += f"β’ **P/E Ratio**: {pe_ratio:.2f}\n" | |
| pb_ratio = info.get('priceToBook', 'N/A') | |
| if pb_ratio != 'N/A': | |
| result += f"β’ **P/B Ratio**: {pb_ratio:.2f}\n" | |
| debt_to_equity = info.get('debtToEquity', 'N/A') | |
| if debt_to_equity != 'N/A': | |
| result += f"β’ **Debt/Equity**: {debt_to_equity:.2f}\n" | |
| # Dividend | |
| dividend_yield = info.get('dividendYield', 'N/A') | |
| if dividend_yield != 'N/A': | |
| result += f"β’ **Dividend Yield**: {dividend_yield:.2%}\n" | |
| return result | |
| except Exception as e: | |
| return f"β Error fetching financial data: {str(e)}" | |