首先,如果这是一个基本问题,我深表歉意,但是我在这里搜索并找不到我正在尝试的答案。我对编程并不陌生,但我对 R 很陌生(而且我的编程有点生疏,因为我已经改变了职业重点)。
我想做的是一个相当简单的(著名的遗言):
- 每天早上
- 扫描整个股票领域(或仅扫描标准普尔 500 指数)
- 显示任何在给定指标 x% 范围内的股票(例如,接近较低的布林带)
这就是我尝试进行概念验证的方式,并将其用作开发自己的指标的跳板。我感谢任何和所有有用的评论、链接等。在此先感谢大家!
首先,如果这是一个基本问题,我深表歉意,但是我在这里搜索并找不到我正在尝试的答案。我对编程并不陌生,但我对 R 很陌生(而且我的编程有点生疏,因为我已经改变了职业重点)。
我想做的是一个相当简单的(著名的遗言):
这就是我尝试进行概念验证的方式,并将其用作开发自己的指标的跳板。我感谢任何和所有有用的评论、链接等。在此先感谢大家!
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"