muffin1974 muffin1974 - 28 days ago 11
R Question

Getting industry from Yahoo.Finance for list of stock ticker

How can I (preferably using R) get the industry classification for a list of stock tickers from Yahoo.Finance, Google Finance or anything else.
To illustrate, I have a list of tickers, such as

ticker_industy <- data.frame(ticker=ticker_list,industry=rep(NA,length(ticker_list)
head(ticker_industry)
ticker industry
1 BDX NA
2 BLL NA
3 CB NA
4 CELG NA
5 CHK NA
6 CI NA


Preferably, R fetches the corresponding industry for each ticker.

Answer

This function should do the work for you...

industry=function(ticker)
{
  url=paste("https://in.finance.yahoo.com/q/in?s=",ticker,sep=',')
  mydata=as.data.frame(readLines(url))
  names(mydata)="text"
  ind=str_match(as.character(mydata$text[117]),'(?:<b>Industry: ?)(.*?)(?:<)')[,2]
  ind=str_replace_all(ind,'&amp;','&')
  return(ind)
}