I'm using the quantmod
package. I've got a vector of tickers like this :
c("AAPL","GOOG","IBM","GS","AMZN","GE")
and I want to create a function to calculate the EBIT margin of a stock (= operating income / total revenue). So for a given stock, I use the following piece of code which only works for GE (provided a ".f" is added a the end of the ticker) :
require(quantmod)
getFinancials("GE",period="A")
ebit.margin <- function(stock.ticker.f){
return(stock.ticker$IS$A["Operating Income",]/stock.ticker$IS$A["Total Revenue",])
}
ebit.margin("GE")
I would like to generalize this function in order to use then the apply
function. There are several difficulties :
- when applying the
quantmod::getFinancial
function to a ticker, the financial statements of the stocks are saved in the default environment. TheviewFinancial
has then to be used to get and print the financial statements. I need a way to get access to the financial statements directly into the function - The function's argument function is a string like "GE.f" but it would more convenient to enter directly the ticker ("GE"). I've tried to use the
paste0
andgsub
to get a string like "GE.f" it doesn't work because "GE.f" doesn't belong to thefinancials
class.
To sum up, I'm a bit lost...
Anaother option is to laod your tickers in an new environnement.
EDIT
No need to use
ls
,get
.... just the handyeapply
(thanks @GSee) which applies FUN to the named values from an environment and returns the results as a listIt's easier if you use
auto.assign=FALSE