Search code examples
rfunctionticker

User defined function with ticker as input?


Here is my code right now:

f=function(Symbol, start, end, interval){
  getSymbols(Symbols=Symbol, from=start, to= end)
  Symbol=data.frame(Symbol)
  
  a=length(Symbol$Symbol.Adjusted)
  b=a/interval
  c=ceiling(b)
  
  origData=as.data.frame(matrix(`length<-`(Symbol$Symbol.Adjusted, c * interval), ncol = interval, byrow = TRUE))
  

  return(origData)
 
}
f("SPY", "2012-01-01", "2013-12-31", 10)

Next I need to Get the adjusted close price and consider this price data only for following tasks. Split daily stock adjusted close price into N blocks as rows in a data frame. So that each block containing M days (columns) data, where M equals to the time interval value. It’s referred as origData in my code. The function is supposed to return the data frame origData, but whenever I try running this it tells me that the Symbol data frame is empty. How do I need to change my function to get the data frame output?


Solution

  • @IRTFM's observations are correct. Incorporating those changes you can change your function to :

    library(quantmod)
    
    f = function(Symbol, start, end, interval){
      getSymbols(Symbols=Symbol, from=start, to= end)
      data= get(Symbol)
      col = data[, paste0(Symbol, '.Adjusted')]
      a=length(col)
      b=a/interval
      c=ceiling(b)
      origData= as.data.frame(matrix(`length<-`(col, c * interval), 
                              ncol = interval, byrow = TRUE))
      return(origData)
    }
    
    f("SPY", "2012-01-01", "2013-12-31", 10)