Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - Does rollapply() allow an array of results from call to function?

# Loading packages

require(forecast)
require(quantmod)

# Loading OHLC xts object

getSymbols('SPY', from = '1950-01-01')

# Selecting weekly Close prices

x <- Cl(to.weekly(SPY))

# ARIMA(p,d,q) estimation and forecasting function

a.ari.fun <- function(x) {

  a.ari <- auto.arima(x = x, d = 1, max.p = 50, max.q = 50, max.P = 50,
                      max.Q = 50, ic = 'aic', approximation = TRUE)
  fore <- forecast.Arima(object = a.ari, h = 4, level = c(.9))
  supp <- tail(fore$lower, 1)
  rest <- tail(fore$upper, 1)
  return(c(supp, rest))

}

# Roll apply ARIMA(p,d,q) in rolling window

rollapplyr(data = tail(x, 800), width = 750, FUN = a.ari.fun)

This code returns me an error because of

return(c(supp, rest))

at the end of a.ari.fun() function I wrote; I'm sure about that because if a.ari.fun() returns just

return(rest)

it works fine.

How do I have to arrange the a.ari.fun() in order to obtain an object suitable to rollapplyr()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like using by.column=FALSE will give what you request.

tail(rollapplyr(data = as.zoo(x), width = 750, FUN = a.ari.fun, by.column=FALSE))

2012-07-13 126.0730 145.8036
2012-07-20 126.1342 145.8616
2012-07-27 128.9303 148.6576
2012-08-03 129.7640 149.4975
2012-08-10 130.5752 150.2954
2012-08-17 132.3789 152.0963

If you have PerformanceAnalytics loaded rollapply.xts will be dispatched instead of rollapply.zoo. I edited to convert the object to zoo first to make sure the right rollapply is called.

EDIT:

Thanks to some patching from @JoshuaUlrich, this now works with rollapply.xts,so you do not have to convert to zoo. Also, rollapply.xts is now registered in the xts package instead of PerformanceAnalytics, so you will get the same results regardless of whether or not PerformanceAnalytics is loaded. You'll need the under development version of xts -- Rev. 765 or later -- which is on R-Forge.

rollapplyr(x, 750, a.ari.fun, by.column=FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...