quantmodでグラフ作成

前回「quantmodで株価データ取得」で取得したデータ「T6758」を使用したグラフを描いてみる。

使用する関数はchartSeries。Rのプロンプトで「?chartSeries」と入力するとブラウザでAPIの仕様を読むことができる。
下記のようなもので、一部引用した。

Description

Charting tool to create standard financial charts given a time series like object. Serves as the base function for future technical analysis additions. Possible chart styles include candles, matches (1 pixel candles), bars, and lines. Chart may have white or black background.

reChart allows for dynamic changes to the chart without having to respecify the full chart parameters.

Usage

chartSeries(x,
type = c("auto", "candlesticks", "matchsticks", "bars","line"),
subset = NULL,
show.grid = TRUE,
name = NULL,
time.scale = NULL,
log.scale = FALSE,
TA = 'addVo()',
TAsep=';',
line.type = "l",
bar.type = "ohlc",
theme = chartTheme("black"),
layout = NA,
major.ticks='auto', minor.ticks=TRUE,
yrange=NULL,
plot=TRUE,
up.col,dn.col,color.vol = TRUE, multi.col = FALSE,
...)

reChart(type = c("auto", "candlesticks", "matchsticks", "bars","line"),
subset = NULL,
show.grid = TRUE,
name = NULL,
time.scale = NULL,
line.type = "l",
bar.type = "ohlc",
theme = chartTheme("black"),
major.ticks='auto', minor.ticks=TRUE,
yrange=NULL,
up.col,dn.col,color.vol = TRUE, multi.col = FALSE,
...)
・・・・・・・・・・・・・・・・・・・・・・

早速使ってみる。
TAオプションは「a vector of technical indicators and params, or character strings」ということなので、インディケータを指定できる。今回は出来高ボリンジャーバンドを指定した。

> chartSeries(T6758, subset='2010::2010-04',theme=chartTheme("white"), TA="addVo(); addBBands()")

関数reChartで、一部の引数のみを指定してグラフを更新する。
下記は期間のみ更新する例。

> reChart(subset="2005-01::2015-12")

EMA5、EMA10、SMA20といったインディケータを描画する場合は次のようにすればいい。

> chartSeries(T6758, subset='2010::2010-04',theme=chartTheme("white"), TA="addVo();addEMA(5,col='red');addEMA(n=10,col='green');addSMA(20,col='blue')")

グラフを開いた状態で、単にaddSMA()などと入力しても追加可能。

> addSMA(75,col="orange")

インディケータの無い状態でグラフを描いてから、後で追加する関数を用意することも可能。

> chartSeries(T6758, subset='2010::2010-04',theme=chartTheme("white"),TA=NULL)
> my_indicator<-function(x){return(x+90)}
> add_my_indicator<-newTA(FUN=my_indicator, preFUN=Cl, legend.name = "My Ind", on=1)
> add_my_indicator()

まず最初にグラフを描いてから、addTA()でグラフとは別にインディケータを表示させることも可能。

> chartSeries(T6758, subset='2010::2010-04',theme=chartTheme("white"),TA=NULL)


インディケータを追加。

> addTA(EMA(Cl(T6758)))
> addTA(EMA(Cl(AAPL)))