Building the LSTM

In order to build the LSTM, we need to import a couple of modules from Keras:

Sequential for initializing the neural network Dense for adding a densely connected neural network layer LSTM for adding the Long Short-Term Memory layer Dropout for adding dropout layers that prevent overfitting

We add the LSTM layer and later add a few Dropout layers to prevent overfitting. We add the LSTM layer with the following arguments:

50 units which is the dimensionality of the output space return_sequences=True which determines whether to return the last output in the output sequence, or the full sequence input_shape as the shape of our training set.

When defining the Dropout layers, we specify 0.2, meaning that 20% of the layers will be dropped. Thereafter, we add the Dense layer that specifies the output of 1 unit. After this, we compile our model using the popular Adam optimizer and set the loss as the mean_squarred_error . This will compute the mean of the squared errors. Next, we fit the model to run on 100 epochs with a batch size of 32. Keep in mind that, depending on the specs of your computer, this might take a few minutes to finish running.

Predicting Future Stock using the Test Set

First we need to import the test set that we’ll use to make our predictions on.

In order to predict future stock prices we need to do a couple of things after loading in the test set:

Merge the training set and the test set on the 0 axis. Set the time step as 60 (as seen previously) Use MinMaxScaler to transform the new dataset Reshape the dataset as done previously

After making the predictions we use inverse_transform to get back the stock prices in normal readable format.

Plotting the Results

Finally, we use Matplotlib to visualize the result of the predicted stock price and the real stock price.

From the plot we can see that the real stock price went up while our model also predicted that the price of the stock will go up. This clearly shows how powerful LSTMs are for analyzing time series and sequential data.

Conclusion

There are a couple of other techniques of predicting stock prices such as moving averages, linear regression, K-Nearest Neighbours, ARIMA and Prophet. These are techniques that one can test on their own and compare their performance with the Keras LSTM. If you wish to learn more about Keras and deep learning you can find my articles on that here and here.

Discuss this post on Reddit and Hacker News.