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"
我發佈了一個答案,但對於S.O來說這不是一個好問題。我們希望你先嚐試一下,當你遇到麻煩時,請來尋求幫助。在這裏,你只是要求我們爲你做一件事,但我們認爲合適,這有點寬泛。 – GSee
反饋非常感謝。不幸的是,對於quantmod和quantstrat,文檔是如此脫節(或缺乏),找到一個理智的起點(特別是對於一個R初學者)證明是非常困難的。我很感謝你的回答 - 它已經成爲我項目的啓動平臺(我已經修改它尋找上層樂隊,並尋找其他一些指標)。再次感謝。 –
如果你有一個時刻,請你解釋一下這個陳述:名字(near.low.band)[near.low.band]。我一直在消化它(我理解它給出的結果),但我不確定我是否明白爲什麼它會給出這些結果。謝謝。 –