From de9df49de9e5c35f1bea0814f773af229e19bf12 Mon Sep 17 00:00:00 2001 From: Bogdan Buduroiu Date: Thu, 8 May 2025 21:46:49 +0800 Subject: [PATCH] chore: performing sparse search with query expansion in langchain --- .../rag-sparse-query-expansion.ipynb | 807 ++++++++++++++++++ 1 file changed, 807 insertions(+) create mode 100644 learn/generation/langchain/rag-sparse-query-expansion.ipynb diff --git a/learn/generation/langchain/rag-sparse-query-expansion.ipynb b/learn/generation/langchain/rag-sparse-query-expansion.ipynb new file mode 100644 index 00000000..06569bdd --- /dev/null +++ b/learn/generation/langchain/rag-sparse-query-expansion.ipynb @@ -0,0 +1,807 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "9abb5eee-b493-42f2-84c4-2615286cfeb5", + "metadata": {}, + "source": [ + "# Leveraging Sparse Embeddings for Financial Reddit Analysis\n", + "\n", + "In this example, we'll build an agent that can search through Reddit posts about stocks and financial markets\n", + "using sparse embeddings. Unlike dense embeddings that capture overall semantic meaning, sparse embeddings excel at \n", + "capturing specific keywords and rare terms - perfect for financial contexts where stock tickers (like AAPL, TSLA) \n", + "and company names need to be precisely matched.\n", + "\n", + "## Why Sparse Embeddings for Financial Data?\n", + "\n", + "Financial discussions on platforms like Reddit often contain:\n", + "1. Stock tickers (PLTR, NVDA) that need exact matching\n", + "2. Company names that might be misspelled (Palanteer vs. Palantir)\n", + "3. Industry-specific jargon that dense embeddings might miss\n", + "\n", + "Sparse embeddings shine here because they:\n", + "- Maintain high precision for exact term matches (crucial for tickers)\n", + "- Preserve term frequency information (how often a stock is mentioned)\n", + "- Allow for better retrieval of documents with rare but important terms\n", + "\n", + "Let's see how we can implement this approach with Pinecone's sparse vector database." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "82002290-c430-4c8a-985e-af78eaa6de19", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Loaded 107 posts from data.json\n" + ] + } + ], + "source": [ + "import os\n", + "import ast\n", + "import json\n", + "from typing import Any, Dict, List\n", + "\n", + "from langchain_core.messages import HumanMessage\n", + "from langchain_core.tools import tool\n", + "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n", + "from langchain_core.runnables import RunnablePassthrough, RunnableWithMessageHistory\n", + "from langchain_openai import ChatOpenAI\n", + "from langchain_pinecone import PineconeSparseVectorStore\n", + "from langchain_pinecone.embeddings import PineconeSparseEmbeddings\n", + "from langchain.agents.format_scratchpad import format_to_openai_function_messages\n", + "from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser\n", + "from pinecone import Pinecone\n", + "\n", + "\n", + "# Check if data.json exists\n", + "# Load the Reddit data from JSON file\n", + "with open('data/finance_investing_data.json', 'r', encoding='utf-8') as f:\n", + " reddit_data = json.load(f)\n", + "\n", + "print(f\"Loaded {len(reddit_data)} posts from data.json\")\n", + "\n", + "# Prepare the posts for indexing\n", + "posts = []\n", + "for item in reddit_data:\n", + " # Extract relevant fields from the dataset\n", + " # Assuming JSON has same columns: [id, title, selftext, subreddit, body]\n", + " posts.append({\n", + " \"id\": item.get(\"id\", \"\"),\n", + " \"title\": item.get(\"title\", \"\"),\n", + " \"content\": item.get(\"selftext\", \"\") if item.get(\"selftext\") else \"\",\n", + " \"subreddit\": item.get(\"subreddit\", \"\"),\n", + " \"score\": 0, # Score not available in this dataset\n", + " \"created_utc\": \"\", # Timestamp not available in this dataset\n", + " \"permalink\": f\"https://reddit.com/r/{item.get('subreddit', 'all')}/comments/{item.get('id', '')}/\"\n", + " })\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "c4cf5d28-61bc-4f07-ac21-4435c411f2fe", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[{'id': '1j0w73o',\n", + " 'title': 'Rate My Portfolio - r/Stocks Quarterly Thread March 2025',\n", + " 'content': \"Please use this thread to discuss your portfolio, learn of other stock tickers & portfolios like [Warren Buffet's](https://buffett.online/en/portfolio/), and help out users by giving constructive criticism.\\n\\nWhy quarterly? Public companies report earnings quarterly; many investors take this as an opportunity to rebalance their portfolios. We highly recommend you do some reading: Check out our wiki's list of [relevant posts & book recommendations.](https://www.reddit.com/r/stocks/wiki/index/#wiki_relevant_posts.2C_books.2C_wiki_recommendations)\\n\\nYou can find stocks on your own by using a scanner like your broker's or [Finviz.](https://finviz.com/screener.ashx) To help further, here's a list of [relevant websites.](https://www.reddit.com/r/stocks/wiki/index/#wiki_relevant_websites.2Fapps)\\n\\nIf you don't have a broker yet, see our [list of brokers](https://www.reddit.com/r/stocks/wiki/index/#wiki_brokers_for_investing) or search old posts. If you haven't started investing or trading yet, then setup your [paper trading to learn basics like market orders vs limit orders.](https://www.reddit.com/r/stocks/wiki/index/#wiki_is_there_a_way_to_practice.3F)\\n\\nBe aware of [Business Cycle Investing](https://eresearch.fidelity.com/eresearch/markets_sectors/sectors/si_business_cycle.jhtml?tab=sibusiness) which Fidelity issues updates to the state of global business cycles every 1 to 3 months (note: Fidelity changes their links often, so search for it since their take on it is enlightening). [Investopedia's take on the Business Cycle](https://www.investopedia.com/articles/investing/061316/business-cycle-investing-ratios-use-each-cycle.asp).\\n\\nIf you need help with a falling stock price, check out Investopedia's [The Art of Selling A Losing Position](https://www.investopedia.com/articles/02/022002.asp) and their [list of biases.](https://www.investopedia.com/articles/stocks/08/capital-losses.asp)\\n\\nHere's a list of all the [previous portfolio stickies.](https://www.reddit.com/r/stocks/search?q=author%3Aautomoderator+title%3A%22Rate+My+Portfolio%22&restrict_sr=on&sort=new&t=all)\",\n", + " 'subreddit': 'stocks',\n", + " 'score': 0,\n", + " 'created_utc': '',\n", + " 'permalink': 'https://reddit.com/r/stocks/comments/1j0w73o/'},\n", + " {'id': '1k6o0i8',\n", + " 'title': 'r/Stocks Daily Discussion & Options Trading Thursday - Apr 24, 2025',\n", + " 'content': 'This is the daily discussion, so anything stocks related is fine, but the theme for today is on stock options, but if options aren\\'t your thing then just ignore the theme.\\n\\nSome helpful day to day links, including news:\\n\\n* [Finviz](https://finviz.com/quote.ashx?t=spy) for charts, fundamentals, and aggregated news on individual stocks\\n* [Bloomberg market news](https://www.bloomberg.com/markets)\\n* StreetInsider news:\\n * [Market Check](https://www.streetinsider.com/Market+Check) - Possibly why the market is doing what it\\'s doing including sudden spikes/dips\\n * [Reuters aggregated](https://www.streetinsider.com/Reuters) - Global news\\n\\n-----\\n\\nRequired info to start understanding options:\\n\\n* [Call option Investopedia video](https://www.investopedia.com/terms/c/calloption.asp) basically a call option allows you to buy 100 shares of a stock at a certain price (strike price), but without the obligation to buy\\n* [Put option Investopedia video](https://www.investopedia.com/terms/p/putoption.asp) a put option allows you to sell 100 shares of a stock at a certain price (strike price), but without the obligation to sell\\n* Writing options switches the obligation to you and you\\'ll be forced to buy someone else\\'s shares (writing puts) or sell your shares (writing calls)\\n\\nSee the following word cloud and click through for the wiki:\\n\\n[Call option - Put option - Exercising an option - Strike price - ITM - OTM - ATM - Long options - Short options - Combo - Debit - Credit or Premium - Covered call - Naked - Debit call spread - Credit call spread - Strangle - Iron condor - Vertical debit spreads - Iron Fly](https://www.reddit.com/r/stocks/wiki/options-themed-post)\\n\\nIf you have a basic question, for example \"what is delta,\" then google \"investopedia delta\" and click the investopedia article on it; do this for everything until you have a more in depth question or just want to share what you learned.\\n\\nSee our past [daily discussions here.](https://www.reddit.com/r/stocks/search?q=author%3Aautomoderator+%22r%2Fstocks+daily+discussion%22&restrict_sr=on&sort=new&t=all) Also links for: [Technicals](https://www.reddit.com/r/stocks/search?q=author%3Aautomoderator+title%3Atechnicals&restrict_sr=on&include_over_18=on&sort=new&t=all) Tuesday, [Options Trading](https://www.reddit.com/r/stocks/search?q=author%3Aautomoderator+title%3Aoptions&restrict_sr=on&include_over_18=on&sort=new&t=all) Thursday, and [Fundamentals](https://www.reddit.com/r/stocks/search?q=author%3Aautomoderator+title%3Afundamentals&restrict_sr=on&include_over_18=on&sort=new&t=all) Friday.',\n", + " 'subreddit': 'stocks',\n", + " 'score': 0,\n", + " 'created_utc': '',\n", + " 'permalink': 'https://reddit.com/r/stocks/comments/1k6o0i8/'},\n", + " {'id': '1k75t88',\n", + " 'title': 'Fox Reporter Says the Trump White House Is Giving Wall Street Executives Inside Info on Tariff Negotiations',\n", + " 'content': 'Fox Business senior correspondent Charles Gasparino reported on Thursday that President Donald Trump’s administration is privately discussing trade tariff deals with Wall Street executives, sharing insights on their current status, which is information not being made public otherwise.\\n\\nCiting “senior Wall Street execs with ties to the White House,” Gasparino wrote on X that people within Trump’s administration have held private discussions with business leaders about an “agreement in principle with India.” He further reported that the deal could be used as a template for other trade deals the administration is working on with Japan and other countries. Markets have taken sharp hits amid uncertainty surrounding Trump’s tariffs and trade deals.\\n\\nSee https://www.mediaite.com/news/fox-reporter-says-the-trump-white-house-is-giving-wall-street-executives-inside-info-on-tariff-negotiations/',\n", + " 'subreddit': 'stocks',\n", + " 'score': 0,\n", + " 'created_utc': '',\n", + " 'permalink': 'https://reddit.com/r/stocks/comments/1k75t88/'},\n", + " {'id': '1k6v7wu',\n", + " 'title': 'China tells US to ‘cancel all unilateral tariffs’ if it wants talks',\n", + " 'content': \"On 24th April, 2025, China's Ministry of Commerce stated that the United States must cancel all unilateral tariffs if it wishes to resume trade negotiations. The announcement reflects a firm stance from Beijing amid elevated trade tensions.\\n\\nChinese officials have also denied that any current negotiations are taking place, despite recent comments from U.S. leadership suggesting progress. In addition to reiterating their demand for tariff removal, China has introduced new export restrictions and initiated cases at the World Trade Organization.\\n\\nTariffs between the two countries now reach as high as 145% on U.S. imports from China and 125% on Chinese imports from the U.S.\\n\\nFull FT article here: [https://www.ft.com/content/3e076fb5-3988-4e21-9119-3fc637afebb8](https://www.ft.com/content/3e076fb5-3988-4e21-9119-3fc637afebb8)\",\n", + " 'subreddit': 'stocks',\n", + " 'score': 0,\n", + " 'created_utc': '',\n", + " 'permalink': 'https://reddit.com/r/stocks/comments/1k6v7wu/'},\n", + " {'id': '1k6pihz',\n", + " 'title': 'Now we know. It was Retail CEOS who got to Trump on Monday',\n", + " 'content': 'As reported by Axios, Trump was shaken Monday after meeting with CEO’s of top retail companies like Target. They warned him that disrupted supply chains due to his China tariffs would mean empty shelves and soaring prices very soon. You can imagine how the optics of bare shelves all around the country would look. \\n\\nMaybe they will get exemptions as Trump’s crony capitalism marches on but a huge number of small businesses won’t and will go under.\\n\\nSomewhere Xi is smirking. \\n\\nhttps://dailyboulder.com/shaken-trump-makes-u-turn-on-tariffs-after-being-rattled-by-dire-ceo-warning/',\n", + " 'subreddit': 'stocks',\n", + " 'score': 0,\n", + " 'created_utc': '',\n", + " 'permalink': 'https://reddit.com/r/stocks/comments/1k6pihz/'}]" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "posts[:5]" + ] + }, + { + "cell_type": "markdown", + "id": "1ebf0466-0349-4d54-bbcc-c4b820680b16", + "metadata": {}, + "source": [ + "## Sparse Vector Index Setup\n", + "\n", + "For our Reddit stocks analysis, we need a specialized vector index that supports sparse vectors.\n", + "Unlike dense vectors (which might be 1024 dimensions with most values being non-zero),\n", + "sparse vectors can have millions of dimensions but only a few non-zero values.\n", + "\n", + "This sparse representation is perfect for capturing the presence of specific terms like \"NVDA\" or \"earnings call\"\n", + "without diluting their importance in a dense representation.\n", + "\n", + "## Sparse Embeddings Model\n", + "\n", + "We'll use Pinecone's specialized sparse embedding model that's designed to:\n", + "1. Identify important financial terms and stock tickers\n", + "2. Create sparse vector representations that emphasize these key terms\n", + "3. Enable high-precision matching for financial queries" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "6d16992c-c709-468d-8bcb-fcb8ba82a76a", + "metadata": {}, + "outputs": [], + "source": [ + "PINECONE_API_KEY = os.environ.get(\"PINECONE_API_KEY\", \"your-api-key\")\n", + "PINECONE_INDEX_NAME = \"reddit-stocks-index\"\n", + "NAMESPACE = \"finance-subreddits\"\n", + "\n", + "pc = Pinecone(api_key=PINECONE_API_KEY)\n", + "\n", + "try:\n", + " index_info = pc.describe_index(PINECONE_INDEX_NAME)\n", + " if index_info.vector_type != \"sparse\":\n", + " raise ValueError(\n", + " f\"Index {PINECONE_INDEX_NAME} exists but is not a sparse index\"\n", + " )\n", + "except Exception as e:\n", + " print(f\"Index not found or error: {e}\")\n", + " print(\"Please create a sparse index first with the appropriate configuration\")\n", + " # Note: Index creation would go here in a real application\n", + " pc.create_index(\n", + " name=PINECONE_INDEX_NAME,\n", + " dimension=None,\n", + " metric=\"dotproduct\",\n", + " spec={\"serverless\": {\"cloud\": \"aws\", \"region\": \"us-east-1\"}},\n", + " vector_type=\"sparse\",\n", + " )\n", + "\n", + "# Initialize the sparse embeddings model\n", + "sparse_embeddings = PineconeSparseEmbeddings(\n", + " model=\"pinecone-sparse-english-v0\", show_progress_bar=True\n", + ")\n", + "\n", + "# Initialize the vector store\n", + "index = pc.Index(PINECONE_INDEX_NAME)\n", + "vector_store = PineconeSparseVectorStore(\n", + " index=index, embedding=sparse_embeddings, namespace=NAMESPACE\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "fa3c17f7-f1f9-4ddb-a14a-af7cf2c4e8a8", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "587db31930ee428cb976530caba96435", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/2 [00:00 List[str]:\n", + " \"\"\"\n", + " Expand a search query into multiple alternative queries to improve search results.\n", + " This is useful when:\n", + " - The original query is vague or ambiguous\n", + " - You need to find synonyms or related terms\n", + " - You want to cover different aspects of the same topic\n", + " - The query contains misspelled company names or stock tickers\n", + " \n", + " For example, a query like \"Tesla stock drop\" could be expanded to:\n", + " - \"TSLA share price decrease\"\n", + " - \"Tesla Motors stock market decline\"\n", + " - \"Elon Musk company stock performance\"\n", + " \n", + " Args:\n", + " query: The original query that needs to be expanded\n", + " num_expansions: Number of alternative queries to generate\n", + " \n", + " Returns:\n", + " A list of expanded queries including the original query\n", + " \"\"\"\n", + " try:\n", + " # Create the LLM for query expansion\n", + " expansion_llm = ChatOpenAI(temperature=0.7)\n", + " \n", + " # Define the prompt template\n", + " prompt = \"\"\"\n", + " You are an expert at expanding search queries to improve search results.\n", + " \n", + " Given a query about stocks, companies, or financial markets, generate {num_expansions} alternative \n", + " queries that capture the same intent but use different wording, synonyms, or related concepts.\n", + " \n", + " For company names, include both the company name and ticker symbol when possible.\n", + " For misspelled company names, include the correct spelling in the alternatives.\n", + " For general topics, i.e. \"tech company performance\", expand these queries to specific companies you know of, like \"Google\", \"Apple\", \"Nvidia\".\n", + "\n", + " For example, a query about Google could expand to: [\"GOOGL\", \"Alphabet\"]\n", + " Another example, a query about FAANG company performance could expand to: [\"META performance\", \"GOOGL performance\", \"AAPL performance\"]\n", + " and so on.\n", + " \n", + " Original query: {query}\n", + " \n", + " Return ONLY a Python list of strings with the alternative queries. \n", + " Do not include any explanations or additional text.\n", + " \"\"\"\n", + " \n", + " # Get response from LLM\n", + " response = expansion_llm.invoke(prompt.format(\n", + " query=query, \n", + " num_expansions=num_expansions\n", + " ))\n", + " \n", + " # Extract the list of alternative queries from the response\n", + " response_text = response.content\n", + " \n", + " # Clean up the response to make it a valid Python list\n", + " if \"```\" in response_text:\n", + " response_text = response_text.split(\"```\")[1]\n", + " if response_text.startswith(\"python\"):\n", + " response_text = response_text[6:]\n", + " \n", + " # Safely evaluate the string as a Python expression\n", + " try:\n", + " expanded_queries = ast.literal_eval(response_text.strip())\n", + " if not isinstance(expanded_queries, list):\n", + " expanded_queries = [response_text.strip()]\n", + " except:\n", + " # Fallback if parsing fails\n", + " expanded_queries = [line.strip() for line in response_text.strip().split('\\n') \n", + " if line.strip() and not line.strip().startswith('[') and not line.strip().endswith(']')]\n", + " \n", + " # Add the original query to the list\n", + " expanded_queries.append(query)\n", + " \n", + " return expanded_queries\n", + " \n", + " except Exception as e:\n", + " return [f\"Error expanding query: {str(e)}\", query]" + ] + }, + { + "cell_type": "markdown", + "id": "16277004-c1a1-4916-a396-cf4237e88fbc", + "metadata": {}, + "source": [ + "## Searching Reddit with Sparse Vectors\n", + "\n", + "Now that we have our query expansion mechanism, let's create a tool that leverages both \n", + "sparse embeddings and query expansion to search through Reddit posts about stocks.\n", + "\n", + "The magic happens in the combination:\n", + "1. Query expansion generates multiple versions of the search query\n", + "2. Each expanded query is converted to a sparse vector representation\n", + "3. Pinecone's sparse similarity search finds the most relevant posts\n", + "4. Results are deduplicated and ranked by relevance" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "883d6054-144a-499d-b56d-716bc4803e2a", + "metadata": {}, + "outputs": [], + "source": [ + "@tool\n", + "def reddit_stock_mentions(query: str, max_results: int = 5) -> List[Dict[str, Any]]:\n", + " \"\"\"\n", + " Search through Reddit posts from finance subreddits like r/wallstreetbets, r/investing, and r/pennystocks\n", + " to find mentions of stocks, companies, or market trends. This tool is useful for finding what retail\n", + " investors are discussing about specific companies or market events.\n", + " \n", + " When using this tool:\n", + " - For company searches, include both the company name and ticker symbol if known (e.g., \"Tesla TSLA\")\n", + " - For misspelled company names, provide the correct spelling\n", + " - Consider alternative terms that might be used on Reddit (e.g., \"$PLTR\" instead of just \"Palantir\")\n", + " - Be specific about the type of information you're looking for (e.g., \"NVIDIA earnings reaction\")\n", + " \n", + " NOTE: This tool automatically uses query expansion to improve search results by generating\n", + " alternative queries and combining the results.\n", + " \n", + " Args:\n", + " query: The search query to find relevant Reddit posts about stocks or companies\n", + " max_results: Maximum number of Reddit posts to return\n", + " \n", + " Returns:\n", + " A list of relevant Reddit posts with metadata\n", + " \"\"\"\n", + " try:\n", + " all_results = []\n", + " seen_docs = set() # To track unique documents\n", + " \n", + " # Search with each query\n", + "\n", + " # Perform the search using sparse vectors\n", + " # This is where the magic happens - sparse vectors excel at matching specific terms\n", + " # like stock tickers and company names with high precision\n", + " docs = vector_store.similarity_search(query=query, k=max_results)\n", + " \n", + " # Add unique results\n", + " for doc in docs:\n", + " # Create a unique identifier for the document\n", + " doc_id = f\"{doc.metadata.get('permalink', '')}\"\n", + " \n", + " # Only add if we haven't seen this document before\n", + " if doc_id not in seen_docs:\n", + " seen_docs.add(doc_id)\n", + " all_results.append({\n", + " \"content\": doc.page_content,\n", + " \"subreddit\": doc.metadata.get(\"subreddit\", \"unknown\"),\n", + " \"score\": doc.metadata.get(\"score\", 0),\n", + " \"date\": doc.metadata.get(\"created_utc\", \"unknown\"),\n", + " \"url\": doc.metadata.get(\"permalink\", \"\"),\n", + " \"matched_query\": query,\n", + " })\n", + " \n", + " # Sort by score (if available) and limit to max_results\n", + " all_results.sort(key=lambda x: x.get(\"score\", 0), reverse=True)\n", + " return all_results[:max_results]\n", + " \n", + " except Exception as e:\n", + " return [{\"error\": f\"Error searching Reddit mentions: {str(e)}\"}]\n" + ] + }, + { + "cell_type": "markdown", + "id": "dad7bcd9-be7a-4896-81c1-17193d273073", + "metadata": {}, + "source": [ + "## Putting It All Together: The Reddit Stocks Agent\n", + "\n", + "Now we'll create an agent that orchestrates our tools to help users find and analyze\n", + "what Reddit is saying about stocks and companies. The agent will:\n", + "\n", + "1. Use query expansion to handle misspellings and terminology variations\n", + "2. Leverage sparse embeddings for precise matching of financial terms\n", + "3. Analyze and summarize the Reddit sentiment about stocks\n", + "\n", + "This approach combines the best of both worlds:\n", + "- LLMs for understanding user intent and generating alternative queries\n", + "- Sparse vector search for high-precision retrieval of financial discussions" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "1d6a9b44-087f-4d57-a215-cd4d8b79e62b", + "metadata": {}, + "outputs": [], + "source": [ + "# Initialize the LLM\n", + "llm = ChatOpenAI()\n", + "\n", + "# Define the tools list\n", + "tools = [expand_query, reddit_stock_mentions]\n", + "\n", + "# Define a system prompt that emphasizes using query expansion\n", + "system_prompt = \"\"\"You are a financial research assistant that helps users find information about stocks and companies from Reddit discussions.\n", + "\n", + "ALWAYS use the expand_query tool first when searching for information. This is critical because:\n", + "1. It helps find alternative terms and synonyms that Reddit users might use\n", + "2. It corrects misspelled company names or stock tickers\n", + "3. It improves search coverage by generating multiple related queries\n", + "\n", + "After expanding the query, use the reddit_stock_mentions tool with the expanded queries to find relevant posts.\n", + "\n", + "Remember to analyze the results and provide a comprehensive summary of what Reddit users are saying about the stock or company in question.\n", + "\"\"\"\n", + "\n", + "# Create the prompt template with message history\n", + "prompt = ChatPromptTemplate.from_messages([\n", + " (\"system\", system_prompt),\n", + " MessagesPlaceholder(variable_name=\"chat_history\"),\n", + " (\"human\", \"{input}\"),\n", + " (\"placeholder\", \"{agent_scratchpad}\"),\n", + "])\n", + "\n", + "# Create a memory for the agent\n", + "from langchain.memory import ConversationBufferMemory\n", + "\n", + "memory = ConversationBufferMemory(\n", + " memory_key=\"chat_history\",\n", + " return_messages=True\n", + ")\n", + "\n", + "# Create the agent using the create_tool_calling_agent approach\n", + "from langchain.agents import create_tool_calling_agent, AgentExecutor\n", + "\n", + "agent = create_tool_calling_agent(\n", + " llm=llm,\n", + " tools=tools,\n", + " prompt=prompt\n", + ")\n", + "\n", + "# Create the agent executor\n", + "agent_executor = AgentExecutor(\n", + " agent=agent,\n", + " tools=tools,\n", + " memory=memory,\n", + " verbose=True,\n", + " handle_parsing_errors=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "4828013a-cfd7-47c1-b1fb-8820f7f54947", + "metadata": {}, + "source": [ + "## Testing Our Agent with Real-World Queries\n", + "\n", + "Let's put our agent to the test with some realistic queries that demonstrate its capabilities:\n", + "1. Handling misspelled company names (Palanteer → Palantir)\n", + "2. Finding discussions about specific events (NVIDIA earnings)\n", + "3. Exploring broader topics (biotech companies)\n", + "\n", + "The agent will:\n", + "- Expand each query to cover different terminology\n", + "- Search using sparse vectors for precise matching\n", + "- Analyze and summarize the Reddit sentiment" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "e01483f6-a92c-446f-bd8a-7048d8a5bf82", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "===== QUERY: What happened to semiconductor companies' stock recently? =====\n", + "\n", + "\n", + "\n", + "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", + "\u001b[32;1m\u001b[1;3m\n", + "Invoking: `expand_query` with `{'query': 'semiconductor companies stock performance', 'num_expansions': 3}`\n", + "\n", + "\n", + "\u001b[0m\u001b[36;1m\u001b[1;3m['Intel stock performance', 'AMD stock performance', 'Nvidia stock performance', 'semiconductor companies stock performance']\u001b[0m\u001b[32;1m\u001b[1;3m\n", + "Invoking: `reddit_stock_mentions` with `{'query': 'Intel stock performance', 'max_results': 5}`\n", + "\n", + "\n", + "\u001b[0m\u001b[33;1m\u001b[1;3m[{'content': 'Title: Intel CFO says tariffs increase chance for economic slowdown, recession getting likelier\\nContent: Source: [https://www.cnbc.com/2025/04/24/intel-cfo-says-tariffs-raise-chance-for-economic-slowdown-recession.html](https://www.cnbc.com/2025/04/24/intel-cfo-says-tariffs-raise-chance-for-economic-slowdown-recession.html)\\n\\n> \\nIntel\\xa0CFO David Zinsner said\\xa0President Donald Trump’s\\xa0tariffs and retaliation from other countries has increased the likelihood of a recession.\\n\\n>“The very fluid trade policies in the U.S. and beyond, as well as regulatory risks, have increased the chance of an economic slowdown, with the probability of a recession growing,” Zinsner said on the company’s quarterly earnings call on Thursday.\\n\\n>Intel reported better-than-expected\\xa0first-quarter results, partially because some customers stockpiled chips ahead of tariffs, the company said. However, guidance for revenue and profit was below expectations, pushing the chipmaker’s stock down more than 5% in extended trading.\\n\\n>Intel’s forecast for the current quarter is $11.2 billion to $12.4 billion. Zinsner said the range is “wider than normal” due to uncertainty caused by tariffs.\\n\\n \\nIntel down -5% overnight. Looks like a gloomy outlook from the chip maker. ', 'subreddit': 'stocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/stocks/comments/1k796l2/', 'matched_query': 'Intel stock performance'}, {'content': \"Title: UAMY: Only US antimony producer (a strategic metal), stock on the move\\nContent: **United States Antimony Corp ($UAMY) is the only US company mining antimony. The stock has been on an upward trend since December, the tariff chaos hasn't hurt it. Based in Dallas, TX, the company has been around since 1968.** As antimony demand surges due to China’s export restrictions and rising geopolitical tensions, $UAMY is strategically expanding production as the ONLY producer in the States. Its Montana smelter and Alaskan 4000 acres of land they recently acquired will push this company forward and it recently re-opened it's Mexico smelter under increased demand.\\n\\nToday, D. Boral Capital analyst Jesse Sobelson initiated coverage on United States Antimony with a Buy rating and announced a price target of $5. It's currently at $3.37, up 3.5% today and climbing.\\n\\n# Financial Overview\\n\\n* 2024 Revenue: $14.94 million, up 72% year-over-year\\n* Net Loss (2024): $1.74 million, a 72% improvement from the previous year\\n* Q3 2024 Revenue: $2.42 million, a 17% increase from Q3 2023\\n* Q3 2024 Gross Profit: $426,000, up 65% year-over-year.\\n\\nThe company has improved its financial performance, with a significant reduction in losses and increased revenues.\\u200b\\n\\n# Key Industry Developments\\n\\n* **China's Export Restrictions**: In September 2024, China restricted antimony exports, amplifying the U.S. and European scramble for alternative sources.\\n* **U.S. Defense Funding**: The Pentagon is considering grants for Alaskan antimony projects, signaling a shift toward domestic sourcing for critical minerals.\\n* **Price Surge**: Antimony prices have tripled in 2024 due to global shortages and heightened demand from military and renewable energy sectors.\\n* **Domestic Shortages**: Nearly two-thirds of U.S. antimony consumption (2019-2022) was sourced from China, underscoring the urgency for domestic production.\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k63vpa/', 'matched_query': 'Intel stock performance'}, {'content': 'Title: Tesla reports 20% Q1 drop in auto revenue\\nContent: Brutal numbers from Tesla after the bell. \\n\\nAs we all know, their stock performance is often decoupled from results. Little movement in futures so far, but curious how it’ll move tomorrow. \\n\\nTotal revenue slid 9% from $21.3 billion a year earlier. Automotive revenue dropped 20% to $14 billion from $17.4 billion in the same period last year.\\n\\nTesla said one reason for the decline was the need to update lines at its four vehicle factories to start making a refreshed version of its popular Model Y SUV. The company also pointed to lower average selling prices and sales incentives as a drag on revenue and profit.\\n\\nNet income plummeted 71% to $409 million, or 12 cents a share, from $1.39 billion or 41 cents a year ago.\\n\\n…\\n\\nThe company refrained from promising growth this year and said it will “revisit our 2025 guidance in our Q2 update.”\\n\\nhttps://www.cnbc.com/2025/04/22/tesla-tsla-earnings-report-q1-2025.html\\n\\nETA: it’s now up a staggering 3% after delivering that terrible news - they must be into the vaporware portion of the call.', 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k5htk8/', 'matched_query': 'Intel stock performance'}, {'content': 'Title: USAS : Q1 Earnings Estimate for Americas Silver Issued By Cormark\\nContent: Americas Silver Corp ([NYSEAMERICAN:USAS](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/)\\xa0–\\xa0[Free Report](https://www.marketbeat.com/arnreports/ReportTickerOptin.aspx?RegistrationCode=TickerHyperlink&Prefix=NYSEAMERICAN&Symbol=USAS)) – Investment analysts at Cormark issued their Q1 2025 earnings per share (EPS) estimates for shares of Americas Silver in a research report issued to clients and investors on Tuesday, April 22nd. Cormark analyst N. Dion expects that the company will post earnings per share of $0.00 for the quarter. Cormark currently has a “Moderate Buy” rating on the stock. The consensus estimate for Americas Silver’s current full-year earnings is ($0.11) per share.\\xa0\\n\\nSeparately, HC Wainwright boosted their price target on shares of Americas Silver from $0.90 to $1.00 and gave the stock a “buy” rating in a research report on Friday, March 28th.\\n\\n# Americas Silver Price Performance\\n\\nShares of\\xa0[USAS stock](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/earnings/)\\xa0opened at $0.62 on Wednesday. The stock has a market cap of $153.43 million, a PE ratio of -3.44 and a beta of 1.20. Americas Silver has a 12 month low of $0.21 and a 12 month high of $0.65. The company has a current ratio of 0.42, a quick ratio of 0.28 and a debt-to-equity ratio of 0.18.\\n\\n# Institutional Trading of Americas Silver\\n\\nHedge funds have recently added to or reduced their stakes in the stock. HighTower Advisors LLC bought a new stake in Americas Silver in the 4th quarter valued at about $47,000. American Century Companies Inc. bought a new stake in shares of Americas Silver in the fourth quarter valued at approximately $73,000. Bank of America Corp DE raised its position in shares of Americas Silver by 273,321.1% in the fourth quarter. Bank of America Corp DE now owns 207,800 shares of the company’s stock valued at $78,000 after purchasing an additional 207,724 shares during the period. JPMorgan Chase & Co. purchased a new stake in shares of Americas Silver during the 4th quarter valued at approximately $94,000. Finally, Cetera Investment Advisers boosted its holdings in Americas Silver by 4.8% in the 4th quarter. Cetera Investment Advisers now owns 428,844 shares of the company’s stock worth $167,000 after buying an additional 19,696 shares during the period. Institutional investors own 13.38% of the company’s stock.\\xa0\\n\\n# About Americas Silver\\n\\nAmericas Gold and Silver Corporation engages in the acquisition, evaluation, exploration, development, and operation of mineral properties. The company explores for silver, lead, zinc and copper. It principally owns 100% interests in the Cosalá Operations consisting of 67 mining concessions that cover approximately 19,385 hectares located in the state of Sinaloa, Mexico; and Galena Complex situated near the town of Wallace in the state of Idaho, the United States.\\n\\n[https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html](https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html)', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6sd43/', 'matched_query': 'Intel stock performance'}, {'content': 'Title: What’s your strategy on selling stocks?\\nContent: Hi guys, I was wondering when you decide when to sell a stock in your portfolio\\n\\nI’m asking because there are times where my stocks are in the green and I’m not sure whether to sell or keep holding. Obviously I like to take profits but sometimes I fear I’ll miss out on bigger returns.\\n\\nSo do guys you sell when you need the cash? Or when you’ve held the stock for over a year? Or you guys just hold until you realize the stock is not going anywhere?\\n\\n', 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k6wi48/', 'matched_query': 'Intel stock performance'}]\u001b[0m\u001b[32;1m\u001b[1;3m\n", + "Invoking: `reddit_stock_mentions` with `{'query': 'AMD stock performance', 'max_results': 5}`\n", + "\n", + "\n", + "\u001b[0m\u001b[33;1m\u001b[1;3m[{'content': \"Title: UAMY: Only US antimony producer (a strategic metal), stock on the move\\nContent: **United States Antimony Corp ($UAMY) is the only US company mining antimony. The stock has been on an upward trend since December, the tariff chaos hasn't hurt it. Based in Dallas, TX, the company has been around since 1968.** As antimony demand surges due to China’s export restrictions and rising geopolitical tensions, $UAMY is strategically expanding production as the ONLY producer in the States. Its Montana smelter and Alaskan 4000 acres of land they recently acquired will push this company forward and it recently re-opened it's Mexico smelter under increased demand.\\n\\nToday, D. Boral Capital analyst Jesse Sobelson initiated coverage on United States Antimony with a Buy rating and announced a price target of $5. It's currently at $3.37, up 3.5% today and climbing.\\n\\n# Financial Overview\\n\\n* 2024 Revenue: $14.94 million, up 72% year-over-year\\n* Net Loss (2024): $1.74 million, a 72% improvement from the previous year\\n* Q3 2024 Revenue: $2.42 million, a 17% increase from Q3 2023\\n* Q3 2024 Gross Profit: $426,000, up 65% year-over-year.\\n\\nThe company has improved its financial performance, with a significant reduction in losses and increased revenues.\\u200b\\n\\n# Key Industry Developments\\n\\n* **China's Export Restrictions**: In September 2024, China restricted antimony exports, amplifying the U.S. and European scramble for alternative sources.\\n* **U.S. Defense Funding**: The Pentagon is considering grants for Alaskan antimony projects, signaling a shift toward domestic sourcing for critical minerals.\\n* **Price Surge**: Antimony prices have tripled in 2024 due to global shortages and heightened demand from military and renewable energy sectors.\\n* **Domestic Shortages**: Nearly two-thirds of U.S. antimony consumption (2019-2022) was sourced from China, underscoring the urgency for domestic production.\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k63vpa/', 'matched_query': 'AMD stock performance'}, {'content': 'Title: Tesla reports 20% Q1 drop in auto revenue\\nContent: Brutal numbers from Tesla after the bell. \\n\\nAs we all know, their stock performance is often decoupled from results. Little movement in futures so far, but curious how it’ll move tomorrow. \\n\\nTotal revenue slid 9% from $21.3 billion a year earlier. Automotive revenue dropped 20% to $14 billion from $17.4 billion in the same period last year.\\n\\nTesla said one reason for the decline was the need to update lines at its four vehicle factories to start making a refreshed version of its popular Model Y SUV. The company also pointed to lower average selling prices and sales incentives as a drag on revenue and profit.\\n\\nNet income plummeted 71% to $409 million, or 12 cents a share, from $1.39 billion or 41 cents a year ago.\\n\\n…\\n\\nThe company refrained from promising growth this year and said it will “revisit our 2025 guidance in our Q2 update.”\\n\\nhttps://www.cnbc.com/2025/04/22/tesla-tsla-earnings-report-q1-2025.html\\n\\nETA: it’s now up a staggering 3% after delivering that terrible news - they must be into the vaporware portion of the call.', 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k5htk8/', 'matched_query': 'AMD stock performance'}, {'content': 'Title: USAS : Q1 Earnings Estimate for Americas Silver Issued By Cormark\\nContent: Americas Silver Corp ([NYSEAMERICAN:USAS](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/)\\xa0–\\xa0[Free Report](https://www.marketbeat.com/arnreports/ReportTickerOptin.aspx?RegistrationCode=TickerHyperlink&Prefix=NYSEAMERICAN&Symbol=USAS)) – Investment analysts at Cormark issued their Q1 2025 earnings per share (EPS) estimates for shares of Americas Silver in a research report issued to clients and investors on Tuesday, April 22nd. Cormark analyst N. Dion expects that the company will post earnings per share of $0.00 for the quarter. Cormark currently has a “Moderate Buy” rating on the stock. The consensus estimate for Americas Silver’s current full-year earnings is ($0.11) per share.\\xa0\\n\\nSeparately, HC Wainwright boosted their price target on shares of Americas Silver from $0.90 to $1.00 and gave the stock a “buy” rating in a research report on Friday, March 28th.\\n\\n# Americas Silver Price Performance\\n\\nShares of\\xa0[USAS stock](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/earnings/)\\xa0opened at $0.62 on Wednesday. The stock has a market cap of $153.43 million, a PE ratio of -3.44 and a beta of 1.20. Americas Silver has a 12 month low of $0.21 and a 12 month high of $0.65. The company has a current ratio of 0.42, a quick ratio of 0.28 and a debt-to-equity ratio of 0.18.\\n\\n# Institutional Trading of Americas Silver\\n\\nHedge funds have recently added to or reduced their stakes in the stock. HighTower Advisors LLC bought a new stake in Americas Silver in the 4th quarter valued at about $47,000. American Century Companies Inc. bought a new stake in shares of Americas Silver in the fourth quarter valued at approximately $73,000. Bank of America Corp DE raised its position in shares of Americas Silver by 273,321.1% in the fourth quarter. Bank of America Corp DE now owns 207,800 shares of the company’s stock valued at $78,000 after purchasing an additional 207,724 shares during the period. JPMorgan Chase & Co. purchased a new stake in shares of Americas Silver during the 4th quarter valued at approximately $94,000. Finally, Cetera Investment Advisers boosted its holdings in Americas Silver by 4.8% in the 4th quarter. Cetera Investment Advisers now owns 428,844 shares of the company’s stock worth $167,000 after buying an additional 19,696 shares during the period. Institutional investors own 13.38% of the company’s stock.\\xa0\\n\\n# About Americas Silver\\n\\nAmericas Gold and Silver Corporation engages in the acquisition, evaluation, exploration, development, and operation of mineral properties. The company explores for silver, lead, zinc and copper. It principally owns 100% interests in the Cosalá Operations consisting of 67 mining concessions that cover approximately 19,385 hectares located in the state of Sinaloa, Mexico; and Galena Complex situated near the town of Wallace in the state of Idaho, the United States.\\n\\n[https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html](https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html)', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6sd43/', 'matched_query': 'AMD stock performance'}, {'content': 'Title: What’s your strategy on selling stocks?\\nContent: Hi guys, I was wondering when you decide when to sell a stock in your portfolio\\n\\nI’m asking because there are times where my stocks are in the green and I’m not sure whether to sell or keep holding. Obviously I like to take profits but sometimes I fear I’ll miss out on bigger returns.\\n\\nSo do guys you sell when you need the cash? Or when you’ve held the stock for over a year? Or you guys just hold until you realize the stock is not going anywhere?\\n\\n', 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k6wi48/', 'matched_query': 'AMD stock performance'}, {'content': \"Title: Gold stocks hitting $3,300/oz\\nContent: Back in early January, I saw a note saying gold might finally have its moment in 2025. At the time, gold was around $2,600 an ounce, and most people were still focused on tech and AI stocks. Honestly, I didn’t think much of it.\\n\\nNow it’s April, and gold just crossed $3,330. That’s a 27% jump in four months. And suddenly, fund managers are calling gold the most crowded trade on Wall Street beating out tech for the first time in two years.\\n\\nA lot happened, Inflation hasn’t cooled down as much as people hoped. There’s still a ton of uncertainty around interest rates. And global tensions whether it’s Ukraine, the Middle East, or China have pushed a lot of people toward what they see as “safer” investments.\\n\\nInstead of buying physical gold or a gold ETF, I started looking into gold mining companies. The basic idea is this: when gold prices go up, mining profits usually go up even faster. That’s because their costs stay fairly flat while the value of what they’re digging up increases. So you get more upside though more risk too.\\n\\nAccording to my research there are three types of gold stocks I’ve been looking at:\\n\\n1. Major producers — big mining companies with steady operations.\\n2. Junior miners — smaller companies that might hit it big with a new discovery, but come with more risk.\\n3. Streaming companies — these guys don’t mine gold themselves. They give money to miners upfront and get a portion of the gold in return. Less risk, but less reward too.\\n\\n \\nHere's what I've been tracking:\\n\\nWheaton Precious Metals (WPM) \\nThis one is a streaming company, so it doesn’t operate mines—it collects a share of gold from others. It’s a lower-risk model and still benefits from rising gold prices. Production is up, and they’re projecting long-term growth. The stock’s up over 50%.\\n\\nAgnico Eagle (AEM) \\nSolid company with operations in Canada, Australia, and a few other places. They’ve been steadily growing reserves and investing in new exploration projects. Up nearly 90% this year.\\n\\nKinross Gold (KGC) \\nIt’s up over 120% so far this year. They’ve been selling off riskier assets and doubling down on stable regions like the U.S., Canada, and Brazil. They’re also using AI and automation to cut costs. It’s starting to pay off.\\n\\nGold stocks have clearly run up. Valuations on some names especially the streaming companies are looking expensive. But at the same time, demand is still strong, and a lot of people see gold as a safe bet if things get worse economically or politically.\\n\\n \\nWould it be safer to just buy a gold ETF instead? Something like GLD or IAU?\\n\\n\\n\\n \\n\", 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k7e847/', 'matched_query': 'AMD stock performance'}]\u001b[0m\u001b[32;1m\u001b[1;3m\n", + "Invoking: `reddit_stock_mentions` with `{'query': 'Nvidia stock performance', 'max_results': 5}`\n", + "\n", + "\n", + "\u001b[0m\u001b[33;1m\u001b[1;3m[{'content': 'Title: $IPM just partnered with NVIDA and is elligible for a $66M Lawsuit Award\\nContent: $IPM just got rid of their unprofitable businesses and had an acquisition in \\n\\nJanuary and are now focused on the cybersecurity / data hosting sector. (this acquisition should 3X their revenue)\\n\\nEarlier in the month they partnered with HPE Private Cloud which is co-developed by NVIDIA\\n\\nThe Stock has received multiple $6+ price targets from wall street analysts.\\n\\nThey won a $66M lawsuit award from Cisco and this will hit their balance sheet any time now which is yet another catalyst. (info is on their latest 10-k filing)\\n\\nThe company has a great balance sheet and their net loss for Q4 was due to around $6M in Acquisition costs/fees and They did sell off their un profitable legacy assets and completed the newtwek acquisition. \\n\\nThe company has 38.7 months of cash left based on quarterly cash burn of -$0.75M and estimated current cash of $9.7M. Zero long term debt with $16m in assets compared to only $4m in liabilities.\\n\\nThe CEO stated they are actively seeking mergers / acquisitions.\\n\\nVanguard owns around 3% of the company which is pretty big and the company has zero dilution filings. The total outstanding share count has went down since 2021.\\n\\nThe chart looks great and bottomed out. I think it is definitely worth looking into. Expecting news soon too. On the last earnings call the CEO sounded very optimistic about the new sector they are targeting', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k64yag/', 'matched_query': 'Nvidia stock performance'}, {'content': 'Title: $IPM just partnered with NVIDIA and has a huge merger and is about to receive $66M from Cisco (huge catalysts coming)\\nContent: $IPM just got rid of their unprofitable businesses and had an acquisition in back in January and are now focused on the cybersecurity / data hosting sector. (this acquisition should 3X their revenue)\\n\\nEarlier in the month they partnered with HPE Private Cloud which is co-developed by NVIDIA\\n\\nThe Stock has received multiple $6+ price targets from wall street analysts.\\n\\nThey won a $66M lawsuit award from Cisco and this will hit their balance sheet any time now which is yet another catalyst. (info is on their latest 10-k filing)\\n\\nThe company has a great balance sheet and their net loss for Q4 was due to around $6M in Acquisition costs/fees and They did sell off their un profitable legacy assets and completed the newtwek acquisition.\\n\\nThe company has 38.7 months of cash left based on quarterly cash burn of -$0.75M and estimated current cash of $9.7M. Zero long term debt with $16m in assets compared to only $4m in liabilities.\\n\\nThe CEO stated they are actively seeking mergers / acquisitions.\\n\\nVanguard owns around 3% of the company which is pretty big and the company has zero dilution filings. The total outstanding share count has went down since 2021.\\n\\nThe chart looks great and bottomed out. I think it is definitely worth looking into. Expecting news soon too. On the last earnings call the CEO sounded very optimistic about the new sector they are targeting.\\n\\nNew contracts should be coming soon because they partnered with $NEWT ($250M company) this month which has 100K+ businesses as customers and will be referring them to $IPM. $NEWT is their biggest customer as well and the same company they bought the NTS business from. I will be swinging this for a while and think it will explode when we get news which will be any day now.', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k70itk/', 'matched_query': 'Nvidia stock performance'}, {'content': \"Title: UAMY: Only US antimony producer (a strategic metal), stock on the move\\nContent: **United States Antimony Corp ($UAMY) is the only US company mining antimony. The stock has been on an upward trend since December, the tariff chaos hasn't hurt it. Based in Dallas, TX, the company has been around since 1968.** As antimony demand surges due to China’s export restrictions and rising geopolitical tensions, $UAMY is strategically expanding production as the ONLY producer in the States. Its Montana smelter and Alaskan 4000 acres of land they recently acquired will push this company forward and it recently re-opened it's Mexico smelter under increased demand.\\n\\nToday, D. Boral Capital analyst Jesse Sobelson initiated coverage on United States Antimony with a Buy rating and announced a price target of $5. It's currently at $3.37, up 3.5% today and climbing.\\n\\n# Financial Overview\\n\\n* 2024 Revenue: $14.94 million, up 72% year-over-year\\n* Net Loss (2024): $1.74 million, a 72% improvement from the previous year\\n* Q3 2024 Revenue: $2.42 million, a 17% increase from Q3 2023\\n* Q3 2024 Gross Profit: $426,000, up 65% year-over-year.\\n\\nThe company has improved its financial performance, with a significant reduction in losses and increased revenues.\\u200b\\n\\n# Key Industry Developments\\n\\n* **China's Export Restrictions**: In September 2024, China restricted antimony exports, amplifying the U.S. and European scramble for alternative sources.\\n* **U.S. Defense Funding**: The Pentagon is considering grants for Alaskan antimony projects, signaling a shift toward domestic sourcing for critical minerals.\\n* **Price Surge**: Antimony prices have tripled in 2024 due to global shortages and heightened demand from military and renewable energy sectors.\\n* **Domestic Shortages**: Nearly two-thirds of U.S. antimony consumption (2019-2022) was sourced from China, underscoring the urgency for domestic production.\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k63vpa/', 'matched_query': 'Nvidia stock performance'}, {'content': 'Title: Tesla reports 20% Q1 drop in auto revenue\\nContent: Brutal numbers from Tesla after the bell. \\n\\nAs we all know, their stock performance is often decoupled from results. Little movement in futures so far, but curious how it’ll move tomorrow. \\n\\nTotal revenue slid 9% from $21.3 billion a year earlier. Automotive revenue dropped 20% to $14 billion from $17.4 billion in the same period last year.\\n\\nTesla said one reason for the decline was the need to update lines at its four vehicle factories to start making a refreshed version of its popular Model Y SUV. The company also pointed to lower average selling prices and sales incentives as a drag on revenue and profit.\\n\\nNet income plummeted 71% to $409 million, or 12 cents a share, from $1.39 billion or 41 cents a year ago.\\n\\n…\\n\\nThe company refrained from promising growth this year and said it will “revisit our 2025 guidance in our Q2 update.”\\n\\nhttps://www.cnbc.com/2025/04/22/tesla-tsla-earnings-report-q1-2025.html\\n\\nETA: it’s now up a staggering 3% after delivering that terrible news - they must be into the vaporware portion of the call.', 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k5htk8/', 'matched_query': 'Nvidia stock performance'}, {'content': 'Title: USAS : Q1 Earnings Estimate for Americas Silver Issued By Cormark\\nContent: Americas Silver Corp ([NYSEAMERICAN:USAS](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/)\\xa0–\\xa0[Free Report](https://www.marketbeat.com/arnreports/ReportTickerOptin.aspx?RegistrationCode=TickerHyperlink&Prefix=NYSEAMERICAN&Symbol=USAS)) – Investment analysts at Cormark issued their Q1 2025 earnings per share (EPS) estimates for shares of Americas Silver in a research report issued to clients and investors on Tuesday, April 22nd. Cormark analyst N. Dion expects that the company will post earnings per share of $0.00 for the quarter. Cormark currently has a “Moderate Buy” rating on the stock. The consensus estimate for Americas Silver’s current full-year earnings is ($0.11) per share.\\xa0\\n\\nSeparately, HC Wainwright boosted their price target on shares of Americas Silver from $0.90 to $1.00 and gave the stock a “buy” rating in a research report on Friday, March 28th.\\n\\n# Americas Silver Price Performance\\n\\nShares of\\xa0[USAS stock](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/earnings/)\\xa0opened at $0.62 on Wednesday. The stock has a market cap of $153.43 million, a PE ratio of -3.44 and a beta of 1.20. Americas Silver has a 12 month low of $0.21 and a 12 month high of $0.65. The company has a current ratio of 0.42, a quick ratio of 0.28 and a debt-to-equity ratio of 0.18.\\n\\n# Institutional Trading of Americas Silver\\n\\nHedge funds have recently added to or reduced their stakes in the stock. HighTower Advisors LLC bought a new stake in Americas Silver in the 4th quarter valued at about $47,000. American Century Companies Inc. bought a new stake in shares of Americas Silver in the fourth quarter valued at approximately $73,000. Bank of America Corp DE raised its position in shares of Americas Silver by 273,321.1% in the fourth quarter. Bank of America Corp DE now owns 207,800 shares of the company’s stock valued at $78,000 after purchasing an additional 207,724 shares during the period. JPMorgan Chase & Co. purchased a new stake in shares of Americas Silver during the 4th quarter valued at approximately $94,000. Finally, Cetera Investment Advisers boosted its holdings in Americas Silver by 4.8% in the 4th quarter. Cetera Investment Advisers now owns 428,844 shares of the company’s stock worth $167,000 after buying an additional 19,696 shares during the period. Institutional investors own 13.38% of the company’s stock.\\xa0\\n\\n# About Americas Silver\\n\\nAmericas Gold and Silver Corporation engages in the acquisition, evaluation, exploration, development, and operation of mineral properties. The company explores for silver, lead, zinc and copper. It principally owns 100% interests in the Cosalá Operations consisting of 67 mining concessions that cover approximately 19,385 hectares located in the state of Sinaloa, Mexico; and Galena Complex situated near the town of Wallace in the state of Idaho, the United States.\\n\\n[https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html](https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html)', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6sd43/', 'matched_query': 'Nvidia stock performance'}]\u001b[0m\u001b[32;1m\u001b[1;3m\n", + "Invoking: `reddit_stock_mentions` with `{'query': 'semiconductor companies stock performance', 'max_results': 5}`\n", + "\n", + "\n", + "\u001b[0m\u001b[33;1m\u001b[1;3m[{'content': 'Title: USAS : Q1 Earnings Estimate for Americas Silver Issued By Cormark\\nContent: Americas Silver Corp ([NYSEAMERICAN:USAS](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/)\\xa0–\\xa0[Free Report](https://www.marketbeat.com/arnreports/ReportTickerOptin.aspx?RegistrationCode=TickerHyperlink&Prefix=NYSEAMERICAN&Symbol=USAS)) – Investment analysts at Cormark issued their Q1 2025 earnings per share (EPS) estimates for shares of Americas Silver in a research report issued to clients and investors on Tuesday, April 22nd. Cormark analyst N. Dion expects that the company will post earnings per share of $0.00 for the quarter. Cormark currently has a “Moderate Buy” rating on the stock. The consensus estimate for Americas Silver’s current full-year earnings is ($0.11) per share.\\xa0\\n\\nSeparately, HC Wainwright boosted their price target on shares of Americas Silver from $0.90 to $1.00 and gave the stock a “buy” rating in a research report on Friday, March 28th.\\n\\n# Americas Silver Price Performance\\n\\nShares of\\xa0[USAS stock](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/earnings/)\\xa0opened at $0.62 on Wednesday. The stock has a market cap of $153.43 million, a PE ratio of -3.44 and a beta of 1.20. Americas Silver has a 12 month low of $0.21 and a 12 month high of $0.65. The company has a current ratio of 0.42, a quick ratio of 0.28 and a debt-to-equity ratio of 0.18.\\n\\n# Institutional Trading of Americas Silver\\n\\nHedge funds have recently added to or reduced their stakes in the stock. HighTower Advisors LLC bought a new stake in Americas Silver in the 4th quarter valued at about $47,000. American Century Companies Inc. bought a new stake in shares of Americas Silver in the fourth quarter valued at approximately $73,000. Bank of America Corp DE raised its position in shares of Americas Silver by 273,321.1% in the fourth quarter. Bank of America Corp DE now owns 207,800 shares of the company’s stock valued at $78,000 after purchasing an additional 207,724 shares during the period. JPMorgan Chase & Co. purchased a new stake in shares of Americas Silver during the 4th quarter valued at approximately $94,000. Finally, Cetera Investment Advisers boosted its holdings in Americas Silver by 4.8% in the 4th quarter. Cetera Investment Advisers now owns 428,844 shares of the company’s stock worth $167,000 after buying an additional 19,696 shares during the period. Institutional investors own 13.38% of the company’s stock.\\xa0\\n\\n# About Americas Silver\\n\\nAmericas Gold and Silver Corporation engages in the acquisition, evaluation, exploration, development, and operation of mineral properties. The company explores for silver, lead, zinc and copper. It principally owns 100% interests in the Cosalá Operations consisting of 67 mining concessions that cover approximately 19,385 hectares located in the state of Sinaloa, Mexico; and Galena Complex situated near the town of Wallace in the state of Idaho, the United States.\\n\\n[https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html](https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html)', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6sd43/', 'matched_query': 'semiconductor companies stock performance'}, {'content': \"Title: UAMY: Only US antimony producer (a strategic metal), stock on the move\\nContent: **United States Antimony Corp ($UAMY) is the only US company mining antimony. The stock has been on an upward trend since December, the tariff chaos hasn't hurt it. Based in Dallas, TX, the company has been around since 1968.** As antimony demand surges due to China’s export restrictions and rising geopolitical tensions, $UAMY is strategically expanding production as the ONLY producer in the States. Its Montana smelter and Alaskan 4000 acres of land they recently acquired will push this company forward and it recently re-opened it's Mexico smelter under increased demand.\\n\\nToday, D. Boral Capital analyst Jesse Sobelson initiated coverage on United States Antimony with a Buy rating and announced a price target of $5. It's currently at $3.37, up 3.5% today and climbing.\\n\\n# Financial Overview\\n\\n* 2024 Revenue: $14.94 million, up 72% year-over-year\\n* Net Loss (2024): $1.74 million, a 72% improvement from the previous year\\n* Q3 2024 Revenue: $2.42 million, a 17% increase from Q3 2023\\n* Q3 2024 Gross Profit: $426,000, up 65% year-over-year.\\n\\nThe company has improved its financial performance, with a significant reduction in losses and increased revenues.\\u200b\\n\\n# Key Industry Developments\\n\\n* **China's Export Restrictions**: In September 2024, China restricted antimony exports, amplifying the U.S. and European scramble for alternative sources.\\n* **U.S. Defense Funding**: The Pentagon is considering grants for Alaskan antimony projects, signaling a shift toward domestic sourcing for critical minerals.\\n* **Price Surge**: Antimony prices have tripled in 2024 due to global shortages and heightened demand from military and renewable energy sectors.\\n* **Domestic Shortages**: Nearly two-thirds of U.S. antimony consumption (2019-2022) was sourced from China, underscoring the urgency for domestic production.\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k63vpa/', 'matched_query': 'semiconductor companies stock performance'}, {'content': \"Title: Gold stocks hitting $3,300/oz\\nContent: Back in early January, I saw a note saying gold might finally have its moment in 2025. At the time, gold was around $2,600 an ounce, and most people were still focused on tech and AI stocks. Honestly, I didn’t think much of it.\\n\\nNow it’s April, and gold just crossed $3,330. That’s a 27% jump in four months. And suddenly, fund managers are calling gold the most crowded trade on Wall Street beating out tech for the first time in two years.\\n\\nA lot happened, Inflation hasn’t cooled down as much as people hoped. There’s still a ton of uncertainty around interest rates. And global tensions whether it’s Ukraine, the Middle East, or China have pushed a lot of people toward what they see as “safer” investments.\\n\\nInstead of buying physical gold or a gold ETF, I started looking into gold mining companies. The basic idea is this: when gold prices go up, mining profits usually go up even faster. That’s because their costs stay fairly flat while the value of what they’re digging up increases. So you get more upside though more risk too.\\n\\nAccording to my research there are three types of gold stocks I’ve been looking at:\\n\\n1. Major producers — big mining companies with steady operations.\\n2. Junior miners — smaller companies that might hit it big with a new discovery, but come with more risk.\\n3. Streaming companies — these guys don’t mine gold themselves. They give money to miners upfront and get a portion of the gold in return. Less risk, but less reward too.\\n\\n \\nHere's what I've been tracking:\\n\\nWheaton Precious Metals (WPM) \\nThis one is a streaming company, so it doesn’t operate mines—it collects a share of gold from others. It’s a lower-risk model and still benefits from rising gold prices. Production is up, and they’re projecting long-term growth. The stock’s up over 50%.\\n\\nAgnico Eagle (AEM) \\nSolid company with operations in Canada, Australia, and a few other places. They’ve been steadily growing reserves and investing in new exploration projects. Up nearly 90% this year.\\n\\nKinross Gold (KGC) \\nIt’s up over 120% so far this year. They’ve been selling off riskier assets and doubling down on stable regions like the U.S., Canada, and Brazil. They’re also using AI and automation to cut costs. It’s starting to pay off.\\n\\nGold stocks have clearly run up. Valuations on some names especially the streaming companies are looking expensive. But at the same time, demand is still strong, and a lot of people see gold as a safe bet if things get worse economically or politically.\\n\\n \\nWould it be safer to just buy a gold ETF instead? Something like GLD or IAU?\\n\\n\\n\\n \\n\", 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k7e847/', 'matched_query': 'semiconductor companies stock performance'}, {'content': \"Title: Don't Sleep on Damon (DMN)\\nContent: This two-wheel electric vehicle company could make for a quick return. Currently, the stock price sits at $0.0035 (as I type this), but they have $100 million in pre-orders for their two motorcycle models, which include safety and accessibility tech you'd find in newer four-wheel vehicles. They're also big on data intelligence, and are open to working with other companies to share info, such as supporting ICE (internal combustion engine) companies to transition. They presented at the Planet MicroCap Showcase just yesterday, which is available online: [https://event.summitcast.com/view/YNz6mnmEsXyrdRxb78w2nX/9WosXgUD44wqvJunNd982Y](https://event.summitcast.com/view/YNz6mnmEsXyrdRxb78w2nX/9WosXgUD44wqvJunNd982Y) (Or just Google it if you don't trust links.) Among other things, they state the global market for electric bikes is forecasted to reach $40 billion by 2030. While the US may have an administration trying to move in the opposite direction of electrification, the world thinks otherwise!\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k70v8k/', 'matched_query': 'semiconductor companies stock performance'}, {'content': 'Title: Tesla reports 20% Q1 drop in auto revenue\\nContent: Brutal numbers from Tesla after the bell. \\n\\nAs we all know, their stock performance is often decoupled from results. Little movement in futures so far, but curious how it’ll move tomorrow. \\n\\nTotal revenue slid 9% from $21.3 billion a year earlier. Automotive revenue dropped 20% to $14 billion from $17.4 billion in the same period last year.\\n\\nTesla said one reason for the decline was the need to update lines at its four vehicle factories to start making a refreshed version of its popular Model Y SUV. The company also pointed to lower average selling prices and sales incentives as a drag on revenue and profit.\\n\\nNet income plummeted 71% to $409 million, or 12 cents a share, from $1.39 billion or 41 cents a year ago.\\n\\n…\\n\\nThe company refrained from promising growth this year and said it will “revisit our 2025 guidance in our Q2 update.”\\n\\nhttps://www.cnbc.com/2025/04/22/tesla-tsla-earnings-report-q1-2025.html\\n\\nETA: it’s now up a staggering 3% after delivering that terrible news - they must be into the vaporware portion of the call.', 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k5htk8/', 'matched_query': 'semiconductor companies stock performance'}]\u001b[0m\u001b[32;1m\u001b[1;3m### Recent Discussions on Semiconductor Companies' Stock Performance:\n", + "\n", + "#### Intel:\n", + "- **Title:** Intel CFO says tariffs increase chance for economic slowdown, recession getting likelier\n", + "- **Content:** Intel CFO David Zinsner mentioned that tariffs and retaliatory actions by other countries have increased the likelihood of an economic slowdown and recession. The company reported better-than-expected first-quarter results, partially due to customers stockpiling chips ahead of tariffs. However, guidance for revenue and profit was below expectations, leading to a more than 5% drop in Intel's stock in extended trading.\n", + "\n", + "#### AMD:\n", + "- **Title:** UAMY: Only US antimony producer (a strategic metal), stock on the move\n", + "- **Content:** Discussion about United States Antimony Corp (UAMY), the only US company mining antimony. The stock has been on an upward trend, unaffected by tariff chaos. The company's financial overview and key industry developments were highlighted, including increased revenue and significant improvements in financial performance.\n", + "\n", + "#### Nvidia:\n", + "- **Title:** $IPM just partnered with NVIDIA and has a huge merger and is about to receive $66M from Cisco (huge catalysts coming)\n", + "- **Content:** Discussion about a company, $IPM, that partnered with NVIDIA and is set to receive a $66M lawsuit award from Cisco. The post mentions positive catalysts, analyst recommendations, balance sheet strength, and ongoing developments in the cybersecurity/data hosting sector.\n", + "\n", + "### Observations:\n", + "- Intel's stock faced a downward trend due to concerns about tariffs and economic slowdown.\n", + "- AMD's stock performance was positive, with the company showing improvements in revenue and financial metrics.\n", + "- Nvidia's partnership and incoming lawsuit award were highlighted as potential catalysts for its stock performance.\n", + "\n", + "It seems that semiconductor stocks have been influenced by various factors such as trade policies, partnerships, and financial performance. Investors are closely monitoring these companies for updates and developments that could impact their stock prices.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "RESULT: ### Recent Discussions on Semiconductor Companies' Stock Performance:\n", + "\n", + "#### Intel:\n", + "- **Title:** Intel CFO says tariffs increase chance for economic slowdown, recession getting likelier\n", + "- **Content:** Intel CFO David Zinsner mentioned that tariffs and retaliatory actions by other countries have increased the likelihood of an economic slowdown and recession. The company reported better-than-expected first-quarter results, partially due to customers stockpiling chips ahead of tariffs. However, guidance for revenue and profit was below expectations, leading to a more than 5% drop in Intel's stock in extended trading.\n", + "\n", + "#### AMD:\n", + "- **Title:** UAMY: Only US antimony producer (a strategic metal), stock on the move\n", + "- **Content:** Discussion about United States Antimony Corp (UAMY), the only US company mining antimony. The stock has been on an upward trend, unaffected by tariff chaos. The company's financial overview and key industry developments were highlighted, including increased revenue and significant improvements in financial performance.\n", + "\n", + "#### Nvidia:\n", + "- **Title:** $IPM just partnered with NVIDIA and has a huge merger and is about to receive $66M from Cisco (huge catalysts coming)\n", + "- **Content:** Discussion about a company, $IPM, that partnered with NVIDIA and is set to receive a $66M lawsuit award from Cisco. The post mentions positive catalysts, analyst recommendations, balance sheet strength, and ongoing developments in the cybersecurity/data hosting sector.\n", + "\n", + "### Observations:\n", + "- Intel's stock faced a downward trend due to concerns about tariffs and economic slowdown.\n", + "- AMD's stock performance was positive, with the company showing improvements in revenue and financial metrics.\n", + "- Nvidia's partnership and incoming lawsuit award were highlighted as potential catalysts for its stock performance.\n", + "\n", + "It seems that semiconductor stocks have been influenced by various factors such as trade policies, partnerships, and financial performance. Investors are closely monitoring these companies for updates and developments that could impact their stock prices.\n" + ] + } + ], + "source": [ + "query = \"What happened to semiconductor companies' stock recently?\"\n", + "\n", + "print(f\"\\n\\n===== QUERY: {query} =====\\n\")\n", + "\n", + "# Run the agent with the query\n", + "result = agent_executor.invoke({\n", + " \"input\": query,\n", + " \"chat_history\": memory\n", + "})\n", + "\n", + "# Print the result\n", + "print(f\"RESULT: {result['output']}\")" + ] + }, + { + "cell_type": "markdown", + "id": "6cfa133a-7a71-4a3c-a8b0-ad6ce4720e3d", + "metadata": {}, + "source": [ + "## How does our search perform without query expansion?\n", + "\n", + "Let's see what we'd be missing out on if we weren't using query expansion in our search.\n", + "\n", + "We'll set up another agent that doesn't have access to the query expansion tool, and use a query we've used above" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "a039fab0-52c5-46f4-af8c-5113f4e8dfe1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", + "\u001b[32;1m\u001b[1;3m\n", + "Invoking: `reddit_stock_mentions` with `{'query': 'semiconductor companies stock recent', 'max_results': 10}`\n", + "\n", + "\n", + "\u001b[0m\u001b[33;1m\u001b[1;3m[{'content': \"Title: RHCO big news out today.. Finalized ACQUISITION of Morrich Lottery Limited and secured LOTTERY, SPORTSBOOK, and CASINO LICENSES\\nContent: This stock has very little volume and its a small float. But looks good with their current financials and this recent completed acquisition to add more to the books.\\n\\nHere's a quick look at their financials from last quarter:\\n\\n•$5.7M in revenue last quarter\\n\\n•Net profitable\\n\\n•$12.9M in assets\\n\\n•No convertible notes\\n\\n•Small float, 24M shares held at DTC (The held at DTC number is the public tradable float)\\n\\n•Completed acquisition news today, (Finalized ACQUISITION of Morrich Lottery Limited and secured lottery, sportsbook and casino licenses)\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k68p7a/', 'matched_query': 'semiconductor companies stock recent'}, {'content': \"Title: Gold stocks hitting $3,300/oz\\nContent: Back in early January, I saw a note saying gold might finally have its moment in 2025. At the time, gold was around $2,600 an ounce, and most people were still focused on tech and AI stocks. Honestly, I didn’t think much of it.\\n\\nNow it’s April, and gold just crossed $3,330. That’s a 27% jump in four months. And suddenly, fund managers are calling gold the most crowded trade on Wall Street beating out tech for the first time in two years.\\n\\nA lot happened, Inflation hasn’t cooled down as much as people hoped. There’s still a ton of uncertainty around interest rates. And global tensions whether it’s Ukraine, the Middle East, or China have pushed a lot of people toward what they see as “safer” investments.\\n\\nInstead of buying physical gold or a gold ETF, I started looking into gold mining companies. The basic idea is this: when gold prices go up, mining profits usually go up even faster. That’s because their costs stay fairly flat while the value of what they’re digging up increases. So you get more upside though more risk too.\\n\\nAccording to my research there are three types of gold stocks I’ve been looking at:\\n\\n1. Major producers — big mining companies with steady operations.\\n2. Junior miners — smaller companies that might hit it big with a new discovery, but come with more risk.\\n3. Streaming companies — these guys don’t mine gold themselves. They give money to miners upfront and get a portion of the gold in return. Less risk, but less reward too.\\n\\n \\nHere's what I've been tracking:\\n\\nWheaton Precious Metals (WPM) \\nThis one is a streaming company, so it doesn’t operate mines—it collects a share of gold from others. It’s a lower-risk model and still benefits from rising gold prices. Production is up, and they’re projecting long-term growth. The stock’s up over 50%.\\n\\nAgnico Eagle (AEM) \\nSolid company with operations in Canada, Australia, and a few other places. They’ve been steadily growing reserves and investing in new exploration projects. Up nearly 90% this year.\\n\\nKinross Gold (KGC) \\nIt’s up over 120% so far this year. They’ve been selling off riskier assets and doubling down on stable regions like the U.S., Canada, and Brazil. They’re also using AI and automation to cut costs. It’s starting to pay off.\\n\\nGold stocks have clearly run up. Valuations on some names especially the streaming companies are looking expensive. But at the same time, demand is still strong, and a lot of people see gold as a safe bet if things get worse economically or politically.\\n\\n \\nWould it be safer to just buy a gold ETF instead? Something like GLD or IAU?\\n\\n\\n\\n \\n\", 'subreddit': 'investing', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/investing/comments/1k7e847/', 'matched_query': 'semiconductor companies stock recent'}, {'content': \"Title: Don't Sleep on Damon (DMN)\\nContent: This two-wheel electric vehicle company could make for a quick return. Currently, the stock price sits at $0.0035 (as I type this), but they have $100 million in pre-orders for their two motorcycle models, which include safety and accessibility tech you'd find in newer four-wheel vehicles. They're also big on data intelligence, and are open to working with other companies to share info, such as supporting ICE (internal combustion engine) companies to transition. They presented at the Planet MicroCap Showcase just yesterday, which is available online: [https://event.summitcast.com/view/YNz6mnmEsXyrdRxb78w2nX/9WosXgUD44wqvJunNd982Y](https://event.summitcast.com/view/YNz6mnmEsXyrdRxb78w2nX/9WosXgUD44wqvJunNd982Y) (Or just Google it if you don't trust links.) Among other things, they state the global market for electric bikes is forecasted to reach $40 billion by 2030. While the US may have an administration trying to move in the opposite direction of electrification, the world thinks otherwise!\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k70v8k/', 'matched_query': 'semiconductor companies stock recent'}, {'content': 'Title: Warrants—USARW, CRMLW\\nContent: I am a newbie to investing and trading, and I’m very interested in materials mining companies, specifically rare earths. Today I was noticing USAR and CRML have warrant stocks (USARW and CRMLW, respectively).\\n\\nIf I want to buy USARW through my brokerage account, how do I figure out the conversion ratio to common stock? And how would I go about converting it in the future if the common stock goes up?', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k7a03r/', 'matched_query': 'semiconductor companies stock recent'}, {'content': \"Title: Why I think LXRX will be bought out\\nContent: I have been going back and forth on this for weeks now, but recently came across an addition to the 10K that was made effective on March 4th, 2025. That has pushed me from uncertain, to fairly convinced (at least enough to share this) that LXRX is in negotiations for a buyout.\\n\\nThis is a list of things that have been pointing to an M&A in my view, with the recent discovery included and linked at the bottom:\\n\\n* New CEO in July, 2024\\n* ‘Strategic repositioning’ in August 2024, with a roughly 50% reduction in headcount following the failed marketing launch of their lead drug, Inpefa\\n* Licensing of Inpefa to Ex US, Ex EU markets only\\n* COO stepped down and nobody new has been appointed\\n* New CFO in January who has processed M&As before\\n* Apparent disinterest in their lead asset, Inpefa, while news articles have been cheering its potential\\n* Management severance plan: A fairly generous golden parachute, was adopted and put into effect on the 4th of March, 2025.\\n* Deal for Exclusive licensing rights with NVO for their least developed drug, which is M&A neutral in my opinion, however they used the $45 million upfront to immediately pay down debt- Cleaning up their balance sheet\\n\\nThere are other things, like lack of insider open market buys and sells, m&a rumours, otm options contracts, recent fda appeals, and the like that could add extra support to the case, but these aren't as definitive in my opinion as the ones listed above.\\n\\nRun it through your favorite AI and see what it see what it says about these breadcrumbs\\n\\n**Disclosure. I am long stock and options on the ticker**\\n\\nLink to golden parachute in 10K: Crtl+f and search “march 4”\\n\\n[https://www.sec.gov/ix?doc=/Archives/edgar/data/0001062822/000106282225000013/lxrx-20241231.htm](https://www.sec.gov/ix?doc=/Archives/edgar/data/0001062822/000106282225000013/lxrx-20241231.htm)\\n\\nm&a rumour:\\n\\n[https://markets.businessinsider.com/news/stocks/lexicon-rumor-highlighted-in-betaville-alert-1034284419](https://markets.businessinsider.com/news/stocks/lexicon-rumor-highlighted-in-betaville-alert-1034284419)\", 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6vjpa/', 'matched_query': 'semiconductor companies stock recent'}, {'content': 'Title: USAS : Q1 Earnings Estimate for Americas Silver Issued By Cormark\\nContent: Americas Silver Corp ([NYSEAMERICAN:USAS](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/)\\xa0–\\xa0[Free Report](https://www.marketbeat.com/arnreports/ReportTickerOptin.aspx?RegistrationCode=TickerHyperlink&Prefix=NYSEAMERICAN&Symbol=USAS)) – Investment analysts at Cormark issued their Q1 2025 earnings per share (EPS) estimates for shares of Americas Silver in a research report issued to clients and investors on Tuesday, April 22nd. Cormark analyst N. Dion expects that the company will post earnings per share of $0.00 for the quarter. Cormark currently has a “Moderate Buy” rating on the stock. The consensus estimate for Americas Silver’s current full-year earnings is ($0.11) per share.\\xa0\\n\\nSeparately, HC Wainwright boosted their price target on shares of Americas Silver from $0.90 to $1.00 and gave the stock a “buy” rating in a research report on Friday, March 28th.\\n\\n# Americas Silver Price Performance\\n\\nShares of\\xa0[USAS stock](https://www.marketbeat.com/stocks/NYSEAMERICAN/USAS/earnings/)\\xa0opened at $0.62 on Wednesday. The stock has a market cap of $153.43 million, a PE ratio of -3.44 and a beta of 1.20. Americas Silver has a 12 month low of $0.21 and a 12 month high of $0.65. The company has a current ratio of 0.42, a quick ratio of 0.28 and a debt-to-equity ratio of 0.18.\\n\\n# Institutional Trading of Americas Silver\\n\\nHedge funds have recently added to or reduced their stakes in the stock. HighTower Advisors LLC bought a new stake in Americas Silver in the 4th quarter valued at about $47,000. American Century Companies Inc. bought a new stake in shares of Americas Silver in the fourth quarter valued at approximately $73,000. Bank of America Corp DE raised its position in shares of Americas Silver by 273,321.1% in the fourth quarter. Bank of America Corp DE now owns 207,800 shares of the company’s stock valued at $78,000 after purchasing an additional 207,724 shares during the period. JPMorgan Chase & Co. purchased a new stake in shares of Americas Silver during the 4th quarter valued at approximately $94,000. Finally, Cetera Investment Advisers boosted its holdings in Americas Silver by 4.8% in the 4th quarter. Cetera Investment Advisers now owns 428,844 shares of the company’s stock worth $167,000 after buying an additional 19,696 shares during the period. Institutional investors own 13.38% of the company’s stock.\\xa0\\n\\n# About Americas Silver\\n\\nAmericas Gold and Silver Corporation engages in the acquisition, evaluation, exploration, development, and operation of mineral properties. The company explores for silver, lead, zinc and copper. It principally owns 100% interests in the Cosalá Operations consisting of 67 mining concessions that cover approximately 19,385 hectares located in the state of Sinaloa, Mexico; and Galena Complex situated near the town of Wallace in the state of Idaho, the United States.\\n\\n[https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html](https://www.defenseworld.net/2025/04/24/q1-earnings-estimate-for-americas-silver-issued-by-cormark.html)', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6sd43/', 'matched_query': 'semiconductor companies stock recent'}, {'content': 'Title: SS Innovations to Uplist to Nasdaq\\nContent: News Link: [https://www.globenewswire.com/news-release/2025/04/24/3067417/0/en/SS-Innovations-to-Uplist-to-Nasdaq.html](https://www.globenewswire.com/news-release/2025/04/24/3067417/0/en/SS-Innovations-to-Uplist-to-Nasdaq.html)\\n\\n \\nFORT LAUDERDALE, Fla., April 24, 2025 (GLOBE NEWSWIRE) -- [**SS Innovations International, Inc.**](https://www.globenewswire.com/Tracker?data=2JGWgvztYvzBB6B3hP2PuBqN2NwaTepB3EDTsNwuIZ7S0SD2APsUcHFyoqtgBd6hYfIC81SZpVJgixhFUK0HfJD6rd27QvAXsztAmpH14tELe5ANn3jSu_JFE2o8CCco) (the “Company” or “SS Innovations”) (OTC: SSII), a developer of innovative surgical robotic technologies dedicated to making robotic surgery affordable and accessible to a global population, today announced that the Company’s common stock has been approved for listing on The Nasdaq Capital Market® (“Nasdaq”). Trading on Nasdaq is expected to commence on April 25, 2025, and the Company’s shares will continue to be listed under the ticker symbol “SSII”.\\n\\nDr. Sudhir Srivastava, Chairman of the Board and Chief Executive Officer of SS Innovations, commented, “Uplisting to Nasdaq marks an exciting milestone for SS Innovations and reflects our team’s achievements in building a world-class robotic surgery technology platform that is designed to offer top-tier quality, safety, efficiency and affordability, enabling cutting-edge robotic surgical procedures for a wider range of patients globally.\\n\\n“The timing of our uplisting coincides with the beginning of our global expansion beyond India – into Nepal, Ecuador, Guatemala, the Philippines, Indonesia, Sri Lanka and Ukraine – and our planned strategic entry into Europe and the United States. We are pursuing EU CE Mark and U.S. FDA approval for our SSi Mantra surgical robotic system, which we anticipate in late 2025 and early 2026, respectively. We believe that the Nasdaq uplisting will enhance market awareness of our growth story, improve transparency, expand our audience of potential investors, and ultimately increase share liquidity.”\\n\\nDr. Srivastava also highlighted the Company’s recent achievements in advancing its clinically validated, patented surgical robotic system, the “SSi Mantra,” including:\\n\\n* Installing 80 SSi Mantra systems in 75 hospitals across India and other countries;\\n* 3,500+ surgeries performed using the SSi Mantra, including over 195 robotic cardiac surgeries with zero reported device-related mortality, injuries, or complications;\\n* Becoming the first and only company in India to receive Central Drugs Standard Control Organization (CDSCO, India’s equivalent of the U.S. FDA) regulatory approval for use of a robotic surgical system in the performance of telesurgery and tele-proctoring procedures. Since receiving such approvals, the Company has performed 16 telesurgeries using SSi Mantra, including the world’s first robotic cardiac telesurgeries over distances up to 1,200 miles; and\\n* Reporting revenue for the year ended December 31, 2024 of $20.6 million, an approximately 251% increase from 2023 revenue of $5.9 million, and gross margin of 40.9%, an increase from 12.3% in 2023.', 'subreddit': 'pennystocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/pennystocks/comments/1k6rzos/', 'matched_query': 'semiconductor companies stock recent'}, {'content': \"Title: Everything about Google's earnings tonight\\nContent: Alphabet reports first-quarter earnings after today's closing bell. They're the second earnings report among the Magnificent Seven stocks which I'll be posting about on each of their earning days. Alphabet is following Tesla, which, despite disappointing results, gained after news of Elon Musk's increased involvement in the company's operations. \\n\\nSo for GOOG, are we going in on calls or puts? I figured we'd at least need to be informed with what's in the know before deciding. In light of the widespread weakness among leading Big Tech companies (all of these companies have experienced higher declines than the broader US market since the beginning of the year), today's Alphabet earnings will be a significant test of how the company operates in a new environment dominated by uncertainty. I'm not only going to be interested in the financial data but I wanna see the message from the management indicating to investors whether Alphabet is navigating safely through our currently uncertain market.\\n\\n**The Chart**\\n\\nFrom a [TA perspective](https://i.imgur.com/uE3nJVz.png) a double bottom pattern may be forming on Alphabet's chart. If today's earnings results turn out to be a positive surprise and the stock price climbs above the $160.77 level, it could signal a reversal of the downward trend that has been affecting the tech giant's shares since the beginning of 2025. \\n\\n**Earnings**\\n\\nFor Q1, it looks like the market is expecting Alphabet to report revenue of $89.1 billion (+11% y/y). From what I've read, operating income is expected to reach $28.58 billion (+12% y/y). This stronger profit growth implies a slight margin improvement to above 32.08% (+0.45 pp). Tbh, it looks like effective cost management will be one of the biggest challenges for Alphabet in this environment. While sustaining strong revenue growth seems less at risk, managing expenses (especially given capital-intensive AI development plans) will be challenging.\\n\\n**Cloud Services**\\n\\nFor those who are aware, Google Cloud is a thing and is driving massive growth for the company. With rivals signaling a slowdown in data center expansion amid rising uncertainty, Alphabet may either follow a cautious strategy (likely dampening growth) or seize the opportunity to gain market share by acting aggressively.\\n\\nThe second approach would be riskier and more costly, potentially causing erosion in the segment’s operating margin. It would, however, be an investment in the better future market position.\\n\\nI'm going to be watching not just the quarterly results but also the forward outlook and management’s tone regarding the Cloud business. It looks like the Forecasted Cloud segment has a revenue of $12.32 billion for Q1 2025. This would be the h[ighest quarterly result in Alphabet's history](https://i.imgur.com/9uWUntD.png). However, operating income is expected to slightly decline versus the prior quarter, but at $1.94 billion it would still be over twice the result from Q1 2024.\\n\\n**Tariffs** \\n\\nOne of the key topics that I'll especially be closely watching tonight is the impact of tariffs and macroeconomic uncertainty on the company’s operations. Among the major Big Tech companies, Alphabet has shown the greatest resilience to potential geopolitical turmoil and has often demonstrated the fastest recovery following periods of uncertainty.\\n\\nAt this point, they do not appear to be in significantly better shape than its peers, with its stock down approximately 17% year-to-date, placing it squarely in the middle of the Magnificent Seven stocks.\\n\\nI think the first step toward rebuilding investor confidence will be outlining the scope and impact of tariffs and overall geopolitical uncertainty on the company’s operations. As such, the types of questions I expect during today’s conference about how strongly tariffs will affect Alphabet’s business. It is worth noting that this isn’t necessarily about the direct impact (which is likely to be limited) but rather the indirect effect of uncertainty on the willingness of Alphabet’s clients to spend on advertising, which constitutes a significant portion of the company’s revenue.\\n\\n**Price Targets**\\n\\nAmid these earnings expectations, analysts have been revising Alphabet's price targets downward. Over the past few weeks, [several top analysts have revised their 12-month price targets for Alphabet](https://www.tipranks.com/stocks/goog/forecast?utm_source=theglobeandmail.com&utm_medium=referral). TD Cowen lowered its target from $210 to $195. UBS cut its target from $209 to $173. Even Scotiabank lowered its target from $232 to $200. Despite that, they all still rate GOOG stock as a Buy, showing they believe in its long-term value.\\n\\nGuggenheim lowered its target from $215 to $190, while Jefferies adjusted its target from $235 to $200, both maintaining a Buy rating. Piper Sandler and Citi followed suit, reducing their targets to $185 and $195 respectively, citing uncertainties in the advertising landscape and macroeconomic pressures.\\n\\nI mean. With all things considered, the stock is down 19% in 2025 so far. Combine that with rising legal risks (mentioned later here) and an uncertain economy, and you have a good reason to reframe expectations. Analysts aren’t necessarily predicting more downside; they’re just being more realistic about the upside, especially in the near term.\\n\\nIf we’re to simplify the analysts’ overall message, it’s that Alphabet’s fundamentals are strong, but the road ahead could be bumpy.\\n\\n**In the news**\\n\\nA federal court recently ruled that Google violated antitrust laws by monopolizing specific digital advertising markets. The court plans to determine suitable remedies soon. Some analysts believe the ruling could eventually lead to the divestiture of certain Google ad segments, though the financial impact on Alphabet is expected to be modest.\\n\\nThere’s also the bigger picture. Between global tariffs, economic uncertainty, and shifts in labor and costs across the tech industry, Alphabet has a lot on its plate. Investors will want to hear how the company manages expenses, hiring, and regional exposure.\\n\\n**Mergers and Acquisitions**\\n\\nAlphabet announced a $32 billion all-cash deal to acquire cloud security platform Wiz. This acquisition aims to enhance Google Cloud’s security capabilities and multi-cloud operations. Analysts are projecting long-term benefits from this acquisition, despite potential short-term market pressures on other cloud service providers.\\n\\nSeparately, Google has decided to maintain its current approach to offering third-party cookie choices in its Chrome browser, emphasizing the importance of online privacy and user control. This decision is part of Google's ongoing Privacy Sandbox initiative, which aims to strengthen online privacy while supporting a sustainable ad-driven internet environment.\\n\\n**What now?**\\n\\nAlphabet’s stock may be down, but most analysts still believe it’s a long-term winner. That’s why Buy ratings remain steady, even if price targets are down. Q1 earnings could be the reset moment Alphabet needs to win back momentum. I'm thinking short term puts for earnings but holding long term shares. Could even sell covered calls for earnings for some extra income, if you already have the shares. Avg price target is $204.\", 'subreddit': 'wallstreetbets', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/wallstreetbets/comments/1k70ero/', 'matched_query': 'semiconductor companies stock recent'}, {'content': \"Title: Rate My Portfolio - r/Stocks Quarterly Thread March 2025\\nContent: Please use this thread to discuss your portfolio, learn of other stock tickers & portfolios like [Warren Buffet's](https://buffett.online/en/portfolio/), and help out users by giving constructive criticism.\\n\\nWhy quarterly? Public companies report earnings quarterly; many investors take this as an opportunity to rebalance their portfolios. We highly recommend you do some reading: Check out our wiki's list of [relevant posts & book recommendations.](https://www.reddit.com/r/stocks/wiki/index/#wiki_relevant_posts.2C_books.2C_wiki_recommendations)\\n\\nYou can find stocks on your own by using a scanner like your broker's or [Finviz.](https://finviz.com/screener.ashx) To help further, here's a list of [relevant websites.](https://www.reddit.com/r/stocks/wiki/index/#wiki_relevant_websites.2Fapps)\\n\\nIf you don't have a broker yet, see our [list of brokers](https://www.reddit.com/r/stocks/wiki/index/#wiki_brokers_for_investing) or search old posts. If you haven't started investing or trading yet, then setup your [paper trading to learn basics like market orders vs limit orders.](https://www.reddit.com/r/stocks/wiki/index/#wiki_is_there_a_way_to_practice.3F)\\n\\nBe aware of [Business Cycle Investing](https://eresearch.fidelity.com/eresearch/markets_sectors/sectors/si_business_cycle.jhtml?tab=sibusiness) which Fidelity issues updates to the state of global business cycles every 1 to 3 months (note: Fidelity changes their links often, so search for it since their take on it is enlightening). [Investopedia's take on the Business Cycle](https://www.investopedia.com/articles/investing/061316/business-cycle-investing-ratios-use-each-cycle.asp).\\n\\nIf you need help with a falling stock price, check out Investopedia's [The Art of Selling A Losing Position](https://www.investopedia.com/articles/02/022002.asp) and their [list of biases.](https://www.investopedia.com/articles/stocks/08/capital-losses.asp)\\n\\nHere's a list of all the [previous portfolio stickies.](https://www.reddit.com/r/stocks/search?q=author%3Aautomoderator+title%3A%22Rate+My+Portfolio%22&restrict_sr=on&sort=new&t=all)\", 'subreddit': 'stocks', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/stocks/comments/1j0w73o/', 'matched_query': 'semiconductor companies stock recent'}, {'content': \"Title: A Very Rapid' Drop In Domestic Demand Is Hitting Airlines\\nContent: \\nComplement to a former post. \\nAny jump in airlines stock price is just dancing around for now\\n\\nThe Travel crisis that is emerging will affect other industries that profit from tourism, like real estate and Banks\\n\\nhttps://finance.yahoo.com/news/very-rapid-drop-domestic-demand-182820043.html\\n\\nhttps://www.reddit.com/r/wallstreetbets/s/7nEvEsNjpp\\n\\nhttps://sherwood.news/business/us-airlines-in-a-recession-southwest-ceo/\\n\\nOn the international front, for majors Airlines, Chinese and other Asian international tourists are crucial to their long-haul operations. Shanghai Pudong round trip to Dallas-Fort Worth is a common route that is seing drastic decrease for AAL.\\n\\nA downturn in both leisure and business tourism leads to reduced hotel occupancy rates, lower room pricing, and decreased revenue, particularly in tourist-centric cities like Las Vegas, Orlando, and New York City.\\n\\nCompanies/stock potentially affected: Host Hotels & Resorts Inc., Park Hotels & Resorts Inc. \\n\\nTenet Healthcare (THC) – Dallas, TX maybe affcted too. They owns hospitals and medical centers, some of which attract foreign patients for medical tourism.\\n\\nCarnival Corporation (CCL) – Miami, FL, world’s largest cruise line, heavily dependent on international tourists, including Chinese travelers.\\n\\nRoyal Caribbean Group (RCL) – Miami, FL, same as Carnival, with an even more aggressive focus on Asia-Pacific expansion, including China-based cruise itineraries.\\n\\nMany Buffalo/NY small businesses rely on Canadian spending. If revenue drop, they cant pay rent, if they cant pay rent, landlords cant service mortage debt. More businesses will close like in covid or after covid.\\n\\nLennar Corporation (LEN) – Miami, FL, one of the largest homebuilders in the U.S has lot of Chinese buyers: Florida (and Texas) have been targets for foreign real estate investment, particularly by Chinese nationals seeking EB-5 visas or U.S. property. So real estate may be affected too, in this case, may be it will relieve pressure on prices, not sure. But for REITS (real estate investment trusts) that owns properties leased to Hotels and restaurants or Malls or international student housing that depends on international travellers or Transit/transcient business, trouble are ahead in all major US Cities. \\n\\nEvent Spaces & Convention Centers: A reduction in MICE (Meetings, Incentives, Conferences, Exhibitions) activities weakens demand for event spaces and the surrounding businesses that support them. ALL major hotels brand affected.\\n\\nDiversified REITs: These entities, with portfolios spanning retail, hotel, and mixed-use developments in major gateway cities, face indirect impacts from the downturn in tourism and international student presence: Vornado Realty Trust (VNO), BXP, Inc. (BXP)\\n\\nThe third financed asset in size for all major banks after government bonds and other bank is real estate ( commercial and residential)\\n\\nalso, if all foreign countries keep rejecting boeing planes delivery like china, it is the whole aerospace sector that is going down with all of the small industries and SMEs that their business model feeds. \\n\\nhttps://fortune.com/article/boeing-ceo-trump-china-tariff-trade-war-planes-economy/\\n\\nWell no wonder T is saying now: we are discussing with China, but they said: heuuu, no we are not discussing yet. remove all tariffs first, holder of negotiation power is obvious. So until all of this is fixed and factoring at least few months of starring, the crash is coming.\\n\\nAnd we have not even talked about the soccer world cup being potentially cancelled in a year by the US, by FiFa or by implicit boycott by countries outside of Usa because not safe and impact on existing contracts with airlines, hotels and hosting cities that have spent millions\\n\\n\\nI won’t hold a high position when shorting airlines, since they are highly volatile and already close to 52 weeks low. but I will average up a short position. Should back test Covid trading range volatility to see how low it can get\", 'subreddit': 'wallstreetbets', 'score': 0.0, 'date': '', 'url': 'https://reddit.com/r/wallstreetbets/comments/1k71daq/', 'matched_query': 'semiconductor companies stock recent'}]\u001b[0m\u001b[32;1m\u001b[1;3mRecent Reddit discussions related to semiconductor companies' stocks did not appear in the search results. However, I found some relevant information from other discussions:\n", + "\n", + "1. In the subreddit r/investing, there was a post discussing gold stocks hitting $3,300/oz. The post highlighted the significant increase in gold prices and the shift of focus towards gold mining companies due to uncertainties in the market. It also provided insights on different types of gold stocks like major producers, junior miners, and streaming companies.\n", + "\n", + "2. Another post from the subreddit r/wallstreetbets discussed Alphabet's (Google) upcoming first-quarter earnings. It mentioned analysts' expectations for revenue growth and operating income, especially focusing on the impact of tariffs and macroeconomic uncertainty on the company's operations. The post also shared information about Alphabet's recent acquisitions and market outlook.\n", + "\n", + "These discussions provide insights into the current trends and market sentiment in industries other than semiconductor companies. If you are specifically looking for information about semiconductor stocks, it may be helpful to explore more discussions or news related to that sector directly.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "data": { + "text/plain": [ + "{'input': \"What happened to semiconductor companies' stock recently?\",\n", + " 'chat_history': [HumanMessage(content=\"What happened to semiconductor companies' stock recently?\", additional_kwargs={}, response_metadata={}),\n", + " AIMessage(content=\"Recent Reddit discussions related to semiconductor companies' stocks did not appear in the search results. However, I found some relevant information from other discussions:\\n\\n1. In the subreddit r/investing, there was a post discussing gold stocks hitting $3,300/oz. The post highlighted the significant increase in gold prices and the shift of focus towards gold mining companies due to uncertainties in the market. It also provided insights on different types of gold stocks like major producers, junior miners, and streaming companies.\\n\\n2. Another post from the subreddit r/wallstreetbets discussed Alphabet's (Google) upcoming first-quarter earnings. It mentioned analysts' expectations for revenue growth and operating income, especially focusing on the impact of tariffs and macroeconomic uncertainty on the company's operations. The post also shared information about Alphabet's recent acquisitions and market outlook.\\n\\nThese discussions provide insights into the current trends and market sentiment in industries other than semiconductor companies. If you are specifically looking for information about semiconductor stocks, it may be helpful to explore more discussions or news related to that sector directly.\", additional_kwargs={}, response_metadata={})],\n", + " 'output': \"Recent Reddit discussions related to semiconductor companies' stocks did not appear in the search results. However, I found some relevant information from other discussions:\\n\\n1. In the subreddit r/investing, there was a post discussing gold stocks hitting $3,300/oz. The post highlighted the significant increase in gold prices and the shift of focus towards gold mining companies due to uncertainties in the market. It also provided insights on different types of gold stocks like major producers, junior miners, and streaming companies.\\n\\n2. Another post from the subreddit r/wallstreetbets discussed Alphabet's (Google) upcoming first-quarter earnings. It mentioned analysts' expectations for revenue growth and operating income, especially focusing on the impact of tariffs and macroeconomic uncertainty on the company's operations. The post also shared information about Alphabet's recent acquisitions and market outlook.\\n\\nThese discussions provide insights into the current trends and market sentiment in industries other than semiconductor companies. If you are specifically looking for information about semiconductor stocks, it may be helpful to explore more discussions or news related to that sector directly.\"}" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show performance before & after query expansion (craft specific query)\n", + "\n", + "# reranker should be an _extra_ \n", + "\n", + "# tool vs baked in use of query expansion\n", + "\n", + "\n", + "agent_wo_expansion = create_tool_calling_agent(\n", + " llm=llm,\n", + " tools=[reddit_stock_mentions],\n", + " prompt=prompt\n", + ")\n", + "\n", + "query = \"What happened to semiconductor companies' stock recently?\"\n", + "\n", + "AgentExecutor(\n", + " agent=agent_wo_expansion,\n", + " tools=tools,\n", + " memory=ConversationBufferMemory(\n", + " memory_key=\"chat_history\",\n", + " return_messages=True\n", + " ),\n", + " verbose=True,\n", + " handle_parsing_errors=True,\n", + ").invoke({\n", + " \"input\": query,\n", + " \"chat_history\": memory\n", + "})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "735119a3-6a84-46d2-a345-fa53d0aaf276", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "12206f75-c8f6-474c-903f-582a5ec03709", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{}" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Clean up\n", + "\n", + "index.delete(delete_all=True, namespace=NAMESPACE)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7b859919-141e-4a7f-be79-8bc6f5c04f0e", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.4" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}