1

I have some simple R code that reads a list of stocks prices. I would like to plot the ZigZag indicator, highlight all the inflection points, and print out the value of the last three inflection points. This is supposed to do that, but it doesn't work properly. Any ideas why?

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 Answers1

2

Here's a 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) )

The problem is that the end of the output from ZigZag will have NA, because you can't know where the last inflection point occurs without future data. This causes there to be NA in infl:

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

And subsetting a vector by NA returns NA:

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

So you need to remove the NA from infl before subsetting your price data to find the price at the last inflection points.

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
Community
  • 1
  • 1
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418