2011年・TOPIXのヒートマップを作ってみた

ggplot2 Time Series Heatmapsにあるグラフがあまりに美しかったのでやったみた。まずはデータ取得・描画用のライブラリをインストールしておく。

install.packages("ggplot2")
install.packages("RFinanceYJ")

ここでは2011年のTOPIXのHeatmapを作成してみた。こんな感じ。う、美しい。。。
【指数版】
(年初からだらだらと下落した様子がわかる)

【日次リターン版】
(3・11後の急落が良く見える)

コードは以下。

library(ggplot2)
library(plyr)
library(RFinanceYJ)
#データ取得
topix <- quoteStockTsData('998405.T', since='2010-12-31', date.end = "2011-12-31")
topix <- data.frame(date = topix$date, value = topix$close)
#↓こっちでやるとリターンベースになる
#topix <- data.frame(date = topix$date[-1], value = topix$value[-1] /topix$value[-nrow(topix)] - 1)
topix <- data.frame(date = topix$date[-1], value = topix$value[-1])
#日付の加工
topix$year       <- as.numeric(as.POSIXlt(topix$date)$year + 1900)
topix$month      <- as.numeric(as.POSIXlt(topix$date)$mon + 1)
topix$monthf     <- factor(topix$month, levels = as.character(1:12), labels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), ordered = TRUE)
topix$weekday    <- as.POSIXlt(topix$date)$wday
topix$weekdayf   <- factor(topix$weekday, levels = rev(0:6), labels = rev(c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")), ordered = TRUE)
topix$yearmonth  <- as.yearmon(topix$date)
topix$yearmonthf <- factor(topix$yearmonth)
topix$week       <- as.numeric(format(topix$date,"%W"))
#データ加工
x <- ddply(topix, .(yearmonthf), transform, monthweek = 1 + week - min(week))
#プロット
P <- ggplot(x, aes(monthweek, weekdayf, fill = value)) + 
  geom_tile(colour = "white") + facet_grid(year~monthf) +  
  scale_fill_gradient(low="red", high="yellow")+
  opts(title = "Time-Series Calendar Heatmap") + 
  xlab("Week of Month") + ylab("")
P