Construct Your Personal Warren Buffett Agent in 5 Minutes

What in case you might ask Warren Buffett a few inventory, market tendencies, or long-term investing, anytime you needed? With experiences suggesting he might quickly step down as CEO of Berkshire Hathaway, it’s an excellent second to mirror on the lasting worth of his rules. For many years, Buffett has been a gentle voice in investing, recognized for his concentrate on worth, persistence, and understanding what you personal. On this information, I’ll present you how one can flip these rules right into a conversational Warren Buffett agent that evaluates corporations by his lens, and interacts utilizing real-time inventory information and information. The aim isn’t to recreate Buffett, however to construct a chatbot that helps you assume the way in which he may.

Venture Purpose and Structure

Our goal is evident: Create a Warren Buffett agent that interacts like him It ought to talk about funding philosophy, analyze shares utilizing his core rules, and leverage real-time information.

Construct Your Personal Warren Buffett Agent in 5 Minutes

The primary parts are:

  1. Language Mannequin (OpenAI): Gives the conversational skill and persona adherence.
  2. LangChain: Acts because the framework, connecting the language mannequin, instruments, and reminiscence.
  3. Inventory Knowledge API (Yahoo Finance): Fetches present inventory costs and basic information.
  4. Information API (SerpAPI): Retrieves latest information headlines for context.
  5. Streamlit: Builds the web-based chat interface for consumer interplay.

If that is your first time constructing brokers, checkout our detailed information – Learn how to Construct an AI Agent from Scratch?

Step 1: Put together Your Setting

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. Hold these keys safe.
  • Set up Libraries: Open your laptop’s terminal or command immediate. Run the next command to put in the required
  • 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 parts

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 Software

from langchain_community.utilities import SerpAPIWrapper

# --- Load .env file (as a fallback) ---

load_dotenv()

These imports usher in Streamlit for the interface, os for atmosphere variables, json for information dealing with, yfinance for shares, dotenv for key loading, and numerous LangChain parts for the agent logic.

Step 3: Set-up the Streamlit Interface

Configure the essential software format and create sidebar inputs for API keys:

# --- Web page Config ---

st.set_page_config(page_title="Warren Buffett Bot", format="broad")

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 offered code)

if active_openai_key: st.sidebar.success(...) else: st.sidebar.error(...)

# Examine and show SerpAPI standing equally

This code units up the visible a part of the Streamlit chatbot software. 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 persona:

# --- 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 Ideas:**

*   **Worth Investing:** Deal with discovering undervalued corporations with stable fundamentals (earnings, low debt, sturdy administration). Decide companies, not inventory tickers.

*   **Lengthy-Time period Horizon:** Suppose 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 worth is considerably under 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. "Danger comes from not realizing what you are doing."

*   **Administration High quality:** Assess the integrity and competence of the corporate's management.

*   **Endurance and Self-discipline:** Await the proper alternatives ("fats pitches"). Keep away from pointless exercise. Be rational and unemotional.

*   **Circle of Competence:** Follow industries and companies you'll be able to moderately perceive. Acknowledge what you do not know.

**Your Communication Fashion:**

*   **Clever and Folksy:** Use easy language, analogies, and occasional humor, very similar to Buffett does in his letters and interviews.

*   **Affected person and Calm:** Reply thoughtfully, avoiding hype or panic.

*   **Academic:** Clarify your reasoning clearly, referencing your core rules.

*   **Prudent:** Be cautious about making particular purchase/promote suggestions with out thorough evaluation based mostly in your rules. Usually, you may clarify *how* you'll analyze it slightly than giving a direct 'sure' or 'no'.

*   **Quote Your self:** Sometimes weave in well-known Buffett quotes the place acceptable (e.g., "Value 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 outdoors your experience (e.g., advanced tech you would not put money into, short-term buying and selling), politely state it isn't your space.

**Interplay Pointers:**

*   When requested for inventory suggestions, first use your instruments to collect basic information (P/E, earnings, debt if attainable) and up to date information.

*   Analyze the gathered data by the lens of your core rules (moat, administration, valuation, long-term prospects).

*   Clarify your thought course of clearly.

*   If an organization appears to suit your standards, specific 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, outdoors circle of competence), clarify why based mostly in your rules.

*   If requested for normal recommendation, draw upon your well-known philosophies.

*   Preserve conversational context utilizing the offered chat historical past. Refer again to earlier factors if related.

Keep in mind: You might be simulating Warren Buffett. Your aim is to offer insights constant together with his philosophy and communication fashion, leveraging the instruments for information when wanted. Don't give definitive monetary recommendation, however slightly educate and clarify the *Buffett approach* of fascinated with investments.

"""

Implement the capabilities that enable the chatbot to get exterior inventory and information information.

# --- Software Definitions ---

# 1. Inventory Knowledge Software (Yahoo Finance) - No modifications wanted right here

@st.cache_data(show_spinner=False) # Add caching for yfinance calls

def get_stock_info(image: str) -> str:

   # ... (preserve the present get_stock_info perform code) ...

   """

   Fetches key monetary information 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 information 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")

       information = {

           "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 information["currentPrice"] == "N/A": return f"Error: Couldn't retrieve present worth for {image}."

       return json.dumps(information)

   besides Exception as e: return f"Error fetching information for {image} utilizing yfinance: {str(e)}."

stock_data_tool = Software(

   identify="get_stock_financial_data",

   func=get_stock_info,

   description="Helpful for fetching basic monetary information for a particular inventory image (ticker)..." # Hold description

)

# 2. Information Search Software (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)

           # Check connectivity throughout creation (non-obligatory, can decelerate startup)

           # search_wrapper.run("check question")

           return Software(

               identify="search_stock_news",

               func=search_wrapper.run,

               description="Helpful for looking out latest information articles a few particular firm or inventory image..." # Hold description

           )

       besides Exception as e:

           print(f"SerpAPI Software Creation Warning: {e}")

           # Fallback to a dummy software if secret is offered however invalid/error happens

           return Software(

               identify="search_stock_news",

               func=lambda x: f"Information search unavailable (SerpAPI key configured, however error occurred: {e}).",

               description="Information search software (at the moment unavailable attributable to configuration error)."

           )

   else:

       # Dummy software if no secret is out there

       return Software(

           identify="search_stock_news",

           func=lambda x: "Information search unavailable (SerpAPI key not offered).",

           description="Information search software (unavailable - API key wanted)."

       )

news_search_tool = create_news_search_tool(active_serpapi_key)

instruments = [stock_data_tool, news_search_tool]

These capabilities change into the ‘senses’ of your inventory information evaluation bot, permitting it to entry present data. Wrapping them as Software 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, usually inside conditional checks.

# --- Primary App Logic ---

# Examine if the important OpenAI secret is offered

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 parts in session state

   reinitialize_agent = False

   # (Add the logic to examine 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 modifications

   # 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 crucial 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 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({"function": "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({"function": "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({"function": "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 software 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 whole 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 check Mr. Buffett agent with a few of our questions. You may entry the identical right here.

Warren Buffett Agent

Our streamlit app appears like this, Right here we have now the choice to fill our personal OpenAI key and SerpAPI key. Now lets check the bot…

Query 1: “Mr. Buffett, might you clarify your core funding philosophy in easy phrases?”

core investment philosophy

Query 2: “Analyze Apple (AAPL) based mostly on its present fundamentals. Would you think about it an excellent long-term funding based mostly in your rules?”

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

Question 3

Based mostly on the above outputs, we are able to 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 generally is a helpful companion for anybody trying to discover worth investing by the lens of timeless rules. Whether or not you’re simply beginning out or refining your strategy, this agent might help you assume extra clearly and patiently in regards to the markets, identical to Buffett would.

You may strive it reside 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.

Incessantly Requested Questions

Q1. The place do I get OpenAI and SerpAPI keys?

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.

Q2. Is the inventory information all the time correct?

A. The bot makes use of Yahoo Finance through yfinance. Whereas typically dependable for extensively traded shares, information can have delays or occasional inaccuracies. It’s good for academic functions however all the time cross-reference with official sources for precise funding selections.

Q3. Can I customise the Buffett persona?

A. Completely. Modify the BUFFETT_SYSTEM_PROMPT string within the code. You may modify his rules, communication fashion, and even add particular information areas.

This fall. Why does the bot typically say the information search is unavailable?

A. This occurs in case you haven’t offered a legitimate SerpAPI key within the sidebar or the .env file, or if there was an error connecting to SerpAPI.

Q5. Can this bot give assured funding recommendation?

A. No. This chatbot is an academic simulation based mostly on Warren Buffett’s fashion and rules. It doesn’t present monetary recommendation. At all times seek the advice of with a certified monetary advisor earlier than making funding selections.

Harsh Mishra is an AI/ML Engineer who spends extra time speaking to Giant Language Fashions than precise people. Captivated with GenAI, NLP, and making machines smarter (so that they don’t change him simply but). When not optimizing fashions, he’s in all probability optimizing his espresso consumption. 🚀☕

Login to proceed studying and revel in expert-curated content material.