[英]R: How can I create a time series object with multiple time scales in an existing R time series class?
[英]R How can I use the apply function to a time series object and keep the dates attached to the specific columns?
我有两个价格系列
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
现在,我想使用TTR封装的SMA功能使系列平滑。
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
在处理许多资产时,这非常繁琐,因此我想使用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
如您所见,日期未附加到特定行,并且使用默认的n = 10移动平均值进行计算。 我的问题是如何使日期保持在动物园输出中。 非常感谢。
尝试这个:
sma.prices <- prices
sma.prices[] <- apply(prices, 2, SMA)
apply返回一个矩阵,该矩阵需要转换为Zoo对象。 为确保新的Zoo系列中的日期与TTR函数返回的日期匹配,您可以首先使用TTR函数及其使用的任何参数定义一个函数,然后使用该函数生成新的Zoo系列。 下面的代码将TTR_fn定义为SMA,an = 3,以定义3天移动平均线,然后使用TTR_fn进行计算并获取正确的日期。
TTR_fn <- function(x) SMA(x, n=3)
sma.prices <- zoo(apply(prices, 2, TTR_fn),
order.by=index(TTR_fn(prices[,1]) ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.