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.
Related
I am currently writing a code to download timeseries (which will then be converted into csv-files) to conduct an event study upon.
The following code (part of the complete code) I wrote:
tickers = c("^AEX", "^ATX", "^BFX", "^FCHI", "^FTSE", "^GDAXI", "^IBEX", "^OMX","^OMXH25", "^OSEAX", "^SSMI", "FTSEMIB.MI")
Aggregate <- getSymbols(tickers,
from = "2014-01-01",
to = "2021-12-31")
na.omit(Aggregate,"iz",interp="linear")
Ticker <- Aggregate
Ticker
class(Ticker)
data1 <-as.data.frame(Ticker)
data1
class(data1)
data2 <- data1 # Duplicate data frame
data2 # Print new data frame
AEX <- ^AEX
write.zoo(AEX,"//Users/TEST/Library/CloudStorage/OneDrive-Personal/Event Study Basis\\AEX.csv",index.name="Date",sep=",")
As the tickers of the indices (^AEX, ^ATX etc.) all possess a "^", which Excel doesn't "eat" I want to make sure the dataframe I want to export to a .csv file does not possess this "^". For a different analysis, the code worked (different tickers) now I get an error every time I try to run it.
My questions:
which command will solve my problem? --> Converting ^AEX into AEX so Excel eats it :)
I have a problem with my R code. I would like to run about 100 regressions and perform this process with a loop. I have tried to program the loop myself using help from YouTube and the like, but I am getting nowhere. Therefore, I would like to ask you if you can help me.
Specifically, it's about the following:
I have a dataset of the 100 companies in the Nasdaq100 and I would like to regress the sales per share with the stock price performance on a quarterly basis. Another problem is that the data set contains these 100 companies and a subset with the respective ticker symbol has to be created for each additional company so that R can access it correctly for each regression.
Here is an excerpt from the code:
Nasdaq_100 = read_xlsx("Nasdaq_100_Sales_Data.xlsx")
#Correlation between quarterly close price and Sales of AMD
AMD <- subset (Nasdaq_100, Nasdaq_100$TickerSymbol=="AMD")
AMD_regression = lm(AMD$Sales ~ AMD$Stockprice_quarterly, data = Nasdaq_100)
summary(AMD_regression)
Can you help me to program this loop for regression analysis?
Thanks in advance for any help!
To convert this to a for loop, first get a list of the .xlsx files in your working directory:
require(data.table)
myfiles <- list.files(pattern="*.xlsx")
Then loop through each file, and saving with minor modifications to your existing code:
for (file in myfiles) {
Nasdaq_100 <- data.table::fread(file)
AMD <- subset (Nasdaq_100, Nasdaq_100$TickerSymbol=="AMD")
AMD_regression = lm(AMD$Sales ~ AMD$Stockprice_quarterly, data = Nasdaq_100)
summary(AMD_regression)
data.table::fwrite(AMD_regression, file=paste0("output_", file), quote = F, sep = "\t", row.names = F)
}
Copy-paste in r and Let me know if it works.
file <- choose.files()
lmset <- data.frame(x='x',y='y')
for(i in seq_len(100))
{
data <- read_excel(file,sheet=i)
lmset <- rbind(lmset,lm(AMD$Sales~AMD$Stockprice_quarterly,data=data)$coefficients)
}
Hi I am trying to download data of multiple stocks from yahoo finance using the quantmod package in R. My method is to create a function using the getSymbols function, and use lapply to apply this to a vector of ticker symbols. Below is my code
get_data <- function(x){getSymbols(x,
from = "2017-01-01",
to = "2021-03-15",
auto.assign = FALSE)}
tickers <- c("AAPL","GOOG","FB","TSLA")
mydata <- lapply(tickers,get_data)
running the last step does not give me the data, just a list with all the tickers stored as characters.
Would appreciate if anyone could tell me where my code is going wrong. Cheers
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 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.