HomeBig DataConstruct Your Personal Warren Buffett Agent in 5 Minutes

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 reviews suggesting he could quickly step down as CEO of Berkshire Hathaway, it’s a great second to replicate 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 learn how to flip these ideas right into a conversational Warren Buffett agent that evaluates corporations by his lens, and interacts utilizing real-time inventory knowledge and information. The objective isn’t to recreate Buffett, however to construct a chatbot that helps you suppose the best way he would possibly.

Undertaking Objective 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 ideas, and leverage real-time knowledge.

Construct Your Personal Warren Buffett Agent in 5 Minutes

The primary parts are:

  1. Language Mannequin (OpenAI): Offers the conversational capability and persona adherence.
  2. LangChain: Acts because the framework, connecting the language mannequin, instruments, and reminiscence.
  3. Inventory Information API (Yahoo Finance): Fetches present inventory costs and basic knowledge.
  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 – 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. Hold 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 (Non-compulsory): 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 prime:

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 Instrument

from langchain_community.utilities import SerpAPIWrapper

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

load_dotenv()

These imports herald Streamlit for the interface, os for setting variables, json for knowledge dealing with, yfinance for shares, dotenv for key loading, and varied 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="vast")

st.title("Warren Buffett Funding Chatbot πŸ“ˆ")

st.caption("Ask me about investing, shares, or market knowledge - within the model 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 energetic (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 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 Ideas:**

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

* Β  **Lengthy-Time period Horizon:** Suppose when it comes to 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 (robust manufacturers, community results, low-cost manufacturing, regulatory benefits).

* Β  **Perceive the Enterprise:** Solely spend money on corporations you perceive. "Threat comes from not figuring out what you are doing."

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

* Β  **Persistence and Self-discipline:** Await the precise 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 Model:**

* Β  **Clever 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 moderately than giving a direct 'sure' or 'no'.

* Β  **Quote Your self:** Often 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 exterior your experience (e.g., complicated tech you would not spend money on, short-term buying and selling), politely state it isn't your space.

**Interplay Pointers:**

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

* Β  Analyze the gathered info by 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 would 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 offered chat historical past. Refer again to earlier factors if related.

Keep in mind: You're simulating Warren Buffett. Your objective is to supply insights constant together with his philosophy and communication model, leveraging the instruments for knowledge when wanted. Don't give definitive monetary recommendation, however moderately educate and clarify the *Buffett means* of eager about investments.

"""

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

# --- Instrument Definitions ---

# 1. Inventory Information Instrument (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:

Β Β Β # ... (hold the prevailing 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 worth for {image}."

Β Β Β Β Β Β Β return json.dumps(knowledge)

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

stock_data_tool = Instrument(

Β Β Β title="get_stock_financial_data",

Β Β Β func=get_stock_info,

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

)

# 2. Information Search Instrument (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-compulsory, can decelerate startup)

Β Β Β Β Β Β Β Β Β Β Β # search_wrapper.run("take a look at question")

Β Β Β Β Β Β Β Β Β Β Β return Instrument(

Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β title="search_stock_news",

Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β func=search_wrapper.run,

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

Β Β Β Β Β Β Β Β Β Β Β )

Β Β Β Β Β Β Β besides Exception as e:

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

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

Β Β Β Β Β Β Β Β Β Β Β return Instrument(

Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β title="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 as a consequence of configuration error)."

Β Β Β Β Β Β Β Β Β Β Β )

Β Β Β else:

Β Β Β Β Β Β Β # Dummy software if no secret is out there

Β Β Β Β Β Β Β return Instrument(

Β Β Β Β Β Β Β Β Β Β Β title="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 features develop into the β€˜senses’ of your inventory knowledge evaluation bot, permitting it to entry present info. Wrapping them as Instrument 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 principle a part of the script, typically inside conditional checks.

# --- Major 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 would 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 speak show

Β Β Β Β Β Β Β Β Β Β Β st.session_state.messages.append({"position": "assistant", "content material": f"Sorry... {e}"})

Β Β Β Β Β Β Β Β Β Β Β st.chat_message("assistant").write(f"Sorry... {e}")

Β Β Β # Non-compulsory: 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 appliance, 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 possibly can entry the identical right here.

Warren Buffett Agent

Our streamlit app appears like this, Right here we’ve got 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?”

core investment philosophy

Query 2: β€œAnalyze Apple (AAPL) primarily based on its present fundamentals. Would you contemplate it a great long-term funding primarily based in your ideas?”

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

Question 3

Primarily based on the above outputs, we will see that the bot is performing effectively 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 could be a helpful companion for anybody seeking to discover worth investing by the lens of timeless ideas. Whether or not you’re simply beginning out or refining your method, this agent will help you suppose extra clearly and patiently concerning the markets, identical to Buffett would.

You possibly can 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.

Regularly Requested Questions

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

OpenAI: Go to platform.openai.com, enroll, 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 knowledge all the time correct?

A. The bot makes use of Yahoo Finance through yfinance. Whereas usually dependable for broadly traded shares, knowledge 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 possibly can modify his ideas, communication model, and even add particular data areas.

This autumn. Why does the bot generally 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 primarily based on Warren Buffett’s model and ideas. It doesn’t present monetary recommendation. At all times seek the advice of with a professional 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. Enthusiastic about GenAI, NLP, and making machines smarter (in order that they don’t exchange him simply but). When not optimizing fashions, he’s most likely optimizing his espresso consumption. πŸš€β˜•

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments