How I built a stock recommendation algorithm using ChatGPT – and how you could do it

Learn how to build a simple stock recommendation model in python — without any prior knowledge of coding

Gabriel M. A. Santos
7 min readApr 2, 2023
Image created with Bing Image Creator

Deciding whether to buy stocks in either Microsoft, Apple, or maybe both, can be a rather daunting task. The more you start reading about certain companies and listening to people’s opinions on different media might even make you more unsure about what stocks you should buy.

So what should you base your decision-making upon? Reading rumors in the news? Make a technical analysis? Listening to your financial advisor? Or maybe listening to advice from the subreddit /wallstreetbets?

Well, unfortunately, there doesn’t exist one perfect recipe to analyze stocks in relation to getting buy/sell indications. However, I tried asking ChatGPT what type of analysis it would recommend making when deciding whether or not to buy a stock. Here’s what it came up with:

  1. Fundamental analysis: Analyze the company’s financial health and performance.
  2. Technical Analysis: Use charts and technical indicators to identify trends and potential price movements.
  3. Industry Analysis: Analyze the industry and market trends.
  4. Management Analysis: Assess the company’s leadership team.
  5. Valuation Analysis: Compare the stock price to its intrinsic value.
  6. Risk Analysis: Assess potential risks associated with investing in the stock.

While these are excellent points, this article will take a deep dive into how I built a stock recommendation algorithm — and how you could do it. So let’s get into it!

Starting, I have myself tried to take different approaches to analyze stocks, varying from analyzing companies’ financial health to making a stock forecasting model, which I previously have described in this article:

However, I didn’t yet try to make an analysis based on technical indicators. So what exactly are technical indicators in stock analysis?

“Technical indicators are tools that help traders and analysts to study the movement and patterns of stock prices based on historical data. They can be used to predict future price movements, identify trends, and generate buy and sell signals.”

And it’s especially the last part from the paragraph above I have focused on, namely “generating buy and sell signals.

There exist various numbers of technical indicators that you could focus on in relation to generating buy or sell signals, but through a bit of research and advisory from ChatGPT, I chose to focus on 4 different technical indicators:

  1. Moving Average: A tool that shows the average price of a stock over a certain period of time, which can help identify whether the stock is trending up or down.
  2. RSI (Relative Strength Index): A tool that helps determine whether a stock is overbought (meaning it might be due for a price drop) or oversold (meaning it might be due for a price increase).
  3. A/D (Accumulation/Distribution) Lines: A tool that helps determine whether there is more buying or selling pressure on a stock based on the relationship between price and trading volume.
  4. ADX (Average Directional Index): A tool that measures the strength of a stock’s trend, which can help identify whether the stock is trending up or down.

So these 4 technical indicators were the ones to go with, and I then tried to see if I, augmented by ChatGPT, could build an algorithm that would analyze a stock based on these indicators, and then give me either a ‘Buy’, ‘Sell’ or ‘Hold’ recommendation.

Thus, the idea was that I, as simply as possible, could insert a stock ticker and then get a recommendation telling me to either buy, sell, or hold a certain stock, based on the 4 technical indicators.

So I simply started to chat with ChatGPT and slowly had a foundation on which I could test the code. I decided to code in python and execute and test the code in PyCharm.

The code extracts the financial data from the ‘yfinance’ (Yahoo Finance) library from a stock ticker that you can insert yourself:

Then, you can specify how long ago you want to download the financial data from:

The code then slowly iterates through the stock ticker you have inserted and calculates the values of the four technical indicators. Afterward, it determines the recommendation based on all the indicators and prints out either ‘Buy’, ‘Sell’, or ‘Recommendation’:

Then, it simply prints out the recommendation in the terminal in PyCharm (or you could simply end the code with a results.to.csv(“/write_your_path_here.csv”) if you would want the output in a csv file instead).

Here is an example output with Microsoft analyzed:

And yes, it’s possible to insert multiple tickers at the beginning of the code. I thought myself that an optimal scenario would be to just extract all the stock tickers from Yahoo Finance, analyze them in relation to the technical indicators, and print out the recommendations in a csv file.

Then, you could have analyzed all the stock tickers in the database from the Yahoo Finance library and have the recommendations in an Excel file, allowing you to simply filter out all those stocks having a ‘Buy’ recommendation.

This would be ideal since you could overcome bias in relation to only analyzing stocks you know of or have heard about before, instead of stocks you might never have heard about before.

However, I wasn’t able to extract stock tickers automatically from the Yahoo Finance library, so what I did instead was finding a database that had all stock tickers and downloaded as many down as I could (they had a paywall if you wanted to download all stock tickers).

Then, I would manually insert all the stock tickers (I think it was about 1000) in the first line of the code, and now I had a full Excel file containing 1000 known and unknown stock ticker symbols, and could easily filter out all those with ‘Buy’ recommendations.

The screenshot below is from the analysis made on February 7th, 2023 filtering out all the ‘Buy’ recommendations:

Anyways, here’s the full code. I would love any feedback, criticism, ideas, or something in between to optimize the code in some way so we can make it better.

Hope you can find it useful!

import yfinance as yf
import pandas as pd

# Define the ticker symbols of the stocks you want to analyze
ticker_symbols = [‘MSFT’]

# Create an empty DataFrame to store the results
results = pd.DataFrame(columns=[‘Ticker’, ‘Moving Average’, ‘RSI’, ‘A/D Lines’, ‘ADX’, ‘Recommendation’])

# Iterate through the ticker symbols
for ticker in ticker_symbols:
# Download historical data for the current ticker
data = yf.download(ticker, start=’2000-01-01')

# Calculate the 200-day moving average
data[‘MA’] = data[‘Close’].rolling(window=200).mean()

# Calculate the RSI
delta = data[‘Close’].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=14).mean()
avg_loss = loss.rolling(window=14).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))

# Calculate A/D Lines
data[‘UpMove’] = data[‘High’] - data[‘High’].shift(1)
data[‘DownMove’] = data[‘Low’].shift(1) - data[‘Low’]
data[‘UpVolume’] = data[‘UpMove’] * data[‘Volume’]
data[‘DownVolume’] = data[‘DownMove’] * data[‘Volume’]
data[‘PosDM’] = data[‘UpMove’]
data[‘NegDM’] = data[‘DownMove’]
data.loc[data.UpMove < data.DownMove, ‘PosDM’] = 0
data.loc[data.UpMove > data.DownMove, ‘NegDM’] = 0
data[‘PosDI’] = data[‘PosDM’].rolling(window=14).mean()
data[‘NegDI’] = data[‘NegDM’].rolling(window=14).mean()
data[‘AD’] = (data[‘PosDI’] - data[‘NegDI’]) / (data[‘PosDI’] + data[‘NegDI’])

# Calculate ADX
data[‘ADX’] = 100 * (data[‘PosDI’] - data[‘NegDI’]) / (data[‘PosDI’] + data[‘NegDI’])
data[‘ADX’] = data[‘ADX’].rolling(window=14).mean()

# Determine the recommendation
if data[‘Close’].iloc[-1] > data[‘MA’].iloc[-1] and rsi.iloc[-1] > 70 and data[‘AD’].iloc[-1] > data[‘AD’].iloc[
-2] and data[‘ADX’].iloc[-1] > 25:
recommendation = ‘Buy’
elif data[‘Close’].iloc[-1] < data[‘MA’].iloc[-1] and rsi.iloc[-1] < 30 and data[‘AD’].iloc[-1] < data[‘AD’].iloc[
-2] and data[‘ADX’].iloc[-1] > 25:
recommendation = ‘Sell’
else:
recommendation = ‘Hold’

# Append the results to the DataFrame
results = results.append(
{‘Ticker’: ticker, ‘Moving Average’: data[‘MA’].iloc[-1], ‘RSI’: rsi.iloc[-1], ‘A/D Lines’: data[‘AD’].iloc[-1],
‘ADX’: data[‘ADX’].iloc[-1], ‘Recommendation’: recommendation}, ignore_index=True)

# Print the results
print(results)

…if you’re interested to see got the algorithm performed on the stock market, make sure to read my newest article:

--

--

Gabriel M. A. Santos

Tech enthusiast with a master's in business & information systems. I write about how tech can improve processes & productivity, offering insights for everyone💡