Skip to content

Instantly share code, notes, and snippets.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
#calculate mean squre error
mse <- history$metrics$val_loss[length(history$metrics$val_loss)]
mse <- round(mse, 7)
mse
# Calculate the mean and standard deviation of the original dataset
mean_return <- mean(return_log)
sd_return <- sd(return_log)
# Rescale the predicted and original values
y_train_pred_rescaled <- y_train_pred_returns * sd_return + mean_return
y_test_pred_rescaled <- y_test_pred_returns * sd_return + mean_return
y_train_rescaled<-y_train * sd_return + mean_return
y_test_rescaled<-y_test * sd_return + mean_return
# Shift the predicted values to start from where the training data predictions end
shift <- length(y_train_pred_rescaled)
# Calculate the predicted returns using the LSTM model
y_train_pred_returns <- model %>% predict(x_train)
y_test_pred_returns <- model %>% predict(x_test)
# Set up the layout of the plots
par(mfrow = c(1,2))
options(repr.plot.width=15, repr.plot.height=8)
# Plot the training and predicted values
plot(y_train, type = "l", col = "green",main="Apple daily Log Returns", xlab = "Day", ylab = "Returns",lwd =3)
lines(y_train_pred_returns, col = "red")
legend(x = "topleft", legend = c("Train", "Train Predictions"), col = c("green", "red"), lwd = 3)
split_data <- function(stock, lookback) {
data_raw <- as.matrix(stock) # convert to matrix
data <- array(dim = c(0, lookback, ncol(data_raw)))
# create all possible sequences of length lookback
for (index in 1:(nrow(data_raw) - lookback)) {
data <- rbind(data, data_raw[index:(index + lookback - 1), ])
}
test_set_size <- round(0.2 * nrow(data))