Using AI to Forecast Stock Market Returns: A Python Experiment Inspired by Research Study
Using AI to Forecast Stock Market Returns: A Python Experiment Inspired by Research Study

A New World of AI-Driven Investing

The stock market has always been a thrilling arena for investors, but in today's rapidly evolving tech landscape, the excitement has reached new heights. Driven by the power of artificial intelligence (AI), a Python script inspired by a study conducted by Alejandro Lopez-Lira and Yuehua Tang at the University of Florida is opening new doors to investment decision-making. In this blog post, we'll explore how this script uses OpenAI's GPT-3.5-turbo to predict stock returns based on financial news sentiment. What's more, I have set up an account on Investopedia to track the results risk-free!

 

The Python Script: This script makes use of OpenAI’s API and Stocknews API to create a (potentially) tool for investors. Here’s a quick rundown of how it works:

  1. Retrieves financial news articles from the Stock News API, focusing on the Technology sector.
def get_news(): url = "https://stocknewsapi.com/api/v1/category?section=alltickers&items=3&page=1&sector=Technology&token=h51c0foqhyenn2jqjt8bvugrrysuwhnczqo2o45o" response = requests.get(url).json() # print(response) news = [] for article in response["data"]: article_info = { "title": article["title"], "text": article["text"], "tickers": article["tickers"], } news.append(article_info) return news
  1. Employs the OpenAI API and GPT-3.5-turbo to assess if the news is good, bad, or uncertain for the stock price of the mentioned company in the short term.
def get_signal(articles): openai.api_key = os.environ.get("OPENAI_API_KEY") # for article in articles: # print(article) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ { "role": "system", "content": "Forget all your previous instructions. Pretend you are a financial expert. You are a financial expert with stock recommendation experience. Answer “YES” if good news, “NO” if bad news, or “UNKNOWN” if uncertain in the first line. Then the ticker of the company, and lastly elaborate with one short and concise sentence if this headline and text is good or bad for the stock price of company in the short term? Do this for all companies/tickers in the message", }, {"role": "user", "content": f"{articles}"}, ], ) signal = response["choices"][0]["message"]["content"] with open("signals.txt", "w") as f: f.write(signal)
  1. Emails the signals to a specified email address.
def send_email(): server = smtplib.SMTP("send.one.com", 587) username = "your_email_here" password = os.environ.get("PASSWORD") send_to = "receiver_email_here" server.starttls() server.login(username, password) msg = EmailMessage() with open("signals.txt", "r") as file: msg.set_content(file.read()) msg["Subject"] = "Signals" msg["From"] = username msg["To"] = send_to server.send_message(msg) return
 

The Research That Sparked It All

The study behind this script examined the potential of ChatGPT and other large language models to predict stock market returns through sentiment analysis of news headlines. The researchers discovered a positive correlation between ChatGPT scores and subsequent daily stock market returns. Furthermore, the study showed that GPT-3.5-turbo outperforms traditional sentiment analysis methods and earlier versions of GPT, signaling that return predictability is an emerging feature of more complex models. Below is an example of the resulting sentiment analysis that GPT-3.5-turbo sends to the specified email address

UNKNOWN TREN - The acquisition of Avant! AI™ may have positive implications for Trend Innovations Holding Inc. in the developing cybersecurity sector.

YES FOBIF - Fobi AI’s acquisition of Passworks SA, a major digital wallet and mobile marketing company in Europe, is a positive development for the company.

NO META - The impending layoffs may indicate negative consequences for Meta's social media platforms, Facebook, Instagram and WhatsApp.

 

Diving Into the Risk-Free Experiment

To test the script's prowess, I established a mockup account on Investopedia, enabling me to simulate investments based on the script-generated signals without risking real money. Although the research suggests GPT-3.5-turbo's superiority over other methods, perfect accuracy in stock market predictions isn't guaranteed. As such, this experiment serves as a supplementary tool for learning about LLM’s potential impact on finance, as well as the emergent capability of capturing accurate sentiment based on short-form news articles.

 

The Future of AI-Driven Investment Strategies

As the world of investing and technology continues to intersect, AI-powered sentiment analysis is worth exploring. This Python script in all its simplicity, born from newly published research, aims to investigate AI's potential to enhance decision-making in stock market investments. While caution is advised when interpreting the results, this experiment might offer valuable insights into AI's role in finance. If you want to follow along or try for yourself, the python script is available Here! I used a lambda function that sends me the resulting sentiments once per day, I purchase the stocks with a positive sentiment and sell them at market opening the next day.