0
votes

I am new in R and I try to use apply function on the xts zoo class, however it shows error. I have a formula: ((2*Close-High-Low)/(High-Low)) * Volume

Input:
y <- getSymbols("0005.HK", auto.assign = FALSE, src = "yahoo")

Error:

y$II <- apply(y,2,function(x) (2Cl(x) - Hi(x) - Lo(x)) / ((Hi(x) - Lo(x)) * Vo(stk)))
Error: unexpected symbol in "apply(y,2,function(x) (2Cl"

and then I tried another one:

Error:
y$II <- apply(y,2,function(x) (2(x[,4]) - x[,2] - x[,3]) / (x[,2] - x[,3]) * x[,5])
Error in FUN(newX[, i], ...) : attempt to apply non-function

After that, I would like to sum the y$II 21 days but I don't know how to do apply function to sum 21 days between every 21 days

IIstd = Sum of 21 ((2*C-H-L)/(H-L)) * V

IInorm = (IIstd / Sum 21 day V) * 100

Anyone can help me ? Please advice, thanks.

1
Maybe typo in 2Cl ... should be 2*Cl ... ?Petr Matousu

1 Answers

0
votes

There are two problems here:

  • 2Cl(x) i s not valid R -- use 2 * Cl(x)
  • all operations on the right hand side are already vectorized so we do not need apply in the first place

For clarity here we have assumed that II = (2C - H - L)/((H-L) * V)and you want 100 times the 21 period volume weighted moving average of that. Modify if that is not what you want.

Try this:

y$II <- (2*Cl(y) - Hi(y) - Lo(y)) / ((Hi(y) - Lo(y)) * Vo(y))

Regarding the second part of the question try this -- rollapplyr is in the zoo package.

wmean <- function(x) weighted.mean(x$II, Vo(x))
y$MeanII <- 100 * rollapplyr(y, 21, wmean, by.column = FALSE, fill = NA)

Also check out the TTR package.

UPDATE: Added answer to second part of question.