R 在 xts 动物园类上使用应用函数 [英] R use apply function on xts zoo class

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

问题描述

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

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 在动物园包中.

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 包.

Also check out the TTR package.

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

UPDATE: Added answer to second part of question.

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

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