CoolFace
Apppublic

crazyafro/financial_intelligence_agent

sourceHugging Facemitupdated 4mo agoView on Hugging Face
0likes
finance_tools.py62 linesDownload Raw Back to tools
1import requests2import os3import yfinance as yf4from langchain.tools import tool5 6@tool7def get_stock_price(ticker: str) -> str:8    """Get the current stock price, market cap, P/E ratio, and 52-week range for a stock ticker symbol (e.g. TSLA, AAPL, MSFT)."""9    try:10        stock = yf.Ticker(ticker.upper())11        info = stock.info12        price = info.get("currentPrice") or info.get("regularMarketPrice", "N/A")13        market_cap = info.get("marketCap", "N/A")14        pe_ratio = info.get("trailingPE", "N/A")15        week_high = info.get("fiftyTwoWeekHigh", "N/A")16        week_low = info.get("fiftyTwoWeekLow", "N/A")17        name = info.get("longName", ticker)18 19        if isinstance(market_cap, (int, float)):20            market_cap = f"${market_cap / 1e9:.2f}B"21 22        return (23            f"๐Ÿ“ˆ {name} ({ticker.upper()})\n"24            f"  Current Price: ${price}\n"25            f"  Market Cap: {market_cap}\n"26            f"  P/E Ratio: {pe_ratio}\n"27            f"  52-Week High: ${week_high} | Low: ${week_low}"28        )29    except Exception as e:30        return f"Error fetching stock data for {ticker}: {str(e)}"31 32@tool33def get_crypto_price(coin_id: str) -> str:34    """Get the current price, market cap, and 24h change for a cryptocurrency. Use CoinGecko IDs like 'bitcoin', 'ethereum', 'solana'."""35    try:36        url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id.lower()}&vs_currencies=usd&include_market_cap=true&include_24hr_change=true"37        data = requests.get(url, timeout=10).json()38        if coin_id.lower() not in data:39            return f"Coin '{coin_id}' not found. Use CoinGecko IDs like 'bitcoin', 'ethereum'."40        coin = data[coin_id.lower()]41        return (42            f"๐Ÿช™ {coin_id.capitalize()}\n"43            f"  Price: ${coin['usd']:,.2f}\n"44            f"  Market Cap: ${coin['usd_market_cap']:,.0f}\n"45            f"  24h Change: {coin['usd_24h_change']:.2f}%"46        )47    except Exception as e:48        return f"Error fetching crypto data: {str(e)}"49 50@tool51def get_exchange_rate(base: str, target: str) -> str:52    """Convert currency exchange rates. Provide base currency (e.g. 'USD') and target currency (e.g. 'EUR', 'GBP', 'JPY')."""53    try:54        api_key = os.getenv("EXCHANGE_RATE_API_KEY")55        url = f"https://v6.exchangerate-api.com/v6/{api_key}/pair/{base.upper()}/{target.upper()}"56        data = requests.get(url, timeout=10).json()57        if data.get("result") != "success":58            return f"Could not fetch rate for {base}/{target}."59        rate = data["conversion_rate"]60        return f"๐Ÿ’ฑ 1 {base.upper()} = {rate} {target.upper()}"61    except Exception as e:62        return f"Exchange rate error: {str(e)}"