yfinance Data Import to a Spreadsheet (2024)

yfinance is a popular open source Python library that provides free access to financial data made available by Yahoo Finance. The yfinance package allows users to write simple Python commands and pull a wide range of financial data, like ticker data, options, fundamental financials, and much more, into a notebook, spreadsheet, or development environment. In the following post, we will show you how to use the most common yfinance Python commands that pull financial data into to a spreadsheet where it can be analyzed, graphed, and monitored. The template uses Row Zero, a cloud based spreadsheet. Continue reading for full instructions or jump to any of the following sections.

  • How to Install yfinance?
  • Import Historical Ticker Data For One Stock
  • Modify Timeframe
  • Import Historical Ticker Data for Multiple Stocks
  • Import Company Fundamentals
  • Options Data
  • Institutional Holders
  • Pros and Cons of yfinance
  • Summary
  • Appendix

Install yfinance

Using yfinance in Row Zero makes it easy to execute commands. Unlike Jupyter notebooks or a code editor, you do not need to worry about running a Python environment. Row Zero takes care of all the comlexity. To start, open a free Row Zero workbook. Next open the Row Zero code window using the right side menu. Then import the yfinance Library with the one line command below and execute the code window by pressing shift + enter or clicking the 'run' button.

import yfinance as yfimport pandas as pd

yfinance Data Import to a Spreadsheet (1)

Import Historical Ticker Data For One Stock

The first and most basic thing to do with yfinance is import historical pricing data for a specific stock ticker. For example, if we wanted to know Tesla's stock price since the IPO, the functions below let us pull that data into the spreadsheet. The same can be done for any other stock ticker and company of interest. Using this function will pull in the date, opening price, high, low, closing price, volume of shares traded, dividends, and stock splits for every day of trading. In the example of Tesla, the data goes all the way back to the IPO on June 29, 2010 when shares began trading at $1.267.

To start, define a python function that expects a ticker symbol argument and returns the stock's pricing history. The yfinance 'Ticker()' function is used in this example and is one of the most popular yfinance functions. Run the code with with shift + enter. There are a number of additional arguments that can be used with history(). Review the appendix at the end of this post for more details.

import yfinance as yfimport pandas as pddef STOCK(ticker): return yf.Ticker(ticker).history(period="max")

Now use that function in the spreadsheet by typing the function with a ticker in any cell and hitting enter. yfinance Data Import to a Spreadsheet (2)

You can also type a ticker in a cell and reference the cell in the formula.

=stock(A0)

yfinance Data Import to a Spreadsheet (3)

The following data table will be returned using both methods, whih shows Tesla's stock price data since it's IPO

yfinance Data Import to a Spreadsheet (4)

Modify Timeframe

yfinance supports various arguments that allow users to specify certain time periods that are applicable to the analysis or dataset they are trying to build. These arguments can be added to functions to modify the amount or range of data returned. Below we review modifying the timeframe in yfinance for the ticker command and use Row Zero's column modification feature to reduce the number of viewable columns. In the Tesla example, if we only wanted to see the ticker data for the past 100 days or 1 year, we could use additional arguments to specific the time period.

Modify timeframe

Update the python command and specify a different period to import the last X days of data.

def STOCK(ticker): return yf.Ticker(ticker).history(period="100d")

Another easy option is to use Row Zero's filters by clicking on the drop down at the top of a column and entering a filter by date. yfinance Data Import to a Spreadsheet (5)

Modify columns

Once the data has been imported to Row Zero, right click and select 'manage columns' to remove columns of data that aren't needed. yfinance Data Import to a Spreadsheet (6)

Import Historical Ticker Data for Multiple Stocks

Now that we know how to import data for one ticket, the function can be applied to multiple tickers. To import data for multiple tickers, use the download() command in yfinance. The paramters for download() can be found at the end of this post.

Use the following command to write a function that imports the closing price for a number of stock tickers. In this example, it is important to set the groupby parameter to either column or Ticker based on the desired structure of the data table.

def get_stock_prices(tickers): data = yf.download(list(tickers), group_by='column', period="1000d", interval='1d') return data[['Close', 'Volume']]

get_stock_prices can be used in Row Zero to reference cells with tickers of interest. See the images below for an example. Get stock prices spreadsheet function

After hitting enter, the function will return the following data table: Get sock prices data table

Import Company Fundamentals

Stock fundamentals refer to the core financial data and performance metrics of a company. Investors us fundamental data to analyze a company's financial health and intrinsic value. Fundamentals include revenue, earnings, profit margins, and growth rates, as well as more complex metrics like price-to-earnings (P/E) ratio, return on equity, and debt-to-equity ratio. In the case of Tesla, fundamentals might show revenue growth, which has been significant due to rising sales of electric vehicles, or its P/E ratio, which reflects investors' high expectations for future growth. An investor would also consider Tesla's operational efficiency, market share in the electric vehicle industry, and its ability to innovate and sustain profitability in a competitive market. The instructions below show how to use yfinance to pull fundamental data for one ticker or multiple.

Fundamentals for one ticker

Yfinance makes it easy to gather fundamental data for various companies using get_financials(). Using the Python function below, pass in a ticker and the function will pull the fundamental data from yfinance into the spreadsheet.

def get_financials(ticker): tck = yf.Ticker(ticker) return tck.get_financials()

yfinance Data Import to a Spreadsheet (7)

Fundamentals for multiple tickers

It may be more helpful to pull fundamental data for multiple companies at once. Do to so, use the function below which expects multiple tickers and will return results from yfinance for all tickers in the selected range.

def get_multiple_financials(tickers): tickers = [yf.Ticker(ticker) for ticker in tickers] dfs = [] # list for each ticker's dataframe for ticker in tickers: # get each financial statement pnl = ticker.financials bs = ticker.balancesheet cf = ticker.cashflow # concatenate into one dataframe fs = pd.concat([pnl, bs, cf]) # make dataframe format nicer # Swap dates and columns data = fs.T # reset index (date) into a column data = data.reset_index() # Rename old index from '' to Date data.columns = ['Date', *data.columns[1:]] # Add ticker to dataframe data['Ticker'] = ticker.ticker dfs.append(data) df = pd.concat(dfs, ignore_index=True) df = df.T.drop_duplicates().T df = df.set_index(['Ticker','Date']) return df

yfinance Data Import to a Spreadsheet (8)

Options Data

yfinance also provides options data for a given ticker symbol with another set of commands. Options data refers to details of options contracts in financial markets. These contracts give the holder the right, but not the obligation, to buy or sell an underlying asset, like a stock, at a predetermined price within a specific timeframe. Key options data include the strike price, expiration date, premiums, and whether the option is a 'call' (betting the asset price will rise) or 'put' (betting the price will fall). Options data can also include the trading volume and open interest for specific contracts, which help investors gauge market sentiment and potential price movements of the underlying asset. Te following instructions show how to pull options data from yfinance.

Get puts for one stock ticker

It is easy to get options data from yfinance using options.puts and options.calls. Below is a function that passes yfinance a ticker and returns the puts for that ticker.

def get_puts(ticker): tck = yf.Ticker(ticker) options = tck.option_chain() return options.puts

yfinance Data Import to a Spreadsheet (9)

Get calls for one stock ticker

The following functions passes a ticker to yfinance and returns the calls associated with the ticker.

def get_calls(ticker): tck = yf.Ticker(ticker) options = tck.option_chain() return options.calls

yfinance Data Import to a Spreadsheet (10)

Get Institutional Holders

Institutional holders are entities like mutual funds, pension funds, insurance companies, investment firms, and other large organizations that invest in sizable quantities of shares. yfinance has a function that will provide information on the instituional holders of a specified stock ticker, making it easy to pull the data into Row Zero.

def get_institutional_holders(ticker): tck = yf.Ticker(ticker) return tck.institutional_holders

yfinance Data Import to a Spreadsheet (11)

Pros and Cons of yfinance

yfinance is a great free tool for analyzing financial data but there are a few pros and cons to consider. Below we review the pros and cons of the open source Python package.

Pros:

  • yfinance is free. There are a few other free financial data sources but they are less widely used. Paid data sources are very expensive (Bloomberg costs $24,000/year)
  • User-friendly. yfinance is easy to install and use. Pypi reports several hundred thousand installs each month.
  • Valuable data. yfinance exposes data for strategic investing decisions.

Cons:

  • Dependencies. yfinance can break if Yahoo Finance ever changes the format of their site. If this were to happen, it is likely the yfinance library would be updated to remedy the situation but access to data may incur a short disruption.
  • Data frequency. The highest frequency data is minute level, which makes yfinance a less suitable option for real time trading.
  • Reliability. Paid data sources typically offer higher fidelity data from more reliable access points, like terminals and APIs.

Summary

Yfinance is a great free resource for pulling and analyzing stock information. It's easy to pull stock prices, fundamentals, options data, and institutional holders among many other options. There are pros and cons to using yfinance. The pros center on it's ease of use and its free price tag. The cons mainly center on reliability and data frequency. If your preference is to work with financial data in a spreadshet, use Row Zero to pull ticker data straght into a spreadsheet and begin your analysis.

Appendix

This section includes additional information about paramters for popular functions available in the yfinance python library. Reference these lists to expand upon the history() and download() functions provided above. There is also additional information on the pypi yfinance page.

history() Parameters

The following are all the parameters for the history() command in yfinance.

:Parameters: period : str Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max Either Use period parameter or use start and end interval : str Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo Intraday data cannot extend last 60 days start: str Download start date string (YYYY-MM-DD) or _datetime. Default is 1900-01-01 end: str Download end date string (YYYY-MM-DD) or _datetime. Default is now prepost : bool Include Pre and Post market data in results? Default is False auto_adjust: bool Adjust all OHLC automatically? Default is True back_adjust: bool Back-adjusted data to mimic true historical prices proxy: str Optional. Proxy server URL scheme. Default is None rounding: bool Round values to 2 decimal places? Optional. Default is False = precision suggested by Yahoo! tz: str Optional timezone locale for dates. (default data is returned as non-localized dates) timeout: None or float If not None stops waiting for a response after given number of seconds. (Can also be a fraction of a second e.g. 0.01) Default is None. **kwargs: dict debug: bool Optional. If passed as False, will suppress error message printing to console.

Download() Paramters

The following are all the parameters for the download() command in yfinance. Each paramater can be used to specify changes in the data returned from each function.

# Download yahoo tickers:Parameters: tickers : str, list List of tickers to download period : str Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max Either Use period parameter or use start and end interval : str Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo Intraday data cannot extend last 60 days start: str Download start date string (YYYY-MM-DD) or _datetime. Default is 1900-01-01 end: str Download end date string (YYYY-MM-DD) or _datetime. Default is now group_by : str Group by 'ticker' or 'column' (default) prepost : bool Include Pre and Post market data in results? Default is False auto_adjust: bool Adjust all OHLC automatically? Default is False actions: bool Download dividend + stock splits data. Default is False threads: bool / int How many threads to use for mass downloading. Default is True proxy: str Optional. Proxy server URL scheme. Default is None rounding: bool Optional. Round values to 2 decimal places? show_errors: bool Optional. Doesn't print errors if True timeout: None or float If not None stops waiting for a response after given number of seconds. (Can also be a fraction of a second e.g. 0.01)
yfinance Data Import to a Spreadsheet (2024)
Top Articles
Latest Posts
Article information

Author: Dr. Pierre Goyette

Last Updated:

Views: 6036

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.