我使用以下代码来识别过去6个月经历过增长的股票。
library(quantmod)
getSymbols("AMZN")
monthly_stock<-to.monthly(AMZN)
adx <- ADX(HLC(monthly_stock), n = 14, maType = "EMA", wilder = TRUE)[, c("DIp", "DIn", "ADX")]
adx$DIp-adx$DIn[(nrow(adx)-5):nrow(adx),]>10
输出
Jul 2015 TRUE
Aug 2015 TRUE
Sep 2015 TRUE
Oct 2015 TRUE
Nov 2015 TRUE
Dec 2015 TRUE
但我这样做&#34;手动&#34;对于每个股票。我想自动化这个过程,以便我一次加载多个股票
stocklist<-c("AMZN","GOOG","AAPL","FB","TSLA")
getSymbols(stocklist)
在这些下载的股票中,我想过滤掉那些满足这些标准的那些(&#34; TRUE&#34;过去6个月),就像我上面所做的那样。有什么建议我怎么做?
答案 0 :(得分:1)
您需要的是diff
功能。
library(quantmod)
getSymbols("AMZN")
monthly_stock<-to.monthly(AMZN)
adx <- ADX(HLC(monthly_stock), n = 14, maType = "EMA", wilder = TRUE)[, c("DIp", "DIn", "ADX")]
adx$DIp-adx$DIn[(nrow(adx)-5):nrow(adx),]>10
adx <- tail(adx, 7)
adx.res <- sapply(1:ncol(adx), function(x){
y <- diff(as.vector(adx[, x]))
if (all(y>0)) {
return(x)
}
})
names(adx)[unlist(adx.res)]
# ADX
答案 1 :(得分:1)
我会按以下几行布置代码:
stock.list = c("AMZN","GOOG","AAPL","FB")
res = list()
for(ss in stock.list) {
stock.data = getSymbols(ss, from="1900-01-01", auto.assign=F)
monthly.data = to.monthly(stock.data)
adx = ADX(HLC(monthly.data),n=14,maType="EMA",wilder=TRUE)[,c("DIp","DIn","ADX")]
monthly.adx = adx$DIp-adx$DIn[(nrow(adx)-5):nrow(adx),]>10
if(all(as.logical(monthly.adx[,1]))) {
res[[ss]] = monthly.adx
}
}
# res is a list.
# names(res) gives you the stock symbols for the interesting stocks
# res[["AMZN"]] contains the data - the adx for the last six months in this case