Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (2024)

In this yfinance Python tutorial, I show how to use yfinance to download stock prices and other financial data for free. Ran Aroussi developed the yfinance Python module, which uses Yahoo Finance APIs. I cover many examples and show you step-by-step how to master yfinance.

Related content: How to Calculate Relative Strength for Stocks in Python

Pros and Cons of yfinance

Cons

The yfinance Python module is for research and educational purposes. Thus, you cannot use any of the data for commercial purposes (personal use only). Also, Yahoo Finance may contain errors, which could be a big concern.

Moreover, volunteer community and Ran are the only ones supporting yfinance. Therefore, things can stop working without any prior notice. Yahoo is notorious for changing its APIs in the past. For instance, as I will mention later, certain functions do not work as of version 0.2.31.

Thus, if you are thinking of relying on yfinance for live trading, it is a very bad idea. If you become serious about trading in the future, consider paid data sources. Yes, they cost money, but it is much better than losing money.

Pros

The stock price and other financial data from yfinance is free. You can prototype, backtest and play around with it to your heart’s content before going live.

Surprisingly, data downloaded with yfinance Python is quite rich. For a beginner, it could be plenty for starters. Also, because so many people are using yfinance, it will likely be around for a while. Unless, of course, Yahoo Finance dismantles its APIs or start charging for data access.

How to Install yfinance Python

1. Install Python

To install yfinance, you need to have a distribution of Python installed on your computer. Python can be installed on virtually any operating system you can think of. Moreover, Python comes pre-installed on Linux operating systems. But, you may have to download and install Python yourself for other operating systems.

2. Install yfinance Python Module

yfinance has the following requirements:

  • Python>= 2.7, 3.4+
  • Pandas>= 1.3.0
  • Numpy>= 1.16.5
  • requests>= 2.31
  • multitasking >= 0.0.7
  • lxml>= 4.9.1
  • appdirs>= 1.4.4
  • pytz>=2022.5
  • frozendict>= 2.3.4
  • peewee>= 3.16.2
  • beautifulsoup4>= 4.11.1
  • html5lib>= 1.1

Do not worry about them for now. Proceed with yfinance installation. Next, open your terminal (Linux, MacOS) or command prompt (Windows) and execute the following:

pip install yfinance

If you are installing yfinance from the Anaconda environment, use this command instead:

conda install -c ranaroussi yfinance

If any of the required packages are missing, yfinance will complain and stop the installation. You can always install the missing package and try installing yfinance again. For instance, if I am missing pandas, I use this command:

pip install pandas

3. Update yfinance

In rare instances, your installed yfinance is not updated and you are stuck with an old version. First, check the most current version at GitHub. Then, execute the following command in the Python environment:

import yfinance as yf print(yf.__version__)

Further, if the version you get is old, run the following command in your terminal (command prompt):

pip install yfinance --upgrade --no-cache-dir

How to Use Yfinance Python Turorial

Every module in Python has its own help page. In case you are lost, you can always type the following in Python to get help on yfinance:

import yfinance as yf help(yf)

yfinance consists of the following 2 classes and a function you will be using for the most part:

  • Ticker (class)
  • Tickers (class)
  • download (standalone function)

If you are not familiar with Python classes or functions, think of it this way. Python classes are templates for objects that can contain their own functions. Once you declare a class with yfinance, there are many things you can do with it. For instance, these include downloading prices, financial statements, ownership and more.

On the other hand, functions are like one-time operations. Once you execute them and get results, you have to call them again and again. In essence, classes let you work with functions in a more convenient way for a particular stock or stocks.

1. How to Download Stock Data with Yfinance?

First, import yfinance module and anything else as needed. Then, initiate an instance of a Ticker class with the desired stock ticker.

# Import modulesimport yfinance as yffrom datetime import datetime, date, timedeltanvda = yf.Ticker("NVDA") # initiate instance of Ticker class for Nvidia stock

The Ticker class lets you download stock prices and other financial data for one stock only. In fact, it is the only way to download financial statements, option chains and other financial data.

1.1. Stock Prices Download

After initiating a Ticker class, specify your start and end dates for price history. You can specify them as “YYYY-MM-DD” strings or the datetime format. Then, we can call the history function to download stock prices for one stock.

end_date = datetime(date.today().year,date.today().month,date.today().day) # today's datestart_date = end_date - timedelta(365) # date a year back from nowstock_data = nvda.history(start=start_date,end=end_date) # get stock prices, dividends, splitsprint(stock_data)

The price data results are in the form of pandas DataFrame:

Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (1)

In general, if you do not know arguments for any yfinance function, you can always find them at GitHub. For instance, the history function takes many more arguments, which can be viewed here on GitHub. Here are the few most important ones:

  • period: period for price history (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max).
  • interval: the size of a bar. Valid values are: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo and 3mo.
  • start: start date. Can be a string formatted as “YYYY-MM-DD” or datetime type.
  • end: end date. Format: the same as start.
  • actions: include or not dividends and stock splits. The default is True.
  • prepost: include or not data outside of regular trading hours. The default is False.
  • auto_adjust: adjust or not prices for splits and dividend. The default is True.

Important note on auto_adjust argument. The history function sets it to True by default. This means that all prices will be adjusted for dividends and splits. On top of that, you will not get Adj Close prices. Instead, your Close prices will be replaced with Adj Close prices. Let me show what I mean by all this. For instance, let’s execute a similar command and set auto_adjust to False.

stock_data = nvda.history(start=start_date,end=end_date,auto_adjust=False) print(stock_data)

This is the result:

Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (2)

here, all prices (OHLC) are on the unadjusted basis, except for Adj Close prices.

Additionally, you can specify an interval (bar size) for the price series, such as by hour, day or month. You can even get minute-by-minute prices. For instance, if you want to obtain weekly stock prices for Nvidia, execute the following:

stock_data = nvda.history(start='2019-01-01',end='2023-10-12',interval='1wk')
Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (3)

Unfortunately, Yahoo has limits on intraday data. Here is the complete list of bar sizes and allowable period for each one.

1.2. Download Financial Statements, Dividends, etc

There are many more functions that you can use with the Ticker class. Type the following command in Python to get the full list of functions:

help(yf.Ticker)

Here is a sample of functions for the yfinance Ticker class:

  • balance_sheet
  • dividends
  • earnings
  • earnings_dates
  • income_stmt
  • info
  • major_holders
  • news
  • quarterly_cash_flow

Beside these functions, there is also a list of legacy functions that have a get_ in them. They are similar to the functions I just showed you. The only difference is that you have to include empty parenthesis for functions that have get_ in them.

For example, if I invoke the earnings_dates function, here is the result I get for Nvidia:

print(nvda.earnings_dates)
Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (4)

Note, that certain functions may not work from the list above. If you try some of them and get an error, don’t be surprised. Yahoo changes its API or removes certain data from time to time. For this reason, yfinance is good enough for testing, but not live trading.

Also, remember, only the Ticker class can download financial data (e.g. financials, dividends, holdings). It is not possible to do so with Tickers class and download function.

1.3. Options Chain Data with yfinance Ticker Class

Also, the yfinance Python module also lets you download options chain data with the Ticker class. If you do not know what options chain is, it is a list of options contracts for a given stock. For instance, if I want to get data for current put and call options, I execute the following command:

nvda_option_chain = nvda.option_chain() #download and store option chainnvda_put_options = nvda_option_chain.puts #get stock putsnvda_call_options = nvda_option_chain.calls #get stock callsprint(nvda_put_options)print(nvda_call_options)

The resulting output is this:

Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (5)

2. Batch Download of Stock Prices with yfinance

To download prices for many stocks in batches, you have two options. These are: (1) Tickers class or (2) download standalone function. They work similarly.

2.1. Batch Download with Ticker Class

To use the Tickers class batch download feature, execute the following command:

tickers = ['NVDA','MSFT','AAPL'] # create list of tickers, could be a string with comma separationstocks = yf.Tickers(tickers)prices = stocks.history(start='2019-01-01',end='2023-10-12',interval='1wk')print (prices)

In response, you will get this output:

Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (6)

This pandas DataFrame contains the following data for these three stocks:

  • OHLCV (Open, High, Low, Close, Volume)
  • dividends
  • stock splits

The Tickers class has also its own download function. It works in exactly the same way as the history function. to get news for stocks. Try this command, and you will see that the results are identical.

prices = stocks.download(start='2019-01-01',end='2023-10-12',interval='1wk')print (prices)

As a side note, you can also use the Tickers class to get news for stocks. This function is the same as for the Ticker class. The only difference is that the Tickers class gets news for many stocks simultaneously.

news=stocks.news()print(news)

2.2. Batch Download with Yfinance “Download” Function

To use the standalone download function, you do not need to create any class instances. You only need to call the download function by supplying necessary arguments.

Furthermore, the arguments for the download function are somewhat similar to the history function. Refer to the GitHub code for a complete list of arguments and their explanations for the download function.

tickers = ['NVDA', 'MSFT', 'AAPL'] # create list of tickersprices = yf.download(tickers,start='2019-01-01',end='2023-10-12',interval='1wk')print (prices)

This produces the following output:

Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (7)

The resulting pandas DataFrame has the following columns:

  • OHLCV (Open, High, Low, Close, Volume)
  • Adjusted Close

The standalone download function sets auto_adjust and actions parameters to False by default. For this reason, you get unadjusted prices with no dividends and splits.

If you want to have adjusted prices together with stock dividends and splits, explicitly set these two parameters to True:

prices=yf.download(tickers,start='2019-01-01',end='2023-10-12',auto_adjust=True,actions=True)

Concluding Remarks

To download the entire code in Python file, use this Dropbox link.

Yfinance is a great Python module allowing you to get a wide variety of financial stock data. I am truly amazed that Yahoo Finance is still letting public download data free of charge. It is hard to tell how long this will last. The best approach is to learn as much as you can while it lasts. Later, you can transition to paid sources for live trading.

Related posts:

What is Economic Moat in Investment Valuation?How to Adjust Valuation EBIT for Operating LeasesHow to Calculate Relative Strength for Stocks in Python
Yfinance Tutorial: How to Get Stock Prices for Free - Andriy Blokhin (2024)
Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6052

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.