{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import yfinance as yf" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['52WeekChange',\n", " 'SandP52WeekChange',\n", " 'address1',\n", " 'ask',\n", " 'askSize',\n", " 'averageDailyVolume10Day',\n", " 'averageVolume',\n", " 'averageVolume10days',\n", " 'beta',\n", " 'bid',\n", " 'bidSize',\n", " 'bookValue',\n", " 'city',\n", " 'companyOfficers',\n", " 'compensationAsOfEpochDate',\n", " 'country',\n", " 'currency',\n", " 'currentPrice',\n", " 'currentRatio',\n", " 'dateShortInterest',\n", " 'dayHigh',\n", " 'dayLow',\n", " 'debtToEquity',\n", " 'dividendRate',\n", " 'dividendYield',\n", " 'earningsGrowth',\n", " 'earningsQuarterlyGrowth',\n", " 'ebitda',\n", " 'ebitdaMargins',\n", " 'enterpriseToEbitda',\n", " 'enterpriseToRevenue',\n", " 'enterpriseValue',\n", " 'exDividendDate',\n", " 'exchange',\n", " 'fiftyDayAverage',\n", " 'fiftyTwoWeekHigh',\n", " 'fiftyTwoWeekLow',\n", " 'financialCurrency',\n", " 'firstTradeDateEpochUtc',\n", " 'floatShares',\n", " 'forwardEps',\n", " 'forwardPE',\n", " 'freeCashflow',\n", " 'fullTimeEmployees',\n", " 'gmtOffSetMilliseconds',\n", " 'grossMargins',\n", " 'grossProfits',\n", " 'heldPercentInsiders',\n", " 'heldPercentInstitutions',\n", " 'impliedSharesOutstanding',\n", " 'industry',\n", " 'industryDisp',\n", " 'industryKey',\n", " 'lastDividendDate',\n", " 'lastDividendValue',\n", " 'lastFiscalYearEnd',\n", " 'lastSplitDate',\n", " 'lastSplitFactor',\n", " 'longBusinessSummary',\n", " 'longName',\n", " 'marketCap',\n", " 'maxAge',\n", " 'messageBoardId',\n", " 'mostRecentQuarter',\n", " 'netIncomeToCommon',\n", " 'nextFiscalYearEnd',\n", " 'numberOfAnalystOpinions',\n", " 'open',\n", " 'operatingCashflow',\n", " 'operatingMargins',\n", " 'payoutRatio',\n", " 'phone',\n", " 'previousClose',\n", " 'priceHint',\n", " 'priceToBook',\n", " 'priceToSalesTrailing12Months',\n", " 'profitMargins',\n", " 'quickRatio',\n", " 'quoteType',\n", " 'recommendationKey',\n", " 'recommendationMean',\n", " 'regularMarketDayHigh',\n", " 'regularMarketDayLow',\n", " 'regularMarketOpen',\n", " 'regularMarketPreviousClose',\n", " 'regularMarketVolume',\n", " 'returnOnAssets',\n", " 'returnOnEquity',\n", " 'revenueGrowth',\n", " 'revenuePerShare',\n", " 'sector',\n", " 'sectorDisp',\n", " 'sectorKey',\n", " 'sharesOutstanding',\n", " 'sharesPercentSharesOut',\n", " 'sharesShort',\n", " 'sharesShortPreviousMonthDate',\n", " 'sharesShortPriorMonth',\n", " 'shortName',\n", " 'shortRatio',\n", " 'state',\n", " 'symbol',\n", " 'targetHighPrice',\n", " 'targetLowPrice',\n", " 'targetMeanPrice',\n", " 'targetMedianPrice',\n", " 'timeZoneFullName',\n", " 'timeZoneShortName',\n", " 'totalCash',\n", " 'totalCashPerShare',\n", " 'totalDebt',\n", " 'totalRevenue',\n", " 'trailingAnnualDividendRate',\n", " 'trailingAnnualDividendYield',\n", " 'trailingEps',\n", " 'trailingPE',\n", " 'trailingPegRatio',\n", " 'twoHundredDayAverage',\n", " 'underlyingSymbol',\n", " 'uuid',\n", " 'volume',\n", " 'website',\n", " 'zip']" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "info = yf.Ticker('GOOG').info\n", "fundamentals = ['forwardPE', 'priceToBook', 'priceToSalesTrailing12Months' 'dividentYield', 'marketCap', 'beta', ]\n", "sorted(info.keys())" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Company Name: Alphabet Inc.\n", "Sector: Communication Services\n", "Industry: Internet Content & Information\n", "Market Capitalization: 2506161389568\n", "P/E Ratio (Trailing): 27.231789\n", "P/E Ratio (Forward): 22.853231\n", "P/B Ratio (Price to Book): 8.027174\n", "P/S Ratio (Price to Sales): 7.3741207\n", "Dividend Yield (%): 0.39\n", "Earnings Per Share (EPS): 7.55\n", "Return on Equity (ROE): 0.32101002\n", "Return on Assets (ROA): 0.16483\n", "Gross Margin (%): 58.13\n", "Operating Margin (%): 32.31\n", "Debt-to-Equity Ratio: 9.324\n", "Current Ratio: 1.95\n", "Quick Ratio: 1.761\n", "Interest Coverage Ratio: 4.22\n", "Revenue Growth (%): 15.1\n", "EPS Growth (%): 36.6\n", "Institutional Ownership (%): 61.46\n", "Insider Ownership (%): 0.02\n" ] } ], "source": [ "def get_stock_fundamentals(ticker: str) -> dict:\n", " \"\"\"\n", " Attempts to fetches key fundamental metrics for a given stock ticker using yfinance.\n", " \n", " :param ticker: Stock symbol (e.g., 'GOOG' for Google)\n", " :return: Dictionary of fundamental metrics with human-readable keys\n", " \"\"\"\n", " stock = yf.Ticker(ticker)\n", " info = stock.info # Fetch general info\n", "\n", " # Define a safe fetch method to avoid entire function failure\n", " def safe_get(key, transform=None):\n", " value = info.get(key, \"Metric not available\")\n", " if value != \"Metric not available\" and transform:\n", " try:\n", " return transform(value)\n", " except Exception:\n", " return \"metric not available\"\n", " return value\n", "\n", " # Extract key financial metrics\n", " fundamentals = {\n", " \"Company Name\": safe_get(\"longName\"),\n", " \"Sector\": safe_get(\"sector\"),\n", " \"Industry\": safe_get(\"industry\"),\n", " \"Market Capitalization\": safe_get(\"marketCap\"),\n", " \n", " # Valuation Metrics\n", " \"P/E Ratio (Trailing)\": safe_get(\"trailingPE\"),\n", " \"P/E Ratio (Forward)\": safe_get(\"forwardPE\"),\n", " \"P/B Ratio (Price to Book)\": safe_get(\"priceToBook\"),\n", " \"P/S Ratio (Price to Sales)\": safe_get(\"priceToSalesTrailing12Months\"),\n", " \"Dividend Yield (%)\": safe_get(\"dividendYield\", lambda x: round(x * 100, 2)),\n", "\n", " # Profitability Metrics\n", " \"Earnings Per Share (EPS)\": safe_get(\"trailingEps\"),\n", " \"Return on Equity (ROE)\": safe_get(\"returnOnEquity\"),\n", " \"Return on Assets (ROA)\": safe_get(\"returnOnAssets\"),\n", " \"Gross Margin (%)\": safe_get(\"grossMargins\", lambda x: round(x * 100, 2)),\n", " \"Operating Margin (%)\": safe_get(\"operatingMargins\", lambda x: round(x * 100, 2)),\n", "\n", " # Financial Health Metrics\n", " \"Debt-to-Equity Ratio\": safe_get(\"debtToEquity\"),\n", " \"Current Ratio\": safe_get(\"currentRatio\"),\n", " \"Quick Ratio\": safe_get(\"quickRatio\"),\n", " \"Interest Coverage Ratio\": safe_get(\n", " \"ebitda\",\n", " lambda ebitda: round(ebitda / info[\"totalDebt\"], 2) if info.get(\"totalDebt\") else \"Metric not available\"\n", " ),\n", "\n", " # Growth Metrics\n", " \"Revenue Growth (%)\": safe_get(\"revenueGrowth\", lambda x: round(x * 100, 2)),\n", " \"EPS Growth (%)\": safe_get(\"earningsGrowth\", lambda x: round(x * 100, 2)),\n", "\n", " # Market & Ownership\n", " \"Institutional Ownership (%)\": safe_get(\"heldPercentInstitutions\", lambda x: round(x * 100, 2)),\n", " \"Insider Ownership (%)\": safe_get(\"heldPercentInsiders\", lambda x: round(x * 100, 2)),\n", " }\n", " \n", " return fundamentals\n", "\n", "# Example Usage\n", "ticker = \"GOOG\"\n", "dict_fundamentals = get_stock_fundamentals(ticker)\n", "for key, value in dict_fundamentals.items():\n", " print(f\"{key}: {value}\")" ] } ], "metadata": { "kernelspec": { "display_name": "finagents_py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.1" } }, "nbformat": 4, "nbformat_minor": 2 }