在整个 XTS 对象列表上使用函数

Using function on the whole list of XTS objects

我正在尝试在 R 中分析烛台形态 Marubozu。到目前为止,我能够下载不同的股票数据,并在一个股票数据中使用“烛台”库找到形态。我想使该过程自动化,以便我可以 运行 同时对许多股票执行 CSPMarubozu 功能。

我的主要问题是我无法真正理解如何将数据列表传递给此函数。在尝试使用 for 循环(尝试 1)执行此操作时,我收到以下错误:“CSPMarubozu 错误((名称(stocks_list[i])),n = 20,ATRFactor = 0.8,: 价格系列必须包含开盘价、最高价、最低价和收盘价。”我知道,我无法将字符变量传递给此函数,但我找不到没有“”标记的索引名称的方法。(例如“AMZN”,我只需要 AMZN

我的另一个尝试(尝试 2)是使用 lapply() 函数来完成,但出现了同样的问题

这是我的代码:

#install.packages(candlesticks)
        library(candlesticks)
        library(tidyquant)
        library(quantmod)
        
    #List of stock codes
    stocks <- c("AAPL","MSFT","GOOG","GOOGL","AMZN","TSLA","FB","ADI","ASML","ADBE","NTES","NFLX","JD","CSCO","AVGO","COST","PEP","CMCSA","PYPL","INTC","QCOM","INTU","TXN","TMUS","HON","AMAT","SBUX","CHTR","ISRG","AMGN","MRNA","ADP","LRCX","MU","TEAM","BKNG","GILD","MDLZ","CSX","PDD","MRVL","WDAY","REGN","KLAC","NXPI","ADSK","MELI","LULU","ILMN","ZM")
    
    #Timestamp
    start = '2019-01-01'
    end = '2020-01-01'
    
    #Stocks data download (creates XTS - objects)
    for (i in stocks)
    {
      i <- getSymbols(i, src = "yahoo", from = start, to = end)
    }
    
    #Stocks data download (creates list of XTS - objects
    stocks_list <- list()
    for (i in stocks){
      stocks_list[[i]] <- getSymbols(i, src = "yahoo", from = start, to = end, auto.assign=FALSE, return.class="xts")
    }
    
    #Finding Marubozu Candlestick in one stock
    AMZN_marubozu<- CSPMarubozu(AMZN, n=20, ATRFactor=.8, maxuppershadowCL=.017, maxlowershadowCL=.017)
    
    #Finding Marubozu Candlestick in the whole list of Stocks
      
      #Try 1
    for (i in names(stocks_list)){
      names(stocks_list[i]) <- CSPMarubozu((names(stocks_list[i])), n=20, ATRFactor=.8, maxuppershadowCL=.017, maxlowershadowCL=.017)
    }
    
      #Try 2
    DoMaru <- function(name)
    {
      CSPMarubozu(name, n=20, ATRFactor=.8, maxuppershadowCL=.017, maxlowershadowCL=.017)
    }
    
    apply_Marubozu <- lapply(stocks_list, DoMaru(stocks_list$name))

这会下载股票,然后显示处理每只股票的三种不同的等效方式。我们使用 dim(...) 但这将被任何需要的处理所取代。请注意,如果 x 是具有 OHLC 以及调整收盘价和成交量的股票的 xts 对象,则 Op(x)、Hi(x)、Lo(x)、Cl(x)、Ad(x) 和 Vo(x)是开盘价、最高价、最低价、收盘价、调整收盘价和成交量的向量。

虽然下面的代码看起来更可取 getSymbols(stocks); L <- mget(stocks) 也可以将股票松散地放入您的工作区,然后将它们收集到列表 L 中。

library(quantmod)
stocks <- c("AAPL", "MSFT", "GOOG")
getSymbols(stocks, env = e <- new.env())

# 1. iterate over components of e
out1 <- eapply(e, function(x) { dim(x) })

L <- as.list(e)

# 2. iterate over names
out2 <- Map(function(nm) { x <- L[[nm]]; dim(x) }, names(L))
out2a <- Map(function(nm) { x <- e[[nm]]; dim(x) }, ls(e))

# 3. iterate over components of list L
out3 <- Map(function(x) { dim(x) }, L)

str(out1)
## List of 3
##  $ AAPL: int [1:2] 3764 6
##  $ GOOG: int [1:2] 3764 6
##  $ MSFT: int [1:2] 3764 6

identical(out1, out2)
## [1] TRUE

identical(out1, out2a)
## [1] TRUE

identical(out1, out3)
## [1] TRUE