Skip to main content
Glama

MCP Securities Analysis

by druce
TearSheet.ipynb210 kB
{ "cells": [ { "cell_type": "markdown", "id": "5dafe599", "metadata": {}, "source": [ "# TearSheet.ipynb\n", "\n", "- doesn't actually generate a tearsheet like a classic print [S&P or Value Line tearsheet](https://financetrain.com/what-is-a-tear-sheet) on a company\n", "- asks Perplexity a few basic questions about the company\n", "- gets info from AlphaVantage\n", "- opens a bunch of browser tabs from major services about the company\n", "- could potentially save those and scrape them to make a tearsheet.\n" ] }, { "cell_type": "markdown", "id": "5ab5ad1f-c5f3-4ed0-91a2-8c5385df9899", "metadata": {}, "source": [ "Updated version\n", "- profile - get info from perplexity , other company profiles, openbb, sec filings, wikipedia generate a description of the company, focus on business model history of the company\n", "- news\n", " - get latest news\n", " - scrape news using scraper - grab headlines matching pattern\n", " - filter stuff by how relevant to the company\n", "- chart\n", "- key ratios, top holders\n", "- generate tear sheet using tools\n", "- question answering chatbot using tools\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "d71cafca", "metadata": {}, "outputs": [], "source": [ "import dotenv\n", "import sys\n", "import os\n", "import re\n", "from datetime import datetime, timedelta\n", "import time\n", "from typing import List, Optional, Dict, Any\n", "from urllib.parse import urljoin, urlparse\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "# should require numpy < 2 for pandas_ta or uses more recent ta-lib module\n", "np.NaN = np.nan\n", "\n", "import openbb\n", "from openbb import obb\n", "from openbb_core.app.model.obbject import OBBject\n", "\n", "import pandas as pd\n", "# import pandas_ta as ta\n", "\n", "import requests\n", "from bs4 import BeautifulSoup\n", "import html2text\n", "\n", "import json\n", "import aiohttp\n", "import tempfile\n", "\n", "import openai\n", "from openai import OpenAI\n", "\n", "import IPython\n", "from IPython.display import HTML, Image, Markdown, display\n", "\n", "from selenium import webdriver\n", "from selenium.webdriver.common.by import By\n", "# use firefox because it updates less often, can disable updates\n", "# recommend importing profile from Chrome for cookies, passwords\n", "# looks less like a bot with more user cruft in the profile\n", "from selenium.webdriver.firefox.options import Options\n", "from selenium.webdriver.firefox.service import Service\n", "\n", "import wikipedia\n", "\n", "import langchain\n", "from langchain_openai import ChatOpenAI\n", "from langchain.tools import WikipediaQueryRun\n", "from langchain_community.utilities import WikipediaAPIWrapper\n", "from langchain.prompts import ChatPromptTemplate\n", "from langchain.schema import HumanMessage\n", "\n", "# from newsapi import NewsApiClient\n", "# # %pip install mem0ai\n", "# import mem0\n", "# from mem0 import MemoryClient\n", "\n", "# brew install ta-lib\n", "# https://ta-lib.org/" ] }, { "cell_type": "code", "execution_count": 4, "id": "174dc59a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dotenv.load_dotenv()\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "6daa94b9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Current year: 2025\n", "Last year: 2024\n", "Date 1 year ago: 2024-08-05\n", "Date now: 2025-08-05\n" ] } ], "source": [ "# Get current year\n", "current_year = datetime.now().year\n", "print(f\"Current year: {current_year}\")\n", "\n", "last_year = datetime.now().year - 1\n", "print(f\"Last year: {last_year}\")\n", "\n", "# Get date 1 year ago (approximate - 365 days)\n", "one_year_ago = datetime.now() - timedelta(days=365)\n", "print(f\"Date 1 year ago: {one_year_ago.strftime('%Y-%m-%d')}\")\n", "\n", "date_today = datetime.now() \n", "print(f\"Date now: {date_today.strftime('%Y-%m-%d')}\")\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "9f59bf5d", "metadata": {}, "outputs": [], "source": [ "company = \"Tesla\"\n", "symbol = \"TSLA\"\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b5fd46f1", "metadata": {}, "outputs": [], "source": [ "temp_dir = tempfile.mkdtemp(prefix='t', dir='tmp')\n", "temp_dir\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ee2ff9ed", "metadata": {}, "outputs": [], "source": [ "temp_dir = 'tx0ybr2zo'" ] }, { "cell_type": "code", "execution_count": null, "id": "cb1c0378", "metadata": {}, "outputs": [], "source": [ "def replace_citations(text, citations):\n", " def replace_match(match):\n", " citation_num = int(match.group(1))\n", " if citation_num <= len(citations):\n", " url = citations[citation_num - 1] # Citations are 0-indexed, references are 1-indexed\n", " return f\" [{citation_num}]({url})\"\n", " return match.group(0) # Return original if citation not found\n", "\n", " return re.sub(r'\\[(\\d+)\\]', replace_match, text)\n", "\n", "def fetch_perplexity(system_prompt, user_prompt, return_images=False):\n", " perplexity_url = \"https://api.perplexity.ai/chat/completions\"\n", " perplexity_model = \"sonar-pro\"\n", "\n", " payload = {\n", " \"model\": perplexity_model,\n", " \"messages\": [\n", " {\n", " \"role\": \"system\",\n", " \"content\": system_prompt,\n", " },\n", " {\n", " \"role\": \"user\",\n", " \"content\": user_prompt,\n", " }\n", " ],\n", " \"return_citations\": True, # Enable citations for markdown links\n", " \"return_images\": return_images, # Optional: disable images if not needed\n", " \"return_related_questions\": False # Optional: disable related questions\n", "}\n", "\n", " perplexity_headers = {\n", " \"Authorization\": f\"Bearer {os.getenv('PERPLEXITY_API_KEY')}\",\n", " \"accept\": \"application/json\",\n", " \"content-type\": \"application/json\"\n", " }\n", "\n", " response = requests.post(perplexity_url, json=payload, headers=perplexity_headers)\n", " response_data = response.json()\n", "\n", " response_str = response_data['choices'][0]['message']['content']\n", " response_str = response_str.replace(\"$\", r\"\\$\")\n", " citations = response_data.get('citations', [])\n", " response_str = replace_citations(response_str, citations)\n", " if return_images:\n", " images = response_data.get('images', [])\n", " if images:\n", " image_str = f\"![Image 1]({images.pop(0)['image_url']})\\n\\n\"\n", " response_str = image_str + response_str\n", " return response_str\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d7d324fc", "metadata": {}, "outputs": [], "source": [ "def get_perplexity_profile(company, symbol, return_images=False):\n", "\n", " system_prompt = \"\"\"\n", "You will act as a securities analyst and investment advisor with deep knowledge of financial markets,\n", "securities analysis, portfolio management. You will maintain a professional yet engaging tone,\n", "in the style of a senior investment bank research analyst.\n", "\"\"\"\n", "\n", " user_prompt = f\"\"\"You will focus on {company} ({symbol}), and provide a comprehensive analysis covering the following aspects:\n", "\n", "Company Profile: An overview of {company}, including its lines of business, history, and recent key developments.\n", "\n", "Major News: Significant events related to {company} or its industry impacting its stock.\n", "\n", "Financial Performance: Recent earnings reports and stock performance compared to expectations, changes in dividends or stock buybacks.\n", "\n", "Analyst Coverage: summarize recent changes to analysts' ratings noting which analyst and firms made upgrades or downgrades; summarize any recent short seller reports noting the firm and analyst.\n", "\n", "Product Announcements: Launch of new products, strategic initiatives, or restructurings.\n", "\n", "Strategic Moves: Information on deals, partnerships, mergers, acquisitions, divestitures, joint ventures, and major new business and revenue.\n", "\n", "Securities Offerings: Announcements related to stock or bond issuances, buybacks, special dividends, or stock splits.\n", "\n", "Management Changes: Significant personnel changes within {company}.\n", "\n", "Stock Price Movements: Notable stock price changes and their reasons.\n", "\n", "Timeline and Future Outlook: A timeline of these events \"\"\"\n", "\n", " return fetch_perplexity(system_prompt, user_prompt, return_images=return_images)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "71d8d3c6", "metadata": {}, "outputs": [], "source": [ "perplexity_str = get_perplexity_profilee(company, symbol, return_images=True)\n", "with open(f'{temp_dir}/{symbol}_perplexity_profile.md', 'w', encoding='utf-8') as f:\n", " f.write(perplexity_str)\n", "\n", "display(Markdown(perplexity_str))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "2e8ad67f", "metadata": {}, "outputs": [], "source": [ "def get_perplexity_analyst_ratings(company, symbol, return_images=False):\n", "\n", " system_prompt = \"\"\"\n", "You will act as a securities analyst and investment advisor with deep knowledge of financial markets,\n", "securities analysis, portfolio management. You will maintain a professional yet engaging tone,\n", "in the style of a senior investment bank research analyst.\n", "\"\"\"\n", "\n", " user_prompt = f\"\"\"What are the current analyst ratings on {company} ({symbol})?\n", " Which short sellers issued reports on {company} since {last_year}, if any? Summarize any notable analyst reports.\"\"\"\n", "\n", " return fetch_perplexity(system_prompt, user_prompt, return_images=False)\n", "\n", "perplexity_str = get_perplexity_analyst_ratings(company, symbol)\n", "with open(f'{temp_dir}/{symbol}_perplexity_ratings.md', 'w', encoding='utf-8') as f:\n", " f.write(perplexity_str)\n", "display(Markdown(perplexity_str))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "2617234b", "metadata": {}, "outputs": [], "source": [ "def get_perplexity_news(company, symbol, return_images=False):\n", "\n", " system_prompt = \"\"\"\n", "You will act as a securities analyst and investment advisor with deep knowledge of financial markets,\n", "securities analysis, portfolio management. You will maintain a professional yet engaging tone,\n", "in the style of a senior investment bank research analyst.\n", "\"\"\"\n", "\n", " user_prompt = f\"\"\"What are there most impactful news stories about {company} ({symbol}) since {last_year}, including management profiles and investigative reports?\n", "For any notable stories, provide the date of publication and the media that reported them.\"\"\"\n", "\n", " return fetch_perplexity(system_prompt, user_prompt, return_images=False)\n", "\n", "perplexity_str = get_perplexity_news(company, symbol)\n", "with open(f'{temp_dir}/{symbol}_perplexity_news.md', 'w', encoding='utf-8') as f:\n", " f.write(perplexity_str)\n", "display(Markdown(perplexity_str))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ab869a96", "metadata": {}, "outputs": [], "source": [ "company_list = wikipedia.search(company)\n", "company_list\n" ] }, { "cell_type": "code", "execution_count": null, "id": "48589e4b", "metadata": {}, "outputs": [], "source": [ "def get_best_wikipedia_match(company_description: str, wikipedia_matches: List[str]) -> str:\n", " \"\"\"\n", " Use LangChain with ChatOpenAI to find the best Wikipedia page match for a company.\n", " \n", " Args:\n", " company_description (str): Description of the company (e.g., \"Tesla (symbol TSLA)\")\n", " wikipedia_matches (List[str]): List of Wikipedia page titles\n", " \n", " Returns:\n", " str: The best matching Wikipedia page title\n", " \"\"\"\n", " \n", " # Initialize the Chat LLM\n", " llm = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0)\n", " \n", " # Create the chat prompt template\n", " prompt = ChatPromptTemplate.from_messages([\n", " (\"system\", \"You are a helpful assistant that selects the most appropriate Wikipedia page for a given company from a list of options.\"),\n", " (\"human\", \"\"\"I am looking for the wikipedia page of {company_description}.\n", "\n", "From the list of wikipedia articles below, tell me the title of the page that is most likely the best matching wikipedia page for {company_description}.\n", "\n", "Wikipedia articles:\n", "{wikipedia_matches}\n", "\n", "Return exactly one page title from this list without any modification. Do not add quotes, explanations, or any other text - just return the exact title as it appears in the list.\n", "\n", "Requirements:\n", "- Must be exactly one of the titles from the provided list\n", "- No modifications, quotes, or additional text\n", "- Focus on the main company page, not specific products or history pages\n", "\n", "Best match:\"\"\")\n", " ])\n", " \n", " # Format the matches as a bulleted list\n", " formatted_matches = \"\\n\".join([f\"• {match}\" for match in wikipedia_matches])\n", " \n", " # Create and invoke the chain\n", " chain = prompt | llm\n", " \n", " try:\n", " result = chain.invoke({\n", " \"company_description\": company_description,\n", " \"wikipedia_matches\": formatted_matches\n", " })\n", " \n", " # Extract the content from the AIMessage\n", " selected_match = result.content.strip()\n", " \n", " # Validate that the result is actually in the original list\n", " if selected_match in wikipedia_matches:\n", " return selected_match\n", " else:\n", " # Fallback: try to find a close match or return the first corporate-looking entry\n", " for match in wikipedia_matches:\n", " if \"Inc.\" in match or \"Corp.\" in match or (company_description.split()[0].lower() in match.lower() and len(match.split()) <= 3):\n", " return match\n", " return wikipedia_matches[0] # Last resort\n", " \n", " except Exception as e:\n", " print(f\"Error occurred: {e}\")\n", " # Simple fallback logic\n", " for match in wikipedia_matches:\n", " if \"Inc.\" in match:\n", " return match\n", " return wikipedia_matches[0]\n", " \n", "company_query = f\"{company} (symbol {symbol})\"\n", "best_match = get_best_wikipedia_match(company_query, company_list)\n", "\n", "print(f\"Best Wikipedia match for '{company_query}': {best_match}\")\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a64c14ba", "metadata": {}, "outputs": [], "source": [ "page_object = wikipedia.page(title=best_match, auto_suggest=False)\n", "\n", "# printing title\n", "print(page_object.original_title)\n", "\n", "# printing links on that page object\n", "#print(page_object.links[0:10])\n", "\n", "# printing html of page_object\n", "h = html2text.HTML2Text()\n", "h.ignore_images = True\n", "h.body_width = 0\n", "h.unicode_snob = True\n", "h.baseurl = 'https://en.wikipedia.org'\n", "markdown_content = h.handle(page_object.html())\n", "with open(f'{temp_dir}/{symbol}_wikipedia.md', 'w', encoding='utf-8') as f:\n", " f.write(perplexity_str)\n", "display(Markdown(markdown_content))\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "e1ddfb91", "metadata": {}, "outputs": [], "source": [ "os.getenv(\"SEC_USER\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "72809ef7", "metadata": {}, "outputs": [], "source": [ "# free API for edgar filing\n", "import sec_parser as sp\n", "from sec_downloader import Downloader\n", "\n", "def fn_get_10k_item_from_symbol(symbol, item=\"1\"):\n", " \"\"\"\n", " Get item 1 (or other number) of the latest 10-K annual report filing for a given symbol.\n", "\n", " Args:\n", " symbol (str): The symbol of the equity.\n", " item (str): The item number to return.\n", "\n", " Returns:\n", " str: The item requested from the latest 10-K annual report filing, or None if not found.\n", "\n", " \"\"\"\n", "\n", " item_text = \"\"\n", " try:\n", " print(\"Getting 10-K Item 1 for %s\" % symbol)\n", " dl = Downloader(os.getenv(\"SEC_FIRM\"), os.getenv(\"SEC_USER\"))\n", " html = dl.get_filing_html(ticker=symbol, form=\"10-K\")\n", " print(\"HTML length: %d characters\" % len(html))\n", " elements = sp.Edgar10QParser().parse(html)\n", " tree = sp.TreeBuilder().build(elements)\n", " # look for e.g. \"Item 1.\"\n", " # sections = [n for n in tree.nodes if re.match(r\"^ITEM 1[A-Z]?\\.\", n.text.strip().upper())]\n", " sections = [n for n in tree.nodes if re.match(\n", " r\"^ITEM\\s+\" + item, n.text.strip().upper())]\n", " print(\"Sections: %d\" % len(sections))\n", " if len(sections) == 0:\n", " return \"\"\n", " item_node = sections[0]\n", " item_text = item_node.text + \"\\n\\n\" + \\\n", " \"\\n\".join([n.text for n in item_node.get_descendants()])\n", " print(\"Item text: %d characters\" % len(item_text))\n", " except Exception as e:\n", " print(\"Error getting 10-K item: %s\" % e)\n", " return item_text\n", "\n", "edgar_10k_item1 = fn_get_10k_item_from_symbol(symbol)\n", "with open(f'{temp_dir}/{symbol}_edgar_10k_item1.txt', 'w', encoding='utf-8') as f:\n", " f.write(edgar_10k_item1)\n", "print(edgar_10k_item1)\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "90de4a73", "metadata": {}, "outputs": [], "source": [ "\n", "obb.account.login(email=os.environ['OPENBB_USER'], password=os.environ['OPENBB_PW'], remember_me=True)\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "88e8d8d7", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "FMPEquityPeersData(peers_list=['AMZN', 'BYDDF', 'BYDDY', 'F', 'GM', 'LCID', 'MULN', 'NIO', 'RIVN', 'TM'])" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "obb.account.login(email=os.environ['OPENBB_USER'], password=os.environ['OPENBB_PW'], remember_me=True)\n", "obj = obb.equity.compare.peers(symbol=symbol, provider='fmp')\n", "peers = obj.results\n", "peers\n" ] }, { "cell_type": "code", "execution_count": 30, "id": "bcae888b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"peers_list\": [\"AMZN\", \"BYDDF\", \"BYDDY\", \"F\", \"GM\", \"LCID\", \"MULN\", \"NIO\", \"RIVN\", \"TM\"]}'" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "1fc7c8c4", "metadata": {}, "outputs": [], "source": [ "for peer in peers.peers_list:\n", " try:\n", " retval = []\n", " obj = obb.equity.profile(peer)\n", " results = obj.results[0]\n", " desc = \"\"\n", " if results.short_description:\n", " desc = results.short_description\n", " elif results.long_description:\n", " desc = results.long_description\n", "\n", " retstr = f\"\"\"\n", "Symbol: {peer}\n", "Name: {results.name}\n", "Country: {results.hq_country}\n", "Industry: {results.industry_category}\n", "Description: {desc}\n", "\"\"\"\n", "# retval.append(results.stock_exchange)\n", " print(retstr)\n", " except Exception as e:\n", "# print(e)\n", "# print()\n", " continue\n", " print()\n" ] }, { "cell_type": "code", "execution_count": 26, "id": "bbac3cd4", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "| | Category | Metric | TSLA |\n", "|---:|:---------------------|:------------------------------|--------------:|\n", "| 0 | Valuation | Trailing P/E | 184.862 |\n", "| 1 | Valuation | Forward P/E | 95.284 |\n", "| 2 | Valuation | PEG Ratio | nan |\n", "| 3 | Valuation | Price/Sales (ttm) | 10.7394 |\n", "| 4 | Valuation | Price/Book | 12.8735 |\n", "| 5 | Valuation | Enterprise Value/Revenue | 10.511 |\n", "| 6 | Valuation | Enterprise Value/EBITDA | 85.899 |\n", "| 7 | Financial Highlights | Market Cap | 9.95761e+11 |\n", "| 8 | Financial Highlights | Enterprise Value | 9.74612e+11 |\n", "| 9 | Financial Highlights | Revenue (ttm) | 9.272e+10 |\n", "| 10 | Financial Highlights | Gross Profit (ttm) | 1.6207e+10 |\n", "| 11 | Financial Highlights | EBITDA | 1.1346e+10 |\n", "| 12 | Financial Highlights | Net Income (ttm) | 5.879e+09 |\n", "| 13 | Profitability | Profit Margin | 0.06344 |\n", "| 14 | Profitability | Operating Margin | 0.04103 |\n", "| 15 | Profitability | Gross Margin | 0.1748 |\n", "| 16 | Profitability | EBITDA Margin | 0.12237 |\n", "| 17 | Profitability | Return on Assets | 0.02911 |\n", "| 18 | Profitability | Return on Equity | 0.08177 |\n", "| 19 | Liquidity | Current Ratio | 2.037 |\n", "| 20 | Liquidity | Quick Ratio | 1.359 |\n", "| 21 | Liquidity | Total Cash | 3.6782e+10 |\n", "| 22 | Liquidity | Total Debt | 1.3134e+10 |\n", "| 23 | Liquidity | Debt/Equity | 16.823 |\n", "| 24 | Per Share | Earnings Per Share (ttm) | 1.67 |\n", "| 25 | Per Share | Book Value Per Share | 23.981 |\n", "| 26 | Per Share | Revenue Per Share | 28.862 |\n", "| 27 | Per Share | Operating Cash Flow Per Share | 4.88769 |" ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import yfinance as yf\n", "import pandas as pd\n", "\n", "def get_fundamental_ratios(symbol):\n", " \"\"\"\n", " Get a comprehensive DataFrame of fundamental ratios and statistics\n", " \"\"\"\n", " ticker = yf.Ticker(symbol)\n", " info = ticker.info\n", " \n", " # Organize ratios by category\n", " valuation_ratios = {\n", " 'Trailing P/E': info.get('trailingPE'),\n", " 'Forward P/E': info.get('forwardPE'),\n", " 'PEG Ratio': info.get('pegRatio'),\n", " 'Price/Sales (ttm)': info.get('priceToSalesTrailing12Months'),\n", " 'Price/Book': info.get('priceToBook'),\n", " 'Enterprise Value/Revenue': info.get('enterpriseToRevenue'),\n", " 'Enterprise Value/EBITDA': info.get('enterpriseToEbitda'),\n", " }\n", " \n", " financial_highlights = {\n", " 'Market Cap': info.get('marketCap'),\n", " 'Enterprise Value': info.get('enterpriseValue'),\n", " 'Revenue (ttm)': info.get('totalRevenue'),\n", " 'Gross Profit (ttm)': info.get('grossProfits'),\n", " 'EBITDA': info.get('ebitda'),\n", " 'Net Income (ttm)': info.get('netIncomeToCommon'),\n", " }\n", " \n", " profitability_ratios = {\n", " 'Profit Margin': info.get('profitMargins'),\n", " 'Operating Margin': info.get('operatingMargins'),\n", " 'Gross Margin': info.get('grossMargins'),\n", " 'EBITDA Margin': info.get('ebitdaMargins'),\n", " 'Return on Assets': info.get('returnOnAssets'),\n", " 'Return on Equity': info.get('returnOnEquity'),\n", " }\n", " \n", " liquidity_ratios = {\n", " 'Current Ratio': info.get('currentRatio'),\n", " 'Quick Ratio': info.get('quickRatio'),\n", " 'Total Cash': info.get('totalCash'),\n", " 'Total Debt': info.get('totalDebt'),\n", " 'Debt/Equity': info.get('debtToEquity'),\n", " }\n", " \n", " per_share_data = {\n", " 'Earnings Per Share (ttm)': info.get('trailingEps'),\n", " 'Book Value Per Share': info.get('bookValue'),\n", " 'Revenue Per Share': info.get('revenuePerShare'),\n", " 'Operating Cash Flow Per Share': info.get('operatingCashflow', 0) / info.get('sharesOutstanding', 1) if info.get('sharesOutstanding') else None,\n", " }\n", " \n", " # Combine all categories\n", " all_ratios = {\n", " **valuation_ratios,\n", " **financial_highlights, \n", " **profitability_ratios,\n", " **liquidity_ratios,\n", " **per_share_data\n", " }\n", " \n", " # Create DataFrame\n", " df = pd.DataFrame(list(all_ratios.items()), columns=['Metric', symbol])\n", " df['Category'] = (\n", " ['Valuation'] * len(valuation_ratios) +\n", " ['Financial Highlights'] * len(financial_highlights) +\n", " ['Profitability'] * len(profitability_ratios) +\n", " ['Liquidity'] * len(liquidity_ratios) +\n", " ['Per Share'] * len(per_share_data)\n", " )\n", "\n", " return df[['Category', 'Metric', symbol]]\n", "\n", "# Usage\n", "ratios_df = get_fundamental_ratios('TSLA')\n", "display(Markdown(ratios_df.to_markdown()))\n" ] }, { "cell_type": "code", "execution_count": 40, "id": "b086e418", "metadata": {}, "outputs": [], "source": [ "\n", "def gfr(symbol):\n", " \"helper function to create ratios dataframe\"\n", " ticker = yf.Ticker(symbol)\n", " info = ticker.info\n", "\n", " # Organize ratios by category\n", " valuation_ratios = {\n", " 'Trailing P/E': info.get('trailingPE'),\n", " 'Forward P/E': info.get('forwardPE'),\n", " 'PEG Ratio': info.get('pegRatio'),\n", " 'Price/Sales (ttm)': info.get('priceToSalesTrailing12Months'),\n", " 'Price/Book': info.get('priceToBook'),\n", " 'Enterprise Value/Revenue': info.get('enterpriseToRevenue'),\n", " 'Enterprise Value/EBITDA': info.get('enterpriseToEbitda'),\n", " }\n", "\n", " financial_highlights = {\n", " 'Market Cap': info.get('marketCap'),\n", " 'Enterprise Value': info.get('enterpriseValue'),\n", " 'Revenue (ttm)': info.get('totalRevenue'),\n", " 'Gross Profit (ttm)': info.get('grossProfits'),\n", " 'EBITDA': info.get('ebitda'),\n", " 'Net Income (ttm)': info.get('netIncomeToCommon'),\n", " }\n", "\n", " profitability_ratios = {\n", " 'Profit Margin': info.get('profitMargins'),\n", " 'Operating Margin': info.get('operatingMargins'),\n", " 'Gross Margin': info.get('grossMargins'),\n", " 'EBITDA Margin': info.get('ebitdaMargins'),\n", " 'Return on Assets': info.get('returnOnAssets'),\n", " 'Return on Equity': info.get('returnOnEquity'),\n", " }\n", "\n", " liquidity_ratios = {\n", " 'Current Ratio': info.get('currentRatio'),\n", " 'Quick Ratio': info.get('quickRatio'),\n", " 'Total Cash': info.get('totalCash'),\n", " 'Total Debt': info.get('totalDebt'),\n", " 'Debt/Equity': info.get('debtToEquity'),\n", " }\n", "\n", " per_share_data = {\n", " 'Earnings Per Share (ttm)': info.get('trailingEps'),\n", " 'Book Value Per Share': info.get('bookValue'),\n", " 'Revenue Per Share': info.get('revenuePerShare'),\n", " 'Operating Cash Flow Per Share': info.get('operatingCashflow', 0) / info.get('sharesOutstanding', 1) if info.get('sharesOutstanding') else None,\n", " }\n", "\n", " # Combine all categories\n", " all_ratios = {\n", " **valuation_ratios,\n", " **financial_highlights,\n", " **profitability_ratios,\n", " **liquidity_ratios,\n", " **per_share_data\n", " }\n", "\n", " # Create DataFrame\n", " df = pd.DataFrame(list(all_ratios.items()), columns=['Metric', symbol])\n", " df['Category'] = (\n", " ['Valuation'] * len(valuation_ratios) +\n", " ['Financial Highlights'] * len(financial_highlights) +\n", " ['Profitability'] * len(profitability_ratios) +\n", " ['Liquidity'] * len(liquidity_ratios) +\n", " ['Per Share'] * len(per_share_data)\n", " )\n", " return df[[\"Category\", \"Metric\", symbol]]\n" ] }, { "cell_type": "code", "execution_count": 41, "id": "147bbb19", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>tsla</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>1.848623e+02</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>9.528395e+01</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>1.073944e+01</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>1.287353e+01</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>1.051100e+01</td>\n", " </tr>\n", " <tr>\n", " <th>6</th>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>8.589900e+01</td>\n", " </tr>\n", " <tr>\n", " <th>7</th>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>9.957609e+11</td>\n", " </tr>\n", " <tr>\n", " <th>8</th>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>9.746123e+11</td>\n", " </tr>\n", " <tr>\n", " <th>9</th>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>9.272000e+10</td>\n", " </tr>\n", " <tr>\n", " <th>10</th>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>1.620700e+10</td>\n", " </tr>\n", " <tr>\n", " <th>11</th>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>1.134600e+10</td>\n", " </tr>\n", " <tr>\n", " <th>12</th>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>5.879000e+09</td>\n", " </tr>\n", " <tr>\n", " <th>13</th>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>6.343999e-02</td>\n", " </tr>\n", " <tr>\n", " <th>14</th>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>4.103000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>15</th>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>1.748000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>16</th>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>1.223700e-01</td>\n", " </tr>\n", " <tr>\n", " <th>17</th>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>2.911000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>18</th>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>8.177000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>19</th>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>2.037000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>20</th>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>1.359000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>21</th>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>3.678200e+10</td>\n", " </tr>\n", " <tr>\n", " <th>22</th>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>1.313400e+10</td>\n", " </tr>\n", " <tr>\n", " <th>23</th>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>1.682300e+01</td>\n", " </tr>\n", " <tr>\n", " <th>24</th>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>1.670000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>25</th>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>2.398100e+01</td>\n", " </tr>\n", " <tr>\n", " <th>26</th>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>2.886200e+01</td>\n", " </tr>\n", " <tr>\n", " <th>27</th>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>4.887690e+00</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " Category Metric tsla\n", "0 Valuation Trailing P/E 1.848623e+02\n", "1 Valuation Forward P/E 9.528395e+01\n", "2 Valuation PEG Ratio NaN\n", "3 Valuation Price/Sales (ttm) 1.073944e+01\n", "4 Valuation Price/Book 1.287353e+01\n", "5 Valuation Enterprise Value/Revenue 1.051100e+01\n", "6 Valuation Enterprise Value/EBITDA 8.589900e+01\n", "7 Financial Highlights Market Cap 9.957609e+11\n", "8 Financial Highlights Enterprise Value 9.746123e+11\n", "9 Financial Highlights Revenue (ttm) 9.272000e+10\n", "10 Financial Highlights Gross Profit (ttm) 1.620700e+10\n", "11 Financial Highlights EBITDA 1.134600e+10\n", "12 Financial Highlights Net Income (ttm) 5.879000e+09\n", "13 Profitability Profit Margin 6.343999e-02\n", "14 Profitability Operating Margin 4.103000e-02\n", "15 Profitability Gross Margin 1.748000e-01\n", "16 Profitability EBITDA Margin 1.223700e-01\n", "17 Profitability Return on Assets 2.911000e-02\n", "18 Profitability Return on Equity 8.177000e-02\n", "19 Liquidity Current Ratio 2.037000e+00\n", "20 Liquidity Quick Ratio 1.359000e+00\n", "21 Liquidity Total Cash 3.678200e+10\n", "22 Liquidity Total Debt 1.313400e+10\n", "23 Liquidity Debt/Equity 1.682300e+01\n", "24 Per Share Earnings Per Share (ttm) 1.670000e+00\n", "25 Per Share Book Value Per Share 2.398100e+01\n", "26 Per Share Revenue Per Share 2.886200e+01\n", "27 Per Share Operating Cash Flow Per Share 4.887690e+00" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gfr('tsla') \n" ] }, { "cell_type": "code", "execution_count": 37, "id": "1f94212f", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>TSLA</th>\n", " <th>AMZN</th>\n", " <th>BYDDF</th>\n", " <th>BYDDY</th>\n", " <th>F</th>\n", " <th>GM</th>\n", " <th>LCID</th>\n", " <th>MULN</th>\n", " <th>NIO</th>\n", " <th>RIVN</th>\n", " <th>TM</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>1.848623e+02</td>\n", " <td>3.258384e+01</td>\n", " <td>2.000000e+01</td>\n", " <td>1.990141e+01</td>\n", " <td>1.417949e+01</td>\n", " <td>8.027481e+00</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>7.441575e+00</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>9.528395e+01</td>\n", " <td>3.475610e+01</td>\n", " <td>1.713596e+00</td>\n", " <td>4.500000e+00</td>\n", " <td>6.320000e+00</td>\n", " <td>4.974456e+00</td>\n", " <td>-2.750000e+00</td>\n", " <td>8.800000e-02</td>\n", " <td>-5.294117e+00</td>\n", " <td>-4.434307e+00</td>\n", " <td>1.150190e+01</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>1.073944e+01</td>\n", " <td>3.402228e+00</td>\n", " <td>1.570778e-01</td>\n", " <td>1.569489e-01</td>\n", " <td>2.376100e-01</td>\n", " <td>2.668458e-01</td>\n", " <td>8.545063e+00</td>\n", " <td>7.787777e-02</td>\n", " <td>1.575678e-01</td>\n", " <td>2.907481e+00</td>\n", " <td>4.924489e-03</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>1.287353e+01</td>\n", " <td>6.826674e+00</td>\n", " <td>5.724422e-01</td>\n", " <td>5.696203e-01</td>\n", " <td>9.769455e-01</td>\n", " <td>7.582378e-01</td>\n", " <td>2.318008e+00</td>\n", " <td>NaN</td>\n", " <td>-2.571429e+01</td>\n", " <td>2.237981e+00</td>\n", " <td>6.592602e-02</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>1.051100e+01</td>\n", " <td>3.468000e+00</td>\n", " <td>3.500000e-02</td>\n", " <td>3.500000e-02</td>\n", " <td>9.480000e-01</td>\n", " <td>8.980000e-01</td>\n", " <td>9.152000e+00</td>\n", " <td>3.047000e+00</td>\n", " <td>4.120000e-01</td>\n", " <td>2.382000e+00</td>\n", " <td>6.900000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>6</th>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>8.589900e+01</td>\n", " <td>1.736200e+01</td>\n", " <td>2.490000e-01</td>\n", " <td>2.440000e-01</td>\n", " <td>2.053100e+01</td>\n", " <td>1.001900e+01</td>\n", " <td>-3.019000e+00</td>\n", " <td>-1.190000e-01</td>\n", " <td>-1.704000e+00</td>\n", " <td>-4.100000e+00</td>\n", " <td>4.703000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>7</th>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>9.957609e+11</td>\n", " <td>2.279622e+12</td>\n", " <td>1.291994e+11</td>\n", " <td>1.290934e+11</td>\n", " <td>4.401725e+10</td>\n", " <td>5.006026e+10</td>\n", " <td>7.435402e+09</td>\n", " <td>6.955740e+05</td>\n", " <td>1.069218e+10</td>\n", " <td>1.455485e+10</td>\n", " <td>2.365562e+11</td>\n", " </tr>\n", " <tr>\n", " <th>8</th>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>9.746123e+11</td>\n", " <td>2.323619e+12</td>\n", " <td>2.897114e+10</td>\n", " <td>2.844296e+10</td>\n", " <td>1.755615e+11</td>\n", " <td>1.684471e+11</td>\n", " <td>7.963166e+09</td>\n", " <td>2.721857e+07</td>\n", " <td>2.794399e+10</td>\n", " <td>1.192613e+10</td>\n", " <td>3.314055e+13</td>\n", " </tr>\n", " <tr>\n", " <th>9</th>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>9.272000e+10</td>\n", " <td>6.700380e+11</td>\n", " <td>8.225185e+11</td>\n", " <td>8.225185e+11</td>\n", " <td>1.852500e+11</td>\n", " <td>1.876000e+11</td>\n", " <td>8.701400e+08</td>\n", " <td>8.931612e+06</td>\n", " <td>6.785765e+10</td>\n", " <td>5.006000e+09</td>\n", " <td>4.803671e+13</td>\n", " </tr>\n", " <tr>\n", " <th>10</th>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>1.620700e+10</td>\n", " <td>3.323830e+11</td>\n", " <td>1.564718e+11</td>\n", " <td>1.564718e+11</td>\n", " <td>1.337600e+10</td>\n", " <td>2.057800e+10</td>\n", " <td>-9.195670e+08</td>\n", " <td>-2.153492e+07</td>\n", " <td>6.924585e+09</td>\n", " <td>-4.670000e+08</td>\n", " <td>9.578038e+12</td>\n", " </tr>\n", " <tr>\n", " <th>11</th>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>1.134600e+10</td>\n", " <td>1.338320e+11</td>\n", " <td>1.165454e+11</td>\n", " <td>1.165454e+11</td>\n", " <td>8.551000e+09</td>\n", " <td>1.681200e+10</td>\n", " <td>-2.638076e+09</td>\n", " <td>-2.293505e+08</td>\n", " <td>-1.639825e+10</td>\n", " <td>-2.909000e+09</td>\n", " <td>7.046819e+12</td>\n", " </tr>\n", " <tr>\n", " <th>12</th>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>5.879000e+09</td>\n", " <td>7.062300e+10</td>\n", " <td>4.481004e+10</td>\n", " <td>4.481004e+10</td>\n", " <td>3.151000e+09</td>\n", " <td>6.524000e+09</td>\n", " <td>-3.107888e+09</td>\n", " <td>-4.391060e+08</td>\n", " <td>-2.429083e+10</td>\n", " <td>-3.846000e+09</td>\n", " <td>4.765086e+12</td>\n", " </tr>\n", " <tr>\n", " <th>13</th>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>6.343999e-02</td>\n", " <td>1.054000e-01</td>\n", " <td>5.452000e-02</td>\n", " <td>5.452000e-02</td>\n", " <td>1.701000e-02</td>\n", " <td>2.545000e-02</td>\n", " <td>-2.757320e+00</td>\n", " <td>0.000000e+00</td>\n", " <td>-3.579700e-01</td>\n", " <td>-7.682800e-01</td>\n", " <td>9.920000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>14</th>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>4.103000e-02</td>\n", " <td>1.143200e-01</td>\n", " <td>4.946000e-02</td>\n", " <td>4.946000e-02</td>\n", " <td>1.072000e-02</td>\n", " <td>4.701000e-02</td>\n", " <td>-2.943790e+00</td>\n", " <td>-1.081451e+01</td>\n", " <td>-5.333000e-01</td>\n", " <td>-5.282300e-01</td>\n", " <td>9.028000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>15</th>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>1.748000e-01</td>\n", " <td>4.960700e-01</td>\n", " <td>1.902300e-01</td>\n", " <td>1.902300e-01</td>\n", " <td>7.221000e-02</td>\n", " <td>1.096900e-01</td>\n", " <td>-1.056800e+00</td>\n", " <td>-2.411090e+00</td>\n", " <td>1.020500e-01</td>\n", " <td>-9.329000e-02</td>\n", " <td>1.993900e-01</td>\n", " </tr>\n", " <tr>\n", " <th>16</th>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>1.223700e-01</td>\n", " <td>1.997400e-01</td>\n", " <td>1.416900e-01</td>\n", " <td>1.416900e-01</td>\n", " <td>4.616000e-02</td>\n", " <td>8.962000e-02</td>\n", " <td>0.000000e+00</td>\n", " <td>0.000000e+00</td>\n", " <td>-2.416600e-01</td>\n", " <td>-5.811000e-01</td>\n", " <td>1.467000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>17</th>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>2.911000e-02</td>\n", " <td>7.699000e-02</td>\n", " <td>4.032000e-02</td>\n", " <td>4.032000e-02</td>\n", " <td>6.340000e-03</td>\n", " <td>2.310000e-02</td>\n", " <td>-2.044300e-01</td>\n", " <td>-8.461600e-01</td>\n", " <td>-1.414500e-01</td>\n", " <td>-1.544500e-01</td>\n", " <td>3.263000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>18</th>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>8.177000e-02</td>\n", " <td>2.477000e-01</td>\n", " <td>2.306600e-01</td>\n", " <td>2.306600e-01</td>\n", " <td>7.152000e-02</td>\n", " <td>6.955000e-02</td>\n", " <td>-5.006200e-01</td>\n", " <td>-1.851312e+01</td>\n", " <td>-1.500650e+00</td>\n", " <td>-5.372400e-01</td>\n", " <td>1.328300e-01</td>\n", " </tr>\n", " <tr>\n", " <th>19</th>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>2.037000e+00</td>\n", " <td>1.024000e+00</td>\n", " <td>8.110000e-01</td>\n", " <td>8.110000e-01</td>\n", " <td>1.101000e+00</td>\n", " <td>1.218000e+00</td>\n", " <td>3.322000e+00</td>\n", " <td>2.530000e-01</td>\n", " <td>8.370000e-01</td>\n", " <td>3.728000e+00</td>\n", " <td>1.260000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>20</th>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>1.359000e+00</td>\n", " <td>7.680000e-01</td>\n", " <td>4.300000e-01</td>\n", " <td>4.300000e-01</td>\n", " <td>9.110000e-01</td>\n", " <td>9.650000e-01</td>\n", " <td>2.798000e+00</td>\n", " <td>7.000000e-03</td>\n", " <td>5.090000e-01</td>\n", " <td>2.722000e+00</td>\n", " <td>8.270000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>21</th>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>3.678200e+10</td>\n", " <td>9.318000e+10</td>\n", " <td>1.533910e+11</td>\n", " <td>1.533910e+11</td>\n", " <td>2.828100e+10</td>\n", " <td>2.093900e+10</td>\n", " <td>3.610905e+09</td>\n", " <td>1.404708e+06</td>\n", " <td>1.972245e+10</td>\n", " <td>7.178000e+09</td>\n", " <td>8.982404e+12</td>\n", " </tr>\n", " <tr>\n", " <th>22</th>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>1.313400e+10</td>\n", " <td>1.595700e+11</td>\n", " <td>4.112797e+10</td>\n", " <td>4.112797e+10</td>\n", " <td>1.602390e+11</td>\n", " <td>1.370490e+11</td>\n", " <td>2.558172e+09</td>\n", " <td>2.518013e+07</td>\n", " <td>3.035403e+10</td>\n", " <td>4.869000e+09</td>\n", " <td>3.879288e+13</td>\n", " </tr>\n", " <tr>\n", " <th>23</th>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>1.682300e+01</td>\n", " <td>4.780800e+01</td>\n", " <td>1.670800e+01</td>\n", " <td>1.670800e+01</td>\n", " <td>3.554470e+02</td>\n", " <td>2.001910e+02</td>\n", " <td>5.276300e+01</td>\n", " <td>NaN</td>\n", " <td>4.149760e+02</td>\n", " <td>7.815400e+01</td>\n", " <td>1.051900e+02</td>\n", " </tr>\n", " <tr>\n", " <th>24</th>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>1.670000e+00</td>\n", " <td>6.560000e+00</td>\n", " <td>7.100000e-01</td>\n", " <td>7.100000e-01</td>\n", " <td>7.800000e-01</td>\n", " <td>6.550000e+00</td>\n", " <td>-1.190000e+00</td>\n", " <td>-4.302852e+04</td>\n", " <td>-1.630000e+00</td>\n", " <td>-3.690000e+00</td>\n", " <td>2.439000e+01</td>\n", " </tr>\n", " <tr>\n", " <th>25</th>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>2.398100e+01</td>\n", " <td>3.131100e+01</td>\n", " <td>2.480600e+01</td>\n", " <td>2.480600e+01</td>\n", " <td>1.132100e+01</td>\n", " <td>6.934500e+01</td>\n", " <td>1.044000e+00</td>\n", " <td>-7.148243e+03</td>\n", " <td>-1.750000e-01</td>\n", " <td>5.429000e+00</td>\n", " <td>2.753086e+03</td>\n", " </tr>\n", " <tr>\n", " <th>26</th>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>2.886200e+01</td>\n", " <td>6.337300e+01</td>\n", " <td>9.412500e+01</td>\n", " <td>9.412500e+01</td>\n", " <td>4.661600e+01</td>\n", " <td>1.820480e+02</td>\n", " <td>3.310000e-01</td>\n", " <td>8.751330e+02</td>\n", " <td>3.282800e+01</td>\n", " <td>4.755000e+00</td>\n", " <td>2.265462e+03</td>\n", " </tr>\n", " <tr>\n", " <th>27</th>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>4.887690e+00</td>\n", " <td>1.135848e+01</td>\n", " <td>3.578402e+01</td>\n", " <td>3.578402e+01</td>\n", " <td>4.739307e+00</td>\n", " <td>2.517651e+01</td>\n", " <td>-6.286589e-01</td>\n", " <td>-1.192432e+01</td>\n", " <td>0.000000e+00</td>\n", " <td>-5.335686e-01</td>\n", " <td>2.836508e+03</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " Category Metric TSLA \\\n", "0 Valuation Trailing P/E 1.848623e+02 \n", "1 Valuation Forward P/E 9.528395e+01 \n", "2 Valuation PEG Ratio NaN \n", "3 Valuation Price/Sales (ttm) 1.073944e+01 \n", "4 Valuation Price/Book 1.287353e+01 \n", "5 Valuation Enterprise Value/Revenue 1.051100e+01 \n", "6 Valuation Enterprise Value/EBITDA 8.589900e+01 \n", "7 Financial Highlights Market Cap 9.957609e+11 \n", "8 Financial Highlights Enterprise Value 9.746123e+11 \n", "9 Financial Highlights Revenue (ttm) 9.272000e+10 \n", "10 Financial Highlights Gross Profit (ttm) 1.620700e+10 \n", "11 Financial Highlights EBITDA 1.134600e+10 \n", "12 Financial Highlights Net Income (ttm) 5.879000e+09 \n", "13 Profitability Profit Margin 6.343999e-02 \n", "14 Profitability Operating Margin 4.103000e-02 \n", "15 Profitability Gross Margin 1.748000e-01 \n", "16 Profitability EBITDA Margin 1.223700e-01 \n", "17 Profitability Return on Assets 2.911000e-02 \n", "18 Profitability Return on Equity 8.177000e-02 \n", "19 Liquidity Current Ratio 2.037000e+00 \n", "20 Liquidity Quick Ratio 1.359000e+00 \n", "21 Liquidity Total Cash 3.678200e+10 \n", "22 Liquidity Total Debt 1.313400e+10 \n", "23 Liquidity Debt/Equity 1.682300e+01 \n", "24 Per Share Earnings Per Share (ttm) 1.670000e+00 \n", "25 Per Share Book Value Per Share 2.398100e+01 \n", "26 Per Share Revenue Per Share 2.886200e+01 \n", "27 Per Share Operating Cash Flow Per Share 4.887690e+00 \n", "\n", " AMZN BYDDF BYDDY F GM \\\n", "0 3.258384e+01 2.000000e+01 1.990141e+01 1.417949e+01 8.027481e+00 \n", "1 3.475610e+01 1.713596e+00 4.500000e+00 6.320000e+00 4.974456e+00 \n", "2 NaN NaN NaN NaN NaN \n", "3 3.402228e+00 1.570778e-01 1.569489e-01 2.376100e-01 2.668458e-01 \n", "4 6.826674e+00 5.724422e-01 5.696203e-01 9.769455e-01 7.582378e-01 \n", "5 3.468000e+00 3.500000e-02 3.500000e-02 9.480000e-01 8.980000e-01 \n", "6 1.736200e+01 2.490000e-01 2.440000e-01 2.053100e+01 1.001900e+01 \n", "7 2.279622e+12 1.291994e+11 1.290934e+11 4.401725e+10 5.006026e+10 \n", "8 2.323619e+12 2.897114e+10 2.844296e+10 1.755615e+11 1.684471e+11 \n", "9 6.700380e+11 8.225185e+11 8.225185e+11 1.852500e+11 1.876000e+11 \n", "10 3.323830e+11 1.564718e+11 1.564718e+11 1.337600e+10 2.057800e+10 \n", "11 1.338320e+11 1.165454e+11 1.165454e+11 8.551000e+09 1.681200e+10 \n", "12 7.062300e+10 4.481004e+10 4.481004e+10 3.151000e+09 6.524000e+09 \n", "13 1.054000e-01 5.452000e-02 5.452000e-02 1.701000e-02 2.545000e-02 \n", "14 1.143200e-01 4.946000e-02 4.946000e-02 1.072000e-02 4.701000e-02 \n", "15 4.960700e-01 1.902300e-01 1.902300e-01 7.221000e-02 1.096900e-01 \n", "16 1.997400e-01 1.416900e-01 1.416900e-01 4.616000e-02 8.962000e-02 \n", "17 7.699000e-02 4.032000e-02 4.032000e-02 6.340000e-03 2.310000e-02 \n", "18 2.477000e-01 2.306600e-01 2.306600e-01 7.152000e-02 6.955000e-02 \n", "19 1.024000e+00 8.110000e-01 8.110000e-01 1.101000e+00 1.218000e+00 \n", "20 7.680000e-01 4.300000e-01 4.300000e-01 9.110000e-01 9.650000e-01 \n", "21 9.318000e+10 1.533910e+11 1.533910e+11 2.828100e+10 2.093900e+10 \n", "22 1.595700e+11 4.112797e+10 4.112797e+10 1.602390e+11 1.370490e+11 \n", "23 4.780800e+01 1.670800e+01 1.670800e+01 3.554470e+02 2.001910e+02 \n", "24 6.560000e+00 7.100000e-01 7.100000e-01 7.800000e-01 6.550000e+00 \n", "25 3.131100e+01 2.480600e+01 2.480600e+01 1.132100e+01 6.934500e+01 \n", "26 6.337300e+01 9.412500e+01 9.412500e+01 4.661600e+01 1.820480e+02 \n", "27 1.135848e+01 3.578402e+01 3.578402e+01 4.739307e+00 2.517651e+01 \n", "\n", " LCID MULN NIO RIVN TM \n", "0 NaN NaN NaN NaN 7.441575e+00 \n", "1 -2.750000e+00 8.800000e-02 -5.294117e+00 -4.434307e+00 1.150190e+01 \n", "2 NaN NaN NaN NaN NaN \n", "3 8.545063e+00 7.787777e-02 1.575678e-01 2.907481e+00 4.924489e-03 \n", "4 2.318008e+00 NaN -2.571429e+01 2.237981e+00 6.592602e-02 \n", "5 9.152000e+00 3.047000e+00 4.120000e-01 2.382000e+00 6.900000e-01 \n", "6 -3.019000e+00 -1.190000e-01 -1.704000e+00 -4.100000e+00 4.703000e+00 \n", "7 7.435402e+09 6.955740e+05 1.069218e+10 1.455485e+10 2.365562e+11 \n", "8 7.963166e+09 2.721857e+07 2.794399e+10 1.192613e+10 3.314055e+13 \n", "9 8.701400e+08 8.931612e+06 6.785765e+10 5.006000e+09 4.803671e+13 \n", "10 -9.195670e+08 -2.153492e+07 6.924585e+09 -4.670000e+08 9.578038e+12 \n", "11 -2.638076e+09 -2.293505e+08 -1.639825e+10 -2.909000e+09 7.046819e+12 \n", "12 -3.107888e+09 -4.391060e+08 -2.429083e+10 -3.846000e+09 4.765086e+12 \n", "13 -2.757320e+00 0.000000e+00 -3.579700e-01 -7.682800e-01 9.920000e-02 \n", "14 -2.943790e+00 -1.081451e+01 -5.333000e-01 -5.282300e-01 9.028000e-02 \n", "15 -1.056800e+00 -2.411090e+00 1.020500e-01 -9.329000e-02 1.993900e-01 \n", "16 0.000000e+00 0.000000e+00 -2.416600e-01 -5.811000e-01 1.467000e-01 \n", "17 -2.044300e-01 -8.461600e-01 -1.414500e-01 -1.544500e-01 3.263000e-02 \n", "18 -5.006200e-01 -1.851312e+01 -1.500650e+00 -5.372400e-01 1.328300e-01 \n", "19 3.322000e+00 2.530000e-01 8.370000e-01 3.728000e+00 1.260000e+00 \n", "20 2.798000e+00 7.000000e-03 5.090000e-01 2.722000e+00 8.270000e-01 \n", "21 3.610905e+09 1.404708e+06 1.972245e+10 7.178000e+09 8.982404e+12 \n", "22 2.558172e+09 2.518013e+07 3.035403e+10 4.869000e+09 3.879288e+13 \n", "23 5.276300e+01 NaN 4.149760e+02 7.815400e+01 1.051900e+02 \n", "24 -1.190000e+00 -4.302852e+04 -1.630000e+00 -3.690000e+00 2.439000e+01 \n", "25 1.044000e+00 -7.148243e+03 -1.750000e-01 5.429000e+00 2.753086e+03 \n", "26 3.310000e-01 8.751330e+02 3.282800e+01 4.755000e+00 2.265462e+03 \n", "27 -6.286589e-01 -1.192432e+01 0.000000e+00 -5.335686e-01 2.836508e+03 " ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "symboldf = get_fundamental_ratios(symbol)\n", "\n", "obb.account.login(email=os.environ['OPENBB_USER'], password=os.environ['OPENBB_PW'], remember_me=True)\n", "obj = obb.equity.compare.peers(symbol=symbol, provider='fmp')\n", "peers = obj.results\n", "peers_list=peers.peers_list\n", "\n", "peers_dflist = [get_fundamental_ratios(p).iloc[:,2] for p in peers_list]\n", "pd.concat([symboldf] + peers_dflist, axis=1)\n" ] }, { "cell_type": "code", "execution_count": 33, "id": "983c6c5b", "metadata": {}, "outputs": [], "source": [ "\n" ] }, { "cell_type": "code", "execution_count": 36, "id": "3ce6c821", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [] }, { "cell_type": "code", "execution_count": 21, "id": "6d61c6ca", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[ Category Metric TSLA\n", " 0 Valuation Trailing P/E 1.848623e+02\n", " 1 Valuation Forward P/E 9.528395e+01\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 1.073944e+01\n", " 4 Valuation Price/Book 1.287353e+01\n", " 5 Valuation Enterprise Value/Revenue 1.051100e+01\n", " 6 Valuation Enterprise Value/EBITDA 8.589900e+01\n", " 7 Financial Highlights Market Cap 9.957609e+11\n", " 8 Financial Highlights Enterprise Value 9.746123e+11\n", " 9 Financial Highlights Revenue (ttm) 9.272000e+10\n", " 10 Financial Highlights Gross Profit (ttm) 1.620700e+10\n", " 11 Financial Highlights EBITDA 1.134600e+10\n", " 12 Financial Highlights Net Income (ttm) 5.879000e+09\n", " 13 Profitability Profit Margin 6.343999e-02\n", " 14 Profitability Operating Margin 4.103000e-02\n", " 15 Profitability Gross Margin 1.748000e-01\n", " 16 Profitability EBITDA Margin 1.223700e-01\n", " 17 Profitability Return on Assets 2.911000e-02\n", " 18 Profitability Return on Equity 8.177000e-02\n", " 19 Liquidity Current Ratio 2.037000e+00\n", " 20 Liquidity Quick Ratio 1.359000e+00\n", " 21 Liquidity Total Cash 3.678200e+10\n", " 22 Liquidity Total Debt 1.313400e+10\n", " 23 Liquidity Debt/Equity 1.682300e+01\n", " 24 Per Share Earnings Per Share (ttm) 1.670000e+00\n", " 25 Per Share Book Value Per Share 2.398100e+01\n", " 26 Per Share Revenue Per Share 2.886200e+01\n", " 27 Per Share Operating Cash Flow Per Share 4.887690e+00,\n", " Category Metric AMZN\n", " 0 Valuation Trailing P/E 3.258384e+01\n", " 1 Valuation Forward P/E 3.475610e+01\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 3.402228e+00\n", " 4 Valuation Price/Book 6.826674e+00\n", " 5 Valuation Enterprise Value/Revenue 3.468000e+00\n", " 6 Valuation Enterprise Value/EBITDA 1.736200e+01\n", " 7 Financial Highlights Market Cap 2.279622e+12\n", " 8 Financial Highlights Enterprise Value 2.323619e+12\n", " 9 Financial Highlights Revenue (ttm) 6.700380e+11\n", " 10 Financial Highlights Gross Profit (ttm) 3.323830e+11\n", " 11 Financial Highlights EBITDA 1.338320e+11\n", " 12 Financial Highlights Net Income (ttm) 7.062300e+10\n", " 13 Profitability Profit Margin 1.054000e-01\n", " 14 Profitability Operating Margin 1.143200e-01\n", " 15 Profitability Gross Margin 4.960700e-01\n", " 16 Profitability EBITDA Margin 1.997400e-01\n", " 17 Profitability Return on Assets 7.699000e-02\n", " 18 Profitability Return on Equity 2.477000e-01\n", " 19 Liquidity Current Ratio 1.024000e+00\n", " 20 Liquidity Quick Ratio 7.680000e-01\n", " 21 Liquidity Total Cash 9.318000e+10\n", " 22 Liquidity Total Debt 1.595700e+11\n", " 23 Liquidity Debt/Equity 4.780800e+01\n", " 24 Per Share Earnings Per Share (ttm) 6.560000e+00\n", " 25 Per Share Book Value Per Share 3.131100e+01\n", " 26 Per Share Revenue Per Share 6.337300e+01\n", " 27 Per Share Operating Cash Flow Per Share 1.135848e+01,\n", " Category Metric BYDDF\n", " 0 Valuation Trailing P/E 2.000000e+01\n", " 1 Valuation Forward P/E 1.713596e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 1.570778e-01\n", " 4 Valuation Price/Book 5.724422e-01\n", " 5 Valuation Enterprise Value/Revenue 3.500000e-02\n", " 6 Valuation Enterprise Value/EBITDA 2.490000e-01\n", " 7 Financial Highlights Market Cap 1.291994e+11\n", " 8 Financial Highlights Enterprise Value 2.897114e+10\n", " 9 Financial Highlights Revenue (ttm) 8.225185e+11\n", " 10 Financial Highlights Gross Profit (ttm) 1.564718e+11\n", " 11 Financial Highlights EBITDA 1.165454e+11\n", " 12 Financial Highlights Net Income (ttm) 4.481004e+10\n", " 13 Profitability Profit Margin 5.452000e-02\n", " 14 Profitability Operating Margin 4.946000e-02\n", " 15 Profitability Gross Margin 1.902300e-01\n", " 16 Profitability EBITDA Margin 1.416900e-01\n", " 17 Profitability Return on Assets 4.032000e-02\n", " 18 Profitability Return on Equity 2.306600e-01\n", " 19 Liquidity Current Ratio 8.110000e-01\n", " 20 Liquidity Quick Ratio 4.300000e-01\n", " 21 Liquidity Total Cash 1.533910e+11\n", " 22 Liquidity Total Debt 4.112797e+10\n", " 23 Liquidity Debt/Equity 1.670800e+01\n", " 24 Per Share Earnings Per Share (ttm) 7.100000e-01\n", " 25 Per Share Book Value Per Share 2.480600e+01\n", " 26 Per Share Revenue Per Share 9.412500e+01\n", " 27 Per Share Operating Cash Flow Per Share 3.578402e+01,\n", " Category Metric BYDDY\n", " 0 Valuation Trailing P/E 1.990141e+01\n", " 1 Valuation Forward P/E 4.500000e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 1.569489e-01\n", " 4 Valuation Price/Book 5.696203e-01\n", " 5 Valuation Enterprise Value/Revenue 3.500000e-02\n", " 6 Valuation Enterprise Value/EBITDA 2.440000e-01\n", " 7 Financial Highlights Market Cap 1.290934e+11\n", " 8 Financial Highlights Enterprise Value 2.844296e+10\n", " 9 Financial Highlights Revenue (ttm) 8.225185e+11\n", " 10 Financial Highlights Gross Profit (ttm) 1.564718e+11\n", " 11 Financial Highlights EBITDA 1.165454e+11\n", " 12 Financial Highlights Net Income (ttm) 4.481004e+10\n", " 13 Profitability Profit Margin 5.452000e-02\n", " 14 Profitability Operating Margin 4.946000e-02\n", " 15 Profitability Gross Margin 1.902300e-01\n", " 16 Profitability EBITDA Margin 1.416900e-01\n", " 17 Profitability Return on Assets 4.032000e-02\n", " 18 Profitability Return on Equity 2.306600e-01\n", " 19 Liquidity Current Ratio 8.110000e-01\n", " 20 Liquidity Quick Ratio 4.300000e-01\n", " 21 Liquidity Total Cash 1.533910e+11\n", " 22 Liquidity Total Debt 4.112797e+10\n", " 23 Liquidity Debt/Equity 1.670800e+01\n", " 24 Per Share Earnings Per Share (ttm) 7.100000e-01\n", " 25 Per Share Book Value Per Share 2.480600e+01\n", " 26 Per Share Revenue Per Share 9.412500e+01\n", " 27 Per Share Operating Cash Flow Per Share 3.578402e+01,\n", " Category Metric F\n", " 0 Valuation Trailing P/E 1.417949e+01\n", " 1 Valuation Forward P/E 6.320000e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 2.376100e-01\n", " 4 Valuation Price/Book 9.769455e-01\n", " 5 Valuation Enterprise Value/Revenue 9.480000e-01\n", " 6 Valuation Enterprise Value/EBITDA 2.053100e+01\n", " 7 Financial Highlights Market Cap 4.401725e+10\n", " 8 Financial Highlights Enterprise Value 1.755615e+11\n", " 9 Financial Highlights Revenue (ttm) 1.852500e+11\n", " 10 Financial Highlights Gross Profit (ttm) 1.337600e+10\n", " 11 Financial Highlights EBITDA 8.551000e+09\n", " 12 Financial Highlights Net Income (ttm) 3.151000e+09\n", " 13 Profitability Profit Margin 1.701000e-02\n", " 14 Profitability Operating Margin 1.072000e-02\n", " 15 Profitability Gross Margin 7.221000e-02\n", " 16 Profitability EBITDA Margin 4.616000e-02\n", " 17 Profitability Return on Assets 6.340000e-03\n", " 18 Profitability Return on Equity 7.152000e-02\n", " 19 Liquidity Current Ratio 1.101000e+00\n", " 20 Liquidity Quick Ratio 9.110000e-01\n", " 21 Liquidity Total Cash 2.828100e+10\n", " 22 Liquidity Total Debt 1.602390e+11\n", " 23 Liquidity Debt/Equity 3.554470e+02\n", " 24 Per Share Earnings Per Share (ttm) 7.800000e-01\n", " 25 Per Share Book Value Per Share 1.132100e+01\n", " 26 Per Share Revenue Per Share 4.661600e+01\n", " 27 Per Share Operating Cash Flow Per Share 4.739307e+00,\n", " Category Metric GM\n", " 0 Valuation Trailing P/E 8.027481e+00\n", " 1 Valuation Forward P/E 4.974456e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 2.668458e-01\n", " 4 Valuation Price/Book 7.582378e-01\n", " 5 Valuation Enterprise Value/Revenue 8.980000e-01\n", " 6 Valuation Enterprise Value/EBITDA 1.001900e+01\n", " 7 Financial Highlights Market Cap 5.006026e+10\n", " 8 Financial Highlights Enterprise Value 1.684471e+11\n", " 9 Financial Highlights Revenue (ttm) 1.876000e+11\n", " 10 Financial Highlights Gross Profit (ttm) 2.057800e+10\n", " 11 Financial Highlights EBITDA 1.681200e+10\n", " 12 Financial Highlights Net Income (ttm) 6.524000e+09\n", " 13 Profitability Profit Margin 2.545000e-02\n", " 14 Profitability Operating Margin 4.701000e-02\n", " 15 Profitability Gross Margin 1.096900e-01\n", " 16 Profitability EBITDA Margin 8.962000e-02\n", " 17 Profitability Return on Assets 2.310000e-02\n", " 18 Profitability Return on Equity 6.955000e-02\n", " 19 Liquidity Current Ratio 1.218000e+00\n", " 20 Liquidity Quick Ratio 9.650000e-01\n", " 21 Liquidity Total Cash 2.093900e+10\n", " 22 Liquidity Total Debt 1.370490e+11\n", " 23 Liquidity Debt/Equity 2.001910e+02\n", " 24 Per Share Earnings Per Share (ttm) 6.550000e+00\n", " 25 Per Share Book Value Per Share 6.934500e+01\n", " 26 Per Share Revenue Per Share 1.820480e+02\n", " 27 Per Share Operating Cash Flow Per Share 2.517651e+01,\n", " Category Metric LCID\n", " 0 Valuation Trailing P/E NaN\n", " 1 Valuation Forward P/E -2.750000e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 8.545063e+00\n", " 4 Valuation Price/Book 2.318008e+00\n", " 5 Valuation Enterprise Value/Revenue 9.152000e+00\n", " 6 Valuation Enterprise Value/EBITDA -3.019000e+00\n", " 7 Financial Highlights Market Cap 7.435402e+09\n", " 8 Financial Highlights Enterprise Value 7.963166e+09\n", " 9 Financial Highlights Revenue (ttm) 8.701400e+08\n", " 10 Financial Highlights Gross Profit (ttm) -9.195670e+08\n", " 11 Financial Highlights EBITDA -2.638076e+09\n", " 12 Financial Highlights Net Income (ttm) -3.107888e+09\n", " 13 Profitability Profit Margin -2.757320e+00\n", " 14 Profitability Operating Margin -2.943790e+00\n", " 15 Profitability Gross Margin -1.056800e+00\n", " 16 Profitability EBITDA Margin 0.000000e+00\n", " 17 Profitability Return on Assets -2.044300e-01\n", " 18 Profitability Return on Equity -5.006200e-01\n", " 19 Liquidity Current Ratio 3.322000e+00\n", " 20 Liquidity Quick Ratio 2.798000e+00\n", " 21 Liquidity Total Cash 3.610905e+09\n", " 22 Liquidity Total Debt 2.558172e+09\n", " 23 Liquidity Debt/Equity 5.276300e+01\n", " 24 Per Share Earnings Per Share (ttm) -1.190000e+00\n", " 25 Per Share Book Value Per Share 1.044000e+00\n", " 26 Per Share Revenue Per Share 3.310000e-01\n", " 27 Per Share Operating Cash Flow Per Share -6.286589e-01,\n", " Category Metric MULN\n", " 0 Valuation Trailing P/E NaN\n", " 1 Valuation Forward P/E 8.800000e-02\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 7.787777e-02\n", " 4 Valuation Price/Book NaN\n", " 5 Valuation Enterprise Value/Revenue 3.047000e+00\n", " 6 Valuation Enterprise Value/EBITDA -1.190000e-01\n", " 7 Financial Highlights Market Cap 6.955740e+05\n", " 8 Financial Highlights Enterprise Value 2.721857e+07\n", " 9 Financial Highlights Revenue (ttm) 8.931612e+06\n", " 10 Financial Highlights Gross Profit (ttm) -2.153492e+07\n", " 11 Financial Highlights EBITDA -2.293505e+08\n", " 12 Financial Highlights Net Income (ttm) -4.391060e+08\n", " 13 Profitability Profit Margin 0.000000e+00\n", " 14 Profitability Operating Margin -1.081451e+01\n", " 15 Profitability Gross Margin -2.411090e+00\n", " 16 Profitability EBITDA Margin 0.000000e+00\n", " 17 Profitability Return on Assets -8.461600e-01\n", " 18 Profitability Return on Equity -1.851312e+01\n", " 19 Liquidity Current Ratio 2.530000e-01\n", " 20 Liquidity Quick Ratio 7.000000e-03\n", " 21 Liquidity Total Cash 1.404708e+06\n", " 22 Liquidity Total Debt 2.518013e+07\n", " 23 Liquidity Debt/Equity NaN\n", " 24 Per Share Earnings Per Share (ttm) -4.302852e+04\n", " 25 Per Share Book Value Per Share -7.148243e+03\n", " 26 Per Share Revenue Per Share 8.751330e+02\n", " 27 Per Share Operating Cash Flow Per Share -1.192432e+01,\n", " Category Metric NIO\n", " 0 Valuation Trailing P/E NaN\n", " 1 Valuation Forward P/E -5.294117e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 1.575678e-01\n", " 4 Valuation Price/Book -2.571429e+01\n", " 5 Valuation Enterprise Value/Revenue 4.120000e-01\n", " 6 Valuation Enterprise Value/EBITDA -1.704000e+00\n", " 7 Financial Highlights Market Cap 1.069218e+10\n", " 8 Financial Highlights Enterprise Value 2.794399e+10\n", " 9 Financial Highlights Revenue (ttm) 6.785765e+10\n", " 10 Financial Highlights Gross Profit (ttm) 6.924585e+09\n", " 11 Financial Highlights EBITDA -1.639825e+10\n", " 12 Financial Highlights Net Income (ttm) -2.429083e+10\n", " 13 Profitability Profit Margin -3.579700e-01\n", " 14 Profitability Operating Margin -5.333000e-01\n", " 15 Profitability Gross Margin 1.020500e-01\n", " 16 Profitability EBITDA Margin -2.416600e-01\n", " 17 Profitability Return on Assets -1.414500e-01\n", " 18 Profitability Return on Equity -1.500650e+00\n", " 19 Liquidity Current Ratio 8.370000e-01\n", " 20 Liquidity Quick Ratio 5.090000e-01\n", " 21 Liquidity Total Cash 1.972245e+10\n", " 22 Liquidity Total Debt 3.035403e+10\n", " 23 Liquidity Debt/Equity 4.149760e+02\n", " 24 Per Share Earnings Per Share (ttm) -1.630000e+00\n", " 25 Per Share Book Value Per Share -1.750000e-01\n", " 26 Per Share Revenue Per Share 3.282800e+01\n", " 27 Per Share Operating Cash Flow Per Share 0.000000e+00,\n", " Category Metric RIVN\n", " 0 Valuation Trailing P/E NaN\n", " 1 Valuation Forward P/E -4.434307e+00\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 2.907481e+00\n", " 4 Valuation Price/Book 2.237981e+00\n", " 5 Valuation Enterprise Value/Revenue 2.382000e+00\n", " 6 Valuation Enterprise Value/EBITDA -4.100000e+00\n", " 7 Financial Highlights Market Cap 1.455485e+10\n", " 8 Financial Highlights Enterprise Value 1.192613e+10\n", " 9 Financial Highlights Revenue (ttm) 5.006000e+09\n", " 10 Financial Highlights Gross Profit (ttm) -4.670000e+08\n", " 11 Financial Highlights EBITDA -2.909000e+09\n", " 12 Financial Highlights Net Income (ttm) -3.846000e+09\n", " 13 Profitability Profit Margin -7.682800e-01\n", " 14 Profitability Operating Margin -5.282300e-01\n", " 15 Profitability Gross Margin -9.329000e-02\n", " 16 Profitability EBITDA Margin -5.811000e-01\n", " 17 Profitability Return on Assets -1.544500e-01\n", " 18 Profitability Return on Equity -5.372400e-01\n", " 19 Liquidity Current Ratio 3.728000e+00\n", " 20 Liquidity Quick Ratio 2.722000e+00\n", " 21 Liquidity Total Cash 7.178000e+09\n", " 22 Liquidity Total Debt 4.869000e+09\n", " 23 Liquidity Debt/Equity 7.815400e+01\n", " 24 Per Share Earnings Per Share (ttm) -3.690000e+00\n", " 25 Per Share Book Value Per Share 5.429000e+00\n", " 26 Per Share Revenue Per Share 4.755000e+00\n", " 27 Per Share Operating Cash Flow Per Share -5.335686e-01,\n", " Category Metric TM\n", " 0 Valuation Trailing P/E 7.441575e+00\n", " 1 Valuation Forward P/E 1.150190e+01\n", " 2 Valuation PEG Ratio NaN\n", " 3 Valuation Price/Sales (ttm) 4.924489e-03\n", " 4 Valuation Price/Book 6.592602e-02\n", " 5 Valuation Enterprise Value/Revenue 6.900000e-01\n", " 6 Valuation Enterprise Value/EBITDA 4.703000e+00\n", " 7 Financial Highlights Market Cap 2.365562e+11\n", " 8 Financial Highlights Enterprise Value 3.314055e+13\n", " 9 Financial Highlights Revenue (ttm) 4.803671e+13\n", " 10 Financial Highlights Gross Profit (ttm) 9.578038e+12\n", " 11 Financial Highlights EBITDA 7.046819e+12\n", " 12 Financial Highlights Net Income (ttm) 4.765086e+12\n", " 13 Profitability Profit Margin 9.920000e-02\n", " 14 Profitability Operating Margin 9.028000e-02\n", " 15 Profitability Gross Margin 1.993900e-01\n", " 16 Profitability EBITDA Margin 1.467000e-01\n", " 17 Profitability Return on Assets 3.263000e-02\n", " 18 Profitability Return on Equity 1.328300e-01\n", " 19 Liquidity Current Ratio 1.260000e+00\n", " 20 Liquidity Quick Ratio 8.270000e-01\n", " 21 Liquidity Total Cash 8.982404e+12\n", " 22 Liquidity Total Debt 3.879288e+13\n", " 23 Liquidity Debt/Equity 1.051900e+02\n", " 24 Per Share Earnings Per Share (ttm) 2.439000e+01\n", " 25 Per Share Book Value Per Share 2.753086e+03\n", " 26 Per Share Revenue Per Share 2.265462e+03\n", " 27 Per Share Operating Cash Flow Per Share 2.836508e+03]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dflist = [get_fundamental_ratios(p) for p in [symbol] + list(peers.peers_list)]\n", "pd\n" ] }, { "cell_type": "code", "execution_count": 22, "id": "63e285bb", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>TSLA</th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>AMZN</th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>BYDDF</th>\n", " <th>Category</th>\n", " <th>...</th>\n", " <th>MULN</th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>NIO</th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>RIVN</th>\n", " <th>Category</th>\n", " <th>Metric</th>\n", " <th>TM</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>1.848623e+02</td>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>3.258384e+01</td>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>2.000000e+01</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>Trailing P/E</td>\n", " <td>7.441575e+00</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>9.528395e+01</td>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>3.475610e+01</td>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>1.713596e+00</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>8.800000e-02</td>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>-5.294117e+00</td>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>-4.434307e+00</td>\n", " <td>Valuation</td>\n", " <td>Forward P/E</td>\n", " <td>1.150190e+01</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>PEG Ratio</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>1.073944e+01</td>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>3.402228e+00</td>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>1.570778e-01</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>7.787777e-02</td>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>1.575678e-01</td>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>2.907481e+00</td>\n", " <td>Valuation</td>\n", " <td>Price/Sales (ttm)</td>\n", " <td>4.924489e-03</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>1.287353e+01</td>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>6.826674e+00</td>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>5.724422e-01</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>NaN</td>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>-2.571429e+01</td>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>2.237981e+00</td>\n", " <td>Valuation</td>\n", " <td>Price/Book</td>\n", " <td>6.592602e-02</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>1.051100e+01</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>3.468000e+00</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>3.500000e-02</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>3.047000e+00</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>4.120000e-01</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>2.382000e+00</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/Revenue</td>\n", " <td>6.900000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>6</th>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>8.589900e+01</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>1.736200e+01</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>2.490000e-01</td>\n", " <td>Valuation</td>\n", " <td>...</td>\n", " <td>-1.190000e-01</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>-1.704000e+00</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>-4.100000e+00</td>\n", " <td>Valuation</td>\n", " <td>Enterprise Value/EBITDA</td>\n", " <td>4.703000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>7</th>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>9.957609e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>2.279622e+12</td>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>1.291994e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>...</td>\n", " <td>6.955740e+05</td>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>1.069218e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>1.455485e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Market Cap</td>\n", " <td>2.365562e+11</td>\n", " </tr>\n", " <tr>\n", " <th>8</th>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>9.746123e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>2.323619e+12</td>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>2.897114e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>...</td>\n", " <td>2.721857e+07</td>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>2.794399e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>1.192613e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Enterprise Value</td>\n", " <td>3.314055e+13</td>\n", " </tr>\n", " <tr>\n", " <th>9</th>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>9.272000e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>6.700380e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>8.225185e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>...</td>\n", " <td>8.931612e+06</td>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>6.785765e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>5.006000e+09</td>\n", " <td>Financial Highlights</td>\n", " <td>Revenue (ttm)</td>\n", " <td>4.803671e+13</td>\n", " </tr>\n", " <tr>\n", " <th>10</th>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>1.620700e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>3.323830e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>1.564718e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>...</td>\n", " <td>-2.153492e+07</td>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>6.924585e+09</td>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>-4.670000e+08</td>\n", " <td>Financial Highlights</td>\n", " <td>Gross Profit (ttm)</td>\n", " <td>9.578038e+12</td>\n", " </tr>\n", " <tr>\n", " <th>11</th>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>1.134600e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>1.338320e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>1.165454e+11</td>\n", " <td>Financial Highlights</td>\n", " <td>...</td>\n", " <td>-2.293505e+08</td>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>-1.639825e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>-2.909000e+09</td>\n", " <td>Financial Highlights</td>\n", " <td>EBITDA</td>\n", " <td>7.046819e+12</td>\n", " </tr>\n", " <tr>\n", " <th>12</th>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>5.879000e+09</td>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>7.062300e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>4.481004e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>...</td>\n", " <td>-4.391060e+08</td>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>-2.429083e+10</td>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>-3.846000e+09</td>\n", " <td>Financial Highlights</td>\n", " <td>Net Income (ttm)</td>\n", " <td>4.765086e+12</td>\n", " </tr>\n", " <tr>\n", " <th>13</th>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>6.343999e-02</td>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>1.054000e-01</td>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>5.452000e-02</td>\n", " <td>Profitability</td>\n", " <td>...</td>\n", " <td>0.000000e+00</td>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>-3.579700e-01</td>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>-7.682800e-01</td>\n", " <td>Profitability</td>\n", " <td>Profit Margin</td>\n", " <td>9.920000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>14</th>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>4.103000e-02</td>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>1.143200e-01</td>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>4.946000e-02</td>\n", " <td>Profitability</td>\n", " <td>...</td>\n", " <td>-1.081451e+01</td>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>-5.333000e-01</td>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>-5.282300e-01</td>\n", " <td>Profitability</td>\n", " <td>Operating Margin</td>\n", " <td>9.028000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>15</th>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>1.748000e-01</td>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>4.960700e-01</td>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>1.902300e-01</td>\n", " <td>Profitability</td>\n", " <td>...</td>\n", " <td>-2.411090e+00</td>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>1.020500e-01</td>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>-9.329000e-02</td>\n", " <td>Profitability</td>\n", " <td>Gross Margin</td>\n", " <td>1.993900e-01</td>\n", " </tr>\n", " <tr>\n", " <th>16</th>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>1.223700e-01</td>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>1.997400e-01</td>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>1.416900e-01</td>\n", " <td>Profitability</td>\n", " <td>...</td>\n", " <td>0.000000e+00</td>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>-2.416600e-01</td>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>-5.811000e-01</td>\n", " <td>Profitability</td>\n", " <td>EBITDA Margin</td>\n", " <td>1.467000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>17</th>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>2.911000e-02</td>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>7.699000e-02</td>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>4.032000e-02</td>\n", " <td>Profitability</td>\n", " <td>...</td>\n", " <td>-8.461600e-01</td>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>-1.414500e-01</td>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>-1.544500e-01</td>\n", " <td>Profitability</td>\n", " <td>Return on Assets</td>\n", " <td>3.263000e-02</td>\n", " </tr>\n", " <tr>\n", " <th>18</th>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>8.177000e-02</td>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>2.477000e-01</td>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>2.306600e-01</td>\n", " <td>Profitability</td>\n", " <td>...</td>\n", " <td>-1.851312e+01</td>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>-1.500650e+00</td>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>-5.372400e-01</td>\n", " <td>Profitability</td>\n", " <td>Return on Equity</td>\n", " <td>1.328300e-01</td>\n", " </tr>\n", " <tr>\n", " <th>19</th>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>2.037000e+00</td>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>1.024000e+00</td>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>8.110000e-01</td>\n", " <td>Liquidity</td>\n", " <td>...</td>\n", " <td>2.530000e-01</td>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>8.370000e-01</td>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>3.728000e+00</td>\n", " <td>Liquidity</td>\n", " <td>Current Ratio</td>\n", " <td>1.260000e+00</td>\n", " </tr>\n", " <tr>\n", " <th>20</th>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>1.359000e+00</td>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>7.680000e-01</td>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>4.300000e-01</td>\n", " <td>Liquidity</td>\n", " <td>...</td>\n", " <td>7.000000e-03</td>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>5.090000e-01</td>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>2.722000e+00</td>\n", " <td>Liquidity</td>\n", " <td>Quick Ratio</td>\n", " <td>8.270000e-01</td>\n", " </tr>\n", " <tr>\n", " <th>21</th>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>3.678200e+10</td>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>9.318000e+10</td>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>1.533910e+11</td>\n", " <td>Liquidity</td>\n", " <td>...</td>\n", " <td>1.404708e+06</td>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>1.972245e+10</td>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>7.178000e+09</td>\n", " <td>Liquidity</td>\n", " <td>Total Cash</td>\n", " <td>8.982404e+12</td>\n", " </tr>\n", " <tr>\n", " <th>22</th>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>1.313400e+10</td>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>1.595700e+11</td>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>4.112797e+10</td>\n", " <td>Liquidity</td>\n", " <td>...</td>\n", " <td>2.518013e+07</td>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>3.035403e+10</td>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>4.869000e+09</td>\n", " <td>Liquidity</td>\n", " <td>Total Debt</td>\n", " <td>3.879288e+13</td>\n", " </tr>\n", " <tr>\n", " <th>23</th>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>1.682300e+01</td>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>4.780800e+01</td>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>1.670800e+01</td>\n", " <td>Liquidity</td>\n", " <td>...</td>\n", " <td>NaN</td>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>4.149760e+02</td>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>7.815400e+01</td>\n", " <td>Liquidity</td>\n", " <td>Debt/Equity</td>\n", " <td>1.051900e+02</td>\n", " </tr>\n", " <tr>\n", " <th>24</th>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>1.670000e+00</td>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>6.560000e+00</td>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>7.100000e-01</td>\n", " <td>Per Share</td>\n", " <td>...</td>\n", " <td>-4.302852e+04</td>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>-1.630000e+00</td>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>-3.690000e+00</td>\n", " <td>Per Share</td>\n", " <td>Earnings Per Share (ttm)</td>\n", " <td>2.439000e+01</td>\n", " </tr>\n", " <tr>\n", " <th>25</th>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>2.398100e+01</td>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>3.131100e+01</td>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>2.480600e+01</td>\n", " <td>Per Share</td>\n", " <td>...</td>\n", " <td>-7.148243e+03</td>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>-1.750000e-01</td>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>5.429000e+00</td>\n", " <td>Per Share</td>\n", " <td>Book Value Per Share</td>\n", " <td>2.753086e+03</td>\n", " </tr>\n", " <tr>\n", " <th>26</th>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>2.886200e+01</td>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>6.337300e+01</td>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>9.412500e+01</td>\n", " <td>Per Share</td>\n", " <td>...</td>\n", " <td>8.751330e+02</td>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>3.282800e+01</td>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>4.755000e+00</td>\n", " <td>Per Share</td>\n", " <td>Revenue Per Share</td>\n", " <td>2.265462e+03</td>\n", " </tr>\n", " <tr>\n", " <th>27</th>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>4.887690e+00</td>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>1.135848e+01</td>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>3.578402e+01</td>\n", " <td>Per Share</td>\n", " <td>...</td>\n", " <td>-1.192432e+01</td>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>0.000000e+00</td>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>-5.335686e-01</td>\n", " <td>Per Share</td>\n", " <td>Operating Cash Flow Per Share</td>\n", " <td>2.836508e+03</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "<p>28 rows × 33 columns</p>\n", "</div>" ], "text/plain": [ " Category Metric TSLA \\\n", "0 Valuation Trailing P/E 1.848623e+02 \n", "1 Valuation Forward P/E 9.528395e+01 \n", "2 Valuation PEG Ratio NaN \n", "3 Valuation Price/Sales (ttm) 1.073944e+01 \n", "4 Valuation Price/Book 1.287353e+01 \n", "5 Valuation Enterprise Value/Revenue 1.051100e+01 \n", "6 Valuation Enterprise Value/EBITDA 8.589900e+01 \n", "7 Financial Highlights Market Cap 9.957609e+11 \n", "8 Financial Highlights Enterprise Value 9.746123e+11 \n", "9 Financial Highlights Revenue (ttm) 9.272000e+10 \n", "10 Financial Highlights Gross Profit (ttm) 1.620700e+10 \n", "11 Financial Highlights EBITDA 1.134600e+10 \n", "12 Financial Highlights Net Income (ttm) 5.879000e+09 \n", "13 Profitability Profit Margin 6.343999e-02 \n", "14 Profitability Operating Margin 4.103000e-02 \n", "15 Profitability Gross Margin 1.748000e-01 \n", "16 Profitability EBITDA Margin 1.223700e-01 \n", "17 Profitability Return on Assets 2.911000e-02 \n", "18 Profitability Return on Equity 8.177000e-02 \n", "19 Liquidity Current Ratio 2.037000e+00 \n", "20 Liquidity Quick Ratio 1.359000e+00 \n", "21 Liquidity Total Cash 3.678200e+10 \n", "22 Liquidity Total Debt 1.313400e+10 \n", "23 Liquidity Debt/Equity 1.682300e+01 \n", "24 Per Share Earnings Per Share (ttm) 1.670000e+00 \n", "25 Per Share Book Value Per Share 2.398100e+01 \n", "26 Per Share Revenue Per Share 2.886200e+01 \n", "27 Per Share Operating Cash Flow Per Share 4.887690e+00 \n", "\n", " Category Metric AMZN \\\n", "0 Valuation Trailing P/E 3.258384e+01 \n", "1 Valuation Forward P/E 3.475610e+01 \n", "2 Valuation PEG Ratio NaN \n", "3 Valuation Price/Sales (ttm) 3.402228e+00 \n", "4 Valuation Price/Book 6.826674e+00 \n", "5 Valuation Enterprise Value/Revenue 3.468000e+00 \n", "6 Valuation Enterprise Value/EBITDA 1.736200e+01 \n", "7 Financial Highlights Market Cap 2.279622e+12 \n", "8 Financial Highlights Enterprise Value 2.323619e+12 \n", "9 Financial Highlights Revenue (ttm) 6.700380e+11 \n", "10 Financial Highlights Gross Profit (ttm) 3.323830e+11 \n", "11 Financial Highlights EBITDA 1.338320e+11 \n", "12 Financial Highlights Net Income (ttm) 7.062300e+10 \n", "13 Profitability Profit Margin 1.054000e-01 \n", "14 Profitability Operating Margin 1.143200e-01 \n", "15 Profitability Gross Margin 4.960700e-01 \n", "16 Profitability EBITDA Margin 1.997400e-01 \n", "17 Profitability Return on Assets 7.699000e-02 \n", "18 Profitability Return on Equity 2.477000e-01 \n", "19 Liquidity Current Ratio 1.024000e+00 \n", "20 Liquidity Quick Ratio 7.680000e-01 \n", "21 Liquidity Total Cash 9.318000e+10 \n", "22 Liquidity Total Debt 1.595700e+11 \n", "23 Liquidity Debt/Equity 4.780800e+01 \n", "24 Per Share Earnings Per Share (ttm) 6.560000e+00 \n", "25 Per Share Book Value Per Share 3.131100e+01 \n", "26 Per Share Revenue Per Share 6.337300e+01 \n", "27 Per Share Operating Cash Flow Per Share 1.135848e+01 \n", "\n", " Category Metric BYDDF \\\n", "0 Valuation Trailing P/E 2.000000e+01 \n", "1 Valuation Forward P/E 1.713596e+00 \n", "2 Valuation PEG Ratio NaN \n", "3 Valuation Price/Sales (ttm) 1.570778e-01 \n", "4 Valuation Price/Book 5.724422e-01 \n", "5 Valuation Enterprise Value/Revenue 3.500000e-02 \n", "6 Valuation Enterprise Value/EBITDA 2.490000e-01 \n", "7 Financial Highlights Market Cap 1.291994e+11 \n", "8 Financial Highlights Enterprise Value 2.897114e+10 \n", "9 Financial Highlights Revenue (ttm) 8.225185e+11 \n", "10 Financial Highlights Gross Profit (ttm) 1.564718e+11 \n", "11 Financial Highlights EBITDA 1.165454e+11 \n", "12 Financial Highlights Net Income (ttm) 4.481004e+10 \n", "13 Profitability Profit Margin 5.452000e-02 \n", "14 Profitability Operating Margin 4.946000e-02 \n", "15 Profitability Gross Margin 1.902300e-01 \n", "16 Profitability EBITDA Margin 1.416900e-01 \n", "17 Profitability Return on Assets 4.032000e-02 \n", "18 Profitability Return on Equity 2.306600e-01 \n", "19 Liquidity Current Ratio 8.110000e-01 \n", "20 Liquidity Quick Ratio 4.300000e-01 \n", "21 Liquidity Total Cash 1.533910e+11 \n", "22 Liquidity Total Debt 4.112797e+10 \n", "23 Liquidity Debt/Equity 1.670800e+01 \n", "24 Per Share Earnings Per Share (ttm) 7.100000e-01 \n", "25 Per Share Book Value Per Share 2.480600e+01 \n", "26 Per Share Revenue Per Share 9.412500e+01 \n", "27 Per Share Operating Cash Flow Per Share 3.578402e+01 \n", "\n", " Category ... MULN Category \\\n", "0 Valuation ... NaN Valuation \n", "1 Valuation ... 8.800000e-02 Valuation \n", "2 Valuation ... NaN Valuation \n", "3 Valuation ... 7.787777e-02 Valuation \n", "4 Valuation ... NaN Valuation \n", "5 Valuation ... 3.047000e+00 Valuation \n", "6 Valuation ... -1.190000e-01 Valuation \n", "7 Financial Highlights ... 6.955740e+05 Financial Highlights \n", "8 Financial Highlights ... 2.721857e+07 Financial Highlights \n", "9 Financial Highlights ... 8.931612e+06 Financial Highlights \n", "10 Financial Highlights ... -2.153492e+07 Financial Highlights \n", "11 Financial Highlights ... -2.293505e+08 Financial Highlights \n", "12 Financial Highlights ... -4.391060e+08 Financial Highlights \n", "13 Profitability ... 0.000000e+00 Profitability \n", "14 Profitability ... -1.081451e+01 Profitability \n", "15 Profitability ... -2.411090e+00 Profitability \n", "16 Profitability ... 0.000000e+00 Profitability \n", "17 Profitability ... -8.461600e-01 Profitability \n", "18 Profitability ... -1.851312e+01 Profitability \n", "19 Liquidity ... 2.530000e-01 Liquidity \n", "20 Liquidity ... 7.000000e-03 Liquidity \n", "21 Liquidity ... 1.404708e+06 Liquidity \n", "22 Liquidity ... 2.518013e+07 Liquidity \n", "23 Liquidity ... NaN Liquidity \n", "24 Per Share ... -4.302852e+04 Per Share \n", "25 Per Share ... -7.148243e+03 Per Share \n", "26 Per Share ... 8.751330e+02 Per Share \n", "27 Per Share ... -1.192432e+01 Per Share \n", "\n", " Metric NIO Category \\\n", "0 Trailing P/E NaN Valuation \n", "1 Forward P/E -5.294117e+00 Valuation \n", "2 PEG Ratio NaN Valuation \n", "3 Price/Sales (ttm) 1.575678e-01 Valuation \n", "4 Price/Book -2.571429e+01 Valuation \n", "5 Enterprise Value/Revenue 4.120000e-01 Valuation \n", "6 Enterprise Value/EBITDA -1.704000e+00 Valuation \n", "7 Market Cap 1.069218e+10 Financial Highlights \n", "8 Enterprise Value 2.794399e+10 Financial Highlights \n", "9 Revenue (ttm) 6.785765e+10 Financial Highlights \n", "10 Gross Profit (ttm) 6.924585e+09 Financial Highlights \n", "11 EBITDA -1.639825e+10 Financial Highlights \n", "12 Net Income (ttm) -2.429083e+10 Financial Highlights \n", "13 Profit Margin -3.579700e-01 Profitability \n", "14 Operating Margin -5.333000e-01 Profitability \n", "15 Gross Margin 1.020500e-01 Profitability \n", "16 EBITDA Margin -2.416600e-01 Profitability \n", "17 Return on Assets -1.414500e-01 Profitability \n", "18 Return on Equity -1.500650e+00 Profitability \n", "19 Current Ratio 8.370000e-01 Liquidity \n", "20 Quick Ratio 5.090000e-01 Liquidity \n", "21 Total Cash 1.972245e+10 Liquidity \n", "22 Total Debt 3.035403e+10 Liquidity \n", "23 Debt/Equity 4.149760e+02 Liquidity \n", "24 Earnings Per Share (ttm) -1.630000e+00 Per Share \n", "25 Book Value Per Share -1.750000e-01 Per Share \n", "26 Revenue Per Share 3.282800e+01 Per Share \n", "27 Operating Cash Flow Per Share 0.000000e+00 Per Share \n", "\n", " Metric RIVN Category \\\n", "0 Trailing P/E NaN Valuation \n", "1 Forward P/E -4.434307e+00 Valuation \n", "2 PEG Ratio NaN Valuation \n", "3 Price/Sales (ttm) 2.907481e+00 Valuation \n", "4 Price/Book 2.237981e+00 Valuation \n", "5 Enterprise Value/Revenue 2.382000e+00 Valuation \n", "6 Enterprise Value/EBITDA -4.100000e+00 Valuation \n", "7 Market Cap 1.455485e+10 Financial Highlights \n", "8 Enterprise Value 1.192613e+10 Financial Highlights \n", "9 Revenue (ttm) 5.006000e+09 Financial Highlights \n", "10 Gross Profit (ttm) -4.670000e+08 Financial Highlights \n", "11 EBITDA -2.909000e+09 Financial Highlights \n", "12 Net Income (ttm) -3.846000e+09 Financial Highlights \n", "13 Profit Margin -7.682800e-01 Profitability \n", "14 Operating Margin -5.282300e-01 Profitability \n", "15 Gross Margin -9.329000e-02 Profitability \n", "16 EBITDA Margin -5.811000e-01 Profitability \n", "17 Return on Assets -1.544500e-01 Profitability \n", "18 Return on Equity -5.372400e-01 Profitability \n", "19 Current Ratio 3.728000e+00 Liquidity \n", "20 Quick Ratio 2.722000e+00 Liquidity \n", "21 Total Cash 7.178000e+09 Liquidity \n", "22 Total Debt 4.869000e+09 Liquidity \n", "23 Debt/Equity 7.815400e+01 Liquidity \n", "24 Earnings Per Share (ttm) -3.690000e+00 Per Share \n", "25 Book Value Per Share 5.429000e+00 Per Share \n", "26 Revenue Per Share 4.755000e+00 Per Share \n", "27 Operating Cash Flow Per Share -5.335686e-01 Per Share \n", "\n", " Metric TM \n", "0 Trailing P/E 7.441575e+00 \n", "1 Forward P/E 1.150190e+01 \n", "2 PEG Ratio NaN \n", "3 Price/Sales (ttm) 4.924489e-03 \n", "4 Price/Book 6.592602e-02 \n", "5 Enterprise Value/Revenue 6.900000e-01 \n", "6 Enterprise Value/EBITDA 4.703000e+00 \n", "7 Market Cap 2.365562e+11 \n", "8 Enterprise Value 3.314055e+13 \n", "9 Revenue (ttm) 4.803671e+13 \n", "10 Gross Profit (ttm) 9.578038e+12 \n", "11 EBITDA 7.046819e+12 \n", "12 Net Income (ttm) 4.765086e+12 \n", "13 Profit Margin 9.920000e-02 \n", "14 Operating Margin 9.028000e-02 \n", "15 Gross Margin 1.993900e-01 \n", "16 EBITDA Margin 1.467000e-01 \n", "17 Return on Assets 3.263000e-02 \n", "18 Return on Equity 1.328300e-01 \n", "19 Current Ratio 1.260000e+00 \n", "20 Quick Ratio 8.270000e-01 \n", "21 Total Cash 8.982404e+12 \n", "22 Total Debt 3.879288e+13 \n", "23 Debt/Equity 1.051900e+02 \n", "24 Earnings Per Share (ttm) 2.439000e+01 \n", "25 Book Value Per Share 2.753086e+03 \n", "26 Revenue Per Share 2.265462e+03 \n", "27 Operating Cash Flow Per Share 2.836508e+03 \n", "\n", "[28 rows x 33 columns]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.concat(dflist, axis=1) " ] }, { "cell_type": "code", "execution_count": 24, "id": "987f7b10", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 3.258384e+01\n", "1 3.475610e+01\n", "2 NaN\n", "3 3.402228e+00\n", "4 6.826674e+00\n", "5 3.468000e+00\n", "6 1.736200e+01\n", "7 2.279622e+12\n", "8 2.323619e+12\n", "9 6.700380e+11\n", "10 3.323830e+11\n", "11 1.338320e+11\n", "12 7.062300e+10\n", "13 1.054000e-01\n", "14 1.143200e-01\n", "15 4.960700e-01\n", "16 1.997400e-01\n", "17 7.699000e-02\n", "18 2.477000e-01\n", "19 1.024000e+00\n", "20 7.680000e-01\n", "21 9.318000e+10\n", "22 1.595700e+11\n", "23 4.780800e+01\n", "24 6.560000e+00\n", "25 3.131100e+01\n", "26 6.337300e+01\n", "27 1.135848e+01\n", "Name: AMZN, dtype: float64" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "adbdcae1", "metadata": {}, "outputs": [], "source": [ "obj = obb.equity.fundamental.filings(symbol, form_type='10-K')\n", "r = obj.results[0]\n", "latest_10k_url = r.report_url\n", "latest_10k_url\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5d0d0a91", "metadata": {}, "outputs": [], "source": [ "client = MemoryClient()\n", "\n", "messages = [\n", " {\"role\": \"user\", \"content\": \"What is Item 1 from the latest annual report from Tesla (symbol TSLA)\"},\n", " {\"role\": \"assistant\", \"content\": result['content']},\n", "]\n", "client.add(messages, user_id=\"tearsheet-TSLA\", output_format=\"v1.1\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f6047496", "metadata": {}, "outputs": [], "source": [ "messages = [\n", " {\"role\": \"user\", \"content\": \"Thinking of making a sandwich. What do you recommend?\"},\n", " {\"role\": \"assistant\", \"content\": \"How about adding some cheese for extra flavor?\"},\n", " {\"role\": \"user\", \"content\": \"Actually, I don't like cheese.\"},\n", " {\"role\": \"assistant\", \"content\": \"I'll remember that you don't like cheese for future recommendations.\"}\n", "]\n", "client.add(messages, user_id=\"alex\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "99f27ec6", "metadata": {}, "outputs": [], "source": [ "# Example showing location and preference-aware recommendations\n", "query = \"I'm craving some pizza. Any recommendations?\"\n", "filters = {\n", " \"AND\": [\n", " {\n", " \"user_id\": \"alex\"\n", " }\n", " ]\n", "}\n", "client.search(query, version=\"v2\", filters=filters)" ] }, { "cell_type": "code", "execution_count": null, "id": "3b06e2ee", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import aiohttp\n", "import talib\n", "from datetime import datetime, timedelta\n", "from typing import Dict, Any\n", "\n", "\n", "class MarketData:\n", " \"\"\"Handles all market data fetching operations.\"\"\"\n", "\n", " def __init__(self):\n", " self.api_key = os.getenv(\"TIINGO_API_KEY\")\n", " if not self.api_key:\n", " raise ValueError(\"TIINGO_API_KEY not found in environment\")\n", "\n", " self.headers = {\"Content-Type\": \"application/json\", \"Authorization\": f\"Token {self.api_key}\"}\n", "\n", " async def get_historical_data(self, symbol: str, lookback_days: int = 365) -> pd.DataFrame:\n", " \"\"\"\n", " Fetch historical daily data for a given symbol.\n", "\n", " Args:\n", " symbol (str): The stock symbol to fetch data for.\n", " lookback_days (int): Number of days to look back from today.\n", "\n", " Returns:\n", " pd.DataFrame: DataFrame containing historical market data.\n", "\n", " Raises:\n", " ValueError: If the symbol is invalid or no data is returned.\n", " Exception: For other unexpected issues during the fetch operation.\n", " \"\"\"\n", " end_date = datetime.now()\n", " start_date = end_date - timedelta(days=lookback_days)\n", "\n", " url = (\n", " f\"https://api.tiingo.com/tiingo/daily/{symbol}/prices?\"\n", " f'startDate={start_date.strftime(\"%Y-%m-%d\")}&'\n", " f'endDate={end_date.strftime(\"%Y-%m-%d\")}'\n", " )\n", "\n", " try:\n", " async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session:\n", " async with session.get(url, headers=self.headers) as response:\n", " if response.status == 404:\n", " raise ValueError(f\"Symbol not found: {symbol}\")\n", " response.raise_for_status()\n", " data = await response.json()\n", "\n", " if not data:\n", " raise ValueError(f\"No data returned for {symbol}\")\n", "\n", " df = pd.DataFrame(data)\n", " df[\"date\"] = pd.to_datetime(df[\"date\"])\n", " df.set_index(\"date\", inplace=True)\n", "\n", " df[[\"open\", \"high\", \"low\", \"close\"]] = df[[\"adjOpen\", \"adjHigh\", \"adjLow\", \"adjClose\"]].round(2)\n", " df[\"volume\"] = df[\"adjVolume\"].astype(int)\n", " df[\"symbol\"] = symbol.upper()\n", "\n", " return df\n", "\n", " except aiohttp.ClientError as e:\n", " raise ConnectionError(f\"Network error while fetching data for {symbol}: {e}\")\n", " except ValueError as ve:\n", " raise ve # Propagate value errors (symbol issues, no data, etc.)\n", " except Exception as e:\n", " raise Exception(f\"Unexpected error fetching data for {symbol}: {e}\")\n", "\n", "\n", "class TechnicalAnalysis:\n", " \"\"\"Technical analysis toolkit using TA-Lib for improved performance.\"\"\"\n", "\n", " @staticmethod\n", " def add_core_indicators(df: pd.DataFrame) -> pd.DataFrame:\n", " \"\"\"Add a core set of technical indicators using TA-Lib.\"\"\"\n", " try:\n", " # Convert to numpy arrays for TA-Lib (required format)\n", " high = df[\"high\"].values\n", " low = df[\"low\"].values\n", " close = df[\"close\"].values\n", " volume = df[\"volume\"].values\n", "\n", " # Adding trend indicators (Simple Moving Averages)\n", " df[\"sma_20\"] = talib.SMA(close, timeperiod=20)\n", " df[\"sma_50\"] = talib.SMA(close, timeperiod=50)\n", " df[\"sma_200\"] = talib.SMA(close, timeperiod=200)\n", "\n", " # Adding volatility indicators\n", " df[\"atr\"] = talib.ATR(high, low, close, timeperiod=14)\n", "\n", " # Calculate Average Daily Range Percentage manually\n", " daily_range = df[\"high\"] - df[\"low\"]\n", " adr = daily_range.rolling(window=20).mean()\n", " df[\"adrp\"] = (adr / df[\"close\"]) * 100\n", "\n", " # Average volume (20-day)\n", " df[\"avg_20d_vol\"] = df[\"volume\"].rolling(window=20).mean()\n", "\n", " # Adding momentum indicators\n", " df[\"rsi\"] = talib.RSI(close, timeperiod=14)\n", "\n", " # MACD indicator\n", " macd, macd_signal, macd_hist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)\n", " df[\"macd\"] = macd\n", " df[\"macd_signal\"] = macd_signal\n", " df[\"macd_histogram\"] = macd_hist\n", "\n", " return df\n", "\n", " except KeyError as e:\n", " raise KeyError(f\"Missing column in input DataFrame: {str(e)}\")\n", " except Exception as e:\n", " raise Exception(f\"Error calculating indicators: {str(e)}\")\n", "\n", " @staticmethod\n", " def check_trend_status(df: pd.DataFrame) -> Dict[str, Any]:\n", " \"\"\"Analyze the current trend status.\"\"\"\n", " if df.empty:\n", " raise ValueError(\"DataFrame is empty. Ensure it contains valid data.\")\n", "\n", " latest = df.iloc[-1]\n", "\n", " # Handle potential NaN values\n", " macd_bullish = False\n", " if not pd.isna(latest[\"macd\"]) and not pd.isna(latest[\"macd_signal\"]):\n", " macd_bullish = latest[\"macd\"] > latest[\"macd_signal\"]\n", "\n", " return {\n", " \"above_20sma\": latest[\"close\"] > latest[\"sma_20\"] if not pd.isna(latest[\"sma_20\"]) else False,\n", " \"above_50sma\": latest[\"close\"] > latest[\"sma_50\"] if not pd.isna(latest[\"sma_50\"]) else False,\n", " \"above_200sma\": latest[\"close\"] > latest[\"sma_200\"] if not pd.isna(latest[\"sma_200\"]) else False,\n", " \"20_50_bullish\": latest[\"sma_20\"] > latest[\"sma_50\"] if not pd.isna(latest[\"sma_20\"]) and not pd.isna(latest[\"sma_50\"]) else False,\n", " \"50_200_bullish\": latest[\"sma_50\"] > latest[\"sma_200\"] if not pd.isna(latest[\"sma_50\"]) and not pd.isna(latest[\"sma_200\"]) else False,\n", " \"rsi\": latest[\"rsi\"] if not pd.isna(latest[\"rsi\"]) else 0,\n", " \"macd_bullish\": macd_bullish,\n", " }\n", "\n", "\n", "# Usage example\n", "async def analyze_symbol(symbol: str):\n", " \"\"\"Complete analysis workflow for a given symbol.\"\"\"\n", " market_data = MarketData()\n", " tech_analysis = TechnicalAnalysis()\n", "\n", " df = await market_data.get_historical_data(symbol)\n", " df = tech_analysis.add_core_indicators(df)\n", " trend = tech_analysis.check_trend_status(df)\n", "\n", " analysis = f\"\"\"\n", "Technical Analysis for {symbol}:\n", "\n", "Trend Analysis:\n", "- Above 20 SMA: {'✅' if trend['above_20sma'] else '❌'}\n", "- Above 50 SMA: {'✅' if trend['above_50sma'] else '❌'}\n", "- Above 200 SMA: {'✅' if trend['above_200sma'] else '❌'}\n", "- 20/50 SMA Bullish Cross: {'✅' if trend['20_50_bullish'] else '❌'}\n", "- 50/200 SMA Bullish Cross: {'✅' if trend['50_200_bullish'] else '❌'}\n", "\n", "Momentum:\n", "- RSI (14): {trend['rsi']:.2f}\n", "- MACD Bullish: {'✅' if trend['macd_bullish'] else '❌'}\n", "\n", "Latest Price: ${df['close'].iloc[-1]:.2f}\n", "Average True Range (14): {df['atr'].iloc[-1]:.2f}\n", "Average Daily Range Percentage: {df['adrp'].iloc[-1]:.2f}%\n", "Average Volume (20D): {df['avg_20d_vol'].iloc[-1]:,.0f}\n", "\"\"\"\n", "# print(analysis)\n", " return df, trend, analysis\n", "\n", "# Example usage:\n", "# df, trend = await analyze_symbol(\"AAPL\")" ] }, { "cell_type": "code", "execution_count": null, "id": "39a5ab47", "metadata": {}, "outputs": [], "source": [ "temp_dir = \"tmp/tx0ybr2zo\" \n" ] }, { "cell_type": "code", "execution_count": null, "id": "a7512776", "metadata": {}, "outputs": [], "source": [ "df, trend, analysis_str = await analyze_symbol(symbol)\n", "with open(f'{temp_dir}/{symbol}_technicals.md', 'w', encoding='utf-8') as f:\n", " f.write(analysis_str)\n", "print(analysis_str)" ] }, { "cell_type": "code", "execution_count": null, "id": "1f3ea996", "metadata": {}, "outputs": [], "source": [ "from openai import OpenAI\n", "from mem0 import Memory\n", "\n", "openai_client = OpenAI()\n", "memory = Memory()\n", "\n", "def chat_with_memories(message: str, user_id: str = \"default_user\") -> str:\n", " # Retrieve relevant memories\n", " relevant_memories = memory.search(query=message, user_id=user_id, limit=3)\n", " memories_str = \"\\n\".join(f\"- {entry['memory']}\" for entry in relevant_memories[\"results\"])\n", "\n", " # Generate Assistant response\n", " system_prompt = f\"You are a helpful AI. Answer the question based on query and memories.\\nUser Memories:\\n{memories_str}\"\n", " messages = [{\"role\": \"system\", \"content\": system_prompt}, {\"role\": \"user\", \"content\": message}]\n", " response = openai_client.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " assistant_response = response.choices[0].message.content\n", "\n", " # Create new memories from the conversation\n", " messages.append({\"role\": \"assistant\", \"content\": assistant_response})\n", " memory.add(messages, user_id=user_id)\n", "\n", " return assistant_response\n", "\n", "def main():\n", " print(\"Chat with AI (type 'exit' to quit)\")\n", " while True:\n", " user_input = input(\"You: \").strip()\n", " if user_input.lower() == 'exit':\n", " print(\"Goodbye!\")\n", " break\n", " print(f\"AI: {chat_with_memories(user_input)}\")\n", "\n", "main()" ] }, { "cell_type": "code", "execution_count": null, "id": "824c5a6b", "metadata": {}, "outputs": [], "source": [ "filters = {\n", " \"AND\": [\n", " {\n", " \"user_id\": \"alex\"\n", " }\n", " ]\n", "}\n", "\n", "all_memories = client.get_all(version=\"v2\", filters=filters, page=1, page_size=50)\n", "\n", "all_memories\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3fd2a735", "metadata": {}, "outputs": [], "source": [ "\n", "def extract(url):\n", " extractor = SECItem1Extractor(url)\n", "\n", " # Analyze document structure first\n", " print(\"Document Structure Analysis:\")\n", " structure = extractor.get_document_structure()\n", "\n", " print(f\"\\nFound {len(structure['anchors'])} anchors:\")\n", " for anchor in structure['anchors'][:10]: # Show first 10\n", " print(f\" - {anchor['name']}: {anchor['text']}\")\n", "\n", " print(f\"\\nFound {len(structure['headings'])} item-related headings:\")\n", " for heading in structure['headings']:\n", " print(f\" - {heading['tag']}: {heading['text']}\")\n", "\n", " print(f\"\\nFound {len(structure['toc_links'])} TOC links:\")\n", " for link in structure['toc_links']:\n", " print(f\" - {link['text']} -> {link['href']}\")\n", "\n", " # Extract Item 1\n", " print(\"\\n\" + \"=\"*50)\n", " print(\"EXTRACTING ITEM 1\")\n", " print(\"=\"*50)\n", "\n", " result = extractor.extract_item1()\n", " if result:\n", " print(f\"Successfully extracted using method: {result['method']}\")\n", " print(f\"Word count: {result['word_count']}\")\n", " print(f\"First 500 characters:\\n{result['content'][:500]}...\")\n", " else:\n", " print(\"Failed to extract Item 1 content\")\n", " return result\n", "\n", "\n", "result = extract(latest_10k_url)\n", "print(result['content'])\n" ] }, { "cell_type": "code", "execution_count": null, "id": "e50df228", "metadata": {}, "outputs": [], "source": [ "print(result['content'])\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ccd856ae", "metadata": {}, "outputs": [], "source": [ "# AlphaVantage overview\n", "url = f\"https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={os.environ['ALPHAVANTAGE_API_KEY']}\"\n", "r = requests.get(url)\n", "data = r.json()\n", "with open(f'{temp_dir}/{symbol}_fundamintals_av.json', 'w', encoding='utf-8') as f:\n", " f.write(json.dumps(data))\n", "pd.DataFrame(data, index=[1]).transpose()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3d889472", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "bfb4e885", "metadata": {}, "outputs": [], "source": [ "exchange = data['Exchange']\n", "\n", "morningstarmap = {'NYSE': 'xnys',\n", " 'NASDAQ': 'xnas'\n", " }\n" ] }, { "cell_type": "code", "execution_count": null, "id": "bc5e2885", "metadata": {}, "outputs": [], "source": [ "now = datetime.now()\n", "end_date = now.strftime('%Y%m%dT%H%M')\n", "sdate = now - timedelta(days=2)\n", "# sdate = datetime(now.year, now.month-1, now.day)\n", "start_date = sdate.strftime('%Y%m%dT%H%M')\n", "start_date, end_date" ] }, { "cell_type": "code", "execution_count": null, "id": "d411abbc", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.alphavantage.co/query?function=NEWS_SENTIMENT&tickers={symbol}&apikey={os.environ[\"ALPHAVANTAGE_API_KEY\"]}&time_from={start_date}&time_to={end_date}'\n", "\n", "r = requests.get(url)\n", "data = r.json()\n", "\n", "for item in data['feed']:\n", " markdown_str = \"\"\n", " date_object = datetime.strptime(item['time_published'], \"%Y%m%dT%H%M%S\")\n", " display_title = item['title'].replace(\"$\", r\"\\$\") # so Markdown doesn't interpret as latex escape\n", " description = item['summary'].replace(\"$\", r\"\\$\")\n", " markdown_str += f\"[{str(date_object)} {display_title}]({item['url']})\\n {description}\"\n", " display(Markdown(markdown_str))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9627b611", "metadata": {}, "outputs": [], "source": [ "NEWSAPI_API_KEY = os.environ['NEWSAPI_API_KEY']\n", "\n", "page_size = 100\n", "q = company\n", "date_24h_ago = datetime.now() - timedelta(hours=24)\n", "formatted_date = date_24h_ago.strftime(\"%Y-%m-%dT%H:%M:%S\")\n", "print(f\"Fetching top {page_size} stories matching {q} since {formatted_date} from NewsAPI\")\n", "\n", "api = NewsApiClient(api_key=NEWSAPI_API_KEY)\n", "# sources = api.get_sources()\n", "# pd.DataFrame(sources['sources'])\n", "\n", "baseurl = 'https://newsapi.org/v2/everything'\n", "\n", "# Define search parameters\n", "params = {\n", " 'q': q,\n", " 'from': formatted_date,\n", " 'language': 'en',\n", " 'sortBy': 'relevancy',\n", " 'apiKey': NEWSAPI_API_KEY,\n", " 'pageSize': 100\n", "}\n", "\n", "# Make API call with headers and params\n", "response = requests.get(baseurl, params=params, timeout=60)\n", "if response.status_code != 200:\n", " print('ERROR: API call failed.')\n", " print(response.text)\n", "else:\n", " data = response.json()\n", " newsapi_df = pd.DataFrame(data['articles'])\n", "\n", " # Print the articles\n", " markdown_str = \"\"\n", " for row in newsapi_df.itertuples():\n", "# date_object = datetime.strptime(row.publishedAt, \"%Y%m%dT%H%M%S\")\n", " display_title = row.title.replace(\"$\", r\"\\$\") # so Markdown doesn't interpret as latex escape\n", " markdown_str += f\"[{row.publishedAt} {display_title}]({row.url}) \\n\\n\"\n", "\n", " display(Markdown(markdown_str))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "7f4c4063", "metadata": {}, "outputs": [], "source": [ "now = datetime.now()\n", "end_date = now.strftime('%Y-%m-%d')\n", "# start_date = datetime.now() - timedelta(days=30)\n", "sdate = datetime(now.year, now.month-1, now.day)\n", "start_date = sdate.strftime('%Y-%m-%d')\n", "start_date, end_date\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a792f20b", "metadata": {}, "outputs": [], "source": [ "API_KEY = os.environ['NEWSFILTER_API_KEY']\n", "API_ENDPOINT = \"https://api.newsfilter.io/search?token={}\".format(API_KEY)\n", "\n", "# Define the news search parameters\n", "queryString = f\"symbols:{symbol} AND publishedAt:[{start_date} TO {end_date}]\"\n", "\n", "payload = {\n", " \"queryString\": queryString,\n", " \"from\": 0,\n", " \"size\": 10\n", "}\n", "\n", "# Send the search query to the Search API\n", "response = requests.post(API_ENDPOINT, json=payload)\n", "\n", "# Read the response\n", "articles = response.json()\n", "\n", "\n", "# Read the response\n", "articles = response.json()\n", "\n", "for item in articles['articles']:\n", " markdown_str = \"\"\n", " date_array = item['publishedAt'].split(\"T\")\n", " datestr = date_array[0] + \"T\" + date_array[1][:8]\n", "# print(item['publishedAt'])\n", "# print(date_array)\n", "# print(datestr)\n", " date_object = datetime.strptime(datestr, \"%Y-%m-%dT%H:%M:%S\")\n", " display_title = item['title'].replace(\"$\", r\"\\$\") # so Markdown doesn't interpret as latex escape\n", " description = item['description'].replace(\"$\", r\"\\$\")\n", "\n", " markdown_str += f\"[{str(date_object)} {display_title}]({item['url']})\\n {description}\"\n", " display(Markdown(markdown_str))" ] }, { "cell_type": "code", "execution_count": null, "id": "60301a18", "metadata": {}, "outputs": [], "source": [ "# https://sethhobson.com/2025/01/building-a-stock-analysis-server-with-mcp-part-1/\n", "\n", "class MarketData:\n", " \"\"\"Handles all market data fetching operations.\"\"\"\n", "\n", " def __init__(self):\n", " self.api_key = os.getenv(\"TIINGO_API_KEY\")\n", " if not self.api_key:\n", " raise ValueError(\"TIINGO_API_KEY not found in environment\")\n", "\n", " self.headers = {\"Content-Type\": \"application/json\", \"Authorization\": f\"Token {self.api_key}\"}\n", "\n", " async def get_historical_data(self, symbol: str, lookback_days: int = 365) -> pd.DataFrame:\n", " \"\"\"\n", " Fetch historical daily data for a given symbol.\n", "\n", " Args:\n", " symbol (str): The stock symbol to fetch data for.\n", " lookback_days (int): Number of days to look back from today.\n", "\n", " Returns:\n", " pd.DataFrame: DataFrame containing historical market data.\n", "\n", " Raises:\n", " ValueError: If the symbol is invalid or no data is returned.\n", " Exception: For other unexpected issues during the fetch operation.\n", " \"\"\"\n", " end_date = datetime.now()\n", " start_date = end_date - timedelta(days=lookback_days)\n", "\n", " url = (\n", " f\"https://api.tiingo.com/tiingo/daily/{symbol}/prices?\"\n", " f'startDate={start_date.strftime(\"%Y-%m-%d\")}&'\n", " f'endDate={end_date.strftime(\"%Y-%m-%d\")}'\n", " )\n", "\n", " try:\n", " async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session:\n", " async with session.get(url, headers=self.headers) as response:\n", " if response.status == 404:\n", " raise ValueError(f\"Symbol not found: {symbol}\")\n", " response.raise_for_status()\n", " data = await response.json()\n", "\n", " if not data:\n", " raise ValueError(f\"No data returned for {symbol}\")\n", "\n", " df = pd.DataFrame(data)\n", " df[\"date\"] = pd.to_datetime(df[\"date\"])\n", " df.set_index(\"date\", inplace=True)\n", "\n", " df[[\"open\", \"high\", \"low\", \"close\"]] = df[[\"adjOpen\", \"adjHigh\", \"adjLow\", \"adjClose\"]].round(2)\n", " df[\"volume\"] = df[\"adjVolume\"].astype(int)\n", " df[\"symbol\"] = symbol.upper()\n", "\n", " return df\n", "\n", " except aiohttp.ClientError as e:\n", " raise ConnectionError(f\"Network error while fetching data for {symbol}: {e}\")\n", " except ValueError as ve:\n", " raise ve # Propagate value errors (symbol issues, no data, etc.)\n", " except Exception as e:\n", " raise Exception(f\"Unexpected error fetching data for {symbol}: {e}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "344977f9", "metadata": {}, "outputs": [], "source": [ "class TechnicalAnalysis:\n", " \"\"\"Technical analysis toolkit with improved performance and readability.\"\"\"\n", "\n", " @staticmethod\n", " def add_core_indicators(df: pd.DataFrame) -> pd.DataFrame:\n", " \"\"\"Add a core set of technical indicators.\"\"\"\n", " try:\n", " # Adding trend indicators\n", " df[\"sma_20\"] = ta.sma(df[\"close\"], length=20)\n", " df[\"sma_50\"] = ta.sma(df[\"close\"], length=50)\n", " df[\"sma_200\"] = ta.sma(df[\"close\"], length=200)\n", "\n", " # Adding volatility indicators and volume\n", " daily_range = df[\"high\"].sub(df[\"low\"])\n", " adr = daily_range.rolling(window=20).mean()\n", " df[\"adrp\"] = adr.div(df[\"close\"]).mul(100)\n", " df[\"avg_20d_vol\"] = df[\"volume\"].rolling(window=20).mean()\n", "\n", " # Adding momentum indicators\n", " df[\"atr\"] = ta.atr(df[\"high\"], df[\"low\"], df[\"close\"], length=14)\n", " df[\"rsi\"] = ta.rsi(df[\"close\"], length=14)\n", " macd = ta.macd(df[\"close\"], fast=12, slow=26, signal=9)\n", " if macd is not None:\n", " df = pd.concat([df, macd], axis=1)\n", "\n", " return df\n", "\n", " except KeyError as e:\n", " raise KeyError(f\"Missing column in input DataFrame: {str(e)}\")\n", " except Exception as e:\n", " raise Exception(f\"Error calculating indicators: {str(e)}\")\n", "\n", " @staticmethod\n", " def check_trend_status(df: pd.DataFrame) -> Dict[str, Any]:\n", " \"\"\"Analyze the current trend status.\"\"\"\n", " if df.empty:\n", " raise ValueError(\"DataFrame is empty. Ensure it contains valid data.\")\n", "\n", " latest = df.iloc[-1]\n", " return {\n", " \"above_20sma\": latest[\"close\"] > latest[\"sma_20\"],\n", " \"above_50sma\": latest[\"close\"] > latest[\"sma_50\"],\n", " \"above_200sma\": latest[\"close\"] > latest[\"sma_200\"],\n", " \"20_50_bullish\": latest[\"sma_20\"] > latest[\"sma_50\"],\n", " \"50_200_bullish\": latest[\"sma_50\"] > latest[\"sma_200\"],\n", " \"rsi\": latest[\"rsi\"],\n", " \"macd_bullish\": latest.get(\"MACD_12_26_9\", 0) > latest.get(\"MACDs_12_26_9\", 0),\n", " }" ] }, { "cell_type": "code", "execution_count": null, "id": "48f09d4b", "metadata": {}, "outputs": [], "source": [ "async def fetch_technical_analysis(symbol):\n", "\n", " market_data = MarketData()\n", " tech_analysis = TechnicalAnalysis()\n", " tadf = await market_data.get_historical_data(symbol)\n", " tadf = tech_analysis.add_core_indicators(tadf)\n", " trend = tech_analysis.check_trend_status(df)\n", " analysis = f\"\"\"\n", " Technical Analysis for {symbol}:\n", "\n", " Trend Analysis:\n", " - Above 20 SMA: {'✅' if trend['above_20sma'] else '❌'}\n", " - Above 50 SMA: {'✅' if trend['above_50sma'] else '❌'}\n", " - Above 200 SMA: {'✅' if trend['above_200sma'] else '❌'}\n", " - 20/50 SMA Bullish Cross: {'✅' if trend['20_50_bullish'] else '❌'}\n", " - 50/200 SMA Bullish Cross: {'✅' if trend['50_200_bullish'] else '❌'}\n", "\n", " Momentum:\n", " - RSI (14): {trend['rsi']:.2f}\n", " - MACD Bullish: {'✅' if trend['macd_bullish'] else '❌'}\n", "\n", " Latest Price: ${df['close'].iloc[-1]:.2f}\n", " Average True Range (14): {df['atr'].iloc[-1]:.2f}\n", " Average Daily Range Percentage: {df['adrp'].iloc[-1]:.2f}%\n", " Average Volume (20D): {df['avg_20d_vol'].iloc[-1]}\n", " \"\"\"\n", " return analysis\n", "\n", "print(await fetch_technical_analysis('TSLA'))\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9623d8cb", "metadata": {}, "outputs": [], "source": [ "\n", "print(analysis)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "e6ad54ef", "metadata": {}, "outputs": [], "source": [ "# open pages via selenium and firefox\n", "outputdir = \"htmldata\"\n", "\n", "# Print the formatted time\n", "print(datetime.now().strftime('%H:%M:%S'), \"Starting\", flush=True)\n", "\n", "firefox_app_path = '/Applications/Firefox.app'\n", "# Path to your geckodriver\n", "geckodriver_path = '/Users/drucev/webdrivers/geckodriver'\n", "# Set up Firefox options to use your existing profile\n", "# important for some sites that need a login, also a generic profile fingerprint that looks like a bot might get blocked\n", "firefox_profile_path = '/Users/drucev/Library/Application Support/Firefox/Profiles/x6dmpnoo.default-release-1'\n", "options = Options()\n", "options.profile = firefox_profile_path\n", "\n", "print(datetime.now().strftime('%H:%M:%S'), \"Initialized profile\", flush=True)\n", "\n", "# Create a Service object with the path\n", "service = Service(geckodriver_path)\n", "\n", "print(datetime.now().strftime('%H:%M:%S'), \"Initialized service\", flush=True)\n", "# Set up the Firefox driver\n", "driver = webdriver.Firefox(service=service, options=options)\n", "\n", "print(datetime.now().strftime('%H:%M:%S'), \"Initialized webdriver\", flush=True)\n", "sleeptime = 10\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d694ae26", "metadata": {}, "outputs": [], "source": [ "# Open a new tab\n", "def open_tab(driver, url):\n", " driver.execute_script(f\"window.open('{url}');\")\n", " # Switch to last one opened - sometimes hangs?\n", " # driver.switch_to.window(driver.window_handles[-1])\n", " # print(url)\n", " # time.sleep(sleeptime)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d3107671", "metadata": {}, "outputs": [], "source": [ "url = f\"https://stockcharts.com/h-sc/ui?s={symbol}&id=p33407302522&def=Y&listNum=1#\"\n", "source = \"Stockcharts\"\n", "# Open the page\n", "open_tab(driver, url)\n", "\n", "# Wait for the page to load\n", "# time.sleep(sleeptime)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "db5b36a6", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.bloomberg.com/search?query={company}'\n", "source = \"Bloomberg\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "b854cf04", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.reuters.com/site-search/?query={company}&offset=0'\n", "source = \"Reuters\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "38912e8f", "metadata": {}, "outputs": [], "source": [ "url = f'https://finance.yahoo.com/quote/{symbol}/news'\n", "source = \"Yahoo quote\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "b546c41f", "metadata": {}, "outputs": [], "source": [ "url = f'https://finance.yahoo.com/quote/{symbol}/key-statistics?ltr=1'\n", "source = \"Yahoo stats\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "b4b8e6ce", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.ft.com/search?q={company}'\n", "source = \"FT\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "936a210b", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.marketwatch.com/investing/stock/{symbol}?mod=search_symbol'\n", "source = \"Marketwatch\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "36bd4b7a", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.barrons.com/market-data/stocks/{symbol}?mod=searchresults_companyquotes&mod=searchbar&search_keywords={company}&search_statement_type=suggested'\n", "source = \"Barrons\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "ecf82b37", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.businessinsider.com/answers#{company}'\n", "\n", "source = \"Insider\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "07a59ba0", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.google.com/finance/quote/{symbol}:{exchange}'\n", "source = \"Google Finance\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "ca5dd4d3", "metadata": {}, "outputs": [], "source": [ "url = f'https://finviz.com/quote.ashx?t={symbol}&p=d'\n", "source = \"FinViz\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "a658c304", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.reddit.com/search?q={company}&include_over_18=on&sort=relevance&t=all'\n", "source = \"Reddit\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "42a06f35", "metadata": {}, "outputs": [], "source": [ "morn_exch = morningstarmap[exchange]\n", "url = f'https://www.morningstar.com/stocks/{morn_exch}/{symbol}/quote'\n", "source = \"Morningstar\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3d8ff0b6", "metadata": {}, "outputs": [], "source": [ "url = f'https://whalewisdom.com/stock/{symbol}'\n", "source = \"WhaleWisdom\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "fee0adb6", "metadata": {}, "outputs": [], "source": [ "url = f'https://www.gurufocus.com/stock/{symbol}/guru-trades'\n", "source = \"GuruFocus\"\n", "open_tab(driver, url)\n", "display(Markdown(f\"[{source}]({url})\"))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1c1162f6", "metadata": {}, "outputs": [], "source": [ "# https://www.barchart.com/stocks/highs-lows/lows?orderBy=highPercent1y&orderDir=asc\n", "# https://stockcharts.com/h-sc/ui?s=%24DJUSEN&id=p33407302522&def=Y&listNum=1\n", "# https://stockcharts.com/h-sc/ui?s=%24DJUSDN&id=p33407302522&def=Y&listNum=1" ] }, { "cell_type": "code", "execution_count": null, "id": "375786c4", "metadata": {}, "outputs": [], "source": [ "# driver.close()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "47e83998", "metadata": {}, "outputs": [], "source": [ "import plotly.graph_objects as go\n", "from plotly.subplots import make_subplots\n", "import pandas as pd\n", "import numpy as np\n", "import yfinance as yf\n", "from datetime import datetime, timedelta\n", "\n", "def create_advanced_stock_chart(symbol, period='2y'):\n", " \"\"\"\n", " Create an advanced stock chart with candlesticks, moving averages, volume, and relative performance\n", "\n", " Parameters:\n", " symbol (str): Stock symbol (e.g., 'TSLA')\n", " period (str): Time period ('1y', '2y', '5y', etc.)\n", " \"\"\"\n", "\n", " # Fetch stock data\n", " stock = yf.Ticker(symbol)\n", " df = stock.history(period=period)\n", "\n", " # Fetch S&P 500 data for relative performance\n", " spy = yf.Ticker('SPY')\n", " spy_df = spy.history(period=period)\n", "\n", " # Calculate moving averages\n", " df['MA_13'] = df['Close'].rolling(window=13).mean() # ~13 weeks (65 trading days)\n", " df['MA_52'] = df['Close'].rolling(window=52).mean() # ~52 weeks (260 trading days)\n", "\n", " # Calculate relative performance vs S&P 500\n", " # Normalize both to starting point and calculate ratio\n", " stock_normalized = df['Close'] / df['Close'].iloc[0]\n", " spy_normalized = spy_df['Close'] / spy_df['Close'].iloc[0]\n", " relative_performance = stock_normalized / spy_normalized\n", "\n", " # Create subplots\n", " fig = make_subplots(\n", " rows=3, cols=1,\n", " shared_xaxes=True,\n", " vertical_spacing=0.02,\n", " row_heights=[0.6, 0.2, 0.2],\n", " subplot_titles=(f'{symbol} Stock Chart', 'Volume', f'{symbol} vs S&P 500 Relative Performance')\n", " )\n", "\n", " # Add candlestick chart\n", " fig.add_trace(\n", " go.Candlestick(\n", " x=df.index,\n", " open=df['Open'],\n", " high=df['High'],\n", " low=df['Low'],\n", " close=df['Close'],\n", " name=symbol,\n", " showlegend=False\n", " ),\n", " row=1, col=1\n", " )\n", "\n", " # Add 13-week moving average\n", " fig.add_trace(\n", " go.Scatter(\n", " x=df.index,\n", " y=df['MA_13'],\n", " mode='lines',\n", " name='13-Week MA',\n", " line=dict(color='blue', width=1.5),\n", " opacity=0.8\n", " ),\n", " row=1, col=1\n", " )\n", "\n", " # Add 52-week moving average\n", " fig.add_trace(\n", " go.Scatter(\n", " x=df.index,\n", " y=df['MA_52'],\n", " mode='lines',\n", " name='52-Week MA',\n", " line=dict(color='red', width=1.5),\n", " opacity=0.8\n", " ),\n", " row=1, col=1\n", " )\n", "\n", " # Add volume bars\n", " colors = ['red' if close < open else 'green' for close, open in zip(df['Close'], df['Open'])]\n", " fig.add_trace(\n", " go.Bar(\n", " x=df.index,\n", " y=df['Volume'],\n", " name='Volume',\n", " marker_color=colors,\n", " opacity=0.6,\n", " showlegend=False\n", " ),\n", " row=2, col=1\n", " )\n", "\n", " # Add relative performance\n", " fig.add_trace(\n", " go.Scatter(\n", " x=df.index,\n", " y=relative_performance,\n", " mode='lines',\n", " name=f'{symbol} vs SPY',\n", " line=dict(color='black', width=1.5),\n", " fill='tonexty' if relative_performance.iloc[-1] > 1 else 'tozeroy',\n", " fillcolor='rgba(0,255,0,0.1)' if relative_performance.iloc[-1] > 1 else 'rgba(255,0,0,0.1)',\n", " showlegend=False\n", " ),\n", " row=3, col=1\n", " )\n", "\n", " # Add horizontal line at 1.0 for relative performance\n", " fig.add_hline(y=1.0, line_dash=\"dash\", line_color=\"gray\", opacity=0.5, row=3, col=1)\n", "\n", " # Update layout\n", " fig.update_layout(\n", " title=f'{symbol} - Advanced Stock Analysis',\n", " height=800,\n", " showlegend=True,\n", " legend=dict(\n", " orientation=\"h\",\n", " yanchor=\"bottom\",\n", " y=1.02,\n", " xanchor=\"right\",\n", " x=1\n", " ),\n", " margin=dict(l=50, r=50, t=80, b=50),\n", " plot_bgcolor='rgba(240,240,240,0.5)',\n", " paper_bgcolor='white'\n", " )\n", "\n", " # Update x-axes\n", " fig.update_xaxes(\n", " rangeslider_visible=False,\n", " showgrid=True,\n", " gridwidth=1,\n", " gridcolor='rgba(128,128,128,0.2)'\n", " )\n", "\n", " # Update y-axes\n", " fig.update_yaxes(\n", " showgrid=True,\n", " gridwidth=1,\n", " gridcolor='rgba(128,128,128,0.2)',\n", " title_text=\"Price ($)\",\n", " row=1, col=1\n", " )\n", "\n", " fig.update_yaxes(\n", " title_text=\"Volume\",\n", " row=2, col=1\n", " )\n", "\n", " fig.update_yaxes(\n", " title_text=\"Relative Performance\",\n", " row=3, col=1\n", " )\n", "\n", " # Remove range slider from candlestick\n", " fig.layout.xaxis.rangeslider.visible = False\n", "\n", " return fig\n", "\n", "# Example usage\n", "if __name__ == \"__main__\":\n", " # Create chart for Tesla\n", " fig = create_advanced_stock_chart('TSLA', period='2y')\n", " fig.show()\n", "\n", " # You can also create charts for other stocks\n", " # fig = create_advanced_stock_chart('AAPL', period='1y')\n", " # fig.show()\n", "\n", "# Additional customization options:\n", "\n", "def add_technical_indicators(fig, df, row=1):\n", " \"\"\"Add additional technical indicators to the chart\"\"\"\n", "\n", " # Bollinger Bands\n", " window = 20\n", " df['BB_Middle'] = df['Close'].rolling(window=window).mean()\n", " df['BB_Std'] = df['Close'].rolling(window=window).std()\n", " df['BB_Upper'] = df['BB_Middle'] + (df['BB_Std'] * 2)\n", " df['BB_Lower'] = df['BB_Middle'] - (df['BB_Std'] * 2)\n", "\n", " # Add Bollinger Bands\n", " fig.add_trace(\n", " go.Scatter(\n", " x=df.index,\n", " y=df['BB_Upper'],\n", " mode='lines',\n", " name='BB Upper',\n", " line=dict(color='purple', width=1, dash='dot'),\n", " opacity=0.6\n", " ),\n", " row=row, col=1\n", " )\n", "\n", " fig.add_trace(\n", " go.Scatter(\n", " x=df.index,\n", " y=df['BB_Lower'],\n", " mode='lines',\n", " name='BB Lower',\n", " line=dict(color='purple', width=1, dash='dot'),\n", " fill='tonexty',\n", " fillcolor='rgba(128,0,128,0.1)',\n", " opacity=0.6\n", " ),\n", " row=row, col=1\n", " )\n", "\n", " return fig\n", "\n", "def customize_chart_appearance(fig):\n", " \"\"\"Apply custom styling to match the original chart aesthetic\"\"\"\n", "\n", " fig.update_layout(\n", " plot_bgcolor='rgba(245,245,220,0.8)', # Beige background\n", " paper_bgcolor='white',\n", " font=dict(size=10, color='black'),\n", " title_font_size=14\n", " )\n", "\n", " # Update candlestick colors\n", " fig.data[0].increasing.fillcolor = 'rgba(0,150,0,0.8)'\n", " fig.data[0].increasing.line.color = 'rgba(0,100,0,1)'\n", " fig.data[0].decreasing.fillcolor = 'rgba(200,0,0,0.8)'\n", " fig.data[0].decreasing.line.color = 'rgba(150,0,0,1)'\n", "\n", " return fig\n", "\n", "# Enhanced example with all features\n", "def create_complete_chart(symbol='TSLA', period='2y'):\n", " \"\"\"Create a complete chart with all technical indicators and styling\"\"\"\n", "\n", " fig = create_advanced_stock_chart(symbol, period)\n", "\n", " # Get the data again for technical indicators\n", " stock = yf.Ticker(symbol)\n", " df = stock.history(period=period)\n", "\n", " # Add technical indicators\n", " fig = add_technical_indicators(fig, df)\n", "\n", " # Apply custom styling\n", " fig = customize_chart_appearance(fig)\n", "\n", " return fig\n", "\n", "# Usage:\n", "# fig = create_complete_chart('TSLA', '2y')\n", "# fig.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "bd56fc94", "metadata": {}, "outputs": [], "source": [ "import yfinance as yf\n", "import pandas as pd\n", "import plotly.graph_objs as go\n", "from plotly.subplots import make_subplots\n", "\n", "def make_stock_chart(symbol):\n", "\n", " # Download weekly data\n", " tsla = yf.download(symbol, interval=\"1wk\", period=\"4y\")\n", " tsla.columns = [col[0] if col[1] == symbol else col[0] for col in tsla.columns]\n", " spx = yf.download(\"^GSPC\", interval=\"1wk\", period=\"4y\")\n", " spx.columns = [col[0] if col[1] == '^GSPC' else col[0] for col in spx.columns]\n", "\n", " # Compute moving averages\n", " tsla['MA13'] = tsla['Close'].rolling(window=13).mean()\n", " tsla['MA52'] = tsla['Close'].rolling(window=52).mean()\n", "\n", " # Compute relative strength vs SPX\n", " relative = tsla['Close'] / spx['Close']\n", " tsla['Rel_SPX'] = relative\n", "\n", " # Create figure with secondary y-axis in the first row\n", " fig = make_subplots(\n", " rows=2, cols=1,\n", " shared_xaxes=True,\n", " row_heights=[0.7, 0.3],\n", " vertical_spacing=0.05,\n", " specs=[[{\"secondary_y\": True}], [{}]], # row 1 has secondary y-axis\n", " subplot_titles=[f\"{symbol} Price with Moving Averages & Volume\", f\"{symbol} Relative to S&P 500\"]\n", " )\n", "\n", " # --- Row 1: Price Candlesticks & MAs (primary y-axis) ---\n", " fig.add_trace(go.Candlestick(\n", " x=tsla.index,\n", " open=tsla['Open'],\n", " high=tsla['High'],\n", " low=tsla['Low'],\n", " close=tsla['Close'],\n", " name=symbol,\n", " increasing_line_color='black',\n", " decreasing_line_color='red'\n", " ), row=1, col=1, secondary_y=False)\n", "\n", " fig.add_trace(go.Scatter(\n", " x=tsla.index,\n", " y=tsla['MA13'],\n", " mode='lines',\n", " name='13-week MA',\n", " line=dict(color='blue')\n", " ), row=1, col=1, secondary_y=False)\n", "\n", " fig.add_trace(go.Scatter(\n", " x=tsla.index,\n", " y=tsla['MA52'],\n", " mode='lines',\n", " name='52-week MA',\n", " line=dict(color='orange')\n", " ), row=1, col=1, secondary_y=False)\n", "\n", " # --- Row 1: Volume on right axis (secondary y-axis) ---\n", " fig.add_trace(go.Bar(\n", " x=tsla.index,\n", " y=tsla['Volume'],\n", " name='Volume',\n", " marker_color='rgba(0, 128, 0, 0.4)',\n", " showlegend=False\n", " ), row=1, col=1, secondary_y=True)\n", "\n", " # --- Row 2: Relative to SPX ---\n", " fig.add_trace(go.Scatter(\n", " x=tsla.index,\n", " y=tsla['Rel_SPX'],\n", " name=symbol + ' / SPX',\n", " mode='lines',\n", " line=dict(color='black')\n", " ), row=2, col=1)\n", "\n", " # Layout adjustments\n", " fig.update_layout(\n", " title=symbol + ' Weekly Chart with MAs, Volume (Right Axis), and Relative Strength',\n", " height=800,\n", " xaxis=dict(rangeslider_visible=False),\n", " showlegend=True\n", " )\n", "\n", " fig.update_yaxes(title_text=\"Price\", row=1, col=1, secondary_y=False)\n", " fig.update_yaxes(title_text=\"Volume\", row=1, col=1, secondary_y=True)\n", " fig.update_yaxes(title_text=f\"{symbol} / SPX\", row=2, col=1)\n", "\n", " fig.show()\n", "\n", "make_stock_chart('TSLA')" ] }, { "cell_type": "code", "execution_count": null, "id": "dae2b602", "metadata": {}, "outputs": [], "source": [ "from plotly.subplots import make_subplots\n", "import plotly.graph_objects as go\n", "\n", "# Create figure with secondary y-axis in the first row\n", "fig = make_subplots(\n", " rows=2, cols=1,\n", " shared_xaxes=True,\n", " row_heights=[0.7, 0.3],\n", " vertical_spacing=0.05,\n", " specs=[[{\"secondary_y\": True}], [{}]], # row 1 has secondary y-axis\n", " subplot_titles=[\"TSLA Price with Moving Averages & Volume\", \"TSLA Relative to S&P 500\"]\n", ")\n", "\n", "# --- Row 1: Price Candlesticks & MAs (primary y-axis) ---\n", "fig.add_trace(go.Candlestick(\n", " x=tsla.index,\n", " open=tsla['Open'],\n", " high=tsla['High'],\n", " low=tsla['Low'],\n", " close=tsla['Close'],\n", " name='TSLA',\n", " increasing_line_color='black',\n", " decreasing_line_color='red'\n", "), row=1, col=1, secondary_y=False)\n", "\n", "fig.add_trace(go.Scatter(\n", " x=tsla.index,\n", " y=tsla['MA13'],\n", " mode='lines',\n", " name='13-week MA',\n", " line=dict(color='blue')\n", "), row=1, col=1, secondary_y=False)\n", "\n", "fig.add_trace(go.Scatter(\n", " x=tsla.index,\n", " y=tsla['MA52'],\n", " mode='lines',\n", " name='52-week MA',\n", " line=dict(color='orange')\n", "), row=1, col=1, secondary_y=False)\n", "\n", "# --- Row 1: Volume on right axis (secondary y-axis) ---\n", "fig.add_trace(go.Bar(\n", " x=tsla.index,\n", " y=tsla['Volume'],\n", " name='Volume',\n", " marker_color='rgba(0, 128, 0, 0.4)',\n", " showlegend=False\n", "), row=1, col=1, secondary_y=True)\n", "\n", "# --- Row 2: Relative to SPX ---\n", "fig.add_trace(go.Scatter(\n", " x=tsla.index,\n", " y=tsla['Rel_SPX'],\n", " name='TSLA / SPX',\n", " mode='lines',\n", " line=dict(color='black')\n", "), row=2, col=1)\n", "\n", "# Layout adjustments\n", "fig.update_layout(\n", " title='TSLA Weekly Chart with MAs, Volume (Right Axis), and Relative Strength',\n", " height=800,\n", " xaxis=dict(rangeslider_visible=False),\n", " showlegend=True\n", ")\n", "\n", "fig.update_yaxes(title_text=\"Price\", row=1, col=1, secondary_y=False)\n", "fig.update_yaxes(title_text=\"Volume\", row=1, col=1, secondary_y=True)\n", "fig.update_yaxes(title_text=\"TSLA / SPX\", row=2, col=1)\n", "\n", "fig.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "cebb3a17", "metadata": {}, "outputs": [], "source": [ "tsla.columns = ['_'.join(filter(None, col)).strip() for col in tsla.columns.values]\n", "tsla\n" ] }, { "cell_type": "code", "execution_count": null, "id": "4bdbee89", "metadata": {}, "outputs": [], "source": [ "tsla = yf.download(\"TSLA\", interval=\"1wk\", period=\"6y\")\n", "tsla.columns = [col[0] if col[1] == 'TSLA' else col[0] for col in tsla.columns]\n", "tsla\n" ] }, { "cell_type": "code", "execution_count": null, "id": "037c9d8d", "metadata": {}, "outputs": [], "source": [ "tod" ] }, { "cell_type": "code", "execution_count": null, "id": "caecd8ed", "metadata": {}, "outputs": [], "source": [ "xxx" ] }, { "cell_type": "code", "execution_count": null, "id": "c9cb19f8", "metadata": {}, "outputs": [], "source": [ "system_prompt = f\"\"\" \n", "You are an expert investment research analyst tasked with creating comprehensive up-to-date company profiles from an institutional investment perspective. Your role is to conduct thorough, objective research and analysis to inform investment decision-making.\n", "\n", "Core Principles\n", "\n", "Analytical Rigor: Apply systematic, data-driven analysis with appropriate skepticism. Validate information across multiple sources and flag any inconsistencies or data quality concerns.\n", "Investment Focus: Frame all analysis through the lens of investment implications. Connect operational details to financial performance, competitive positioning, and risk/return profiles.\n", "Objectivity: Present balanced analysis that acknowledges both positive and negative factors. Avoid promotional language and maintain professional neutrality throughout.\n", "Timely Information: Attempt to present the latest information as of today, {date_today}. Note dates of sources referenced. Do not treat possibly outdated information as current.\n", "Forward-looking perspective: Include historical information for context to understand the current situation and future prospects. Information that impacts future prospects and drives investment returns going forward is of most interest.\n", "Research Methodology\n", "Multi-Source Verification: Cross-reference information from company filings, financial databases, industry reports, and credible news sources. When sources conflict, note discrepancies and assess reliability.\n", "Systematic Information Gathering: Use available tools methodically:\n", "\n", "Financial data APIs for quantitative metrics and peer comparisons\n", "Web search for recent developments, analyst coverage, and industry context\n", "Company filings and investor materials for official positions\n", "News aggregation for market sentiment and risk factor identification\n", "\n", "Quality Standards: Prioritize authoritative sources (SEC filings, earnings calls, established financial media, recognized research firms) over speculative or promotional content. Flag when analysis relies on limited or potentially biased sources.\n", "Analytical Framework\n", "Strategic Context: Position the company within its industry ecosystem, considering competitive dynamics, market maturity, regulatory environment, and secular trends.\n", "Financial Analysis: Go beyond basic metrics to understand business quality, cash generation, capital efficiency, and financial flexibility. Connect financial trends to underlying business drivers.\n", "Risk Assessment: Identify and categorize risks systematically (operational, financial, competitive, regulatory, ESG). Assess probability and potential impact of key risk scenarios.\n", "Valuation Perspective: While not providing specific price targets, discuss valuation approaches relevant to the business model and highlight key variables that drive investment returns.\n", "Output Expectations\n", "Professional Tone: Write in the clear, authoritative style of institutional research. Use precise financial terminology while remaining accessible to sophisticated investors.\n", "Evidence-Based Conclusions: Support all analytical points with specific data, examples, or credible sources. Distinguish between factual information and analytical interpretation.\n", "Actionable Insights: Focus on information that would influence investment decisions. Highlight critical factors for ongoing monitoring and key questions for further due diligence.\n", "Structured Presentation: Follow the specific organizational structure provided in the user prompt, ensuring logical flow and appropriate depth for each section.\n", "Key Reminders\n", "\n", "Maintain objectivity and avoid advocacy for any investment position\n", "Clearly distinguish between company-provided information and independent analysis\n", "Note when information is incomplete, uncertain, or requires further investigation\n", "Focus on material factors that could significantly impact investment outcomes\n", "Present analysis that would meet institutional investment committee standards\n", "\n", "Your goal is to produce a comprehensive, professional-grade company profile that enables informed investment decision-making through rigorous research and balanced analysis.\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "id": "d1ccea77", "metadata": {}, "outputs": [], "source": [ "user_prompt = f\"\"\"\n", "\n", "Using everything found so far and everything you can find by using tools and doing deep research, write a report on Tesla (symbol TSLA) in the straightforward factual style of a Wall Street equity research analyst, in 8 sections:\n", "\n", "1. Profile\n", "• History with origin story and key historical milestones\n", "• Core business and competitors\n", "• Major news events since {last_year}\n", "\n", "2. Business Model:\n", "• Describe their core businesses, products and services.\n", "• Outline their key revenue streams, customer segments, and monetization strategies.\n", "• Analyze key characteristics of markets it operates in:\n", " - customer acquisition costs\n", " - retention metrics\n", " - sales cycles\n", " - seasonal or cyclical business patterns\n", " - margins, market size, growth trajectory and factors affecting them\n", "• Explain sources of competitive advantage such as network effects, switching costs, brands, intellectual property, regulatory moats, and other barriers to entry.\n", "\n", "3. Competitive Landscape:\n", "• Identify their main competitors, including direct, adjacent, and emerging competitors.\n", "• Compare key metrics such as market share, product differentiation, pricing power, and growth trajectories.\n", "\n", "4. Supply Chain Positioning:\n", "• Describe their role in the upstream (supplier-side) and downstream (customer/distribution) parts of the supply chain.\n", "• Identify key suppliers, partners, distributors, and any major dependencies or concentrations.\n", "\n", "5. Financial and Operating Leverage:\n", "• Analyze the company’s use of financial leverage (debt levels, interest obligations, credit ratings).\n", "• Analyze operating leverage (fixed vs. variable cost structure, scalability, margin sensitivity to revenue changes).\n", "• Analyze cash flow generation and working capital dynamics.\n", "• Analyze capital allocation strategy (dividends, buybacks, reinvestment).\n", "\n", "6. Valuation:\n", "• Identify appropriate valuation methodologies, including income-based (e.g., DCF), asset-based (eg book value and sum of parts), market-based (e.g. peer multiples and comparisons), and LBO analysis\n", "• Highlight important valuation inputs and metrics (growth rates, margins, discount rates, terminal value assumptions).\n", "• Summarize current ratings and analyst opinions, including recent changes.\n", "• Note the stock's volatility, liquidity, if it is widely covered and owned, if it is a hedge fund story stock or meme stock, what macro factors it is sensitive to\n", "\n", "7. Recent developments, News Search and Risk Factors:\n", "• Conduct a deep news search for significant positive and negative news items since {last_year}, including:\n", " • Revenue and earnings trends\n", " • Management changes\n", " • New product launches\n", " • Restructurings, mergers, acquisitions, divestitures, strategic partnerships\n", " • Short-seller reports or allegations.\n", " • Regulatory investigations or lawsuits.\n", " • Product failures, operational issues, or supply chain disruptions.\n", " • Major wins (e.g., partnerships, large customer wins, successful product launches).\n", " • Insider trading activity and institutional ownership changes\n", "• Summarize key themes from media coverage, analyst reports, and public filings since {last_year}.\n", "• Note controversies, reputational risks, and governance concerns if any.\n", "• Discuss what companies might be potential acquisition targets or acquirers of the company, based on overlapping or complementary customer bases, product offerings, and technical capabilities.\n", "• Note any other key themes or trends that you think are important.\n", "\n", "8. Overall Assessment:\n", "• Summarize the company’s strategic position and the stock's investment risk/reward profile\n", " • Strengths, weaknesses, opportunities, threats\n", " • Bear case and bull case\n", " • The level of risk\n", " • Any critical “watch points” for further due diligence and ongoing monitoring.\n", "\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "id": "65b7d1c8", "metadata": {}, "outputs": [], "source": [ "!ls tmp/tx0ybr2zo/ \n" ] }, { "cell_type": "code", "execution_count": null, "id": "eee8d6fb", "metadata": {}, "outputs": [], "source": [ "balance sheet\n", "income statement\n" ] }, { "cell_type": "code", "execution_count": null, "id": "4525247d", "metadata": {}, "outputs": [], "source": [ "upload_files = {\n", " 'edgar_10k_item1.txt': f'SEC 10K Item 1',\n", " 'perplexity_profile.md': f'Company profile from Perplexity',\n", " 'peers.txt': f'List of Peers',\n", " 'fundamentals_av.json': f'Fundamentals for company and peers',\n", " 'perplexity_ratings.md': f'Analyst ratings from Perplexity',\n", " 'technicals.md': f'Current technicals',\n", " 'perplexity_news.md': f'Company news from Perplexity',\n", " 'wikipedia.md': f'Wikipedia profile'\n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "6db41124", "metadata": {}, "outputs": [], "source": [ "# current_files = [f\"{temp_dir}/{symbol}_{f}\" for f in upload_files]\n", "current_files = [str(f) for f in Path(temp_dir).iterdir() if f.is_file()]\n", "\n", "# Sort files by size (smallest to largest)\n", "current_files_by_size = sorted(current_files, key=lambda f: Path(f).stat().st_size)\n", "current_files_by_size\n" ] }, { "cell_type": "code", "execution_count": null, "id": "217d5c4d", "metadata": {}, "outputs": [], "source": [ "for file_path in current_files_by_size:\n", " parts = file_path.split('_', 1)\n", " result = file_path[len(parts[0])+1:]\n", " if result in upload_files:\n", " print(result, \": \", upload_files[result])\n", " else:\n", " print(\"notfound\") " ] }, { "cell_type": "code", "execution_count": null, "id": "ad26ce1e", "metadata": {}, "outputs": [], "source": [ "import tiktoken\n", "\n", "# Initialize tiktoken encoder (using GPT-4 encoding)\n", "encoding = tiktoken.get_encoding(\"cl100k_base\") # or \"gpt-4\" \n", "\n", "additional_context = \"\"\n", "total_tokens = 0\n", "files_processed = []\n", "\n", "for file_path in current_files_by_size:\n", " try:\n", " # Read file content\n", " with open(file_path, 'r', encoding='utf-8') as file:\n", " file_content = file.read()\n", " \n", " # Count tokens in this file\n", " file_tokens = len(encoding.encode(file_content))\n", " \n", " # Check if adding this file would exceed the limit\n", " if total_tokens + file_tokens > 90000:\n", " print(f\"Stopping before {file_path} - would exceed 90,000 tokens\")\n", " break\n", " \n", " # Add to context and update counters\n", " parts = file_path.split('_', 1)\n", " section_title = file_path[len(parts[0])+1:]\n", " additional_context += f\"# {symbol} {section_title}\\n\"\n", " additional_context += file_content + \"\\n\\n\" # Add some separation between files\n", " total_tokens += file_tokens\n", " files_processed.append(file_path)\n", " \n", " print(f\"Added {file_path}: {file_tokens} tokens (Total: {total_tokens})\")\n", " \n", " except (UnicodeDecodeError, OSError, FileNotFoundError) as e:\n", " print(f\"Error reading {file_path}: {e}\")\n", " continue\n", "\n", "print(f\"\\nProcessed {len(files_processed)} files\")\n", "print(f\"Total tokens: {total_tokens}\")\n", "print(f\"Total characters in additional_context: {len(additional_context)}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "db6518c0", "metadata": {}, "outputs": [], "source": [ "print(additional_context)" ] }, { "cell_type": "code", "execution_count": null, "id": "70b44058", "metadata": {}, "outputs": [], "source": [ "keylist = list(upload_files.keys())\n", "keylist = keylist[len(files_processed):]\n", "file_list=[client.files.create(\n", " file=open(f\"{temp_dir}/{symbol}_{f}\", \"rb\"), purpose=\"assistants\") \n", " for f in keylist]\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5337d577", "metadata": {}, "outputs": [], "source": [ "file_list" ] }, { "cell_type": "code", "execution_count": null, "id": "b4cbcfbd", "metadata": {}, "outputs": [], "source": [ " • company + \"analyst report\" OR \"research note\" downgrade OR upgrade\n", " • use perplexity to search for company + \"profile\" or \"executive profile\" and ask: \"What are the most significant investigative reports and executive profiles about company published in 2023-2024?\"\n" ] }, { "cell_type": "code", "execution_count": null, "id": "330f9253", "metadata": {}, "outputs": [], "source": [ "client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n", "\n", "response = client.responses.create(\n", " model=\"o3-deep-research\",\n", " input=[\n", " {\n", " \"role\": \"developer\",\n", " \"content\": [\n", " {\n", " \"type\": \"input_text\",\n", " \"text\": system_prompt,\n", " }\n", " ]\n", " },\n", " {\n", " \"role\": \"user\",\n", " \"content\": [\n", " {\n", " \"type\": \"input_text\",\n", " \"text\": user_prompt,\n", " }\n", " ]\n", " }\n", " ],\n", " reasoning={\n", " \"summary\": \"auto\"\n", " },\n", " tools=[\n", " {\n", " \"type\": \"web_search_preview\"\n", " },\n", " {\n", " \"type\": \"code_interpreter\",\n", " \"container\": {\n", " \"type\": \"auto\",\n", " \"file_ids\": [f.id for f in file_list]\n", " }\n", " }\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "ca9e9107", "metadata": {}, "outputs": [], "source": [ "since current year -1" ] }, { "cell_type": "code", "execution_count": null, "id": "4bedcf3d", "metadata": { "scrolled": false }, "outputs": [], "source": [ "response_text = response.output[-1].content[0].dict()['text']\n", "response_text = response_text.replace(r'$',r'\\$')\n", "display(Markdown(response_text))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "90712ad9", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "mcp", "language": "python", "name": "mcp" }, "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.13" } }, "nbformat": 4, "nbformat_minor": 5 }

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/druce/MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server