Need help with this code for LSMT forecasting stock prices

Hello guys,

I came up with a project:
I want to perform a prediction of stock closing values using an LSTM model. Specific plan: I want the AI to forecast the closing values for the next 90 days, which will also be displayed in a graph. I also want an evaluation system that evaluates the AI based on its accuracy in making forecasts.

For this task I have the following code:

!pip install yfinance
import pandas as pd
import pandas_datareader as pdr
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from sklearn.metrics import mean_squared_error
import yfinance as yf

# Step 1: Collect stock data for Adobe Systems Incorporated (ADBE) from Yahoo Finance
df ='ADBE', start="2000-01-01", end="2030-02-05")

# Step 2: Preprocess the data
# Drop the Adj Close column, as we don't need it for the prediction
df.drop(['Adj Close'], axis=1, inplace=True)

# Normalize the data
scaler = MinMaxScaler(feature_range=(0, 1))
df = scaler.fit_transform(df)

# Split the data into training and test sets
training_data_len = int(len(df) * 0.8)
training_data = df[0:training_data_len, :]
test_data = df[training_data_len:, :]

# Reshape the data into a format suitable for use with an LSTM
def create_training_data(training_data, look_back):
    X_train, y_train = [], []
    for i in range(len(training_data) - look_back - 1):
        a = training_data[i:(i + look_back), :]
        y_train.append(training_data[i + look_back, 0])
    return np.array(X_train), np.array(y_train)

look_back = 30
X_train, y_train = create_training_data(training_data, look_back)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)

# Step 3: Build the LSTM model
model = Sequential()model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=True))
model.compile(loss='mean_squared_error', optimizer='adam')

# Step 4: Train the LSTM model, y_train, epochs=1, batch_size=32)

# Step 5: Use the trained LSTM model 
def create_test_data(test_data, look_back):
    X_test = []        
    for i in range(len(test_data) - look_back - 1):
        a = test_data[i:(i + look_back), :]
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 5))
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)

y_test = test_data[look_back:, 0]
y_test = scaler.inverse_transform(y_test.reshape(-1, 1))

rmse = np.sqrt(mean_squared_error(y_test, predictions))
print('Test RMSE: %.3f' % rmse)

# Step 6: Use the trained LSTM model to make predictions for the next 90 days
df2 = pdr.DataReader('ADBE', data_source='yahoo', start='2023-02-06', end='2023-05-06')
last_price = df2['Close'][-1]

prediction_dates = pd.date_range(start='2023-02-06', end='2023-05-06', freq='D')
df2 = pd.DataFrame(index=prediction_dates, columns=['Prediction'])
df2['Prediction'] = last_price

for i in range(90):
    df2['Close'] = df2['Prediction']
    df2['Close'] = scaler.transform(df2[['Close']])
    X_test = df2[i:i + look_back][['Close']]
    X_test = np.array(X_test)
    X_test = np.reshape(X_test, (1, look_back, 1))
    prediction = model.predict(X_test)
    prediction = scaler.inverse_transform(prediction)
    df2['Prediction'][i + look_back] = prediction

# Step 7: Plot the predicted closing values for the next 90 days
plt.figure(figsize=(15, 8))
plt.ylabel('Closing Value')
plt.title('Adobe Systems Inc. (ADBE) Predicted Closing Values for the Next 90 Days')

The compiler is giving some errors. Can someone watch this code through and modify it, so that it will work or provide info on how to improve the code? I’m working on it for a week now and its frustrating. There are plenty of synatx error, I just thought that their will be some pros here that could help me out.

Thank you very much in advance.

!whatever is not python code.

X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
needed the 2nd closing parenthesis.

model = Sequential()model.add... needs newline after Sequential().

But really, you should not be asking us to fix such things. Read the tutorial and manuals to learn Python syntax. If you have a specific syntax error message you really cannot understand after some real effort, snip the minimal code that exhibits the error, show the traceback, and ask.

Thank you for your response. I’m working on it for a week now and its frustrating. There are plenty of synatx error, I just thought that their will be some pros here that could help me out.

  1. Load your code (without the non-python line) into IDLE (or another editor/IDE that allows one to quickly check syntax) .
  2. Check the syntax with Run => Check module (Alt-X) (or whatever for whatever one uses).
  3. If there is an error:
    3.1 Read the message, if any, in the popup;
    3.2 Find the red error location colorization;
    3.3 Correct the code;
    3.4 Repeat step 2.

Example from your code:

At step 3, message is '(' is not closed; the ‘(’ after ‘reshape’ is marked. Notice that there is a 2nd ‘(’ on the line and guess that a 2nd ‘)’ is needed at the end. This works to fix the line.

At step 3 again, the previous fix worked and the error is further down. There is message in the popup; moded = Sequential()moded is highlighted. `)m is obviously wrong; something must be inserted. Guess that ‘\n’ is needed after the call.

Now continue.

In the future, check the code every few lines or so instead of after ~100. Also run more often.