This article demonstrates how to create a simple chatbot using Langchain that can fetch and provide current and historical stock prices. We’ll leverage the power of Large Language Models (LLMs) and the yfinance
library to build this interactive tool.
Prerequisites
- Python 3.6+
- Langchain Library: Install using
pip install langchain
- OpenAI API Key: You’ll need an API key from OpenAI.
- yfinance Library: Install using
pip install yfinance
The Python Code
Here’s the Python code that implements the stock price chatbot:
import os
from langchain.chat_models import ChatOpenAI
from langchain.agents import create_openapi_agent
from langchain.tools import tool
import yfinance as yf
# You'll need an OpenAI API key
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY" # Replace with your actual API key
# Initialize the ChatOpenAI model
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
@tool
def get_stock_price(ticker: str) -> float:
\"\"\"Get the current stock price for a given ticker symbol.\"\"\"
try:
data = yf.Ticker(ticker)
info = data.info
if 'currentPrice' in info:
return info['currentPrice']
elif 'regularMarketPrice' in info:
return info['regularMarketPrice']
else:
return f"Could not retrieve the current price for {ticker}."
except Exception as e:
return f"An error occurred: {e}"
@tool
def get_historical_stock_data(ticker: str, period: str = "1mo") -> str:
\"\"\"Get historical stock data for a given ticker and period (e.g., 1mo, 3mo, 1y, 5y).\"\"\"
try:
data = yf.Ticker(ticker)
hist = data.history(period=period)
return hist.to_string()
except Exception as e:
return f"An error occurred: {e}"
tools = [get_stock_price, get_historical_stock_data]
# Create the agent
stock_agent = create_openapi_agent(
llm=llm,
tools=tools,
prompt=(
"You are a helpful chatbot that can provide information about stock prices."
"Use the available tools to answer user questions about current and historical stock data."
"Be concise and informative in your responses."
)
)
# Example usage:
if __name__ == "__main__":
while True:
query = input("Ask about a stock price (or type 'exit'): ")
if query.lower() == 'exit':
break
response = stock_agent.run(query)
print(response)
Explanation of the Code
- Import Libraries: We import necessary libraries from Langchain (for the LLM and agent creation) and
yfinance
for fetching stock data. - Set OpenAI API Key: Ensure you replace
"YOUR_OPENAI_API_KEY"
with your actual OpenAI API key. This is used for authentication. - Initialize Language Model: We initialize a
ChatOpenAI
model (gpt-3.5-turbo
in this case) with atemperature
of 0 for more deterministic responses. - Define Tools: We define two functions,
get_stock_price
andget_historical_stock_data
, and decorate them with@tool
. This makes them accessible to the Langchain agent.get_stock_price
fetches the current stock price for a given ticker.get_historical_stock_data
fetches historical stock data for a specified ticker and period.
- Create Tools List: We create a list containing our defined tools.
- Create the Agent: We use
create_openapi_agent
to instantiate our Langchain agent, providing the LLM, the list of tools, and a prompt that defines the agent’s role and behavior. - Example Usage: The
if __name__ == "__main__":
block demonstrates how to run the chatbot in a loop, taking user input and printing the agent’s response.
Running the Chatbot
- Save the code as a Python file (e.g.,
stock_chatbot.py
). - Install the required libraries using
pip install langchain openai yfinance
. - Replace
"YOUR_OPENAI_API_KEY"
with your actual OpenAI API key. - Run the script from your terminal using
python stock_chatbot.py
. - You can then ask questions like “What is the current price of AAPL?” or “Get me the historical stock data for TSLA over the last month.”
Further Exploration
This is a basic example. You can extend this chatbot in many ways, such as:
- Adding error handling for invalid ticker symbols or API issues.
- Improving the prompt to guide the agent for more specific responses.
- Integrating memory to maintain conversation history.
- Adding more sophisticated tools for news, financial ratios, or charting.
- Building a web interface using frameworks like Flask or Streamlit.
Explore the Langchain documentation to learn more about its capabilities and how to build more advanced applications.
Leave a Reply