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.
The code of the method could be downloaded on my Github.
The method structure could be resumed in the image bellow
Method creation:
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] "Downloading stock data..."
## [1] "fitting..."
## [1] "predicting..."
## [1] "MSE: 2.53399089471135"
## [1] "-----------------------------------"
## [1] "Execution completed..."
## $parameters
## stock_name start_date end_date arima_compare
## 1 META 2019-01-01 2022-09-12 FALSE
##
## [1] "MSE"
## # A tibble: 1 x 1
## mse
## <dbl>
## 1 2.53
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] "Downloading stock data..."
## [1] "fitting..."
## [1] "predicting..."
## [1] "MSE: 0.420328804831862"
## [1] "Starting ARIMA... "
## variable value
## 1 lstm 4.203288e-01
## 2 arima 7.725121e-05
## [1] "-----------------------------------"
## [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.203288e-01
## 2 arima 7.725121e-05
As we can see, on this example, the ARIMA model was capable to make a better prediction comparing with the LSTM model.
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.