Predicting Stock Prices using LSTM Neural Networks with TensorFlow

Python
Deep Learning

In this example, we're using an LSTM neural network in TensorFlow to predict stock prices based on historical data.

 1|  import numpy as np
 2|  import pandas as pd
 3|  import tensorflow as tf
 4|  from tensorflow.keras.models import Sequential
 5|  from tensorflow.keras.layers import LSTM, Dense
 6|  from sklearn.metrics import mean_squared_error
 7|  
 8|  # Load and preprocess data
 9|  data = pd.read_csv('stock_data.csv')
10|  data = data.dropna()
11|  close_prices = data['Close'].values.reshape(-1, 1)
12|  
13|  # Scale the data
14|  from sklearn.preprocessing import MinMaxScaler
15|  scaler = MinMaxScaler()
16|  scaled_prices = scaler.fit_transform(close_prices)
17|  
18|  # Split the data into training and testing sets
19|  train_size = int(len(scaled_prices) * 0.8)
20|  test_size = len(scaled_prices) - train_size
21|  train_prices, test_prices = scaled_prices[0:train_size,:], scaled_prices[train_size:len(scaled_prices),:]
22|  
23|  # Define the function to create the dataset for training the LSTM model
24|  def create_dataset(dataset, time_steps=1):
25|      dataX, dataY = [], []
26|      for i in range(len(dataset)-time_steps-1):
27|          a = dataset[i:(i+time_steps), 0]
28|          dataX.append(a)
29|          dataY.append(dataset[i + time_steps, 0])
30|      return np.array(dataX), np.array(dataY)
31|  
32|  # Set the number of time steps and create the training and testing datasets
33|  time_steps = 30
34|  X_train, y_train = create_dataset(train_prices, time_steps)
35|  X_test, y_test = create_dataset(test_prices, time_steps)
36|  
37|  # Reshape the input data for the LSTM model
38|  X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
39|  X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
40|  
41|  # Define the LSTM model architecture
42|  model = Sequential()
43|  model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
44|  model.add(LSTM(units=50))
45|  model.add(Dense(units=1))
46|  
47|  # Compile the model
48|  model.compile(optimizer='adam', loss='mean_squared_error')
49|  
50|  # Train the model
51|  model.fit(X_train, y_train, epochs=100, batch_size=32)
52|  
53|  # Make predictions on the testing set
54|  predictions = model.predict(X_test)
55|  
56|  # Scale the predictions back to their original values
57|  predictions = scaler.inverse_transform(predictions)
58|  
59|  # Evaluate the performance of the model
60|  rmse = np.sqrt(mean_squared_error(y_test, predictions))
61|  print(f'Root Mean Squared Error: {rmse}')
1 Upvote
Did you find this snippet useful?

Sign up to bookmark this in your snippet library