Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to plot a OHLC cluster by cluster in R

I am trying to plot OHLC charts in R with by where they belong in a kmeans cluster.

I have created a kmeans cluster on my data and added the cluster where it fits to my XTS data.

                    Open   High     Low   Close ..2
2008-06-25 18:00:00    0 0.0017  0.0000  0.0015   9
2008-06-25 22:00:00    0 0.0102 -0.0045  0.0080   6
2008-06-26 02:00:00    0 0.0014 -0.0002  0.0000   9
2008-06-26 06:00:00    0 0.0005 -0.0003  0.0003   9
2008-06-26 10:00:00    0 0.0016 -0.0025  0.0010   9
2008-06-26 14:00:00    0 0.0010 -0.0011 -0.0007   9

The last column is the cluster it belongs to.

I am trying to figure out the best way to plot this in R with the OHLC bar chart and grouped by the last column.

I have look through quantmod and the plot overviews but I can't seem to figure out how to do this?

like image 722
Jerry Avatar asked Oct 18 '25 10:10

Jerry


1 Answers

Try something like that

s <- get(getSymbols('SPY'))["2012::"]
s$h <- Hi(s) / Op(s) - 1
s$l <- Lo(s) / Op(s) - 1
s$c <- Cl(s) / Op(s) - 1
s$cluster <- as.numeric(kmeans(s[,7:9] , centers = 6)$cluster)
chart_Series(xts(coredata(s)[order(s$cluster),],order.by = index(s))

And the outcome is

enter image description here

Obviously it's only for display.

A second approach would be to plot a TA on top of the plot

chart_Series(s)
add_TA(Lo(s) * 0.99 , on=1 , type = 'p' , cex = 1.5 , pch = 20 , col = s$cluster)

And the output

enter image description here

like image 77
haki Avatar answered Oct 20 '25 23:10

haki