The Easiest Way to Pull Stock Data into your Python Program: yfinance | by Kevin Tang | Towards Data Science

I’ve been working on a fun stock ticker project recently and I came across something I’ve never thought about before: what’s the best way to pull current and historical stock market price data into my Python program?
It turns out that for me, the best option was yfinance — a Python library that gives you current and historical stock market price data from Yahoo Finance, and so much more. The cool thing is that it is entirely free, doesn’t require an API key, and allows for a relatively high throughput of 2,000 requests per hour. And the cooler thing is that you (yes you right there!) can get stock data into your Python program so easily and it’s as simple as these few steps I’ll show you below.
I’m using Python 3.8 but anything above Python 3.4 should be supported. You can be running on Linux, Mac, or Windows. (If you’re on Windows, I’d recommend you check out WSL2, how to get started, and everything it can do — if you do use WSL2, be sure to follow the Linux commands)
To start, we want to create our Python virtual environment named envand activate it.
For Linux/Mac Terminal
python3 -m venv envsource env/bin/activate
For Windows PowerShell
python3 -m venv env.\env\Scripts\Activate.ps1
Now that we’ve got our Python virtual environment setup and activated, let’s install yfinance into this virtual environment so we can use it. The next command is the same for whichever platform you’re on.
pip install yfinance
Now yfinance is installed and we’re ready to write some Python code!
Let’s try out some of yfinance’s most basic, but likely most commonly used features.
I was working on a stock ticker so I wanted the current current price of a stock. Let’s get the current price of a stock and the previous close price of a stock— in this Python example, we’ll use TSLA.
import yfinance as yfstock_info = yf.Ticker('TSLA').info# stock_info.keys() for other properties you can exploremarket_price = stock_info['regularMarketPrice']previous_close_price = stock_info['regularMarketPreviousClose']print('market price ', market_price)print('previous close price ', previous_close_price)
Okay, so if we are running this during the hours the stock market is open, the price information does change and update in real time. How fast are updates? Prices change as fast as Yahoo Finance updates price, which is plenty fast enough for my purposes. It’s probably not fast enough for something like a high frequency trading bot, but Python might not be the best for that anyways.
Next let’s look at some historical data. If we want to plot it, we’ll have to install some additional Python libraries to help us out — matplotlib to plot and pendulum to do some easy time conversions for us.
pip install matplotlib pendulum
Now let’s look at TSLA’s past 2 years of stock price with an interval of every 1 month. You can see these numbers are flexible and can be changed to fit your use case.
import yfinance as yfimport pendulumimport matplotlib.pyplot as pltprice_history = yf.Ticker('TSLA').history(period='2y', # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max                                   interval='1wk', # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo                                   actions=False)time_series = list(price_history['Open'])dt_list = [pendulum.parse(str(dt)).float_timestamp for dt in list(price_history.index)]plt.style.use('dark_background')plt.plot(dt_list, time_series, linewidth=2)
I hope you find the yfinance library as hassle-free to set up and incorporate into your project as I did! There is a lot to explore and more information and examples can be found at https://pypi.org/project/yfinance/.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.