1

我有一些简单的 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) )
4

1 回答 1

2

这是一个可重现的示例

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

因此,您需要在对价格数据进行子集化之前删除NAfrominfl以找到最后一个拐点的价格。

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
于 2016-12-03T13:44:58.900 回答