What in case you might ask Warren Buffett a couple of inventory, market traits, or long-term investing, anytime you wished? With reviews suggesting he could quickly step down as CEO of Berkshire Hathaway, it’s a very good second to mirror on the lasting worth of his ideas. For many years, Buffett has been a gentle voice in investing, identified for his give attention to worth, endurance, and understanding what you personal. On this information, I’ll present you the way to flip these ideas right into a conversational Warren Buffett agent that evaluates corporations by way of his lens, and interacts utilizing real-time inventory knowledge and information. The purpose isn’t to recreate Buffett, however to construct a chatbot that helps you suppose the best way he would possibly.
Venture Objective and Structure
Our goal is obvious: Create a Warren Buffett agent that interacts like him It ought to focus on funding philosophy, analyze shares utilizing his core ideas, and leverage real-time knowledge.

The primary elements are:
- Language Mannequin (OpenAI): Supplies the conversational potential and persona adherence.
- LangChain: Acts because the framework, connecting the language mannequin, instruments, and reminiscence.
- Inventory Knowledge API (Yahoo Finance): Fetches present inventory costs and basic knowledge.
- Information API (SerpAPI): Retrieves current information headlines for context.
- Streamlit: Builds the web-based chat interface for consumer interplay.
If that is your first time constructing brokers, checkout our detailed information – Easy methods to Construct an AI Agent from Scratch?
Step 1: Put together Your Atmosphere
Earlier than coding, guarantee your laptop is prepared.
- Set up Python: You want Python model 3.8 or newer.
- Get API Keys: Acquire an API key from OpenAI for language capabilities. Get one other key from SerpAPI for information searches. Maintain these keys safe.
- Set up Libraries: Open your laptop’s terminal or command immediate. Run the next command to put in the mandatory
- Python packages:
pip set up langchain langchain-openai langchain-community openai yfinance google-search-results streamlit python-dotenv streamlit-chat
- Create .env File (Elective): Within the listing the place you’ll save your script, you’ll be able to create a file named .env. Add your keys like this:
OPENAI_API_KEY="sk-YOUR_KEY_HERE"
SERPAPI_API_KEY="YOUR_KEY_HERE"
Step 2: Begin the Script and Import Libraries
Create a brand new Python file (e.g., buffett_chatbot.py). Start by importing the required modules on the high:
import streamlit as st
import os
import json
import yfinance as yf
from dotenv import load_dotenv
# LangChain elements
from langchain_openai import ChatOpenAI
from langchain.brokers import AgentExecutor, create_openai_functions_agent
from langchain.reminiscence import ConversationBufferMemory
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import SystemMessage # No want for HumanMessage/AIMessage right here anymore
from langchain.instruments import Device
from langchain_community.utilities import SerpAPIWrapper
# --- Load .env file (as a fallback) ---
load_dotenv()
These imports usher in Streamlit for the interface, os for surroundings variables, json for knowledge dealing with, yfinance for shares, dotenv for key loading, and numerous LangChain elements for the agent logic.
Step 3: Set-up the Streamlit Interface
Configure the essential utility structure and create sidebar inputs for API keys:
# --- Web page Config ---
st.set_page_config(page_title="Warren Buffett Bot", structure="extensive")
st.title("Warren Buffett Funding Chatbot 📈")
st.caption("Ask me about investing, shares, or market knowledge - within the fashion of Warren Buffett.")
# --- API Key Enter in Sidebar ---
st.sidebar.header("API Configuration")
# Initialize session state for keys if they do not exist
if 'openai_api_key' not in st.session_state:
st.session_state.openai_api_key = ""
if 'serpapi_api_key' not in st.session_state:
st.session_state.serpapi_api_key = ""
# Create textual content enter fields for keys, storing values in session state
input_openai_key = st.sidebar.text_input(
"OpenAI API Key", sort="password", worth=st.session_state.openai_api_key, key="openai_input"
)
input_serpapi_key = st.sidebar.text_input(
"SerpAPI API Key", sort="password", worth=st.session_state.serpapi_key, key="serpapi_input"
)
# Replace session state with present enter values
st.session_state.openai_api_key = input_openai_key
st.session_state.serpapi_key = input_serpapi_key
# Decide which keys are lively (consumer enter takes precedence)
active_openai_key = st.session_state.openai_api_key or os.getenv("OPENAI_API_KEY")
active_serpapi_key = st.session_state.serpapi_api_key or os.getenv("SERPAPI_API_KEY")
# --- Show API Standing ---
st.sidebar.header("API Standing")
# (Add the if/else blocks utilizing st.sidebar.success/error/warning as within the supplied code)
if active_openai_key: st.sidebar.success(...) else: st.sidebar.error(...)
# Verify and show SerpAPI standing equally
This code units up the visible a part of the Streamlit chatbot utility. It makes use of st.session_state to recollect the API keys entered by the consumer throughout their session.
Step 4: Outline Core Settings and the Buffett Persona
Set up constants for the AI mannequin and outline the detailed directions (system immediate) that form the chatbot’s character:
# --- Constants & Immediate ---
MODEL_NAME = "gpt-4o" # Specify the OpenAI mannequin
TEMPERATURE = 0.5 # Controls AI creativity (decrease is extra predictable)
MEMORY_KEY = "chat_history" # Key for storing dialog historical past
BUFFETT_SYSTEM_PROMPT = """
You're a conversational AI assistant modeled after Warren Buffett, the legendary worth investor. Embody his persona precisely.
**Your Core Rules:**
* **Worth Investing:** Give attention to discovering undervalued corporations with stable fundamentals (earnings, low debt, sturdy administration). Decide companies, not inventory tickers.
* **Lengthy-Time period Horizon:** Assume by way of many years, not days or months. Discourage short-term hypothesis and market timing.
* **Margin of Security:** Solely make investments when the market value is considerably beneath your estimate of intrinsic worth. Be conservative.
* **Enterprise Moats:** Favor corporations with sturdy aggressive benefits (sturdy manufacturers, community results, low-cost manufacturing, regulatory benefits).
* **Perceive the Enterprise:** Solely put money into corporations you perceive. "Threat comes from not understanding what you are doing."
* **Administration High quality:** Assess the integrity and competence of the corporate's management.
* **Persistence and Self-discipline:** Await the appropriate alternatives ("fats pitches"). Keep away from pointless exercise. Be rational and unemotional.
* **Circle of Competence:** Persist with industries and companies you'll be able to fairly perceive. Acknowledge what you do not know.
**Your Communication Type:**
* **Sensible and Folksy:** Use easy language, analogies, and occasional humor, very like Buffett does in his letters and interviews.
* **Affected person and Calm:** Reply thoughtfully, avoiding hype or panic.
* **Instructional:** Clarify your reasoning clearly, referencing your core ideas.
* **Prudent:** Be cautious about making particular purchase/promote suggestions with out thorough evaluation primarily based in your ideas. Usually, you would possibly clarify *how* you'd analyze it reasonably than giving a direct 'sure' or 'no'.
* **Quote Your self:** Sometimes weave in well-known Buffett quotes the place applicable (e.g., "Worth is what you pay; worth is what you get.", "Be fearful when others are grasping and grasping when others are fearful.").
* **Acknowledge Limitations:** If requested about one thing exterior your experience (e.g., complicated tech you would not put money into, short-term buying and selling), politely state it isn't your space.
**Interplay Tips:**
* When requested for inventory suggestions, first use your instruments to collect basic knowledge (P/E, earnings, debt if attainable) and up to date information.
* Analyze the gathered info by way of the lens of your core ideas (moat, administration, valuation, long-term prospects).
* Clarify your thought course of clearly.
* If an organization appears to suit your standards, categorical cautious optimism, emphasizing the necessity for additional due diligence by the investor.
* If an organization does not match (e.g., too speculative, excessive P/E with out justification, exterior circle of competence), clarify why primarily based in your ideas.
* If requested for common recommendation, draw upon your well-known philosophies.
* Keep conversational context utilizing the supplied chat historical past. Refer again to earlier factors if related.
Bear in mind: You're simulating Warren Buffett. Your purpose is to offer insights constant along with his philosophy and communication fashion, leveraging the instruments for knowledge when wanted. Don't give definitive monetary recommendation, however reasonably educate and clarify the *Buffett means* of fascinated about investments.
"""
Implement the features that enable the chatbot to get exterior inventory and information knowledge.
# --- Device Definitions ---
# 1. Inventory Knowledge Device (Yahoo Finance) - No adjustments wanted right here
@st.cache_data(show_spinner=False) # Add caching for yfinance calls
def get_stock_info(image: str) -> str:
# ... (hold the present get_stock_info operate code) ...
"""
Fetches key monetary knowledge for a given inventory image utilizing Yahoo Finance...
"""
strive:
ticker = yf.Ticker(image)
information = ticker.information
if not information or information.get('regularMarketPrice') is None and information.get('currentPrice') is None and information.get('previousClose') is None:
hist = ticker.historical past(interval="5d")
if hist.empty:
return f"Error: Couldn't retrieve any knowledge for image {image}."
last_close = hist['Close'].iloc[-1] if not hist.empty else 'N/A'
current_price = information.get("currentPrice") or information.get("regularMarketPrice") or last_close
else:
current_price = information.get("currentPrice") or information.get("regularMarketPrice") or information.get("previousClose", "N/A")
knowledge = {
"image": image, "companyName": information.get("longName", "N/A"),
"currentPrice": current_price, "peRatio": information.get("trailingPE") or information.get("forwardPE", "N/A"),
"earningsPerShare": information.get("trailingEps", "N/A"), "marketCap": information.get("marketCap", "N/A"),
"dividendYield": information.get("dividendYield", "N/A"), "priceToBook": information.get("priceToBook", "N/A"),
"sector": information.get("sector", "N/A"), "business": information.get("business", "N/A"),
"abstract": information.get("longBusinessSummary", "N/A")[:500] + ("..." if len(information.get("longBusinessSummary", "")) > 500 else "")
}
if knowledge["currentPrice"] == "N/A": return f"Error: Couldn't retrieve present value for {image}."
return json.dumps(knowledge)
besides Exception as e: return f"Error fetching knowledge for {image} utilizing yfinance: {str(e)}."
stock_data_tool = Device(
identify="get_stock_financial_data",
func=get_stock_info,
description="Helpful for fetching basic monetary knowledge for a particular inventory image (ticker)..." # Maintain description
)
# 2. Information Search Device (SerpAPI) - Now makes use of active_serpapi_key
def create_news_search_tool(api_key):
if api_key:
strive:
params = {"engine": "google_news", "gl": "us", "hl": "en", "num": 5}
search_wrapper = SerpAPIWrapper(params=params, serpapi_api_key=api_key)
# Take a look at connectivity throughout creation (non-obligatory, can decelerate startup)
# search_wrapper.run("take a look at question")
return Device(
identify="search_stock_news",
func=search_wrapper.run,
description="Helpful for looking out current information articles a couple of particular firm or inventory image..." # Maintain description
)
besides Exception as e:
print(f"SerpAPI Device Creation Warning: {e}")
# Fallback to a dummy instrument if key's supplied however invalid/error happens
return Device(
identify="search_stock_news",
func=lambda x: f"Information search unavailable (SerpAPI key configured, however error occurred: {e}).",
description="Information search instrument (at the moment unavailable as a result of configuration error)."
)
else:
# Dummy instrument if no key's accessible
return Device(
identify="search_stock_news",
func=lambda x: "Information search unavailable (SerpAPI key not supplied).",
description="Information search instrument (unavailable - API key wanted)."
)
news_search_tool = create_news_search_tool(active_serpapi_key)
instruments = [stock_data_tool, news_search_tool]
These features grow to be the ‘senses’ of your inventory knowledge evaluation bot, permitting it to entry present info. Wrapping them as Device objects makes them usable by LangChain.
Step 6: Assemble the LangChain Agent
Configure the core AI logic: the language mannequin, the immediate construction, reminiscence administration, and the agent executor that ties them collectively. This occurs inside the primary a part of the script, typically inside conditional checks.
# --- Major App Logic ---
# Verify if the important OpenAI key's supplied
if not active_openai_key:
st.warning("Please enter your OpenAI API Key within the sidebar...", icon="🔑")
st.cease() # Cease if no key
# --- LangChain Agent Setup (conditional on key) ---
strive:
# Initialize the OpenAI LLM
llm = ChatOpenAI(
mannequin=MODEL_NAME, temperature=TEMPERATURE, openai_api_key=active_openai_key
)
# Create the immediate template
prompt_template = ChatPromptTemplate.from_messages(
[
SystemMessage(content=BUFFETT_SYSTEM_PROMPT),
MessagesPlaceholder(variable_name=MEMORY_KEY),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
# Initialize or re-initialize agent elements in session state
reinitialize_agent = False
# (Add the logic to test if 'agent_executor' exists or if keys modified)
# ...
if reinitialize_agent:
# Initialize reminiscence
st.session_state['memory'] = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)
# Create the agent
agent = create_openai_functions_agent(llm, instruments, prompt_template)
# Create the executor
st.session_state['agent_executor'] = AgentExecutor(
agent=agent, instruments=instruments, reminiscence=st.session_state['memory'], verbose=True, # Set verbose=False for manufacturing
handle_parsing_errors=True, max_iterations=5
)
# Retailer keys used for this agent occasion
st.session_state.agent_openai_key = active_openai_key
st.session_state.agent_serpapi_key = active_serpapi_key
# st.experimental_rerun() # Rerun to use adjustments
# Proceed with chat historical past initialization and show...
That is the core LangChain chatbot growth part. It units up the agent utilizing the persona, instruments, and reminiscence, enabling clever dialog through OpenAI API integration. Utilizing st.session_state right here is important for sustaining the agent’s reminiscence throughout consumer interactions.
Step 7: Implement the Chat Interplay Loop
Add the code that handles displaying the dialog and processing consumer enter by way of the agent.
# --- Chat Historical past and Interplay ---
# Initialize chat historical past if it does not exist
if "messages" not in st.session_state:
st.session_state["messages"] = [
{"role": "assistant", "content": "Greetings! ..."} # Initial message
]
# Show current chat messages
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
# Get new consumer enter
if immediate := st.chat_input("Ask Buffett Bot..."):
# Show consumer message
st.session_state.messages.append({"position": "consumer", "content material": immediate})
st.chat_message("consumer").write(immediate)
# Put together enter for the agent
agent_input = {"enter": immediate}
# Invoke the agent executor
strive:
with st.spinner("Buffett is pondering..."):
# Get the executor occasion from session state
agent_executor_instance = st.session_state['agent_executor']
response = agent_executor_instance.invoke(agent_input)
# Show assistant response
output = response.get('output', "Sorry, an error occurred.")
st.session_state.messages.append({"position": "assistant", "content material": output})
st.chat_message("assistant").write(output)
besides Exception as e:
# Deal with errors throughout agent execution
error_message = f"An error occurred: {str(e)}"
st.error(error_message, icon="🔥")
# Add error to talk show
st.session_state.messages.append({"position": "assistant", "content material": f"Sorry... {e}"})
st.chat_message("assistant").write(f"Sorry... {e}")
# Elective: Add the button to clear historical past
if st.sidebar.button("Clear Chat Historical past"):
# (Code to clear st.session_state.messages and st.session_state.reminiscence)
st.rerun()
This half makes the Streamlit chatbot utility interactive. It reads consumer enter, sends it to the LangChain agent executor, and shows each the consumer’s question and the bot’s generated response.
Step 8: Run the Warren Buffett Agent
Save the entire Python script. Open your terminal within the script’s listing and run:
streamlit run buffett_chatbot.py
Run this file within the terminal and your browser will open the applying, prepared so that you can enter API keys and work together with the chatbot.
Analysing the Output
Let’s take a look at Mr. Buffett agent with a few of our questions. You may entry the identical right here.

Our streamlit app seems like this, Right here now we have the choice to fill our personal OpenAI key and SerpAPI key. Now lets take a look at the bot…
Query 1: “Mr. Buffett, might you clarify your core funding philosophy in easy phrases?”

Query 2: “Analyze Apple (AAPL) primarily based on its present fundamentals. Would you take into account it a very good long-term funding primarily based in your ideas?”

Query 3: “What are your ideas on Microsoft (MSFT) contemplating its current information and developments?”

Based mostly on the above outputs, we will see that the bot is performing nicely and utilizing all its functionalities to get to the ultimate output. It’s utilizing Warren Buffet persona that we outlined earlier to reply all of the questions. The bot is using yfinance to get the newest inventory costs and PE ratios. SerpAPI is used to get the newest information on the shares.
Conclusion
This Warren Buffett agent is usually a helpful companion for anybody seeking to discover worth investing by way of the lens of timeless ideas. Whether or not you’re simply beginning out or refining your strategy, this agent will help you suppose extra clearly and patiently concerning the markets, similar to Buffett would.
You may strive it dwell right here: BuffettBot on Hugging Face.
Have a query you’d just like the agent to reply? Drop it within the feedback, I’d love to listen to what you ask and the way the agent responds.
Regularly Requested Questions
OpenAI: Go to platform.openai.com, join, and navigate to the API keys part.
SerpAPI: Go to serpapi.com, register, and discover your API key in your account dashboard.
A. The bot makes use of Yahoo Finance through yfinance. Whereas typically dependable for extensively traded shares, knowledge can have delays or occasional inaccuracies. It’s good for instructional functions however at all times cross-reference with official sources for precise funding choices.
A. Completely. Modify the BUFFETT_SYSTEM_PROMPT string within the code. You may modify his ideas, communication fashion, and even add particular information areas.
A. This occurs in case you haven’t supplied a legitimate SerpAPI key within the sidebar or the .env file, or if there was an error connecting to SerpAPI.
A. No. This chatbot is an academic simulation primarily based on Warren Buffett’s fashion and ideas. It doesn’t present monetary recommendation. All the time seek the advice of with a professional monetary advisor earlier than making funding choices.
Login to proceed studying and luxuriate in expert-curated content material.