Rhodo
Rhodo

Reputation: 1334

Dealing with multi-column time series in TTR

I download 2 daily stock histories going back to 2000:

library(quantmod)
check <- c("FB","GOOG")
getSymbols(check, from='2000-01-01')

Isolate the last prices:

close <- cbind(Cl(GOOG),Cl(FB))

Now I would like to use some of the tools in the very nice 'TTR' package, for instance SMA:

smacheck <- SMA(close,50)
Error in `colnames<-`(`*tmp*`, value = c("GOOG.Close.SMA.50", "FB.Close.SMA.50":
  length of 'dimnames' [2] not equal to array extent

FB has a shorter history than GOOG. How do I get this to work across both stocks, regardless of when the NA's start?

Upvotes: 2

Views: 530

Answers (2)

CHP
CHP

Reputation: 17189

You can just use apply function

SMAs <- xts(apply(close, MARGIN = 2, FUN = "SMA", n = 50), index(close))
head(SMAs)
##            GOOG.Close FB.Close
## 2004-08-19         NA       NA
## 2004-08-20         NA       NA
## 2004-08-23         NA       NA
## 2004-08-24         NA       NA
## 2004-08-25         NA       NA
## 2004-08-26         NA       NA

tail(SMAs)
##            GOOG.Close FB.Close
## 2013-10-29   899.6198  46.7544
## 2013-10-30   902.9198  46.9664
## 2013-10-31   906.1448  47.2042
## 2013-11-01   909.2114  47.4282
## 2013-11-04   912.3294  47.5816
## 2013-11-05   915.4320  47.7570

Upvotes: 1

Joshua Ulrich
Joshua Ulrich

Reputation: 176698

This has nothing to do with the missing values. SMA doesn't currently work on objects with more than one column. You need to run SMA on each column individually.

library(quantmod)
e <- new.env()
getSymbols('GOOG;FB', from='2000-01-01', env=e)
smacheck <- do.call(merge, eapply(e, function(x) SMA(Cl(x), 50)))

Upvotes: 3

Related Questions