Tutorial técnico · em inglês

Stock prediction LSTM Neural Network function

This method creates a LSTM neural net capable of predict a stock time series using Keras.

RStudioRedes Neurais
Photo by Sigmund on Unsplash
Photo by Sigmund on Unsplash

This method creates a LSTM neural net capable of predict a stock time series using Keras.

I wrote about LSTM and time series on this article in RPubs site (in Portuguese).

The code of the method could be downloaded on my Github.

Execution steps

The method structure could be resumed in the image bellow

Code Examples

Method creation:

#using GitHub Strocture
source('lstm_stock_function.R')

On a first example I with use META (Facebook, WhatsApp, Instagram, etc) stocks and for now I don´t need a ARIMA comparison

return_meta <- 
    lstm_stock(
      stock_name = 'META', 
      start_date = '2019-01-01', 
      lstm_executions = 10, 
      lstm_verbose = F)
## [1] "-----------------------------------"
## [1] "Execution completed..."
## $parameters
##   stock_name start_date   end_date arima_compare
## 1       META 2019-01-01 2022-09-12         FALSE
## 
## [1] "MSE"
## 1  2.53

As we can see the data shows us a growing trend and the normalization was needed to create the neural net.

The prediction plot show that the model was capable to predict results remarkably close to the real prices

On a second example the lstm_stock will use data from Petrobrás (brazilian oil company). The data will be extract from Bovespa (brazilian stock market) from 2015 until today. The method will execute a LSTM neural net with 10 iterations and in the end will also execute and ARIMA model to compare the results

return_petr4 <- 
    lstm_stock(
      origin = '^BVSP', 
      stock_name = 'PETR4.SA', 
      start_date = '2015-01-01', 
      lstm_executions = 10, 
      arima_compare = T,
      lstm_verbose = F)

## [1] "Execution completed..."
## $parameters
##   stock_name start_date   end_date arima_compare
## 1   PETR4.SA 2015-01-01 2022-09-12          TRUE
## 
## [1] "MSE"
##   variable        value
## 1     lstm 4.203284e-01
## 2    arima 7.725121e-05

Again, the data shows us a growing trend and the normalization was needed to create the neural net.

The LSTM prediction chart (on left) show us some error on the predicted value, while the ARIMA model present a better result. That perception could be confirmed by the MSE results:

## [1] "MSE"
##   variable        value
## 1     lstm 4.203284e-01
## 2    arima 7.725121e-05

To end this text, if you find some bug or “brain cramp” please e-mail me on marcosmhs@live.com and I will be glad on correct the code and register your name on the credits.