require(quantmod)
getSymbols("AAPL", from = "2013-06-01", to = "2013-12-31")
## [1] "AAPL"
t <- chartSeries(AAPL, name = "Apple", subset = "2013-06::2013-12", type = "candlesticks")
# candleChart(AAPL)
addCCI()
# t是一个S4类型的变量(mode(t)),由若干个Slot构成(可直接查看t的内容),各个Slot用@符号来引用,就像list类型中用$符号引用成员变量一样(一个Slot本身可以是list类型)
x <- as.matrix(t@xdata)
xx <- HLC(x)
# xx <- HLC(AAPL)
# 计算CCI指标
cci <- CCI(xx, n = 20, maType = "SMA", c = 0.015)
# 计算CCI指标判断买入点和卖出点的正确性
success <- 0
failure <- 0
for (i in 2:length(cci)) {
bPredicted <- FALSE
if (is.na(cci[i - 1]))
next
if ((cci[i - 1] < 100 && cci[i] > 100) || (cci[i - 1] < -100 && cci[i] >
-100)) {
if (Cl(AAPL)[[i - 1]] < Cl(AAPL)[[i]]) {
bPredicted <- TRUE
success <- success + 1
} else {
failure <- failure + 1
}
cat(sprintf("Buy-in point: %s where CCI is %.2f, predicted: %s\n", rownames(cci)[i],
cci[i], bPredicted))
} else if ((cci[i - 1] > 100 && cci[i] < 100) || (cci[i - 1] > -100 && cci[i] <
-100)) {
if (Cl(AAPL)[[i - 1]] > Cl(AAPL)[[i]]) {
bPredicted <- TRUE
success <- success + 1
} else {
failure <- failure + 1
}
cat(sprintf("Sell-out point: %s where CCI is %.2f, predicted: %s\n",
rownames(cci)[i], cci[i], bPredicted))
}
}
## Buy-in point: 2013-07-01 where CCI is -71.23, predicted: TRUE
## Buy-in point: 2013-07-17 where CCI is 106.36, predicted: TRUE
## Sell-out point: 2013-07-19 where CCI is 77.63, predicted: TRUE
## Buy-in point: 2013-07-24 where CCI is 148.51, predicted: TRUE
## Sell-out point: 2013-08-08 where CCI is 85.44, predicted: TRUE
## Buy-in point: 2013-08-13 where CCI is 162.03, predicted: TRUE
## Sell-out point: 2013-08-22 where CCI is 91.03, predicted: FALSE
## Sell-out point: 2013-09-11 where CCI is -322.46, predicted: TRUE
## Buy-in point: 2013-09-19 where CCI is -58.92, predicted: TRUE
## Buy-in point: 2013-10-14 where CCI is 110.51, predicted: TRUE
## Sell-out point: 2013-10-29 where CCI is 89.06, predicted: TRUE
## Sell-out point: 2013-11-20 where CCI is -120.95, predicted: TRUE
## Buy-in point: 2013-11-21 where CCI is -71.93, predicted: TRUE
## Buy-in point: 2013-11-26 where CCI is 209.01, predicted: TRUE
## Sell-out point: 2013-12-10 where CCI is 90.48, predicted: TRUE
# 计算准确率
cat(sprintf("Predict accurancy: %.2f%%", success * 100/(success + failure)))
## Predict accurancy: 93.33%