I have one column in a dataframe that consists of ticker codes such as AAPL (for Apple stock), TWTR (for Twitter), and many more. I am trying to create a new column where it will return the number of stocks for each ticker code that have been computed from the stock API data.
But when I ran the code below, the new column "Stock Quantity" returned NA for every row. Does anyone have the solution to this?
library(Quandl)
portfolio <- data.frame(Code=c("AAPL", "TWTR", "MSFT"),
startingPeriod=c("2015-01-01", "2015-01-01", "2015-01-01"),
Investment=c("5000", "10000", "15000"),
stringsAsFactors=FALSE)
numberofStock <- function(pf) {
API <- Quandl(paste0("WIKI/", pf$Code), type = "raw",
start_date = pf$startingPeriod, end_date=Sys.Date())
pf["StockQuantity"] <- floor(pf$Investment_01 / tail(API$Open,1))
return(pf)
}
numberofStock(portfolio)