11.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.

11.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 AAPL.Adjusted
## 2007-01-03  3.081786  3.092143 2.925000   2.992857  1238319600      2.573566
## 2007-01-04  3.001786  3.069643 2.993571   3.059286   847260400      2.630688
## 2007-01-05  3.063214  3.078571 3.014286   3.037500   834741600      2.611954
# Get OHLC data
price<-OHLC(AAPL)
head(price, n=3)
##            AAPL.Open AAPL.High AAPL.Low AAPL.Close
## 2007-01-03  3.081786  3.092143 2.925000   2.992857
## 2007-01-04  3.001786  3.069643 2.993571   3.059286
## 2007-01-05  3.063214  3.078571 3.014286   3.037500

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.

11.2.2 Standard dynamic graph

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

dygraph(OHLC(AAPL))

11.2.3 Event line

We want to decorate the dynamic graph by a line to indicate one-day event. To do it, we do it line by line using the function dyEvent() puting the date information, label, and location of the label.

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") 

11.2.4 Shading

Event sometimes lasts more one day. Then we would like to highlight the whole period of time. Usually, highlighting over economic recession period is common in economic graphics. It can be used to mark periods when the market is bearish.

graph<-dygraph(Cl(SPY), main = "SPY") 
dyShading(graph, from="2007-08-09", 
          to="2011-05-11", color="#FFE6E6")

11.2.5 Candle Chart

The dynamic candle stick chart is dynamic in the sense that mouse over the stick would gives the four prices (open, high, low, close). We will use the function dyCandlestick().

AAPL <- tail(AAPL, n=30)
graph<-dygraph(OHLC(AAPL))
dyCandlestick(graph)