问题
What I want to do is fairly easy but I haven't been able to figure it out. I thought I could do something similar to that outlined here
I have a character vector of tickers that are xts OHLC objects returned by getSymbols
. I want to loop through each ticker in symbols and pass the symbol to adjustOHLC
to adjust for splits:
symbols = c("FCX", "SPY")
for(symbol in symbols){
return(adjustOHLC(symbol,adjust =c("split"), use.Adjusted=FALSE))
}
It seems adjustOHLC
does not grab the value of the variable 'symbol':
debug: div <- getDividends(symbol.name)
Browse[2]> symbol.name
[1] "symbol"
Browse[2]>
Error in download.file(paste(yahoo.URL, Symbol.name, "&a=", from.m, "&b=", :
cannot open URL 'http://ichart.finance.yahoo.com/table.csv?s=symbol&a=0&b=01&c=1970&d=3&e=14&f=2012&g=v&ignore=.csv'
In addition: Warning message:
In download.file(paste(yahoo.URL, Symbol.name, "&a=", from.m, "&b=", :
cannot open: HTTP status was '404 Not Found'
If I use get(symbols)
I get the same result (similar approach was used in the link I show at the top of this post):
for(symbol in symbols){
return(adjustOHLC(get(symbol),adjust =c("split"), use.Adjusted=FALSE))
}
debug: div <- getDividends(symbol.name)
Browse[2]> symbol.name
[1] "get(symbol)"
Browse[2]>
Error in download.file(paste(yahoo.URL, Symbol.name, "&a=", from.m, "&b=", :
cannot open URL 'http://ichart.finance.yahoo.com/table.csv?s=get(symbol)&a=0&b=01&c=1970&d=3&e=14&f=2012&g=v&ignore=.csv'
In addition: Warning message:
In download.file(paste(yahoo.URL, Symbol.name, "&a=", from.m, "&b=", :
cannot open: HTTP status was '404 Not Found'
I thought I could also make use of lapply
to make this faster but think I'm stuck with the above issue first.
lapply(symbols, function(x) adjustOHLC(x, adjust=c("split"), use.Adjusted=FALSE) )
Seems easy enough - I apologize if this is so trivial. Appreciate the help.
回答1:
The x
argument of adjustOHLC
should be an xts object. So, you need to use get
to get it. But, if the yahoo ticker symbols is different than the name of the xts object (get(symbol)
in this case), then you need to use the symbol.name
argument. Also, you'll need to assign the values inside your for loop because adjustOHLC does not "auto.assign" like getSymbols
does.
symbols = c("FCX", "SPY")
getSymbols(symbols, src='yahoo')
for(symbol in symbols){
assign(symbol,adjustOHLC(get(symbol, pos=.GlobalEnv), symbol.name=symbol,
adjust=c("split"), use.Adjusted=FALSE))
}
Since you mentioned using lapply, here's how you could use it
adjusted.list <- lapply(symbols, function(x) {
adjustOHLC(get(x, pos=.GlobalEnv), symbol.name=x, adjust=c("split"),
use.Adjusted=FALSE)
})
names(adjusted.list) <- symbols
来源:https://stackoverflow.com/questions/10156552/adjustohlc-need-solution-to-loop-through-character-vector-of-tickers