如何将技术指标应用于股票清单

时间:2017-07-02 04:35:13

标签: r lapply quantstrat technical-indicator

我正在尝试将MACD和RSI技术指标应用于股票清单的调整后价格。该代码的最终目标是基于2个指标为每个股票生成买/卖信号。但是,我在使用lapply函数应用指标时遇到了问题。我很感激你的帮助。谢谢!

#Load Packages
    library(quantstrat) 

#Initialise Settings
    start.date <- "2016-01-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
    "Z74.SI" #Singtel   
    )

#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
    AdjPrices <- do.call(merge, lapply(tickers, function(x) Ad(get(x))))

#Apply MACD Indicator
    MACD <- lapply(AdjPrices, MACD, list(AdjPrices, nFast =12, nSlow = 26, nSig = 9))

1 个答案:

答案 0 :(得分:4)

请改为尝试:

MACD <- lapply(AdjPrices, FUN = MACD, nFast =12, nSlow = 26, nSig = 9)

也许你最终想要这样的东西?

    z <- do.call(merge, lapply(AdjPrices, function(x, nFast, nSlow, nSig) {
        y <- MACD(x, nFast, nSlow, nSig) 
        colnames(y) <- paste0(colnames(y),".", gsub(pattern = ".Adjusted", replacement = "", x = colnames(x)))
        y
        }, nFast = 12, nSlow = 26, nSig = 9))

> tail(z)
            macd.JPM signal.JPM   macd.FB signal.FB  macd.SPY signal.SPY
2017-06-23 0.5439033  0.2746984 0.7333757 0.6242897 0.4931503  0.5617852
2017-06-26 0.5628315  0.3323250 0.7378923 0.6470103 0.4735852  0.5441452
2017-06-27 0.6455863  0.3949773 0.5754388 0.6326960 0.3884193  0.5130000
2017-06-28 0.8647098  0.4889238 0.5809413 0.6223450 0.3883060  0.4880612
2017-06-29 1.1460891  0.6203568 0.4633677 0.5905496 0.3134080  0.4531306
2017-06-30 1.3738249  0.7710504 0.3627919 0.5449980 0.2656285  0.4156302

编辑,对正在发生的事情的其他解释:

在上面的lapply函数调用中,定义了一个匿名函数(这一位:function(x, nFast, nSlow, nSig) { ..... }),它计算一个自动收录器的MACD,然后重命名这些列。请注意,此函数没有&#34; name&#34;,或换句话说,该函数未分配给变量(编写此代码将函数分配给R中的变量,例如use_macd <- function() {}

以上代码等同于以下(更详细)代码,其中我们明确定义lapply将调用的函数,然后将结果与do.call(merge ....结合起来

use_MACD <- function(x, nFast, nSlow, nSig) {
               y <- MACD(x, nFast, nSlow, nSig) 
               colnames(y) <- paste0(colnames(y),".", gsub(pattern = ".Adjusted", replacement = "", x = colnames(x)))
               y
}


tickerLst <- lapply(AdjPrices, FUN = use_MACD, nFast = 12, nSlow = 26, nSig = 9)
# Now have a list of "macd" values for each ticker.

#Combine into one xts object:
z <- do.call(merge, tickerLst)