library(ChangeAnomalyDetection)
## Loading required package: TTR
## Loading required package: xts
## Loading required package: zoo
## Attaching package: 'zoo'
## The following object(s) are masked from 'package:base':
##
## as.Date, as.Date.numeric
library(ggplot2)
## Find out what's changed in ggplot2 with news(Version == "0.9.0", package =
## "ggplot2")
library(RFinanceYJ)
## Loading required package: XML
library(reshape2)
yahoo <- quoteStockXtsData("4689.t", since = "2011-01-01")
head(yahoo)
## Open High Low Close Volume AdjClose
## 2011-01-04 31650 31850 31500 31700 59831 31700
## 2011-01-05 31050 31400 30150 30200 160383 30200
## 2011-01-06 30200 30600 30050 30250 114564 30250
## 2011-01-07 30250 30550 30100 30200 77564 30200
## 2011-01-11 30100 30550 29560 30450 106584 30450
## 2011-01-12 30600 30900 30500 30750 69012 30750
yahoo <- as.data.frame(yahoo)
yahoo$date <- as.POSIXct(rownames(yahoo))
ggplot(yahoo, aes(x = date, y = Close)) + geom_line()
change.score <- changeAnomalyDetection(x = yahoo$Close,
term = 30, order = c(1, 1, 0))
tail(change.score)
## [1] -0.1897 -0.3702 -0.3717 -0.3783 -0.3589 -0.3209
yahoo$change.score <- change.score
ggplot(yahoo, aes(x = date, y = change.score)) +
geom_line()
ggplotで同時にプロットするために、少し加工する。
この手の整形は、reshape2パッケージのmelt関数が便利
yahoo <- yahoo[yahoo$change.score != 0, ]
yahoo$change.score <- yahoo$change.score * 2000 +
10000
yahoo.melt <- melt(yahoo, id.vars = "date", measure.vars = c("Close",
"change.score"))
ggplot(yahoo.melt, aes(x = date, y = value)) +
geom_line(aes(col = variable))