![](/img/trans.png)
[英]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.