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)
Here's a start.
library(dplyr)
company.initial =
portfolio %>%
mutate(Investment = as.numeric(Investment) ) %>%
group_by(Code) %>%
summarize(start_date = min(startingPeriod),
total_investment = sum(Investment) )
company__date =
company.initial %>%
group_by(Code) %>%
do(with(.,
Quandl(paste0("WIKI/", Code),
type = "raw",
start_date = start_date,
end_date = Sys.Date() ) ) )
company =
company__date %>%
group_by(Code) %>%
summarize(last_open = last(Open)) %>%
left_join(company.initial) %>%
mutate(StockQuantity = total_investment / last_open)