Home » Business » Can OpenAI’s ChatGPT Help us Predict Stock Market Prices?

Can OpenAI’s ChatGPT Help us Predict Stock Market Prices?

Can AI help us obtain financial freedom?

Without a doubt, ChatGPT from OpenAI is an amazing invention! As someone who loves to write about finance and employ data science in the process, this AI technology is a great combination of both my passions. I decided to test it out by asking a simple yet direct question: Could this tool fulfill my desire for financial success as well as satisfy my inner nerd? Let’s find out!

Maybe another strategy can help us? What if we tried to enlist OpenAI’s assistance in writing a program that can estimate prices? Is this a viable way to get bypass chatgpt filters?

Let’s see what happens. It looks like the robot is quite intelligent, and if it succeeds, many people will be spared from making bad investments without doing their homework first.

You might also want to read: Can ChatGPT pick Stocks better than your Fund Manager

Step 1 — I Asked ChatGPT to write Some Code

I started by asking the AI to generate some code that would be able to predict stock prices.

import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# Load the stock data
df = pd.read_csv('stock_data.csv')

# Select the features to use for prediction
X = df[['Open', 'High', 'Low', 'Volume']]

# Select the target variable
y = df['Close']

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)

# Evaluate the model on the test set
score = model.score(X_test, y_test)
print(f'Test score: {score:.2f}')

We even asked to Chatgpt to gives us a short bit of documentation to explain what the code does.

Also Read:  3 Reasons to Partner With an Enterprise

Let’s fire up the code and see what happens. Ah… looks like we have an issue here. We don’t seem to have the file stock_data.csv. Can ChatGPT lend us a hand with this? 🤔 Let’s find out

Step 2 — Asking ChatGPT to Fix the Mistake

import pandas as pd
from pandas_datareader import data

# Set the ticker and the start and end dates
ticker = 'AAPL'
start_date = '2010-01-01'
end_date = '2020-12-31'

# Use the DataReader to download the data
df = data.DataReader(ticker, 'yahoo', start_date, end_date)

# Save the DataFrame to a CSV file
df.to_csv('stock_data.csv', index=False)

Look’s like it is downloading Apple stock-prices, let’s go with that!

Its still giving me the error. Let’s fix it.

Here is the new code

import yfinance as yf

# Set the ticker and the start and end dates
ticker = 'AAPL'
start_date = '2010-01-01'
end_date = '2020-12-31'

# Use the Ticker object to download the data
ticker_data = yf.Ticker(ticker)
df = ticker_data.history(start=start_date, end=end_date)

# Save the DataFrame to a CSV file
df.to_csv('stock_data.csv', index=True)

Finally this is working.

Step 3 — Re-Running the Code

After re-running the code, here’s what I got:

Also Read:  Maximizing Your Winnings: Tips and Strategies for Successful Betting on South Carolina Sites

Let’s ask chatgpt what does this mean:

ChatGPT has presented us with a potential method of predicting prices accurately. Can it give us the perfect forecast?

No. Sadly not.

Step 4 — Asking a More Specific Question

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# Load the data into a Pandas DataFrame
df = pd.read_csv('stock_data.csv')

# Create a new DataFrame with only the closing prices
prices = df[['Close']]

# Shift the prices so that the first row corresponds to today's price and the second row corresponds to yesterday's price
prices_shifted = prices.shift(1)

# Add a column with tomorrow's closing price
prices_shifted['Tomorrow'] = prices['Close']

# Drop the first row, which has a null value for yesterday's price
prices_shifted = prices_shifted.dropna()

# Separate the target variable (tomorrow's closing price) from the input features (yesterday's closing price)
X = prices_shifted[['Close']]
y = prices_shifted['Tomorrow']

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create a Linear Regression model
model = LinearRegression()

# Train the model on the training data
model.fit(X_train, y_train)

# Make predictions on the test data
y_pred = model.predict(X_test)

# Calculate the test score
test_score = model.score(X_test, y_test)
print(f'Test score: {test_score:.2f}')

# Use the model to predict tomorrow's closing price based on today's closing price
today_close = df['Close'].iloc[-1]
tomorrow_close_prediction = model.predict([[today_close]])[0]
print(f'Predicted closing price for tomorrow: {tomorrow_close_prediction:.2f}')

Let’s run it and see what it happens:

A perfect predictor, again?! Let’s dig into this. Our price data was only downloaded up until 2020–12–31:

Also Read:  Elevate Your Home: A Comprehensive Guide to Window Solutions in San Antonio

So, the prediction should be for the closing price of the next trading day, which is 2020–12–31. To check if it’s accurate, let’s take a look at prices on Yahoo! Finance.

Here’s the closing price that was fed in:

The Adjusted Close price used for training and prediction was not accurate, as the actual Adjusted Close on December 30th ended up being 131.12 instead of 132.4 as predicted. Clearly, this predictor isn’t perfect after all!

Wrapping Up

ChatGPT is truly astounding. As a novice, you can request it to craft some operational code and even aid in debugging. However, be mindful that this tool might give you the impression that your code is running excellently while minor issues may go unnoticed.

Thus, for beginners who utilize ChatGPT should still check their financial models cautiously, as even a small blunder can be costly. Fortunately, ChatGPT incorporates some warnings to help prevent this from happening.

Leave a Comment