我试图根据布林带来筛选一些列表中的几只股票。
我们说这是列表:c("AMZN","GOOG","TSLA","AAPL")
这就是我尝试启动代码的方式:
stock.list = c("AMZN","GOOG","TSLA","AAPL")
res = list()
for(ss in stock.list) {
stock.data = na.omit(getSymbols(ss, from="1900-01-01", auto.assign=F))
}
我不确定如何继续进行,但我想过滤列表中的股票,只选择那些低于第二个标准差50天平均值的股票:addBBands(n=50, sd=2)
我该怎么做?
答案 0 :(得分:1)
将收盘价提取到单个xts数据框,并使用zoo包中的rollapply计算波段。顺风顺水。
library(quantmod)
stock.list = c("AMZN","GOOG","TSLA","AAPL")
res = list()
# Modifying your loop to store closing prices in a separate data frame
df = xts()
for(ss in stock.list) {
res[[ss]] <-na.omit(getSymbols(ss, from="1900-01-01", auto.assign=F))
names(res[[ss]]) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")
df <- cbind(df, res[[ss]][, "Close"])
}
names(df) <- stock.list
# Calculate standard deviation and moving average
sigma <- rollapply(df,
width = 50,
FUN = sd,
by.column = TRUE,
align = "right",
fill = NA)
mu <- rollapply(df,
width = 50,
FUN = mean,
by.column = TRUE,
align = "right",
fill = NA)
# Calculate bollinger bands
upperBand <- mu + 1.96 * sigma
lowerBand <- mu - 1.96 * sigma
# Detect signals
breachedUpper <- df > upperBand
breachedLower <- df < lowerBand
# AAPL has breached its upper band
tail(breachedUpper)