Home > front end >  writing a function to get last traded stock price with quantmod package
writing a function to get last traded stock price with quantmod package

Time:12-12

library(quantmod)

last_price<-function(i){
  for (i in stock_list)
    price<-getQuote(i)
  return(price$Last)
}

stock_list<-c("AAPL","TSLA")

last_price(stock_list)

hi guys, just have a function to download the last traded prices from the defined stock list, in this case, ideally, the function will return the last traded price of APPLE & TESLA, however, only the last traded price of APPLE is returned, pretty sure something is wrong with the way I write my function, mind giving me a hand on this? Am I missing something if I want my function to loop through the list? Thanks a lot.

CodePudding user response:

As it is a for loop, and the price is updated in each iteration, it returns only the last one. We need to have a list created to store the output. In addition, the arguments to the function should match.

last_price <- function(stock_list){
  out <- vector('list', length(stock_list))
  names(out) <- stock_list
  for (stock in stock_list)
   {
     price_last<-getQuote(stock)$Last
     out[[stock]] <- price_last
 }
  return(out)
}

-testing

> price_list <- last_price(stock_list)
> str(price_list)
List of 2
 $ AAPL: num 142
 $ TSLA: num 179

There is no need to loop as getQuote can take a vector of values

> getQuote(stock_list)
              Trade Time   Last     Change   % Change   Open   High    Low    Volume
AAPL 2022-12-09 16:00:04 142.16 -0.4899902 -0.3434912 142.34 145.56 140.91  76097011
TSLA 2022-12-09 16:00:04 179.05  5.6100006  3.2345480 173.84 182.50 173.36 104872336
> getQuote(stock_list)$Last
[1] 142.16 179.05

CodePudding user response:

Here is a one-liner sapply solution.

suppressPackageStartupMessages(
  library(quantmod)
)

last_price <- function(stock_list){
  sapply(stock_list, \(s) getQuote(s)$Last)
}

stock_list<-c("AAPL","TSLA")

last_price(stock_list)
#>   AAPL   TSLA 
#> 142.16 179.05

Created on 2022-12-11 with reprex v2.0.2


Edit

After reading akrun's answer, if you want a function to get the last price, transform his vectorized getQuote solution into a function.

last_price <- function(stock_list) {
  setNames(getQuote(stock_list)$Last, stock_list)
}

last_price(stock_list)
#>   AAPL   TSLA 
#> 142.16 179.05

Created on 2022-12-11 with reprex v2.0.2

  • Related