Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ChatOllama does not parse yfinance output correctly #28934

Open
5 tasks done
dlin95123 opened this issue Dec 27, 2024 · 2 comments
Open
5 tasks done

ChatOllama does not parse yfinance output correctly #28934

dlin95123 opened this issue Dec 27, 2024 · 2 comments
Labels
🤖:bug Related to a bug, vulnerability, unexpected error with an existing feature Ɑ: models Related to LLMs or chat model modules

Comments

@dlin95123
Copy link

Checked other resources

  • I added a very descriptive title to this issue.
  • I searched the LangChain documentation with the integrated search.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).

Example Code

from dotenv import load_dotenv
import os

load_dotenv()

from langchain_ollama import ChatOllama
from langchain_openai import ChatOpenAI
from langchain_groq import ChatGroq
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate

from langchain_core.tools import tool
import yfinance as yf

llm = ChatOllama(model='llama3.1', temperature=0)
#llm = ChatGroq(model='llama-3.1-8b-instant', temperature =0)
#llm = ChatOpenAI(model='gpt-4o-mini', temperature = 0)

from langchain_core.tools import tool, StructuredTool
from datetime import date

@tool
def company_information(ticker: str) -> dict:
"""Use this tool to retrieve company information like address, industry, sector, company officers, business summary, website,
marketCap, current price, ebitda, total debt, total revenue, debt-to-equity, etc."""

ticker_obj = yf.Ticker(ticker)
ticker_info = ticker_obj.get_info()

return ticker_info

@tool
def last_dividend_and_earnings_date(ticker: str) -> dict:
"""
Use this tool to retrieve company's last dividend date and earnings release dates.
It does not provide information about historical dividend yields.
"""
ticker_obj = yf.Ticker(ticker)

return ticker_obj.get_calendar()

@tool
def summary_of_mutual_fund_holders(ticker: str) -> dict:
"""
Use this tool to retrieve company's top mutual fund holders.
It also returns their percentage of share, stock count and value of holdings.
"""
ticker_obj = yf.Ticker(ticker)
mf_holders = ticker_obj.get_mutualfund_holders()

return mf_holders.to_dict(orient="records")

@tool
def summary_of_institutional_holders(ticker: str) -> dict:
"""
Use this tool to retrieve company's top institutional holders.
It also returns their percentage of share, stock count and value of holdings.
"""
ticker_obj = yf.Ticker(ticker)
inst_holders = ticker_obj.get_institutional_holders()

return inst_holders.to_dict(orient="records")

@tool
def stock_grade_updrages_downgrades(ticker: str) -> dict:
"""
Use this to retrieve grade ratings upgrades and downgrades details of particular stock.
It'll provide name of firms along with 'To Grade' and 'From Grade' details. Grade date is also provided.
"""
ticker_obj = yf.Ticker(ticker)

curr_year = date.today().year

upgrades_downgrades = ticker_obj.get_upgrades_downgrades()
upgrades_downgrades = upgrades_downgrades.loc[upgrades_downgrades.index > f"{curr_year}-01-01"]
upgrades_downgrades = upgrades_downgrades[upgrades_downgrades["Action"].isin(["up", "down"])]

return upgrades_downgrades.to_dict(orient="records")

@tool
def stock_splits_history(ticker: str) -> dict:
"""
Use this tool to retrieve company's historical stock splits data.
"""
ticker_obj = yf.Ticker(ticker)
hist_splits = ticker_obj.get_splits()

return hist_splits.to_dict()

@tool
def stock_news(ticker: str) -> dict:
"""
Use this to retrieve latest news articles discussing particular stock ticker.
"""
ticker_obj = yf.Ticker(ticker)

return ticker_obj.get_news()

from langchain.agents import AgentExecutor
from langchain.agents import create_tool_calling_agent

#from langchain.prompts import ChatPromptTemplate
from langchain_core.prompts import MessagesPlaceholder

tools = [
company_information,
last_dividend_and_earnings_date,
stock_splits_history,
summary_of_mutual_fund_holders,
summary_of_institutional_holders,
stock_grade_updrages_downgrades,
stock_news
]
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. Try to answer user query using available tools. Parse the input carefully.",
),
MessagesPlaceholder(variable_name="messages"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)

agent = create_tool_calling_agent(llm, tools, prompt)

agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

from langchain_core.messages import HumanMessage

resp = agent_executor.invoke({"messages": [HumanMessage(content="What is address of Nike?")]})

Error Message and Stack Trace (if applicable)

No response

Description

I am testing local LLMs with ChatOllama and using llama3.1 for answering output from yfinance. I found that it cannot answer simple question like "What is Nike's address?". It can answer longer questions okay, just not short question.

It works pretty well with ChatOpenAI() and ChatGroq() with the same model. You can reproduce the issue with the attached code.

System Info

System Information

OS: Windows
OS Version: 10.0.22631
Python Version: 3.12.8 (tags/v3.12.8:2dc476b, Dec 3 2024, 19:30:04) [MSC v.1942 64 bit (AMD64)]

Package Information

langchain_core: 0.3.28
langchain: 0.3.12
langchain_community: 0.3.12
langsmith: 0.2.3
langchain_groq: 0.2.2
langchain_huggingface: 0.1.0
langchain_ollama: 0.2.1
langchain_openai: 0.2.12
langchain_text_splitters: 0.3.3
langgraph_sdk: 0.1.45

Optional packages not installed

langserve

Other Dependencies

aiohttp: 3.11.10
async-timeout: Installed. No version info available.
dataclasses-json: 0.6.7
groq: 0.13.1
httpx: 0.27.2
httpx-sse: 0.4.0
huggingface-hub: 0.25.1
jsonpatch: 1.33
langsmith-pyo3: Installed. No version info available.
numpy: 1.26.4
ollama: 0.4.4
openai: 1.58.1
orjson: 3.10.12
packaging: 24.2
pydantic: 2.9.2
pydantic-settings: 2.7.0
PyYAML: 6.0.2
requests: 2.32.3
requests-toolbelt: 1.0.0
sentence-transformers: 3.3.1
SQLAlchemy: 2.0.36
tenacity: 9.0.0
tiktoken: 0.8.0
tokenizers: 0.21.0
transformers: 4.47.0
typing-extensions: 4.12.2

@dosubot dosubot bot added Ɑ: models Related to LLMs or chat model modules 🤖:bug Related to a bug, vulnerability, unexpected error with an existing feature labels Dec 27, 2024
@keenborder786
Copy link
Contributor

You need to update your system Prompt and make it more comprehensive, something like this should work:

## System Prompt for Agent

You are a financial insights assistant equipped with specialized tools for retrieving and analyzing stock market data and company information. You have access to the following tools to assist users effectively:

1. **`company_information(ticker: str)`**  
   Retrieve comprehensive company details, including address, industry, sector, officers, business summary, website, financial metrics (e.g., market cap, EBITDA, total debt, revenue, debt-to-equity ratio), and current price.

2. **`last_dividend_and_earnings_date(ticker: str)`**  
   Get the most recent dividend payment date and earnings release dates for a company.

3. **`summary_of_mutual_fund_holders(ticker: str)`**  
   Provide a summary of the top mutual fund holders, including their percentage of shares, stock count, and the value of their holdings.

4. **`summary_of_institutional_holders(ticker: str)`**  
   Offer insights into the top institutional holders of a company, detailing their percentage of shares, stock count, and the value of their holdings.

5. **`stock_grade_updrages_downgrades(ticker: str)`**  
   Retrieve the latest grade rating upgrades and downgrades for a stock, including the firms involved, the updated grades, previous grades, and the dates of these actions.

6. **`stock_splits_history(ticker: str)`**  
   Access the historical stock split data for a company.

7. **`stock_news(ticker: str)`**  
   Fetch the latest news articles discussing the specified stock ticker.

### Role and Instructions
You act as a professional financial assistant for users, providing accurate and timely information based on their queries. Your role involves:
- Understanding user needs and selecting the appropriate tool.
- Explaining the information retrieved clearly and concisely.
- Providing actionable insights or clarifications when necessary.

When a user mentions a stock ticker (e.g., "AAPL" for Apple Inc.), ensure:
- You confirm the ticker's validity before processing.
- You provide responses in a structured and professional tone.

Always prioritize user understanding by avoiding jargon and ensuring outputs are directly relevant to their inquiries.

@dlin95123
Copy link
Author

Your modified system prompt yields the same results. It does not improve the results. Note that ChatGroq yields correct answers for both system prompts (my original and your modified) with the same LLM model, Llama3.1:8b, as used for ChatOllama. With ChatGroq, it answers the address correctly. But with ChatOllama, it yields the following answer:

Based on the provided JSON data, here are some key statistics and insights about Nike, Inc. (NKE):

Financials

  • Market Capitalization: $113.8 billion
  • Enterprise Value: $116.6 billion
  • Total Debt: $121.3 billion
  • Cash and Cash Equivalents: $10.2 billion
  • Earnings Per Share (EPS): $3.24 (trailing), $3.23 (forward)
  • Revenue Growth: -0.104% (quarter-over-quarter)

Valuation

  • Price-to-Earnings (P/E) Ratio: 23.59 (trailing), 29.07 (forward)
  • Price-to-Book (P/B) Ratio: 7.96
  • Dividend Yield: 0.0208%
  • Forward P/E Ratio: 29.07

Growth

  • Earnings Growth: -0.255% (quarter-over-quarter)
  • Revenue Growth: -0.104% (quarter-over-quarter)

Operational Performance

  • Gross Margin: 44.97%
  • Operating Margin: 10.43%
  • Return on Equity (ROE): 37.98%
  • Free Cash Flow: $6.57 billion

Analyst Estimates

  • Average Analyst Rating: Buy
  • Recommendation Mean: 2.18
  • Number of Analysts: 34

Industry and Market Positioning

Please note that these statistics are based on the provided JSON data and may not reflect the current market situation or future performance of Nike, Inc. (NKE).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🤖:bug Related to a bug, vulnerability, unexpected error with an existing feature Ɑ: models Related to LLMs or chat model modules
Projects
None yet
Development

No branches or pull requests

2 participants