The AI Financial Analyst Advantage: How GPT-4o is Revolutionizing Investment Strategies
Introduction:
In today’s digital age, we are constantly bombarded with financial data and stock analysis from various social media platforms like Twitter, Reddit, and TikTok. Often, the intricate financial analysis performed by seasoned day traders can seem almost alien to the average investor. This inspired me to leverage AI to create a tool that could simplify this process.
Imagine scrolling through your favorite social media feed and coming across a stock chart that catches your eye. Instead of trying to decipher the complex patterns and financial jargon, what if you could take a screenshot of that chart and let AI do the heavy lifting for you? My project aims to do just that, by integrating OpenAI’s latest model, GPT-4o, with a Flask web application.
Project Overview
Objective: The primary goal of this project is to build an application that can:
- Analyze Stock Charts: Take a screenshot of a stock chart and provide an in-depth financial analysis of the stock.
- Financial Statistics Retrieval: Pull comprehensive financial statistics for the company associated with the stock chart.
- Investment Analysis: Let GPT-4o provide a holistic financial analysis of the company, highlighting key benchmarks to assess its investment potential.
How It Works
Stock Chart Analysis
- Using advanced vision capabilities, the application can interpret and analyze the data presented in a stock chart screenshot.
- The AI evaluates key indicators such as moving averages, volume, and trend lines to provide insights into the stock’s performance.
Financial Statistics Retrieval
- By leveraging the
yfinance
library, the application fetches real-time financial data for the company, including earnings reports, revenue, profit margins, and other crucial metrics. - This data is used to paint a comprehensive picture of the company’s financial health.
Overall Financial Analysis
The application integrates with the OpenAI API to generate a detailed financial analysis report. The report includes:
- The application integrates with the OpenAI API to generate a detailed financial analysis report
- The report includes a breakdown of the company’s financial performance, comparisons to industry benchmarks, and an assessment of the company’s potential as an investment
Why This Matters
The stock market can be intimidating for many, especially those without a background in finance. This tool aims to democratize financial analysis by making it accessible and understandable to a broader audience. By combining AI’s analytical power with real-time financial data, investors can make more informed decisions without needing to decode complex charts and reports themselves.
Incorporating OpenAI’s GPT-4o
On Monday, May 13th, OpenAI released their newest foundational model, GPT-4o. Dubbed the “omni” model, GPT-4o marks a significant leap towards more intuitive human-computer interaction. This cutting-edge technology accepts a wide range of inputs, including text, audio, images, and videos, and can generate diverse outputs such as text, audio, and images.
Enhanced Capabilities:
- Speed and Efficiency: GPT-4o can respond to audio prompts in as little as 232 milliseconds, with an average response time of 320 milliseconds, rivaling human conversation speeds.
- Multilingual Proficiency: The model showcases notable improvements in non-English languages, making it highly versatile for global users.
- Advanced Vision and Audio Comprehension: With enhanced capabilities in vision and audio comprehension, GPT-4o outperforms existing models, making it perfect for analyzing stock charts and financial data.
- Cost and Efficiency: GPT-4o offers a 50% cost reduction and increased efficiency through the API, making advanced AI technology more accessible and affordable.
By integrating GPT-4o into my project, I can leverage its powerful vision and language processing capabilities to provide faster, more accurate financial analysis. This enhances the user experience, making it easier for investors to understand stock performance and company fundamentals.
Why Flask?
For this project, I decided to use Flask. Flask is a lightweight WSGI web application framework in Python, designed with simplicity and flexibility in mind, making it an excellent choice for developing web applications. The project is organized into three main files: app.py
, index.html
, and style.css
.
Key Components
1. app.py
app.py
is the core of the project. It handles the application logic, including data fetching, chart generation, and the integration of GPT-4o for financial analysis.
Here are some key functions and their roles:
- Image Handling Functions:
def save_image(image_data, filename):
with open(filename, 'wb') as f:
f.write(base64.b64decode(image_data))
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
- Plotting Stock Data
def plot_stock_data(hist, ticker, indicators):
plt.switch_backend('Agg')
plt.figure(figsize=(10, 5))
for indicator in indicators:
plt.plot(hist[indicator], label=indicator)
plt.title(f'{ticker} Stock Price')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid()
img = io.BytesIO()
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
save_image(plot_url, f'images/{ticker}_stock_plot.png')
plt.close()
return plot_url
- Analyzing Stock Image with GPT-4o
def analyze_stock_image(image_path):
base64_image = encode_image(image_path)
response = client.chat.completions.create(
model='gpt-4o',
messages=[
{"role": "system", "content": "You are a helpful financial stock analyst who provides insights on stock data."},
{"role": "user", "content": [
{"type": "text", "text": "Can you describe the chart below?"},
{"type": "image_url", "image_url": {
"url": f"data:image/png;base64,{base64_image}"}
}
]}
],
temperature=0.0,
)
return response.choices[0].message.content
- In the provided code, I highlight how GPT-4o is used to analyze an image of the stock chart. We use Matplotlib to generate the chart, save it locally, and encode it as a base64 string to send to GPT-4o for analysis.
- Generating Financial Analysis
def generate_financial_analysis(chart_summary, financials):
messages = [
{"role": "system", "content": "You are a helpful financial analyst. Provide a detailed financial analysis based on the given chart summary and financial data. Make sure to give insights on the company's financial performance and to output using markdown format."},
{"role": "user", "content": f"Chart Summary:\n{chart_summary}\n\nFinancial Data:\nInfo: {financials['info']}\nActions: {financials['actions']}\nDividends: {financials['dividends']}\nSplits: {financials['splits']}\nIncome Statement: {financials['income_stmt']}\nBalance Sheet: {financials['balance_sheet']}\nCash Flow: {financials['cashflow']}\nMajor Holders: {financials['major_holders']}\nInstitutional Holders: {financials['institutional_holders']}\nInsider Transactions: {financials['insider_transactions']}"}
]
response = client.chat.completions.create(
model='gpt-4o',
messages=messages,
temperature=0.0,
)
return response.choices[0].message.content
- The code combines the chart summary and additional financial metrics retrieved via
yfinance
to generate a comprehensive financial analysis using GPT-4o. - Flask Route
@app.route('/', methods=['GET', 'POST'])
def index():
ticker = None
indicators = ['Close']
plot_url = None
stock_data = {}
analysis = None
if request.method == 'POST':
ticker = request.form['ticker']
indicators = request.form.getlist('indicators') or ['Close']
stock_data = fetch_stock_data(ticker)
plot_url = plot_stock_data(stock_data['hist'], ticker, indicators)
image_path = f'images/{ticker}_stock_plot.png'
chart_summary = analyze_stock_image(image_path)
raw_analysis = generate_financial_analysis(chart_summary, stock_data)
analysis = markdown2.markdown(raw_analysis)
return render_template('index.html', plot_url=plot_url, ticker=ticker, indicators=indicators, stock_data=stock_data, analysis=analysis)
- The main route handles the form submission, processes the input, generates the chart, analyzes it using GPT-4o, and renders the results.
2. index.html
index.html
provides the basic structure for our Flask application. It includes the form for user input and sections for displaying the generated stock chart and financial analysis.
<!DOCTYPE html>
<html>
<head>
<title>Stock Trends</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Stock Trends</h1>
<form method="POST">
<input type="text" name="ticker" placeholder="Enter stock ticker" value="{{ ticker }}" required>
<div>
<label><input type="checkbox" name="indicators" value="Close" {% if 'Close' in indicators %}checked{% endif %}> Close Price</label>
<label><input type="checkbox" name="indicators" value="Open" {% if 'Open' in indicators %}checked{% endif %}> Open Price</label>
<label><input type="checkbox" name="indicators" value="High" {% if 'High' in indicators %}checked{% endif %}> High Price</label>
<label><input type="checkbox" name="indicators" value="Low" {% if 'Low' in indicators %}checked{% endif %}> Low Price</label>
<label><input type="checkbox" name="indicators" value="Volume" {% if 'Volume' in indicators %}checked{% endif %}> Volume</label>
</div>
<button type="submit">Get Trend</button>
</form>
{% if plot_url %}
<h2>{{ ticker }} Stock Price</h2>
<img src="data:image/png;base64,{{ plot_url }}" alt="{{ ticker }} Stock Price">
<h3>Financial Analysis - GPT-4o Generated</h3>
<div>{{ analysis|safe }}</div>
{% endif %}
</body>
</html>
3. style.css
style.css
provides the styling for the web application, ensuring it is visually appealing and user-friendly.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f4f4f4;
}
h1 {
margin-top: 20px;
}
form {
margin: 20px 0;
}
input[type="text"] {
padding: 10px;
margin-right: 10px;
border-radius: 5px;
border: 1px solid #ccc;
}
label {
margin-right: 10px;
}
button {
padding: 10px 20px;
border-radius: 5px;
border: none;
background-color: #007bff;
color: white;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
img {
margin-top: 20px;
max-width: 80%;
}
div {
margin-top: 20px;
text-align: left;
}
Final State of the Application
Here are some screenshots that showcase the final state of the application:
- Stock Trends Form and Chart:
2. Financial Company & Chart Summary:
3. Detailed Financial Analysis:
4. GPT-4o Analyst Recommendations and Insights:
Conclusion
By integrating GPT-4o with Flask, this project harnesses the power of cutting-edge AI technology to provide enhanced financial analysis. GPT-4o’s advanced vision and language processing capabilities enable it to generate detailed and accurate financial reports, making it an invaluable tool for investors. Flask provides the web framework to build a user-friendly interface, allowing users to easily interact with the application.
This combination of GPT-4o and Flask offers a robust solution for anyone looking to better understand stock performance and company fundamentals. Stay tuned as I continue to develop and refine this exciting project!
Get in Touch / Code Repo
Linkedin — https://www.linkedin.com/in/ryan-k-ba8274122/
Github Repository — https://github.com/klapp101/ai_financial_analyst
Helpful Resources: