Yfinance Python Tutorial (2022) - Analyzing Alpha
Yfinance Python Tutorial (2022) - Analyzing Alpha
Ran Aroussi is the man behind yfinance, a Python library that gives you easy access
to financial data available on Yahoo Finance. Since Yahoo decommissioned their AP on
May 15th,2017 (a move that left developers searching for an adequate alternative),
Ran's yfinance fit the bill. The software gained traction and has been downloaded
over 100k times with around 300k+ installs per month, according to PyPi!
Read on if you're interested in learning how to use the yfinance API to download
financial data for free.
https://analyzingalpha.com/yfinance-python 1/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
You can even follow along with The yfinance Python Tutorial Jupyter Notebook.
But before you get too excited, you need to ask yourself:
If you've decided to use Yahoo Finance as a data source, yfinance is the way to go.
It's the most popular way to access Yahoo Data, and the API is open-source and free
to use. There are other free and paid APIs to access Yahoo's data, but yfinance is the
best place to start, and here's why.
1. It's simple to use
2. It returns data as Pandas DataFrames
3. One-minute bar granularity
If you're using AI to perform sentiment analysis, you can't you yfinance. You'll have to
grab that data directly or use another API.
yfinance Classes
After loading yfinance, you'll have access to the following:
obj = yf.Ticker(‘goog’)
Now we can use the various methods to grab the data we want.
Most of the methods are self-explainatory, but here are a few that might trip new
users up:
1. Actions - Corporate actions such as dividends and splits
2. Analysis - EPS targets and revsisions
3. Info - Commonly queried data as a dictionary
4. Recommendations - Analyst buy, hold and sell ratings
Let's download historical market data using the history method. We can see that
history takes the following parameters:
def history(self, period="1mo", interval="1d",
auto_adjust=True, back_adjust=False,
"""
:Parameters:
period : str
https://analyzingalpha.com/yfinance-python 5/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
interval : str
start: str
Default is 1900-01-01
end: str
Default is now
prepost : bool
Default is False
auto_adjust: bool
back_adjust: bool
proxy: str
rounding: bool
tz: str
Default is None.
**kwargs: dict
debug: bool
"""
Don't feel overwhelmed. The defaults are great, and in most cases, we'll only be
changing the period or dates and the interval.
Let's grab the most recent thirty days daily data for Google. Remember, data is
returned as a pandas dataframe:
goog = yf.Ticker('goog')
https://analyzingalpha.com/yfinance-python 6/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
data = goog.history()
data.head()
data.head()
Please note that you're limited to the daily granularity when downloading multiple
tickers. If you want to get more granular, up to minute granularity, you'll need to use
the Ticker object above.
Now back to multiple ticker downloading...
We need to pass download a list of tickers instead of a single ticker and optionally let
the method know how to group the tickers -- by ticker or column (column is the
default). We can also optionally use threads to download the tickers faster.
def download(tickers, start=None, end=None, actions=False, threads=True,
:Parameters:
period : str
interval : str
start: str
Default is 1900-01-01
end: str
Default is now
group_by : str
prepost : bool
Default is False
auto_adjust: bool
actions: bool
proxy: str
https://analyzingalpha.com/yfinance-python 8/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
rounding: bool
show_errors: bool
"""
Let's download the most recent monthly data for Google and Facebook (META).
data = yf.download(['GOOG','META'], period='1mo')
data.head()
Let's group by the ticker, and provide start and end dates for the same tickers.
data = yf.download(['GOOG','META'], start='2021-12-10', end='2021-12-30', group_by=
data.head()
META GOOG
We can see that the Ticker object 'dhr' provides a lot of data to consume. Many of the
get_ methods give us exciting fundamental data.
Using one of my favorite industrial companies, Danaher, let's run through some
examples.
We can get Danaher's general and frequently-used information using the info
method, which returns a dictionary.
dhr = yf.Ticker('DHR')
info = dhr.info
info.keys()
https://analyzingalpha.com/yfinance-python 10/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
'Healthcare'
Let's grab Danaher's annual revenue and earnings using the earnings method .
dhr.earnings
Revenue Earnings
Year
And if the provided methods don't work, we can calculate financial ratios using the
financial statements.
dhr.get_financials()
https://analyzingalpha.com/yfinance-python 11/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
We can also concatenate all financial statements together to calculate the ratios more
easily.
pnl = dhr.financials
bs = dhr.balancesheet
cf = dhr.cashflow
fs = pd.concat([pnl,bs,cf])
print(fs)
https://analyzingalpha.com/yfinance-python 12/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
I also often find it helpful to transpose the data and have the time as the index and the
column as the data field.
fs.T
[4 rows x 68 columns]
tickers
Now let's turn this list into a list of ticker objects using list comprehension.
tickers = [yf.Ticker(ticker) for ticker in fang]
https://analyzingalpha.com/yfinance-python 13/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
Now let's concatenate all of the financial data together. We'll loop through each ticker,
aggregating the profit and loss, balance sheet, and cash flow statement. We'll then
add this data to a list.
Once we have a list of each company's aggregated financial statements, we'll
concatenate them, removing duplicate headings.
dfs = [] # list for each ticker's dataframe
pnl = ticker.financials
bs = ticker.balancesheet
cf = ticker.cashflow
data = fs.T
data = data.reset_index()
data['Ticker'] = ticker.ticker
dfs.append(data)
https://analyzingalpha.com/yfinance-python 14/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
Now that we have a list of dataframes, we need to iterate through concatenating them
and fixing the duplicate headers using pandas.io.parser .
We'll also reindex the dataframe to make it cleaner to use.
parser = pd.io.parsers.base_parser.ParserBase({'usecols': None})
for df in dfs:
df.columns = parser._maybe_dedup_names(df.columns)
df = pd.concat(dfs, ignore_index=True)
df = df.set_index(['Ticker','Date'])
Ticker Date
Congratulations! Now you have the ticker's financial information organized by ticker
and date. You can now use Pandas to pull out any data of interest.
chain for an expiry, or the entire chain if you don't specify a date.
aapl = yf.Ticker('aapl')
options = aapl.option_chain()
calls
https://analyzingalpha.com/yfinance-python 16/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
puts
https://analyzingalpha.com/yfinance-python 17/20
How to Get Institutional Holders Using yfinance
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
meta = yf.Ticker('meta')
fb.get_cashflow()
https://analyzingalpha.com/yfinance-python 18/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
Empty DataFrame
Index: []
Facebook and Meta are the same company, but they return different data. This is just
one of the many risks of using Yahoo Finance.
Ticker.Info Keys
Here's everything that ticker.info provides:
dict_keys(['zip', 'sector', 'fullTimeEmployees', 'longBusinessSummary', 'city', 'ph
https://analyzingalpha.com/yfinance-python 19/20
23/02/2022, 17:39 yfinance Python Tutorial (2022) - Analyzing Alpha
But if you're looking to do some high-level research and free what you need, yfinance
has got you covered.
https://analyzingalpha.com/yfinance-python 20/20