在R中触发一系列股票的触发器

时间:2013-08-19 19:04:50

标签: r

首先,如果这是一个基本问题我道歉,但是我在这里搜索并且无法找到我正在尝试的答案。我不是编程新手,但我是R的新手(我的编程有点生疏,因为我改变了职业生涯的重点)。

我想做的是一个相当简单的(着名的遗言):

  • 每天早上
  • 扫描整个股票市场(或只是S& P 500)
  • 告诉我任何特定指标x%的股票(例如,接近较低的布林带)

这就是我试图做概念验证的方法,以及作为开发我自己的指标的跳板的用途。我感谢任何和所有有用的评论,链接等。在此先感谢所有!

1 个答案:

答案 0 :(得分:4)

library(quantmod)

# a vector of stock tickers to look at
s <- c("AA", "AXP", "BA", "BAC", "CAT", "CSCO", "CVX", "DD", "DIS", 
"GE", "HD", "HPQ", "IBM", "INTC", "JNJ", "JPM", "KO", "MCD", 
"MMM", "MRK", "MSFT", "PFE", "PG", "T", "TRV", "UNH", "UTX", 
"VZ", "WMT", "XOM")

e <- new.env()  # an environment to hold our data
getSymbols(s, from=Sys.Date()-50, src="yahoo", env=e) # download stock prices

# create a parameter
pct <- 0.01 # look for close prices that are lower than 1% above lower bband.

# eapply loops over every object in the environment and applies a function to it.
# our function calculates the value of the lower BBand increased by "pct"
# Then it returns TRUE or FALSE depending on whether the stock price is below that.
# eapply returns a list, which we can `unlist` into a named vector
near.low.band <- unlist(eapply(e, function(x) {
  bband.dn <- as.numeric(last(BBands(HLC(x))$dn))
  as.numeric(last(Cl(x))) <  bband.dn * (1 + pct)
}))

# get the names where the value is TRUE
names(near.low.band)[near.low.band]
# [1] "XOM"  "JNJ"  "JPM"  "VZ"   "UTX"  "INTC" "MMM"  "MCD"  "CSCO" "PFE" 
#[11] "GE"   "T"    "BAC"  "CVX"  "MRK"  "TRV"  "KO"   "PG"   "WMT"  "DIS" 
#[21] "UNH"  "HD"   "BA"   "IBM" 

# And the ones that are not below our threshold?
names(near.low.band)[!near.low.band]
#[1] "DD"   "HPQ"  "AXP"  "AA"   "CAT"  "MSFT"