marino89
marino89

Reputation: 909

R quantmod::getFinancials

I'm using the quantmodpackage. 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 applyfunction. There are several difficulties :

To sum up, I'm a bit lost...

Upvotes: 3

Views: 2675

Answers (2)

agstudy
agstudy

Reputation: 121568

Anaother option is to laod your tickers in an new environnement.

tickers <-  new.env()
s <- c("AAPL","GOOG","IBM","GS","AMZN","GE")
lapply(s, getFinancials,env=tickers)
sapply(ls(envir=tickers),
       function(x) {x <- get(x) ## get the varible name
                    x$IS$A["Operating Income", ] / x$IS$A["Total Revenue",]})

              AAPL.f     AMZN.f       GE.f    GOOG.f      GS.f     IBM.f
2012-09-29 0.3529596 0.01106510 0.11811969 0.2543099 0.2689852 0.2095745
2011-09-24 0.3121507 0.01792957 0.13753327 0.3068724 0.1676678 0.1964439
2010-09-25 0.2818704 0.04110630 0.09415548 0.3540466 0.2804621 0.1974867
2009-09-26 0.2736278 0.04606471 0.06387029 0.3514585 0.3837401 0.1776439

EDIT

No need to use ls, get.... just the handy eapply (thanks @GSee) which applies FUN to the named values from an environment and returns the results as a list

eapply(tickers, function(x) 
              x$IS$A["Operating Income", ] / x$IS$A["Total Revenue",])

Upvotes: 4

GSee
GSee

Reputation: 49810

It's easier if you use auto.assign=FALSE

s <- c("AAPL","GOOG","IBM","GS","AMZN","GE")
fin <- lapply(s, getFinancials, auto.assign=FALSE)
names(fin) <- s
lapply(fin, function(x) x$IS$A["Operating Income", ] / x$IS$A["Total Revenue",])
#$AAPL
#2012-09-29 2011-09-24 2010-09-25 2009-09-26 
# 0.3529596  0.3121507  0.2818704  0.2736278 
#
#$GOOG
#2012-12-31 2011-12-31 2010-12-31 2009-12-31 
# 0.2543099  0.3068724  0.3540466  0.3514585 
#
#$IBM
#2012-12-31 2011-12-31 2010-12-31 2009-12-31 
# 0.2095745  0.1964439  0.1974867  0.1776439 
#
#$GS
#2012-12-31 2011-12-31 2010-12-31 2009-12-31 
#0.2689852  0.1676678  0.2804621  0.3837401 
#
#$AMZN
#2012-12-31 2011-12-31 2010-12-31 2009-12-31 
#0.01106510 0.01792957 0.04110630 0.04606471 
#
#$GE
#2012-12-31 2011-12-31 2010-12-31 2009-12-31 
#0.11811969 0.13753327 0.09415548 0.06387029 

Upvotes: 6

Related Questions