R在XTS Zoo类上使用Apply函数 [英] R use apply function on xts zoo class

查看:112
本文介绍了R在XTS Zoo类上使用Apply函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R语言的新手,我尝试在xts zoo类上使用apply函数,但是显示错误.我有一个公式:(((2 * Close-High-Low)/(High-Low))*音量

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"

然后我尝试了另一个:

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

在那之后,我想对y $ II 21天进行求和,但是我不知道如何在每21天之间对21天进行求和.

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 = 21之和((2 * C-H-L)/(H-L))* V

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

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

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

任何人都可以帮助我吗?请指教,谢谢.

Anyone can help me ? Please advice, thanks.

推荐答案

这里有两个问题:

  • 2Cl(x)我不是有效的R-使用2 * Cl(x)
  • 右侧的所有操作已经矢量化,因此我们首先不需要apply
  • 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

为清楚起见,在此我们假设II =(2C-H-L)/((H-L)* V),并且您想要100倍于21周期体积加权移动平均值.如果那不是您想要的,请进行修改.

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.

尝试一下:

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

关于问题的第二部分,请尝试以下操作-rollapplyr在zoo软件包中.

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)

还要签出TTR包.

更新:在问题的第二部分中添加了答案.

UPDATE: Added answer to second part of question.

这篇关于R在XTS Zoo类上使用Apply函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆