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
## 2007-01-03 12.32714 12.36857 11.70000 11.97143 309579900
## 2007-01-04 12.00714 12.27857 11.97429 12.23714 211815100
## 2007-01-05 12.25286 12.31428 12.05714 12.15000 208685400
## AAPL.Adjusted
## 2007-01-03 10.41635
## 2007-01-04 10.64755
## 2007-01-05 10.57173
# Get OHLC data
price<-OHLC(AAPL)
head(price, n=3)
## AAPL.Open AAPL.High AAPL.Low AAPL.Close
## 2007-01-03 12.32714 12.36857 11.70000 11.97143
## 2007-01-04 12.00714 12.27857 11.97429 12.23714
## 2007-01-05 12.25286 12.31428 12.05714 12.15000
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:
- standard dynamic,
- shading,
- event line, and
- 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)