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)
2
Answers
You might want to start by converting
portfolio$startingPeriod
to data typeDate
by usingas.Date
. Also, you are passing two vectors,portfolio$Code
andportfolio$startingPeriod
, to the functionQuandl()
. You may want to try using anlapply()
function to iterate each value of those two functions.EDIT: You will also need to convert
portfolio$Investment
tonumeric
usingas.numeric()
. Here is how the code should look:Here’s a start.