I want to be able to generate tables that show select financial statement line items and financial statement ratios (e.g., revene, OpEx, EBITDA, enterprise value). I'm trying to get getFin to accept a list of tickers.
library(quantmod)
library(xts)
ticker <- c("MS", "GS", "CS")
ticker1 <- getSymbols(ticker)
getFin(ticker1) #env.class
income<-viewFin(ticker1, "IS","A") # annual income statement
balancesheet<-viewFin(ticker1,"BS","A") # annual balance sheet
However, getFin is only recognizing the MS ticker as MS.f, so GS.f and CS.f do not get added to the environment. This also prevents income and balancesheet to be added to the environment.
Let me know how this can be fix. Thanks for the help.
Load the data into an environment you create, rather than the global environment. Then use eapply to loop over all objects in the environment and call viewFin on each.
e <- new.env()
getFin(paste0(ticker,collapse=";"), env=e)
income <- eapply(e, viewFin, type="IS", period="A")
balancesheet <- eapply(e, viewFin, type="BS", period="A")
income and balancesheet will be lists of the relevant statements for each of the objects specified by ticker.
Related
I am currently trying to create a bid ask model on R for 12 companies. I have already figured out how to get stock prices for 12 companies and how to apply the equation to it.
Now I need to create a function which will give me the final spread for individual companies from the list of companies i have.
For eg: I have stock prices for SBUX, AAPL and GOOG. When I run my function, it shows the answer for all the 3 companies but I want to create a function which will allow me to specify say SBUX for example and it shows me the spread just for SBUX.
This is the code I have used for all the companies
library(quantmod)
library(dplyr)
#To get the daily prices of the stocks
sdate <- "2017-11-29"
tickers <-
c("SBUX","C","AAPL","AMZN","CAT","DAL","MCD","GS","K","VZ","PEP","CVX")
Stock_Prices = NULL
for(ticker in tickers)
Stock_Prices <- cbind(Stock_Prices, getSymbols(ticker, src =
"yahoo",from=sdate,auto.assign=F)[,6])
colnames(Stock_Prices) <- tickers
p<-diff(Stock_Prices[1:253])
p[is.na(p)] <- 0
n_days=252
cov1<-cov(p[1:n_days],p[2:(n_days+1)])
2*sqrt(cov1) `
So can someone help me implement a function where I can find the diff, cov and the 2 sqrt for individual stocks instead of for all at once?
I am using the Quandl API in R to download the historical stock market data listed in NSE India.
The below code gives me the historical data for ICICI and PNB but needs manual entries for each stock to fetch the data. How do we download the historical data for all the stocks listed in NSE without writing these manual statements for each stock.
library(Quandl)
Quandl.api_key("API_Key")
## Download the data Set
ICICI = Quandl("NSE/ICICIBANK",collapse="daily",start_date="2018-01-01",type="raw")
PNB= Quandl("NSE/PNB",collapse="daily",start_date="2018-01-01",type="raw")
## Add another ("Stock") coloumn in Datasets using cbind command
ICICI<-cbind(ICICI,Stock="")
PNB<-cbind(PNB,Stock="")
## Paste the stock name in stock column
ICICI$Stock<-paste(ICICI$Stock,"ICICI",sep="")
PNB$Stock<-paste(PNB$Stock,"PNB",sep="")
## Consolidate under one dataset
Master_Data<-rbind(ICICI,PNB)
I do have a list of all the stocks name in an excel file as follows.
NSE/20MICRONS
NSE/3IINFOTECH
NSE/3MINDIA
NSE/A2ZMES
NSE/AANJANEYA
NSE/AARTIDRUGS
NSE/AARTIIND
NSE/AARVEEDEN
NSE/ABAN
NSE/ABB
NSE/ABBOTINDIA
NSE/ABCIL
NSE/ABGSHIP
Any help would be really appreciated.
Regards,
Akash
This worked for me, I hope it will be running for you too.
I have tested it.
Make a list (lyst in the code) items of all the companies for you want the data, like below. Then use lapply to save everything in a new list, like lyst_dwnld in the code.
If you want to avoid manually typing all that name as list, then you can save your excel sheet of names as a data frame and then use the same concept as below.
Code:
lyst <- list(icici = "NSE/ICICIBANK", pnb = "NSE/PNB")
lyst_dwnld <- lapply(names(lyst),
function(x)Quandl(lyst[[x]],
collapse="daily",
start_date="2018-01-01",type="raw"))
Output:
YOu can check if the data is downloaded or not, by quickly seeing the head.
> lapply(lyst_dwnld, head,2)
[[1]]
Date Open High Low Last Close Total Trade Quantity Turnover (Lacs)
1 2018-05-25 298.4 300.95 294.6 296.20 295.65 13541580 40235.19
2 2018-05-24 293.7 299.00 291.2 298.15 297.70 11489424 33952.28
[[2]]
Date Open High Low Last Close Total Trade Quantity Turnover (Lacs)
1 2018-05-25 81.95 84.55 81.30 83.60 83.35 19102160 15875.32
2 2018-05-24 80.70 82.50 80.05 82.35 82.10 19933989 16229.67
EDITED:
In you are unable to make a list using a dataframe, here is what you can do.
1) Read your data in excel to R dataframe using (readxl).
2) I have read a sample data and called it df.
df <- readxl::read_excel('path_where_excel_resides_with_name_of_excel_and_extension')
3) Name the column, something meaningful. I just used "name" here for this single column excel.
names(df) <- "name"
4) Use strsplit, to split the column(keep the original column), fetech only the second name out of it.
df$co_name <- lapply(strsplit(df$name, "/"),`[[`,2)
Now you can create the lyst object which is used in earlier code.
lyst <- as.list(df$name)
names(lyst) <- df$co_name
Please let me know in case this doesn't work out for you or in case of any issues. Thanks
The data is available until 2018 only via Quandl.
You can use BatchGetSymbols library in R to download further data. There is one issue that I noticed while downloading from Yahoo finance was that sometimes the data was missing for a few months in a year. Advised to use with caution before implementing any analysis and check the consistency of the data.
The following code is for reference:
if (!require(BatchGetSymbols)) install.packages('BatchGetSymbols')
#Package to download yahoo finance stock prices from internet directly
library(BatchGetSymbols)
first.date <- Sys.Date() - (365*5) #5 years back
last.date <- Sys.Date()
freq.data <- 'monthly' #change it as you like. example:'daily'
tickers <- c('RELIANCE.NS','TCS.NS')
# Reliance, Tcs
l.out <- BatchGetSymbols(tickers = tickers,
first.date = first.date,
last.date = last.date,
freq.data = freq.data,
cache.folder = file.path(your_directory_path,"stock_prices"))
str(l.out)
# To check download status of all stocks
l.out$df.control
# Actual Stock prices downloaded
head(l.out$df.tickers)
Alternate Method
I found this link during my web browsing and I am yet to implement it after understanding. Hopefully, this might help you further.
https://www.r-bloggers.com/extracting-eod-data-from-nse/
I'm trying to collect mutual fund performance data via open and close prices from quantmod. I have scraped a list of 5000 some funds and am trying to loop through and get one open and close price for each fund. I'm having difficulty calling the xts object yielded by getSymbols() as it is called invisibly into the environment. Since the object is stored as its ticker name, I tried calling it by its ticker name.
Code so far:
## loop thru list and use quantmod to calculate performance from 1/2/14 to 12/31/14
for(i in 1:4881){
ticker <- tickernames[i]
getSymbols(ticker)
Open <- ticker["2014-01-02",1]
Close <- ticker["2014-12-31",4]
performance2014[i] = (Open - Close)/Open
}
Is there a way I can call the object using ls()?
The key is to set the auto.assign argument to FALSE in getSymbols. This way you deactivate getSymbols automatic assignment to the global environment.
Here's an example that should guide you through step by step:
require(quantmod)
#Vector of symbols to fetch prices for
symbols <- c('MSFT','SBUX','GOOGL')
#Initialize a list to store the fetched prices
myList <- list()
#Loop through symbols, fetch prices, and store in myList
myList <-lapply(symbols, function(x) {getSymbols(x,auto.assign=FALSE)} )
#Housekeeping
names(myList) <- symbols
#Access MSFT prices
myList[['MSFT']]
#Access SBUX prices
myList[['SBUX']]
#Access GOOGL prices
myList[['GOOGL']]
Hope this answered your question.
I'm currently downloading stock data using GetSymbols from the Quantmod package and calculating the daily stock returns, and then combining the data into a dataframe. I would like to do this for a very large set of stock symbols. See example below. In stead of doing this manually I would like to use a For Loop if possible or maybe use one of the apply functions, however I can not find the solution.
This is what I currently do:
Symbols<-c ("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE","T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
length(Symbols)
#daily returns for selected stocks & SP500 Index
SP500<-as.xts(dailyReturn(na.omit(getSymbols("^GSPC",from=StartDate,auto.assign=FALSE))))
S1<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[1],from=StartDate,auto.assign=FALSE))))
S2<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[2],from=StartDate,auto.assign=FALSE))))
S3<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[3],from=StartDate,auto.assign=FALSE))))
S4<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[4],from=StartDate,auto.assign=FALSE))))
S5<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[5],from=StartDate,auto.assign=FALSE))))
S6<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[6],from=StartDate,auto.assign=FALSE))))
S7<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[7],from=StartDate,auto.assign=FALSE))))
S8<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[8],from=StartDate,auto.assign=FALSE))))
S9<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[9],from=StartDate,auto.assign=FALSE))))
S10<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[10],from=StartDate,auto.assign=FALSE))))
....
S20<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[20],from=StartDate,auto.assign=FALSE))))
SPportD<-cbind(SP500,S1,S2,S3,S4,S5,S6,S7,S8,S9,S10,S11,S12,S13,S14,S15,S16,S17,S18,S19,S20)
names(SPportD)[1:(length(Symbols)+1)]<-c("SP500",Symbols)
SPportD.df<-data.frame(index(SPportD),coredata(SPportD),stringsAsFactors=FALSE)
names(SPportD.df)[1:(length(Symbols)+2)]<-c(class(StartDate),"SP500",Symbols)
Any suggestions?
Thanks!
dailyReturn uses close prices, so I would recommend you either use a different function (e.g. TTR::ROC on the Adjusted column), or adjust the close prices for dividends/splits (using adjustOHLC) before calling dailyReturn.
library(quantmod)
Symbols <- c("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE",
"T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
# create environment to load data into
Data <- new.env()
getSymbols(c("^GSPC",Symbols), from="2007-01-01", env=Data)
# calculate returns, merge, and create data.frame (eapply loops over all
# objects in an environment, applies a function, and returns a list)
Returns <- eapply(Data, function(s) ROC(Ad(s), type="discrete"))
ReturnsDF <- as.data.frame(do.call(merge, Returns))
# adjust column names are re-order columns
colnames(ReturnsDF) <- gsub(".Adjusted","",colnames(ReturnsDF))
ReturnsDF <- ReturnsDF[,c("GSPC",Symbols)]
lapply is your friend:
Stocks = lapply(Symbols, function(sym) {
dailyReturn(na.omit(getSymbols(sym, from=StartDate, auto.assign=FALSE)))
})
Then to merge:
do.call(merge, Stocks)
Similar application for the other assignments
Packages are quantmod for data download and PerformanceAnalytics for analysis/plotting.
care must be taken with time series date alignment
Code
require(quantmod)
require(PerformanceAnalytics)
Symbols<-c ("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE","T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
length(Symbols)
#Set start date
start_date=as.Date("2014-01-01")
#Create New environment to contain stock price data
dataEnv<-new.env()
#download data
getSymbols(Symbols,env=dataEnv,from=start_date)
#You have 19 symbols, the time series data for all the symbols might not be aligned
#Load Systematic investor toolbox for helpful functions
setInternet2(TRUE)
con = gzcon(url('https://github.com/systematicinvestor/SIT/raw/master/sit.gz', 'rb'))
source(con)
close(con)
#helper function for extracting Closing price of getsymbols output and for date alignment
bt.prep(dataEnv,align='remove.na')
#Now all your time series are correctly aligned
#prices data
stock_prices = dataEnv$prices
head(stock_prices[,1:3])
# head(stock_prices[,1:3])
# BAC CVX DIS
#2014-01-02 16.10 124.14 76.27
#2014-01-03 16.41 124.35 76.11
#2014-01-06 16.66 124.02 75.82
#2014-01-07 16.50 125.07 76.34
#2014-01-08 16.58 123.29 75.22
#2014-01-09 16.83 123.29 74.90
#calculate returns
stock_returns = Return.calculate(stock_prices, method = c("discrete"))
head(stock_returns[,1:3])
# head(stock_returns[,1:3])
# BAC CVX DIS
#2014-01-02 NA NA NA
#2014-01-03 0.019254658 0.001691638 -0.002097810
#2014-01-06 0.015234613 -0.002653800 -0.003810275
#2014-01-07 -0.009603842 0.008466376 0.006858349
#2014-01-08 0.004848485 -0.014232030 -0.014671208
#2014-01-09 0.015078408 0.000000000 -0.004254188
#Plot Performance for first three stocks
charts.PerformanceSummary(stock_returns[,1:3],main='Stock Absolute Performance',legend.loc="bottomright")
Performance Chart:
I would like to cycle through a list of tickers, get their financials and export them to CSV files in a folder on my desktop. However, I have been having trouble with an error in R related to viewFinancials() in the Quantmod package. The code and error are shown below.
And so, my question is how to assign a variable as an object of class financial so that my loop runs properly? Or if anyone has another alternative, I would be excited to hear it!
Here is the error message:
Error in viewFinancials(co.f, "BS", "Q") :
‘x’ must be of type ‘financials’
Here is the code I am working on:
tickers <- c('AAPL','ORCL','MSFT')
for(i in 1:length(tickers)){
co <- tickers[1]
#co.f <- paste(co,".f",sep='') #First attempt, was worth a try
co.f <- getFin(co, auto.assign=T) # automatically assigns data to "co.f" object
BS.q<-viewFinancials(co.f,'BS',"Q") # quarterly balance sheet
IS.q<-viewFinancials(co.f,"IS","Q") # quarterly income statement
CF.q<-viewFinancials(co.f,"CF","Q") # quarterly cash flow statement
BS<-viewFinancials(co.f,"BS","A") # annual balance sheet
IS<-viewFinancials(co.f,"IS","A") # annual income statement
CF<-viewFinancials(co.f,"CF","A") # annual cash flow statement
d<-Sys.Date()
combinedA <- rbind(BS,IS,CF)
combinedQ <- rbind(BS.q,IS.q,CF.q)
BSAfile <- paste('/Users/dedwards/Desktop/RFinancials/',d,' ',co,'_BS_A.csv',sep='')
BSQfile <- paste('/Users/dedwards/Desktop/RFinancials/',d,' ',co,'_BS_Q.csv',sep='')
write.csv(combinedA, file = BSAfile, row.names=TRUE)
write.csv(combinedQ, file = BSQfile, row.names=TRUE)
}
co.f contains the name of the object in the workspace that actually contains the financials object. To actually use that object you need to call get(co.f)
obj <- get(co.f)
# now you can use obj where you were previously trying to use co.f
Alternatively it looks like
co.f <- getFin(co, auto.assign = FALSE)
also works and is probably more straight forward.
Rather than writing a loop, you might consider the tidyquant package which enables multiple stocks to be passed to the tq_get() function. Setting tq_get(get = "financials") will allow you to download the financials for multiple stocks. Here's and example:
library(tidyquant)
c("FB", "AMZN", "NFLX", "GOOG") %>%
tq_get(get = "financials")
This returns a nested data frame of all the financial statement data (income statement, balance sheet, cashflow) in both annual and quarterly periods. You can use the unnest() function to peel away the layers.
If you need to save the data, you can unnest then write to a csv using the write_csv() function.