How to Extract Financial Data for Many Tickers (Stocks) from Yahoo Finance in Python
Recently, one of my friends wanted to extract data for multiple stocks from yahoo finance using python. What he wanted to extract were financial information such as Market Capitalization as of now, Fifty Two Weeks’ Low Price, Fifty Two Weeks’ High Price and Forward PE ratio in particular.
When we discussed, I suggested him the following high level solution, using which I asked him to develop his own dashboard kind of solution.
Let me explain how we can retrieve the above and many more financial information of almost any stock listed any of the exchanges that Yahoo Finance has the data of.
We first need to install the package ‘yahooquery’ using pip, as follows:
pip install yahooquery
This package offers many good functions that makes our life easy.
Then we will import ‘Ticker’ function from it and also import pandas package as follows:
from yahooquery import Ticker
import pandas as pd
Let’s create a list of tickers for which data has to be retrieved. In my case, below are some of the tickers from a very huge list, and all of these are listed stocks from Bombay Stock Exchange India.
tickers = [“OMKAR.BO”, “KCLINFRA.BO”, “MERMETL.BO”, “PRIMIND.BO”, “VISIONCO.BO”, “PANAFIC.BO”, “KARANWO.BO”, “SOURCEIND.BO”, “WELCURE.BO”]
Next, we run the query for each of the tickers in the list and fetch data as a long dictionary of the data, which can be transposed into a pandas dataframe as follows:
t = Ticker(tickers)
data = t.quotes
df = pd.DataFrame(data).T
Lastly, we can print the data for specific variable(s), say, Market Capitalization, as shown in the below code:
df[‘marketCap’]
We can even check which all variables are there in the dataframe:
df.columns
That’s all, folks!
Hope this will help all those people who are planning to build some dashboards (or even databases) to do some other types of analysis of financial data from specific stocks.