Downloading Data for Your Trading Strategy from Yahoo! Finance Using Python

Yahoo!Finance is one of the most popular websites for investors. It offers various market data on stocks, bonds, currencies, and cryptocurrencies. It also offers market news, reports and analysis, options, and fundamental data, which sets it apart from some of its competitors.

yfinance is a Python library that allows users to download historical data from Yahoo Finance for free. It also includes fundamental data such as income statements, trading multiples, and dividends, among many others.

In this article, we are going to look at what yfinance is, how to install it, and how to get historical market and fundamental data using Python.

Related reading:

What is yfinance?

yfinance is a popular open source library developed by Ran Aroussi as a means to access financial data available on Yahoo!Finance.

Yahoo Finance used to have its own official API, but this was taken down on May 15, 2017, after widespread data misuse. Today there are a variety of unofficial APIs and libraries for accessing the same data, including, of course, yfinance.

The main drawback would be in the quality of the data, since it is not guaranteed that they are correct. However, it’s still a free API.

We have covered the aspect of bad data in our comprehensive backtesting guide.

Python-related resources

We have written many articles about Python, and you might find these interesting:

Installing yfinance

Installing the yfinance library is pretty simple, but be aware that Python and PIP have to be installed beforehand. Now all you need is to open the terminal of your computer and write the following prompt:

pip install yfinance

And that’s it! And just in case, remember that you need to import the library in the notebook that you will be working with. 

yfinance functions

The yfinance library has a ton of functions, but we can simplify into 3 modules:

yf.Ticker

yf.download

yf.pandas_datareader

The first one, yf.Tickers, is used for almost everything. We will show you later all the functions it includes.

yf.Download is obviously for downloading historical data. It returns a dataframe with the open, low, high, close, adjusted close, and volume on any ticker.

Finally, yf.pandas_datareader is for back compatibility with legacy code, which we will ignore since if you’re reading this, you are probably a new user of the library.

How to download historical prices using Yahoo Finance

Downloading historical data of a stock is easier than you think. We just need to create a variable and use the yf.download function.

How to download historical prices using Yahoo finance

The result of this simple line of code is all the historical open, high, low, close, ad