Use yfinance to Get Stock Prices for Free (3 Steps)

This tutorial will show the basics of using Python package yfinance to get the most recent stock price and store it in a CSV file. First, you need to have a CSV file of ticker and you want to get the most updated stock prices. Then, you want to use Python to automatically retrieve stock prices.

A CSV table with the company name and Ticker name. You can also download the CSV sheet on Github.

CompanyTicker
AffirmAFRM
BlockSQ
CoinbaseCOIN
LendingClubLC
RobinhoodHOOD
SoFiSOFI
UpstartUPST
PaypalPYPL
IntuitINTU
Company Name and Ticker List for yfinance

Three Steps of Using yfinance to Download Stock Prices for Free

You need to run the following code and I break it into different components to explain. (Note that, you need to put the following code in the same folder as the CSV file folder. ) You can download the Python code here.

Step 1: Import Needed Packages

First, you need to import needed packages, pandas, and read the CSV file into the environment

  • yfinance — A python library that offers a threaded and Pythonic way to download market data from Yahoo! Finance.
  • pandas — An open source data analysis and manipulation tool, built on top of the Python programming language.
# import yfinance and pandas
import yfinance as yf
import pandas as pd

# read CSV file of tickers from Github
FinTech_tickers=pd.read_csv("https://raw.githubusercontent.com/TidyPython/data_visualization/main/Ticker.csv")
# print out the list of tickers
print(FinTech_tickers)

Output:

       Company Ticker
0       Affirm   AFRM
1        Block     SQ
2     Coinbase   COIN
3  LendingClub     LC
4    Robinhood   HOOD
5         SoFi   SOFI
6      Upstart   UPST
7       Paypal   PYPL
8       Intuit   INTU

Step 2: Key function using yfinance

Then, we define a function to download the needed data. The reason why we need to define such a function is that: we need to download more than one ticker. That is, we have multiple tickers that we need to get stock prices.

# define what we want to download using yfinance
def download_most_recent_price(ticker_new):
    data=yf.download(  
        tickers=ticker_new,
        period="1d",
        interval="1d",
        auto_adjust=True,
        prepost=True,
        threads=True,
        proxy=None
    )
    data=data.reset_index()
    data["Ticker_name"]=ticker_new
    data_new=pd.DataFrame({
        'Ticker':ticker_new,
        'Date':data["Date"],
        'Close_price':data["Close"]
    })
    return(data_new)

Step 3: for loop with yfinance

Define an empty data frame. Then, repeat using the function defined in part b to write it into the data frame. Finally, write the data frame into a CSV file.

# Define an empty dataframe
df_combined = pd.DataFrame()

# loop function with yfinance function
for index, row in FinTech_tickers.iterrows():
    df_tempt=download_most_recent_price(row['Ticker'])
    df_combined=df_combined.append(df_tempt)
    print(df_combined)

# save stock prices as a CSV file to local folder
df_combined.to_csv("FinTech_prices_sample.csv")

You will then see the CSV file as follows. You can download it as a CSV file here.

TickerDateClose_price
AFRM4/1/202246.42
SQ4/1/2022137.09
COIN4/1/2022190.73
LC4/1/202215.79
HOOD4/1/202213.5592
SOFI4/1/20229.485
UPST4/1/2022110.71
PYPL4/1/2022117.47
INTU4/1/2022485.64
FinTech Stock Princes

Further Reading