GPT-4 for Financial Statements: Building an AI Analyst (2024)

In our previous tutorials on GPT-3 and GPT-4, we've looked at several use cases for LLMs in finance such as earnings call summaries, stock screener assistants, and various research assistants.

In this guide, we'll focus on another use case of LLMs for finance: specifically, using GPT-4 to summarize and analyze financial statements.

The financial statement assistant will retrieve statements, write a summary, and provide an insightful analysis of the chosen time period.

We've integrated an updated version of this financial statements AI analyst into the MLQ app, which you can sign up for here.

GPT-4 for Financial Statements: Building an AI Analyst (1)

We'll walk through how to build a simple Streamlit app where users can:

  • Select the desired financial statement (i.e. income statement, balance sheet, cash flow)
  • Choose the desired statement period (i.e.annual or quarterly)
  • Choose the number of past statements to analyze (i.e. past 4 statements)
  • Input a stock ticker and click run
GPT-4 for Financial Statements: Building an AI Analyst (2)

As you can see, the Streamlit app first returns the raw DataFrame for the financial statements so we can confirm the numbers, then provides a summary of key financial metrics from the statement in a more user-friendly way, and finally provides an analysis of the statements.

GPT-4 for Financial Statements: Building an AI Analyst (3)
GPT-4 for Financial Statements: Building an AI Analyst (4)

While still quite a simple application, I think this idea of using LLMs to summarize raw financial data and provide basic financial analysis, key takeaways, and highlight interesting insights that may not be immediately noticed by the lesser trained financial eye is quite a very powerful idea in finance.

Alright now that we know what we're building, let's jump into the code.

Step 0: Installs & Imports

Before we dive into the code, first make sure you have installed all necessary libraries with pip:

pip install streamlit openai requests

Next, we'll need to import the following libraries into our app and set our OpenAI and Financial Modeling Prep API key in apikey.py:

import streamlit as stimport openaiimport requestsimport osfrom apikey import OPENAI_API_KEY, FMP_API_KEYopenai.api_key = OPENAI_API_KEY

Step 1: Retrieving Financial Statements

Alright next let's set up a few functions to retrieve financial statements from the Financial Modeling Prep API. These statements can be three types: income statements, balance sheets, and cash flow statements.

Below, we'll write a function that takes in the company's ticker, the number of past time periods to retrieve (limit), the statements frequency (period i.e. annual or quarterly) and the type of statement to retrieve:

def get_financial_statements(ticker, limit, period, statement_type): if statement_type == "Income Statement": url = f"https://financialmodelingprep.com/api/v3/income-statement/{ticker}?period={period}&limit={limit}&apikey={FMP_API_KEY}" elif statement_type == "Balance Sheet": url = f"https://financialmodelingprep.com/api/v3/balance-sheet-statement/{ticker}?period={period}&limit={limit}&apikey={FMP_API_KEY}" elif statement_type == "Cash Flow": url = f"https://financialmodelingprep.com/api/v3/cash-flow-statement/{ticker}?period={period}&limit={limit}&apikey={FMP_API_KEY}" data = get_jsonparsed_data(url) if isinstance(data, list) and data: return pd.DataFrame(data) else: st.error("Unable to fetch financial statements. Please ensure the ticker is correct and try again.") return pd.DataFrame()

Here, get_jsonparsed_data(url) is a helper function to send a GET request to the provided url and parse the JSON response.

Step 2: Generate Financial Statements Summary with GPT-4

Next, instead of just display the raw dataframe table, we're also going to first summarize key metrics from the statement.

Raw financial statements are often challenging to comprehend for users without a financial background. To make these statements more accessible and insightful, we'll use GPT-4 to generate a textual summary.

To do so, we'create a function called generate_financial_summary(), which takes as input the DataFrame of financial statements and the statement type. Based on the statement type, we then loop through each statement retrieved and display a few key metrics before the analysis:

def generate_financial_summary(financial_statements, statement_type): """ Generate a summary of financial statements for the statements using GPT-3.5 Turbo or GPT-4. """ # Create a summary of key financial metrics for all four periods summaries = [] for i in range(len(financial_statements)): if statement_type == "Income Statement": summary = f""" For the period ending {financial_statements['date'][i]}, the company reported the following: ... """ elif statement_type == "Balance Sheet": summary = f""" For the period ending {financial_statements['date'][i]}, the company reported the following: ... """ elif statement_type == "Cash Flow": summary = f""" For the period ending {financial_statements['date'][i]}, the company reported the following: ... """ summaries.append(summary)

Next, we combine all these individual period summaries into a single string:

 # Combine all summaries into a single string all_summaries = "\n\n".join(summaries)

After creating the financial statement summaries, we're then going to use GPT-4 to analyze them and provide insights such as the changes in certain metrics over time (i.e. how have R&D expenses changed over the past year).

There's definitely some more prompt engineering we can do that will improve GPT-4's output here, for example by providing a few examples of real-world financial analysis could improve the output via few-shot learning, although this will do for now:

 # Call GPT-4 for analysis response = openai.ChatCompletion.create( model="gpt-4", messages=[ { "role": "system", "content": "You are an AI trained to provide financial analysis based on financial statements.", }, { "role": "user", "content": f""" Please analyze the following data and provide insights:\n{all_summaries}.\n Write each section out as instructed in the summary section and then provide analysis of how it's changed over the time period. ... """ } ] ) return response['choices'][0]['message']['content']

Step 3: Building the Streamlit App

Alright that's all we need for our starter GPT-4 analyst, let's now go and put this together in a Streamlit app. To do so, we'll define a function called financial_statements(), which contains the Streamlit code to enable an interactive UI for the financial assistant:

def financial_statements(): st.title('GPT-4 & Financial Statements') statement_type = st.selectbox("Select financial statement type:", ["Income Statement", "Balance Sheet", "Cash Flow"]) col1, col2 = st.columns(2) with col1: period = st.selectbox("Select period:", ["Annual", "Quarterly"]).lower() with col2: limit = st.number_input("Number of past financial statements to analyze:", min_value=1, max_value=10, value=4) ticker = st.text_input("Please enter the company ticker:") if st.button('Run'): if ticker: ticker = ticker.upper() financial_statements = get_financial_statements(ticker, limit, period, statement_type) with st.expander("View Financial Statements"): st.dataframe(financial_statements) financial_summary = generate_financial_summary(financial_statements, statement_type) st.write(f'Summary for {ticker}:\n {financial_summary}\n')

And finally, to run our application we'll create this main function, where I've added a sidebar dropdown for additional assistants that I'll be building in the near future (details to come):

def main(): st.sidebar.title('AI Financial Analyst') app_mode = st.sidebar.selectbox("Choose your AI assistant:", ["Financial Statements"]) if app_mode == 'Financial Statements': financial_statements()if __name__ == '__main__': main()

With that, we have everything we need and can run the app locally with streamlit run app.py.

Let's go and test it out again with the past 4 annual balance sheet statements for AAPL:

GPT-4 for Financial Statements: Building an AI Analyst (5)
GPT-4 for Financial Statements: Building an AI Analyst (6)

Not bad.

Summary: GPT-4 for Financial Statements

In this guide, we saw how we can we make raw financial data a bit more human-readable and accessible with GPT-4.

While some may financial wizards may enjoy staring at raw data in spreadsheets, my guess is that the majority of people would prefer to analyze financial data in a more "AI assisted" way that includes summaries of the data, and insightful analysis that brings to light key metrics that may have otherwise been overlooked.

While this is of course just a starting point for a full-fledged AI analyst, over the next few articles we'll explore a few other similar applications of LLMs to financial data. As mentioned, I think there's a massive opportunity to use LLMs and "bring financial data to life" bringing allowing users to to chat with this type of data.

To really achieve that, another next step will be to make this app more chat-oriented and allow users to ask follow-up questions and truly be able to chat with financial data, although we'll save that for another article.

GPT-4 for Financial Statements: Building an AI Analyst (2024)

FAQs

Can you use ChatGPT to analyze financial statements? ›

Analysts can use ChatGPT to analyze financial statements and other data to make investment decisions.

Can GPT 4 do financial modelling? ›

With GPT-4's code interpreter capabilities, financial modeling becomes more intricate and insightful. The efficient retrieval of financial documents and data simplifies and accelerates the analytical workflow.

Can AI analyse financial statements? ›

AI prompts can streamline the analysis of financial statements by extracting key data points, detecting patterns and anomalies, generating insights, and providing recommendations based on the data.

Can GPT 4 help with accounting? ›

GPT-4 AI technology can analyze your data and automatically detect discrepancies between your accounting records and bank statement.

Can ChatGPT analyze a balance sheet? ›

ChatGPT - Balance Sheet Analyzer. A balance sheet analyzer focusing on summarizing earnings and calculating cash runways.

Can I use ChatGPT for accounting? ›

ChatGPT also helps with Excel formulas to calculate the data value in spreadsheets which you can use for accounting. All you need to do is give it the data to work with and clear instructions for what you want to calculate in any cell, roll, or column. Here's a brilliant example of ChatGPT creating an Excel formula.

Can ChatGPT 4 read financial statements? ›

Can chatgpt analyze financial statements? - Quora. YES. GPT-4 is especially effective as you can attach Excel spreadsheets (and PDFs for analysis) as well as use a plugin that can read a URL containing the financial statements directly.

What GPT-4 Cannot do? ›

GPT4, once trained, does not change during use. It doesn't learn from its mistakes nor from correctly solved problems. It notably lacks an optimization step in problem-solving that would ensure previously unsolvable problems can be solved and that this problem-solving ability persists.

Can GPT-4 replace data analyst? ›

Results show GPT-4 can perform better than or on par with data analysts.

Which AI tool is best for financial analysis? ›

Top 5 AI Finance Tools In 2024
  • NetSuite Text Enhance uses AI to help create various types of business content directly within NetSuite. ...
  • Booke AI streamlines the bookkeeping process by automating repetitive tasks and correcting common errors. ...
  • Vic AI is designed to transform the way businesses handle invoice processing.
Mar 26, 2024

Is AI going to replace financial analysts? ›

Not to mention, human financial analysts bring creativity and critical thinking AI doesn't tend to possess. So, it is unlikely that AI will fully replace financial analysts, or at least any time in the near future. Instead, they may work together to improve efficiency and accuracy in decision-making processes.

Which AI reads financial statements? ›

Key takeaways:

The integration of AI in the financial industry has reduced processing time and increased productivity. Parseur is the best AI tool to extract financial data.

Can GPT-4 pass the CPA? ›

ChatGPT4 averaged a score of 85.1% across all sections of four major accounting exams and passed them all, according to research by a team of US and German scholars.

Did ChatGPT fail the CPA exam? ›

Yes, ChatGPT failed the exam and showcased its limitations. Mainly, it can't distill complicated information like a CPA needs to. But guess what, that's your job.

Can ChatGPT do bookkeeping? ›

This article identifies several uses of ChatGPT in accounting that may improve your business productivity. You can perform accounting tasks, brainstorm, research, analyze financial information for insights and decision-making, and gain digital assistance in business communications with human oversight.

Can ChatGPT analyse accounts? ›

Data analysis is a crucial aspect of accounting, and Chat GPT can assist in this area as well. With its advanced data processing capabilities, Chat GPT can quickly analyse large amounts of financial data and provide insights that can help accountants make informed decisions.

Can ChatGPT read annual reports? ›

Gain a high-level understanding of a company

Now, you can get that by reading annual reports, investor presentations, and so on. But you can also use ChatGPT to get an initial, high-level understanding. For example, I asked it to “explain to me Tesla's exact business model”, and here's what I got: Source: ChatGPT.

What is the best way to analyze financial statements? ›

Several techniques are commonly used as part of financial statement analysis. Three of the most important techniques are horizontal analysis, vertical analysis, and ratio analysis. Horizontal analysis compares data horizontally, by analyzing values of line items across two or more years.

Top Articles
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 6271

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.