I have this sample list of stocks:
stock.list = c("AMZN","GOOGL","AAPL","FB","TSLA")
And I have this following function:
fnct<-function(x){
require(quantmod)
ticker <- getSymbols(x,src="google", auto.assign=FALSE)
#number of rows
n<-nrow(ticker)
# last day's close
lastvalue <- as.numeric((ticker[n,4]))
# previous day's close
prevvalue <- as.numeric((ticker[n-1,4]))
# price change
prchange <- lastvalue - prevvalue
res<-(
paste0(prchange)
)
return(res)
}
The output of the function is a number that represents a difference between the closure prices of the last day and the day before that (essentially, positive number in the output means that the stock price went up, and negative means that it went down)
For example, using this function for AMZN
today returns a positive number:
> fnct('AMZN')
[1] "17.3200000000001"
I would like to apply the function to the list of stocks so that it only displays those stocks names that had positive changes (>0
), and, if possible, numeric value of change next to them (essentially, eliminating stocks with negative change)
So the ideal output would be something like this:
AMZN 17.3200000000001
GOOGL 14.95
...and so on
This is what I came up with so far, but it does not work
for(x in stock.list) {
paste0(x,fnct(x))
}
I know this does not eliminate stocks with negative changes, but this is how far I could go. Even this doesn't seem to work.
Ideally, it should be robust enough to skip NA
's (for example, misspelled stock name in the list, or missing data for a particular stock in the list)
Any suggestions? Thanks in advance.
The smallest fix would be to change your loop to...
for (x in stock.list) {
if(as.numeric(fnct(x)) >= 0) print(paste(x, fnct(x)))
}
It's your function that needs to made tolerant to typos and the simplest behaviour is to have it skip over any unfound symbols instead of trying to guess what you were going for.
fnct <- function(x) {
require(quantmod)
ticker <- suppressWarnings(tryCatch({ getSymbols(x, src="google", auto.assign=FALSE) }, error = function(e) NULL))
if (!is.null(ticker)) {
#number of rows
n <- nrow(ticker)
# last day's close
lastvalue <- as.numeric((ticker[n,4]))
# previous day's close
prevvalue <- as.numeric((ticker[n-1,4]))
# price change
prchange <- lastvalue - prevvalue
res <- paste0(prchange)
} else {
res <- "Not found"
}
return(res)
}
Then your loop becomes:
for (x in stock.list) {
result <- fnct(x)
if (result == "Not found" || (as.numeric(result) >= 0 & as.numeric(result) < 100) ) print(paste(x, result))
}
Just to clarify, this is the most direct way to go from what you had to what you want. It's not necessarily the best way.