[R] knitr+sendmailR でHTMLレポート配信

R Advent Calendar2012、4日目です。

ふと、Rで分析した結果を定常的にメールでレポートしたいなーと思ったので、knitr+sendmailRで試してみた。

大きくは、以下のような流れ。

  • RStudioで分析&レポート作成
  • 上で作成したRmdファイルからHTMLファイルを生成
  • 生成されたHTMLを読み込んで、HTMLメールを送信


ただ、最新版(1.1-1)のsendmailRだと、Content-Typeを内部で上書きされてHTMLメールが出来なかったので、前のバージョン(1.0-0)を使用した。

$ wget http://cran.r-project.org/src/contrib/Archive/sendmailR/sendmailR_1.0-0.tar.gz

> install.packages("sendmailR_1.0-0.tar.gz")

Rmdファイルの用意

今回は、異常検知(変化点検出)のパッケージを作ってみた - yokkunsの日記の時に作ったものを改良した。

  • stock_anomaly_detection_sample.Rmd
株価異常検知
=======================================
```{r,echo=FALSE,warning=FALSE,error=FALSE,message=FALSE}
library(ChangeAnomalyDetection)
library(ggplot2)
library(RFinanceYJ)
library(reshape2)
library(xtable)
```

```{r warning=FALSE,echo=FALSE}
stock <- quoteStockXtsData("2432.t", since="2011-01-01")
stock <- as.data.frame(stock)
stock$date <- as.POSIXct(rownames(stock))
```

## 過去20日間の株価
```{r warning=FALSE,echo=FALSE,results='asis'}
stock.tail <- tail(stock,n=20)
stock.tail$date <- as.character(stock.tail$date)
print(xtable::xtable(stock.tail),type="html")
```

## 過去20日間のClose値推移
```{r fig.width=12, fig.height=6,warning=FALSE,echo=FALSE}
ggplot(stock, aes(x=date,y=Close,col="Stock")) +
  geom_line() + 
  geom_point()
```

```{r,warning=FALSE,echo=FALSE}
change.score <- changeAnomalyDetection(x=stock$Close, term=30, order=c(1,1,0))
stock$change.score <- change.score
```

## 過去20日間のClose値異常スコア
```{r warning=FALSE,echo=FALSE,results='asis'}
stock.tail <- tail(stock,n=20)[,c("date","Close","change.score")]
stock.tail$date <- as.character(stock.tail$date)
print(xtable::xtable(stock.tail),type="html")
```

## 異常スコアの推移
```{r fig.width=12, fig.height=6,warning=FALSE,echo=FALSE}
ggplot(stock, aes(x=date,y=change.score,col="Score")) +
  geom_line()
```

Rmdファイルを読み込んでHTMLメールを送信

以下のような、R実行スクリプトを作成

  • sendStockAnomalyDetectionReport.R
#!/usr/bin/env Rscript

library(knitr)
library(markdown)
library(sendmailR)

main <- function(){
  mail.from    <- "yokkuns@tkul.jp"
  mail.to      <- "yokkuns@tkul.jp"
  mail.subject <- "Sample Report"
  rmd.file     <- "stock_anomaly_detection_sample.Rmd" #RStudioで作成したRmdファイル

  ## HTMLレポート送信
  sendHtmlReport(rmd.file,mail.from,mail.to,mail.subject)
}

sendHtmlReport <- function(rmd.file,from,to,subject,headers=list(),control=list()){
  f <- rmd.file
  md.file <- paste(f,"md",sep=".")
  html.file <- paste("~/public_html/",f,".html",sep="") ## ブラウザからも確認出来るように公開ディレクトリに生成する

  knit(input=rmd.file,output=md.file)
  markdownToHTML(file=md.file,output=html.file)
  html.str <- paste(readLines(html.file),collapse="\n")
  body <- html.str
  headers <- list(`Content-Type`="text/html; charset = \"utf-8\"",
                  `Content-Trensfer-Encoding`="7bit")
  ## control <- list(smtpServer="hogehoge.com",smtpPort=25)
  sendmail(from,to,subject,body,headers=headers,control)
}

## 実行
main()

実行

$ chmod +x sendStockAnomalyDetectionReport.R
$ ./sendStockAnomalyDetectionReport.R

結果

無事、メールが届いた!

http://gyazo.com/a8a1d2b5cc11a691e6869fbf0203dcb7.png


しかし、何故か、画像が表示されない・・・
ちょっと調べる時間が無かったので、生成されるHTMLのURLを記載する事にした。

  • stock_anomaly_detection_sample.Rmdに追記
## 詳細
詳細については、以下のURLをご確認下さい。

http://example.com/~yokkuns/stock_anomaly_detection_sample.html


これで、クリックすれば以下のようなレポートが見れるのでオッケー(という事にしよう)