问题
# 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()
?
回答1:
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)
来源:https://stackoverflow.com/questions/12019164/does-rollapply-allow-an-array-of-results-from-call-to-function