【问题标题】:Warning in for loopfor循环中的警告
【发布时间】:2017-12-23 07:39:37
【问题描述】:

我的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)

【问题讨论】:

    标签: r quantstrat technical-indicator


    【解决方案1】:

    可能是 MACD.res[nrow(MACD.res),2i] 。 你应该这样做MACD.res[nrow(MACD.res),2*i]

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 2018-06-22
      • 2018-09-30
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多