根据布林带筛选股票
Screen stocks based on Bollinger bands
我正在尝试根据布林带筛选列表中的几只股票。
假设这是列表: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))
}
我不确定如何进一步进行,但我想将列表中的股票过滤为 select 仅低于 50 天平均值的第二个标准差的股票:addBBands(n=50, sd=2)
我该怎么做?
将收盘价提取到单个 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)
我正在尝试根据布林带筛选列表中的几只股票。
假设这是列表: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))
}
我不确定如何进一步进行,但我想将列表中的股票过滤为 select 仅低于 50 天平均值的第二个标准差的股票:addBBands(n=50, sd=2)
我该怎么做?
将收盘价提取到单个 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)