Engineering7 min read

AI Investment Advisor: Personalized Investment Insights

Looking for personalized investment advice based on your risk profile? In this article, you'll learn how to build an AI-powered Investment Advisor to analyze your financial data and generate customized recommendations. Let’s dive in and explore how AI is transforming financial planning!

Tega Adeyemi
Tega Adeyemi
AI Investment Advisor: Personalized Investment Insights

If you've ever wanted to make investment suggestions based on your risk profile, which is gauged by a questionnaire, we have a solution for you. Today, we're introducing an exciting new project: an AI-powered Investment Advisor tool that helps individual clients of investment banks get personalized recommendations tailored to their financial profiles and risk tolerance. Imagine having a personal assistant who not only understands your financial needs but also generates curated investment advice—effortlessly. Let's dive in!

Introducing Our AI Investment Advisor Tool

Our latest project is all about personalization. We built a smart tool that taps into AI to help individual clients navigate the world of investments—right from their phone or computer screen. Whether you are a financial advisor managing many clients or an individual investor looking for insights, this tool will make personalized investment advice seamless and precise. Here’s what it can do:

The result? Clients receive custom advice based on their preferences and risk appetites, and advisors save time while managing their clients' portfolios more efficiently.

AI Investment Advisor: Personalized Investment Insights — Tega Adeyemi | Cohorte
Risk Profiling and recommendations report
AI Investment Advisor: Personalized Investment Insights — Tega Adeyemi | Cohorte
Detailed tables and charts on historical performance of recommended Stocks

Behind the Scenes: How Does It Work?

Let’s dive into how we brought this idea to life. Under the hood, this tool uses:

Here’s how each of these components makes our tool special.

Setting Up the App with Streamlit

We’ve designed this tool using Streamlit, a framework that allows us to make a visually appealing, yet functional, web application. Once you open the app, you’ll be welcomed by a simple interface that guides you to create a personalized investment plan.

import streamlit as st

st.title("InvestiGenie: Personalized AI Investment Advisor")
st.write("Welcome to InvestiGenie! Let's create a personalized investment plan based on your financial goals and risk tolerance.")

The Streamlit app serves as an interactive front-end where users (both advisors and individual clients) can enter relevant financial information and receive personalized investment recommendations. The welcoming interface sets the stage for users to be guided step-by-step through the process.

Classifying Risk Profiles with AI

Understanding your risk tolerance is key to making suitable investment decisions. We achieve this using OpenAI’s GPT-4O Mini model. The client starts by answering a series of questions related to their finances and risk appetite. Once the client’s information is gathered, our tool uses OpenAI to classify the user into one of three categories—Conservative, Moderate, or Aggressive—based on the responses.

Here's the function that handles risk profiling:

def classify_risk_profile(investment_performance, age_group, dependants, investment_percentage, income_sources, investment_loss_reaction, portfolio_protection, market_fluctuation, vacation_job_loss, unexpected_investment):
    prompt = f"""You are a financial expert. Based on the answers to a questionnaire, classify the investor as 'Conservative', 'Moderate', or 'Aggressive'.
    Provide the reasoning in proper JSON format with two keys: 'profile' and 'explanation'.
    Here are the results of the questionnaire:
    ... (followed by each question and answer)"""
    try:
        with st.spinner("Classifying your risk profile..."):
            completion = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[{"role": "user", "content": prompt}],
            )
        return completion.choices[0].message.content.strip()
    except Exception as e:
        st.error(f"Error generating investment recommendations: {e}")
        return ""

The above code takes the user’s responses, formats them into a prompt for OpenAI, and classifies their risk profile. The output is JSON-formatted for easy interpretation, which makes it perfect for guiding the rest of the tool in providing suitable recommendations.

Fetching Stock Recommendations

Once a user’s risk profile is determined, the next step is fetching the appropriate stock recommendations from our curated list of top 50 US stocks. Using the Notion API, we query our database to find the stocks that match the user's profile—for example, clients classified as Conservative will receive recommendations for lower-beta stocks with higher dividend yields.

def fetch_filtered_stocks(risk_profile):
    try:
        results = notion.databases.query(database_id=DATABASE_ID).get("results")
    except Exception as e:
        st.error(f"Error fetching data from Notion: {e}")
        return []

    filtered_stocks = []
    for page in results:
        properties = page["properties"]
        ticker = properties["Ticker"]["title"][0]["text"]["content"]
        beta = properties["Beta"]["number"]
        dividend_yield = properties["Dividend Yield"]["number"]

        if risk_profile == "Conservative" and beta < 1 and dividend_yield >= 0.02:
            filtered_stocks.append(ticker)
        elif risk_profile == "Moderate" and 1 <= beta <= 1.5:
            filtered_stocks.append(ticker)
        elif risk_profile == "Aggressive" and beta > 1.5:
            filtered_stocks.append(ticker)

    return filtered_stocks

The stock recommendation logic is straightforward: based on the user’s risk profile, it filters through our Notion database and selects the best-matching stocks. This way, a Conservative investor would be recommended stable companies, while an Aggressive investor would see options for growth stocks with higher risks.

Visualizing Stock Performance

One of the best features of this tool is its ability to visualize historical performance of recommended stocks. This helps clients get a better idea of how potential investments have fared in the market.

def plot_stock_performance(filtered_stocks):
    if not filtered_stocks:
        st.warning("No stocks available to plot performance.")
        return

    st.write("\\n### Historical Performance of Recommended Stocks")
    data = pd.DataFrame()

    for ticker in filtered_stocks:
        stock = yf.Ticker(ticker)
        history = stock.history(period="6mo")["Close"]
        if not history.empty:
            data[ticker] = (history / history.iloc[0] - 1) * 100

    if not data.empty:
        plt.figure(figsize=(10, 6))
        for column in data.columns:
            plt.plot(data.index, data[column], label=column)
        plt.xlabel("Date")
        plt.ylabel("Percentage Return")
        plt.title("Historical Performance of Recommended Stocks")
        plt.legend()
        st.pyplot(plt)
    else:
        st.warning("No data available to plot.")

In this function, we use Yahoo Finance (yfinance) to fetch the historical stock data for the selected recommendations and plot the returns over time. This visualization allows clients to see trends and assess the potential of each recommendation visually.

Why This Tool is a Game Changer for Investment Banks

This AI-powered Investment Advisor tool transforms how individual clients interact with investment decisions. Here’s why:

Use Cases

This AI Investment Advisor can be used by:

Wrapping Up

This project has been incredibly fun to develop, and we believe it has the potential to change the game for both individual investors and financial advisors. This is just a basic prototype, which can be built upon with more complex use cases. The mix of OpenAI for intelligent analysis, Notion API for organizing information, and Streamlit for easy-to-use interfaces results in a powerful tool that anyone—from advisors to individual investors—can benefit from.

Let us know what you think! We’re always open to ideas to make this better and provide even more value to clients and advisors alike. With this AI Investment Recommender, we’re taking the next step toward simplifying personalized investing. Thanks for joining us on this journey!

Tega AdeyemiNovember 26, 2024