I am trying to create a Neuralnet app in R that gets the last 20 years of 20 stocks using GetSP500stocks. That part works just fine, but when I try to get the price adjusted out of that list into a new list to then calculate the 10, 50, and 200 moving day average I get the following error
Even tried to use specific column name df_Svalues[[i]] <- stockValues[[i]]$tickers.adjusted but get the same error. Can anyone help me with this?
Here is the code I have so far:
#import libraries
library(quantmod)
library(BatchGetSymbols)
library(TTR)
library(shiny)
library(lubridate)
library(neuralnet) # Neural net library
#import the first 20 stocks
df_SP500 <- GetSP500Stocks()
tickers <- head(df_SP500$Tickers,20)
head(tickers) # Debug code
str(tickers) # Debug code
#set date
my_date <- Sys.Date()
first.date <- my_date %m-% years(20)
last.date <- Sys.Date()
print(my_date) # debug code
print(last.date) # debug code
print(first.date) # debug code
#pull data from tickers
stockValues <- list()
for (i in 1:length(tickers)){
stockValues[[i]] <- getSymbols(tickers[i],auto.assign = FALSE, from = first.date)
}
head(stockValues)
str(stockValues)
#set up list for values
df_Svalues <- list()
colnames(stockValues[[i]])
for (i in 1:length(tickers)){
df_Svalues[[i]] <- stockValues[[i]]$tickers.adjusted
df_Svalues[[i]]$mav10 <- 0
df_Svalues[[i]]$mav50 <- 0
df_Svalues[[i]]$mav200 <- 0
}
str(df_Svalues)
CodePudding user response:
This should do it:
#import libraries
library(quantmod)
library(BatchGetSymbols)
library(TTR)
library(shiny)
library(lubridate)
library(neuralnet) # Neural net library
#import the first 20 stocks
df_SP500 <- GetSP500Stocks()
tickers <- head(df_SP500$Tickers,20)
#set date
my_date <- Sys.Date()
first.date <- my_date %m-% years(20)
last.date <- Sys.Date()
#pull data from tickers
stockValues <- list()
for (i in 1:length(tickers)){
stockValues[[i]] <- getSymbols(tickers[i],auto.assign = FALSE, from = first.date)
}
#set up list for values
df_Svalues <- list()
for (i in 1:length(tickers)){
df_Svalues[[i]] <- stockValues[[i]][,paste0(tickers[i], ".Adjusted")]
df_Svalues[[i]]$mav10 <- 0
df_Svalues[[i]]$mav50 <- 0
df_Svalues[[i]]$mav200 <- 0
}
head(df_Svalues[[1]])
#> MMM.Adjusted mav10 mav50 mav200
#> 2002-05-09 37.62977 0 0 0
#> 2002-05-10 37.80853 0 0 0
#> 2002-05-13 38.28524 0 0 0
#> 2002-05-14 38.72916 0 0 0
#> 2002-05-15 38.58317 0 0 0
#> 2002-05-16 38.55637 0 0 0
Created on 2022-05-09 by the reprex package (v2.0.1)
The difference is that this line:
df_Svalues[[i]] <- stockValues[[i]]$tickers.adjusted
should be changed to the one below:
df_Svalues[[i]] <- stockValues[[i]][,paste0(tickers[i], ".Adjusted")]
In R if you're trying to make a name out of a variable, you need to paste the variable value and other character string together first. Or at least that's how I've always done it. Alternatively, you could have used stockValues[[i]][,6]
if the values you want are always in the sixth column.