The Future of Finance: An AI-driven Approach to automate the Assessment of a Stock´s Intrinsic… (2024)

The Future of Finance: An AI-driven Approach to automate the Assessment of a Stock´s Intrinsic… (3)

In this article, I demonstrate how you can build an AI-driven model for evaluating company healthness as a supportive metric in stock evaluation processes. The entire model is developed in Python, utilizing data from the AlphaVantage API and leveraging the capabilities of OpenAI’s GPT-4 API for its language model components.

Note: The model should be seen as a blueprint for future enhancements, such as incorporating more in-depth stock data, leveraging vectorized knowledge bases, making the analysis easier to understand, or similar.

As a small private investor, navigating through the jungle of the stock market is no triviality. All too often, we are confronted by prevailing market sentiments and numerous online recommendations…and frequently, we follow those impressions with little to no validation.

What I mean by that is that we regularly find ourselves ignoring the fundamental aspects of the companies in which we want to invest. Don´t get me wrong, traders searching for short-term profits are bound to focus on the latest sentiments. I’m talking about building a strong portfolio for sustainable returns. Many big investors built their wealth by searching for undervalued stocks, meaning, companies that perform generally well by looking at fundamental metrics, yet whose stock prices fail to accurately mirror this success. A strategy like this could also be profitable for small investors, simply in finding a good entry price.

Let’s make an example: At the time I wrote this article, the Nvidia (NVDA) stock was skyrocketing quite some time, driven by various hypes like generative artificial intelligence, crypto markets, and so on. However, they currently have a P/E ratio (Price to Earnings ratio) of about 71 (If a stock has a P/E ratio of 71, it means you are paying $71 for every $1 of the company’s earnings — sounds ridiculous, right?). Would you say it is still a good point to buy and hold some of their stocks? Hard question… If the hype is on its peak, entering means that you bought on the peak and mostly experience losses shortly after the buy.

Hence, one key of wise investing is a thorough analysis of a company’s fundamentals, ensuring that the underlying stock price is grounded in reality and that its valuation is justified. By focusing on solid fundamental data in combination with potentially undervalued stock prices, we can make strategically sound decisions with the benefit of investing in a high-potential stock early, safeguarding our portfolios against future volatility and ensuring long-term growth.

I understand that analyzing the health of a company and its stock can be a daunting task, often involving a thorough examination of numerous financial documents such as income statements, balance sheets, and cash flow reports. Furthermore, such data can also be hard to understand for non-experts.

Fortunately, we find ourselves in an era where AI solutions are at the forefront of innovation, with Large Language Models (LLMs) paving the way in comprehending, analyzing, and interpreting complex texts. Motivated by these emerging technologies, I have directed my focus towards integrating them with the financial sector to provide meaningful support not only to private investors but also to professionals in the banking industry.

Today, I will unveil how one can employ the financial data API AlphaVantage in tandem with the capabilities of GPT-4, equipped with effective prompting strategies. This combination is designed to break up and evaluate a company’s financial well-being simply by inputting its stock ticker.

Join me as we embark on this exciting venture, blending the power of AI with finance to unlock new possibilities for investors.

Searching how to simplify the complexities of the stock market and make informed investment decisions, my approach is grounded in leveraging generative AI and comprehensive financial data. The model is based on two powerful tools: the AlphaVantage API and GPT-4 text generation API from OpenAI. This combination allows us to not only fetch but also deeply analyze and interpret the vast sea of financial information that dictates stock market movements. The model is fully coded in Python.

AlphaVantage as a Financial Data Vendor

AlphaVantage is our gateway to both, up-to-date and historical financial data. By using its API, we gain access to a wealth of information, from basic stock metrics to more complex financial data.

I will build a Python class that is instrumental in our process and designed to seamlessly retrieve data such as income statements, balance sheets, cash flow, and much more. This functionality enables us to extract key metrics that form the backbone of our analysis. You can claim your free API-key for here: https://www.alphavantage.co/support/#api-key

Integrating GPT-4 for Enhanced Analysis

The true innovation of our approach, however, lies in the integration of GPT-4, more precisely, the gpt-4–0125-preview model, which is the latest GPT-4 model from OpenAI with a huge context window of 128,000 tokens and training data up to december 2023.

This Large Language Model (LLM) excels in understanding, analyzing, and interpreting text, making it an important ally in our financial analysis toolkit. By thoroughly constructing prompts that summarize the financial data retrieved by AlphaVantage, we can harness GPT-4’s capabilities to generate comprehensive analysis of a company’s financial standing and investment potential.

A Dual-Pronged Analytical Framework

My methodology encompasses “quasi”-quantitative and qualitative dimensions of financial text analysis:

Quasi-Quantitative Analysis: The model examine financial metrics extracted from the company’s reports — revenue, net income, EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization), and more. This examination is not merely about numbers but about understanding the story they tell regarding the company’s operational efficiency, profitability, and growth prospects.

Qualitative Analysis: Here, we dive into market sentiment and current news summaries, assessing how external perceptions and narratives might impact the stock’s valuation and investor sentiment.

Objective

The apex of this process is a custom-tailored analysis that not only evaluates the financial health of a company but also contextualizes its investment potential within the broader market landscape. By specifying a stock ticker, we can obtain an analysis that considers current valuations, market capitalization, analyst target prices, and even the nuanced implications of market sentiments. In the end, the model’s analysis is concluded in a health score between 0–100.

 __ __ _ __ __
/ / ___ / /_ ( ) _____ _____ ____ ____/ / ___ / /
/ / / _ \ / __/ |/ / ___/ / ___/ / __ \ / __ / / _ \ / /
/ /___/ __// /_ (__ ) / /__ / /_/ // /_/ / / __/ /_/
/_____/\___/ \__/ /____/ \___/ \____/ \__,_/ \___/ (_)

Let’s get to the fun stuff, coding the model :-)

Before we start, we need to install the OpenAI library and import some packages that we need right after. Further, I create a Config class that simply stores the API keys:

!pip install -q --upgrade openai
import openai
import requests
from typing import Dict, List, Union
class Config:
OPENAI_API_KEY = "YOUR_API_KEY"
ALPHA_VANTAGE_API_KEY = "YOUR_API_KEY"

Our journey starts with the development of a Python class that is able to fetch robust financial data. Designed with simplicity and efficiency in mind, this class is the bridge between the vast databases of AlphaVantage and our analytical engine.

class AlphaVantageAPI:
BASE_URL = "https://www.alphavantage.co/query"

def __init__(self, api_key: str):
self.api_key = api_key

def fetch_data(self, function: str, ticker_symbol: str, additional_params: Dict[str, Union[str, bool]] = None) -> Dict[str, Union[str, List, Dict]]:
params = {'function': function, 'symbol': ticker_symbol, 'apikey': self.api_key}
if additional_params:
params.update(additional_params)
response = requests.get(self.BASE_URL, params=params)
try:
response.raise_for_status()
return response.json()
except requests.HTTPError:
print(f"Failed to fetch {function} data for {ticker_symbol}.")
return {}

def fetch_financials(self, ticker_symbol: str) -> List[Dict[str, Union[str, List, Dict]]]:
functions = [
("OVERVIEW", {}),
("INCOME_STATEMENT", {'annualReports': True}),
("BALANCE_SHEET", {'annualReports': True}),
("CASH_FLOW", {'annualReports': True}),
("EARNINGS", {'annualEarnings': True}),
("RSI", {'interval': 'monthly', 'time_period': '10', 'series_type': 'open'}),
("NEWS_SENTIMENT", {'limit': '50'})
]

all_data = []
for func, params in functions:
data = self.fetch_data(func, ticker_symbol, params)
if data:
processed_data = self.process_data(func, data)
all_data.extend(processed_data)

return all_data

def process_data(self, function: str, data: Dict[str, Union[str, List, Dict]]) -> List[Dict[str, Union[str, List, Dict]]]:
processed_data = []
if function == "OVERVIEW":
processed_data.append({"Type": function, "Data": data})
elif function in ["INCOME_STATEMENT", "BALANCE_SHEET", "CASH_FLOW", "EARNINGS"]:
reports = data.get('annualReports') or data.get('annualEarnings')
if reports:
for report in reports:
processed_data.append({"Type": function, "Data": report})
elif function == "RSI":
rsi_values = list(data.get('Technical Analysis: RSI', {}).items())[:12]
processed_data.append({"Type": function, "Data": rsi_values})
elif function == "NEWS_SENTIMENT":
news_items = data.get('feed', [])[:20]
summaries = [{"News data": item.get('summary')} for item in news_items if 'summary' in item]
processed_data.append({"Type": function, "Data": summaries})
return processed_data

The FinancialAnalyzer class embodies the transition from raw financial data to financial intelligence by using OpenAI’s GPT-4 API. They have an easy to use Python library that allows you to communicate with their mighty model inside your notebook or application.

class FinancialAnalyzer:
def __init__(self, api_key: str = Config.OPENAI_API_KEY):
self.api_key = api_key
openai.api_key = self.api_key

@staticmethod
def construct_prompt(company_name: str, fetched_data: List[Dict[str, str]]) -> str:
prompt = f"Please provide an in-depth analysis of {company_name}'s financial health and its potential as an investment opportunity. Structure your response with the following headings and include detailed evaluations as described:\n"
prompt += "📈 Analysis >>>>> Overview of the data sources and metrics to be analyzed.\n"
prompt += "----------------------------------------------\n"
prompt += "🍎 Financial Health Evaluation >>>>> Detailed analysis based on key financial metrics such as Revenue, Net Income, EBITDA, Operating Margin, Gross Profit, PERatio, PEGRatio, Book Value, and Return on Assets and Equity. Use bullet points for each metric and provide a brief analysis.\n"
prompt += "----------------------------------------------\n"
prompt += "💸 Investment Opportunity Evaluation >>>>> Evaluate the stock's current valuation, market cap, analyst target price, beta, cash positions and news sentiments. Discuss the implications of these factors on the stock being undervalued or not.\n"
prompt += "==============================================\n"
prompt += "🔮 **Conclusion** =====> Summarize the financial health score out of 100 and state whether the stock is a good investment opportunity based on the analysis.\n\n"
prompt += "Here is the data to be analyzed: \n"
for data in fetched_data:
prompt += f"\nType: {data}\n"
if 'Fiscal Date Ending' in data:
prompt += f"Fiscal Date Ending: {data['Fiscal Date Ending']}\n"
prompt += "Data:\n"
for key, value in data.items():
prompt += f"{key}: {value}\n"
return prompt

def analyze_financial_data(self, company_name: str, fetched_data: List[Dict[str, Dict[str, str]]]) -> str:
prompt = self.construct_prompt(company_name, fetched_data)

try:
completion = openai.chat.completions.create(
model="gpt-4-0125-preview",
messages=[
{"role": "system", "content": "You are a financial analysis expert. Your responses should be structured with the following headings: 📈 Analysis, 🍎 Financial Health Evaluation, 💸 Investment Opportunity Evaluation, and 🔮 Conclusion. For each section, provide detailed evaluations using bullet points for key metrics in the Financial Health Evaluation, and a summary conclusion with a financial health score out of 100."},
{"role": "user", "content": prompt},
]
)
response = completion.choices[0].message.content
return response.strip()
except Exception as e:
return f"Failed to generate analysis due to an error: {str(e)}"

That’s it!

Let’s try the model and input “NVDA” for Nvidia’s ticker value and see what the model returns.

TICKER = "NVDA"

av_api = AlphaVantageAPI(Config.ALPHA_VANTAGE_API_KEY)
financial_data = av_api.fetch_financials(TICKER)

analyzer = FinancialAnalyzer()
analysis = analyzer.analyze_financial_data(TICKER, financial_data)
print(analysis)

[Info] Executed on Februar 21st, 2024

📈 **Analysis**

To evaluate NVIDIA Corporation's financial health and investment potential,
I will analyze a comprehensive set of data, including income statements,
balance sheets, cash flows, earnings reports, relative strength index (RSI)
values, and news sentiment. This analysis will incorporate key metrics such
as revenue, net income, EBITDA, operating and gross profit margins,
P/E ratios, book value, return on assets and equity, market cap, analyst
ratings, and recent news sentiments. This thorough examination aims to
provide a holistic view of NVIDIA's current financial standing and future
prospects.

----------------------------------------------
🍎 **Financial Health Evaluation**

- **Revenue**: Growth seen from $16.67B (2021) to $26.97B (2023), showing
strong sales performance.
- **Net Income**: Increased from $4.33B (2021) to $4.37B in the latest
fiscal year, indicating profitability.
- **EBITDA**: An upward trend from $5.69B (2021) to $22.16B (2023),
showing operational efficiency improvement.
- **Operating Margin**: Experience fluctuations, evident from changes
year-on-year, but overall shows a robust margin reflecting in a 57.5% TTM.
- **Gross Profit**: Ascending trend from $10.39B (2021) to $15.36B (2023),
indicating superior control over cost of goods sold.
- **PERatio**: High at 91.75, suggesting the market has
high expectations for future earnings growth.
- **PEGRatio**: 0.708 indicates the stock could be undervalued based on
its expected growth rate.
- **Book Value**: $13.49, reflecting the company’s net asset value from
a balance sheet perspective.
- **Return on Assets**: 27.2% TTM shows effective use of assets to generate
profits.
- **Return on Equity**: 69.2% TTM indicates high efficiency in generating
returns on shareholder equity.

🔹 **Financial Health Score**: 85/100

----------------------------------------------
💸 **Investment Opportunity Evaluation**

- **Market Cap**: $1.715 trillion, highlighting NVIDIA's substantial market
size and investment.
- **Analyst Target Price**: $712.49, suggesting potential upside from the
current trading price.
- **Beta**: 1.684 indicates higher volatility than the market, implying
higher potential returns albeit with higher risk.
- **Cash Positions**: Strong, with cash and equivalents of $3.39 billion,
providing financial flexibility.
- **News Sentiments**: Mixed, with mentions of lawsuits against high-profile
tech companies (including Meta) but also highlighting NVIDIA’s potential in
crucial tech areas. Positive earnings growth and an increase in dividend
suggest a strong business model.

🔹 **Implications**: Given its market cap, RSI values indicating overbought
conditions in recent months, mixed news sentiments, and a solid analyst
target price overshooting current levels, NVDA seems undervalued in terms
of growth prospects despite its high P/E ratio. However, volatility could
be a concern for risk-averse investors.

==============================================
🔮 **Conclusion**

Based on NVIDIA's robust financial health, evidenced by solid revenue and net
income growth, high EBITDA, and strong efficiency ratios, alongside a
promising outlook from analysts and the market sentiment,
NVDA scores a **financial health grade of 85 out of 100**.
Considering the analysis, NVIDIA Corporation represents a good investment
opportunity, especially for those willing to take on higher market risk
for potentially greater rewards. It's advisable for investors to consider
market volatility and the company's current high valuation in their decisions.

I think that’s a quite good analysis for simply entering a stock ticker. Regardless, if you are a professional or a small private trader, validations like that could really support your investment decision making process, or at least, save time. I already use that in my search process of finding new potential stock investments and it really helps me save tons of time going through all of the data by myself.

I really hope you liked this one and it helps you getting a small step further of doing great investments in the financial market 🙂 In one of my next articles, I will show you how you can embed this model in a web application and host it through Microsoft’s Azure Cloud Services in order to gain even more convenience by coding a simple User Interface (UI).

But that’s it for now. Don’t forget to throw some claps!

If you’ve enjoyed this article and feel moved to support my work, a small donation would be deeply appreciated (click here for donation). Every contribution, no matter the size, helps me continue sharing stories like this with you ❤️

The Future of Finance: An AI-driven Approach to automate the Assessment of a Stock´s Intrinsic… (2024)
Top Articles
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 5919

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.