skip to Main Content

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


  1. You might want to start by converting portfolio$startingPeriod to data type Date by using as.Date. Also, you are passing two vectors, portfolio$Code and portfolio$startingPeriod, to the function Quandl(). You may want to try using an lapply() function to iterate each value of those two functions.

    EDIT: You will also need to convert portfolio$Investment to numeric using as.numeric(). Here is how the code should look:

    portfolio <- data.frame(Code=c("AAPL", "TWTR", "MSFT"),
                            startingPeriod=as.Date(c("2015-01-01", "2015-01-01", "2015-01-01")),
                            Investment=as.numeric(c("5000", "10000", "15000")), 
                            stringsAsFactors=FALSE)
    
    
    numberofStock <- function(pf) {lapply(seq_along(nrow(portfolio)), function(x){
        API <- Quandl(paste0("WIKI/", pf$Code[x]), type = "raw", 
                      start_date = pf$startingPeriod[x], end_date=Sys.Date())
    
        pf["StockQuantity"] <- floor(pf$Investment[x] / tail(API$Open,1))
    
        return(pf)
        })
    }
    
    numberofStock(portfolio)
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search