R quantmod::getFinancials [英] R quantmod::getFinancials
问题描述
我正在使用 quantmod
包.我有一个像这样的股票代码向量:
I'm using the quantmod
package. I've got a vector of tickers like this :
c("AAPL","GOOG","IBM","GS","AMZN","GE")
我想创建一个函数来计算股票的 EBIT 利润率(= 营业收入/总收入).因此,对于给定的股票,我使用以下仅适用于 GE 的代码(前提是在股票代码的末尾添加了.f"):
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")
我想概括这个函数以便使用 apply
函数.有几个困难:
I would like to generalize this function in order to use then the apply
function. There are several difficulties :
- 将
quantmod::getFinancial
函数应用于股票代码时,股票的财务报表保存在默认环境中.然后必须使用viewFinancial
来获取和打印财务报表.我需要一种方法可以直接在函数中访问财务报表 - 函数的参数函数是一个类似GE.f"的字符串,但直接输入代码(GE")会更方便.我尝试使用
paste0
和gsub
来获取像GE.f"这样的字符串它不起作用,因为GE.f"不属于financials
类.
- 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.
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
编辑
无需使用 ls
、get
.... 只需方便的 eapply
(感谢 @GSee)将 FUN 应用于命名来自环境的值并将结果作为列表返回
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",])
这篇关于R quantmod::getFinancials的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!