データは平等

ノンプロがRで株価とかファイナンスの分析をするとき,quantmodパッケージを使うのは常套手段.
そのあとPerformanceAnalyticsパッケージとかでポートフォリオ分析というかバックテストをすることが多いと思う.
そんな一連の流れをdplyrチェーンで成し遂げてしまう恐ろしいパッケージが存在するらしい.

本記事はこちらの借景.とはいえ,丸パクリDeNAいと思う.
www.business-science.io

コピペできた方がいいでしょ?以下,そのままRstudioに貼り付けて結果を確認してください.

install.packages("tidyquant")
require(tidyquant)

# FB, AMZN, NFLX, GOOGの4本値と修正株価,出来高が入ったテストファイル
data(FANG)
FANG

# PerformanceAnalysisの関数がtq_performanceで呼び出せる
FANG %>%
  group_by(symbol) %>%
  # 調整済終値を日次リターンに変換
  tq_transmute(ohlc_fun   = Ad,
               mutate_fun = periodReturn,
               period     = "daily") %>%
  # ベンチマークNULLで日次リターンのSharpeRatioを計算
  # それぞれの引数はperformanceAnalyticsとおなじ
  # FUN="Stdev"は,そのままだとES/SD/VaRのシャープ比が出るので,SDSharpeを出すため
  tq_performance(Ra              = daily.returns,
                 Rb              = NULL,
                 performance_fun = SharpeRatio,
                 Rf              = 0,
                 p               = 0.95,
                 FUN             = "StdDev")

つぎは月次リバランスでポートフォリオを作ってみる.

# リバランスウエイトを設定
weights <- c(0.50, 0.25, 0.25, 0.00)

FANG %>%
  group_by(symbol) %>%
  tq_transmute(ohlc_fun   = Ad,
               mutate_fun = periodReturn,
               # 月次リバランスなので
               period     = "monthly") %>%
  tq_portfolio(assets_col  = symbol,
               returns_col = monthly.returns,
               weights     = weights) -> FANG_portfolio

FANG_portfolio

# 初期投資額
init.investment <- 10000

# チャートを描く.geom_smoothで平滑化ラインを挿入
FANG_portfolio %>%
  mutate(wealth.index = init.investment * cumprod(1 + portfolio.returns)) %>%
  ggplot(aes(x = date, y = wealth.index)) +
  geom_line(size = 2, color = palette_light()[[3]]) +
  geom_smooth(method = "loess") +
  labs(title = "Individual Portfolio: Comparing the Growth of $10K",
       subtitle = "Quickly visualize performance",
       x = "Year|Month-end", y = "Investment Value") +
  theme_tq() +
  scale_y_continuous(labels = scales::dollar)

# パフォーマンスをテーブルで出力
FANG_portfolio %>%
  tq_performance(Ra = portfolio.returns,
                 Rb = NULL,
                 performance_fun = table.Stats)

株価を指数表示にしてプロットしたいこともありましょう.

FANG %>%
  group_by(symbol) %>%
  tq_transmute(ohlc_fun   = Ad,
               mutate_fun = periodReturn,
               period     = "monthly") %>%
  mutate(wealth.index = 10000 * cumprod(1 + monthly.returns)) %>%
  ggplot(aes(x = date, y = wealth.index, color = symbol)) +
  geom_line(size = 1.5) +
  labs(title = "Stocks: Comparing the Growth of $10K",
       subtitle = "New theme for financial visualizations",
       x = "", y = "Investment Value") +
  scale_y_continuous(labels = scales::dollar) +
  theme_tq() +
  scale_color_tq(theme = "light")

とんでもない.財務諸表やらバリュエーションやらが手に入る
getの引数はhelp参照.

AAPL_data <- tq_get("AAPL", get = c("key.ratios", "key.stats"))
AAPL_data

# key.ratioの項目をextendする
AAPL_data %>% 
  unnest(key.ratios)
AAPL_data %>%
  unnest(key.ratios) %>%
  unnest(data)

# key.statsの項目をextendする
AAPL_data %>% 
  unnest(key.stats, .drop = TRUE) %>% t()

ここからが恐ろしい.指数構成銘柄もとれる!!

tq_index("DJI")

# とれる指数リストはこちら(いまのところ米国指数だけ)
tq_index_options()

取引所上場銘柄のリストも手に入る!!

tq_exchange("NASDAQ")

# とれる取引所リストはこちら(今のところ米国だけ)
tq_exchange_options()

すごくね!?

このパッケージでは,ソースはUS Yahooとか,Morningstarとか,基本的に米国のデータしか扱えないところが残念.
ただ,ちかいうちに誰かがYahoo Japanとかから引っ張ってこれるような仕組みを作るのでしょう.
こうやって簡単にプログラムできて,データが自由に使えるようになると,気合いがある人はバランスファンドの1%近い信託報酬を節約できるようになるのでしょう.
すでに,米国ではそうだってことですね.

一方,こういうパッケージに限って,日本のプロの方々は社内のしがらみで会社のPCから使えなかったりするらしい.