1

I have a data frame of stock data with information back 10 years on 100+ stocks. I am trying to run the MACD function in quantmod on this data but cannot figure out how to split the calculation by different stocks. For example a little bit of my data frame looks like this:

   data<-structure(list(market = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 3L, 3L), .Label = c("AD1", "AD2", "AD3"), class = "factor"), 
date = structure(c(15623, 15624, 15625, 15628, 15623, 15624, 
15625, 15628, 15625, 15628), class = "Date"), open = c(101.52, 
101.68, 102.1, 101.99, 100.73, 100.85, 101.57, 101.01, 100.56, 
100.42), high = c(102.07, 102.39, 102.36, 102.07, 101.4, 
101.59, 101.62, 101.35, 100.56, 100.71), low = c(101.26, 
101.56, 101.63, 101.5, 100.59, 100.85, 101.07, 100.97, 100.56, 
100.41), last = c(101.78, 102.08, 101.76, 101.91, 101.08, 
101.37, 101.06, 101.21, 100.41, 100.56)), .Names = c("market", 
"date", "open", "high", "low", "last"), row.names = c(1L, 2L, 
3L, 4L, 5L, 6L, 7L, 8L, 11L, 12L), class = "data.frame", na.action = structure(9:10,.Names = c("9", 
"10"), class = "omit"))

How do I pass this data frame into the MACD function while getting it to calculate each market separately. Thank you for the help. I am new to R.

Tim
  • 776
  • 3
  • 8
  • 15
  • This is a good place to start: http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega – harkmug Apr 11 '13 at 18:39

2 Answers2

2

You can use by here to group by market and apply the function to each group.

library(quantmod)
by(data,data$market,function(x)
{
  ## coerece the group to an xts object
  dat.xts <- xts(x[,-c(1:2)],x$date)
  ## EMA ~ MACD with type 'EMA'
  EMA( dat.xts,n=min(nrow(dat.xts),10))

})

data$market: AD1
               [,1]
2012-10-10       NA
2012-10-11       NA
2012-10-12       NA
2012-10-15 101.8225
--------------------------------------------------------------------------------------------------------------- 
data$market: AD2
             [,1]
2012-10-10     NA
2012-10-11     NA
2012-10-12     NA
2012-10-15 101.04
--------------------------------------------------------------------------------------------------------------- 
data$market: AD3
             [,1]
2012-10-12     NA
2012-10-15 100.49
agstudy
  • 119,832
  • 17
  • 199
  • 261
0

Firstly, MACD function in quantmod expects xts not data.frame.

So what you need to do is first split data.frame by market and then convert each of resultant data.frame into xts and then apply macd function.

LL <- split(data, data$market)

result <- lapply(LL, 
       function(DF) { 
           XTS <- xts(DF[, -2], order.by = as.POSIXct(DF$date, format="%Y-%m-%d", tz="GMT"),tzone='GMT')
           return(MACD(XTS$last))                
       }
      )
CHP
  • 16,981
  • 4
  • 38
  • 57
  • any idea why I would be getting "Error in rowSums(x) : 'x' must be numeric" error – Tim Apr 11 '13 at 19:58