Hello,
runSum calculates a running sum looking back a fixed distance n, e.g. 20.
How do I calculate a dynamic runSum function for an xts object?
In
otherwords, I want to calculate a running sum at each point in time
looking back a variable distance. In this example, values governed by
the vector VL.
Here's a minimum reproducible example:
library(quantstrat)
symbols = c('^GSPC')
start.date <- as.Date("2010-01-01")
end.date <- as.Date("2013-12-31")
getSymbols(symbols, from=as.character(start.date), to=as.character(end.date),adjust=T)
"acF1" <- function(x, n1=5, n2=10, n3=20, nacF1=25, n0=20, ...) {
var1 <- x - lag(x,1,na.pad=T)
var2 <- runSD(x, n=n1, sample=TRUE, cumulative=FALSE)
var3 <- runMean(var2, n=n2, cumulative=FALSE)
VL <- ifelse( trunc(n3/(var2/var3))>nacF1, nacF1, trunc(n3/(var2/var3)))
p_pos <- ifelse(var1>=0, var1, 0)
out1 <- runSum(p_pos, n=n0, cumulative=FALSE)
res <- cbind(var1, var2, var3, VL, p_pos, out1)
colnames(res) <- c("var1","var2","var3","VL", "p_pos", "out1")
reclass(res)
}
acf1 <- acF1( GSPC[,c("GSPC.Close")], n1=5, n2=10, n3=20, nacF1=25, n0=20)
acf1
So on
2010-02-02, I want runSum to be looking back 23 points as governed by VL , not 20 points
2010-02-03, I want runSum to be looking back 24 points as governed by VL, not 20 points
etc etc
2013-12-31, I want runSum to be looking back 25 points as governed by VL, not 20 points
Amarjit
dynamic runSum
2 messages · amarjit chandhial, Gabor Grothendieck
1 day later
On Thu, Aug 7, 2014 at 9:32 AM, amarjit chandhial
<a.chandhial at btinternet.com> wrote:
Hello, runSum calculates a running sum looking back a fixed distance n, e.g. 20. How do I calculate a dynamic runSum function for an xts object? In otherwords, I want to calculate a running sum at each point in time looking back a variable distance. In this example, values governed by the vector VL.
The width argument in rollapplyr in the zoo package can be a vector. It can't be NA though so we have used 1 in those cases here and at the end used na.omit to get rid of the junk at the beginning: na.omit(rollapplyr(acf1, ifelse(is.na(acf1$VL), 1, acf1$VL), sum))