R中的锯齿形指示器

时间:2016-12-03 00:48:05

标签: r technical-indicator

我有一些简单的R代码,可以读取股票价格列表。我想绘制ZigZag指标,突出显示所有拐点,并打印出最后三个拐点的值。应该这样做,但它没有正常工作。有什么想法吗?

library(TTR)

mydata <-read.csv("EURUSD.csv", sep=",",header=TRUE)

attach(mydata)

plot(BAR, PRICE)

zz <- ZigZag(PRICE, change = 5, percent = TRUE)

lines(zz, col = "blue")

#get the inflection points
infl <- c( FALSE, diff(diff(zz)>0)!=0   )
points(mydata$BAR[infl ], mydata$PRICE[infl ], col="red")

#print the last 3 inflection points
print( tail(mydata$PRICE[infl],1) )
print( tail(mydata$PRICE[infl],2) )
print( tail(mydata$PRICE[infl],3) )

1 个答案:

答案 0 :(得分:1)

这是reproducible example

library(TTR)
data(ttrc)

x <- tail(ttrc, 150)
zz <- ZigZag(x$Close, change = 5, percent = TRUE)

plot(x$Date, x$Close)
lines(x$Date, zz, col = "blue")

#get the inflection points
infl <- c( FALSE, diff(diff(zz)>0)!=0   )
points(x$Date[infl ], x$Close[infl ], col="red")

#print the last 3 inflection points
print( tail(x$Close[infl],1) )
print( tail(x$Close[infl],2) )
print( tail(x$Close[infl],3) )

问题是ZigZag的输出结尾会有NA,因为如果没有将来的数据,您无法知道最后一个拐点的位置。这会导致NA中出现infl

R> tail(infl,15)
 [1] FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA    NA    NA
[13]    NA    NA    NA

NA对矢量进行子集化会返回NA

R> (1:10)[c(1, NA, 10)]
[1]  1 NA 10

因此,您需要在对价格数据进行子集化之前从NA中删除infl,以便在最后一个拐点处找到价格。

R> infl <- na.omit(c(FALSE, diff(sign(diff(zz))) != 0))
R> #print the last 3 inflection points
R> tail(x$Close[infl],1)
[1] 44.27
R> tail(x$Close[infl],2)
[1] 48.61 44.27
R> tail(x$Close[infl],3)
[1] 45.32 48.61 44.27