简体   繁体   中英

R How can I use the apply function to a time series object and keep the dates attached to the specific columns?

I have two price series

require(quantmod)
require(TTR)

tickers = c("IBM","SPY")
getSymbols(tickers, from="2010-10-20", to="2014-09-22")
prices = do.call(merge, lapply(tickers, function(x) Cl(get(x))))

> head(prices)
          IBM.Close SPY.Close
2010-10-20    139.07    117.87
2010-10-21    139.83    118.13
2010-10-22    139.67    118.35
2010-10-25    139.84    118.70
2010-10-26    140.67    118.72
2010-10-27    141.43    118.38

now I want to smooth the series using the SMA function of the TTR package.

sma.IMB = SMA(prices[,1])
sma.SPY = SMA(prices[,2])

sma.prices = cbind(sma.IBM, sma.SPY)

> head(sma.prices)
           IBM.Close.SMA.3 SPY.Close.SMA.3
2010-10-20              NA              NA
2010-10-21              NA              NA
2010-10-22        139.5233        118.1167
2010-10-25        139.7800        118.3933
2010-10-26        140.0600        118.5900
2010-10-27        140.6467        118.6000

This is very tedious when dealing with many assets, so I want to shorten this procedure using apply

sma.prices = apply(prices, 2, SMA)

> head(sma.prices)
     IBM.Close SPY.Close
[1,]        NA        NA
[2,]        NA        NA
[3,]        NA        NA
[4,]        NA        NA
[5,]        NA        NA
[6,]        NA        NA

> sma.prices[9:11,]
     IBM.Close SPY.Close
[1,]        NA        NA
[2,]   141.217   118.504
[3,]   141.727   118.712

As you see the date is not attached to the specific row and the default n=10 moving average is used for calculation. My question is how to keep the dates to the zoo output. Thanks a lot.

Try this:

sma.prices <- prices
sma.prices[] <- apply(prices, 2, SMA)

apply returns a matrix which needs to be converted to a zoo object. To insure that the dates in the new zoo series match the dates returned by the TTR function, you could first define a function with the TTR function and any parameters used by it and then use that to produce the new zoo series. The code below defines TTR_fn as SMA with an=3 to define a 3-day moving average and then uses TTR_fn to both do the calculations and to get the proper dates.

TTR_fn <- function(x)  SMA(x, n=3)
sma.prices  <- zoo(apply(prices, 2, TTR_fn), 
                   order.by=index(TTR_fn(prices[,1]) ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM