我的for
循环无法正常工作。我有以下警告信息:imaginary parts discarded in coercion
。这个问题的解决方法是什么?另外,有什么方法可以让我的代码更有效率或有更好的风格?
# Load Packages
library(quantstrat)
# Initialize Settings
start.date <- "2017-05-01"
end.date <- as.character(Sys.Date())
# Stock Tickers
tickers <- c("JPM", # JP Morgan
"FB", # Facebook
"SPY", # S&P 500
"AMZN", # Amazon
"WMT", # Wal-Mart
"LVMUY", # LVMH
"MCD", # Mac Donald's
"BMW", # BMW
"KO", # Coca-Cola
"G13.SI" # Genting Sg
)
# Retrieving Stock Data
options("getSymbols.yahoo.warning"=FALSE)
suppressMessages(getSymbols(Symbols = tickers, from = start.date,
to = end.date, src = "yahoo", adjust = TRUE))
# Grouping Adjusted Prices and Interpoloating NA Values
ClPrices <- do.call(merge, lapply(tickers, function(x) Cl(get(x))))
ClPrices <- na.approx(ClPrices)
# Apply MACD
MACD.res <- do.call(merge, lapply(ClPrices, function(x, nFast, nSlow, nSig) {
y <- MACD(x, nFast, nSlow, nSig)
colnames(y) <- paste0(colnames(y),".", gsub(pattern = ".Close",
replacement = "", x = colnames(x)))
y
}, nFast = 12, nSlow = 26, nSig = 9))
# Apply RSI
RSI.res <- do.call(merge, lapply(ClPrices, function(x, n) {
t <- RSI(x, n=14)
colnames(t) <- paste0(colnames(t), ".",
gsub(pattern = ".Close", replacement = "", x = colnames(x)))
t
}, n = 14))
# Generating Buy/Sell Signals
Signals <- "Initialise"
for (i in 1:ncol(ClPrices)){
if((MACD.res[nrow(MACD.res),2i] > MACD.res[nrow(MACD.res),2i-1]) &&
(MACD.res[nrow(MACD.res)-1,2i] < MACD.res[nrow(MACD.res)-1,2i-1]) &&
(RSI.res[nrow(RSI.res),i] < 30)){
Signals[i] <- paste("Buy", tickers[i])
} else if ((MACD.res[nrow(MACD.res),2i] < MACD.res[nrow(MACD.res),2i-1]) &&
(MACD.res[nrow(MACD.res)-1,2i] > MACD.res[nrow(MACD.res)-1,i]) &&
(RSI.res[nrow(RSI.res),i] > 80)) {
Signals[i] <- paste("Sell", tickers[i])
} else {
Signals[i] <-paste("No trade", tickers[i])
}
}
# Output
View(Signals)