3.2 dygraphs package

The package dygraphs produces dynamic graphics so that user can interact with the graph.

To illustrate our idea, we use stock data download using Quantmod package.

3.2.1 Get Data Using Quantmod

The following code install and download the quantmod package. Then it downloads the daily stock price data of Apple (ticker: AAPL).

We use getSymbols() to download data:

install.packages("quantmod")
library(quantmod)
# getSymbols(): to get data
getSymbols("AAPL")

Take a look at the data:

# OHLCVA data
head(AAPL,n=3)
##            AAPL.Open AAPL.High  AAPL.Low AAPL.Close AAPL.Volume
## 2003-01-02 0.4816753 0.5004593 0.4813400  0.4964343    45357200
## 2003-01-03 0.4964343 0.5007950 0.4893903  0.4997887    36863400
## 2003-01-06 0.5041489 0.5158889 0.4991176  0.4997887    97633200
##            AAPL.Adjusted
## 2003-01-02      0.704906
## 2003-01-03      0.709669
## 2003-01-06      0.709669
# Get OHLC data
price<-OHLC(AAPL)
head(price, n=3)
##            AAPL.Open AAPL.High  AAPL.Low AAPL.Close
## 2003-01-02 0.4816753 0.5004593 0.4813400  0.4964343
## 2003-01-03 0.4964343 0.5007950 0.4893903  0.4997887
## 2003-01-06 0.5041489 0.5158889 0.4991176  0.4997887

The following code install and download the dygraphs package.

install.packages("dygraphs")
library(dygraphs)
getSymbols("AAPL")
getSymbols("SPY")

We will plot four different dynamic plots:

  1. standard dynamic,
  2. shading,
  3. event line, and
  4. candle chart.

3.2.2 Standard dynamic graph

The function dygraph() display time series data interactively. Move your mouse on the diagram.

dygraph(OHLC(AAPL))
AAPL.Open
AAPL.High
AAPL.Low
AAPL.Close
0
20
40
60
80
100
120
140
160
180
200
220
240
2010

3.2.3 Shading

graph<-dygraph(Cl(SPY), main = "SPY") 
dyShading(graph, from="2007-08-09", 
          to="2011-05-11", color="#FFE6E6")
SPY
60
70
80
90
100
110
120
130
140
150
Jan 2004
Jan 2005
Jan 2006
Jan 2007
Jan 2008
Jan 2009
Jan 2010
Jan 2011
Jan 2012

3.2.4 Event line

graph<-dygraph(OHLC(AAPL), main = "AAPL") 
graph<-dyEvent(graph,"2007-6-29",
               "iphone", labelLoc = "bottom") 
graph<-dyEvent(graph,"2010-5-6", 
               "Flash Crash", labelLoc = "bottom") 
graph<-dyEvent(graph,"2014-6-6", 
               "Split", labelLoc = "bottom") 
dyEvent(graph,"2011-10-5",
        "Jobs", labelLoc = "bottom") 
AAPL
AAPL.Open
AAPL.High
AAPL.Low
AAPL.Close
0
20
40
60
80
100
120
140
160
180
200
220
240
2010

3.2.5 Candle Chart

AAPL <- tail(AAPL, n=30)
graph<-dygraph(OHLC(AAPL))
dyCandlestick(graph)
AAPL.Open
AAPL.High
AAPL.Low
AAPL.Close
170
175
180
185
190
195
200
205
10 Mar
17 Mar
24 Mar
31 Mar
07 Apr
14 Apr