Estimated reading time: 4 minutes

Building a Stock Price Chatbot with Langchain

Building a Stock Price Chatbot with Langchain

This article demonstrates how to create a simple using Langchain that can fetch and provide current and historical stock prices. We’ll leverage the power of Large Language Models () and the yfinance library to build this interactive tool.

Prerequisites

  • 3.6+
  • Langchain Library: Install using pip install langchain
  • OpenAI 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
 = 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

  1. Import Libraries: We import necessary libraries from Langchain (for the LLM and agent creation) and yfinance for fetching stock data.
  2. Set OpenAI API Key: Ensure you replace "YOUR_OPENAI_API_KEY" with your actual OpenAI API key. This is used for authentication.
  3. Initialize Language Model: We initialize a ChatOpenAI model (gpt-3.5-turbo in this case) with a temperature of 0 for more deterministic responses.
  4. Define Tools: We define two functions, get_stock_price and get_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.
  5. Create Tools List: We create a list containing our defined tools.
  6. 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.
  7. 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

  1. Save the code as a Python file (e.g., stock_chatbot.py).
  2. Install the required libraries using pip install langchain openai yfinance.
  3. Replace "YOUR_OPENAI_API_KEY" with your actual OpenAI API key.
  4. Run the script from your terminal using python stock_chatbot.py.
  5. 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.

Agentic AI (40) AI Agent (27) airflow (7) Algorithm (29) Algorithms (70) apache (51) apex (5) API (115) Automation (59) Autonomous (48) auto scaling (5) AWS (63) aws bedrock (1) Azure (41) BigQuery (22) bigtable (2) blockchain (3) Career (6) Chatbot (20) cloud (128) cosmosdb (3) cpu (41) cuda (14) Cybersecurity (9) database (121) Databricks (18) Data structure (16) Design (90) dynamodb (9) ELK (2) embeddings (31) emr (3) flink (10) gcp (26) Generative AI (18) gpu (23) graph (34) graph database (11) graphql (4) image (39) indexing (25) interview (7) java (33) json (73) Kafka (31) LLM (48) LLMs (41) Mcp (4) monitoring (109) Monolith (6) mulesoft (4) N8n (9) Networking (14) NLU (5) node.js (14) Nodejs (6) nosql (26) Optimization (77) performance (167) Platform (106) Platforms (81) postgres (4) productivity (20) programming (41) pseudo code (1) python (90) pytorch (19) RAG (54) rasa (5) rdbms (5) ReactJS (1) realtime (2) redis (15) Restful (6) rust (2) salesforce (15) Spark (34) sql (58) tensor (11) time series (18) tips (12) tricks (29) use cases (67) vector (50) vector db (5) Vertex AI (21) Workflow (57)

Leave a Reply