Python Fetching Financial Data
In Python, to perform quantitative analysis, you first need to obtain financial data. There are multiple libraries in Python that can be used to fetch financial market data.
The library used for the examples on this site isyfinance。
Install as follows:
pip install yfinance
yfinanceLibrary Usageyf.download()The function for downloading financial data.
The following is its basic syntax format:
yf.download(tickers, start=None, end=None, actions=False, threads=True)
Parameter Description:
tickers:
- Description:The code of the financial instrument (stock, index, fund, etc.) to download data for.
- Type:String (single code) or list (multiple codes).
- Example: "AAPL"、["AAPL", "GOOGL"]。
start:
- Description:The start date for downloading data.
- Type:String (date format: "YYYY-MM-DD").
- Default value:None, meaning start from the earliest available date.
- Example: "2020-01-01"。
end:
- Description:The end date for downloading data.
- Type:String (date format: "YYYY-MM-DD").
- Default value:None, meaning end at the latest available date.
- Example: "2022-01-01"。
actions:
- Description:Whether to include stock dividends, splits, and other information.
- Type:Boolean.
- Default value: False。
- Example:
actions=True。
threads:
- Description:Whether to use multithreading to download data.
- Type:Boolean.
- Default value: True。
- Example:
threads=False。
In yfinance, stock codes for China A-shares need to have the exchange suffix appended. The suffix for the Shanghai Stock Exchange (SSE) is.SS, and the suffix for the Shenzhen Stock Exchange (SZSE) is.SZ。
Below is a simple example usingyfinanceto fetch stock data for Kweichow Moutai (600519.SS):
Example
# Shanghai Stock Exchange, Moutai company stock code
symbol = "600519.SS"
# Or, Shenzhen Stock Exchange, Luzhou Laojiao company stock code
# luzhou_laojiao_szse = yf.Ticker('000568.SZ')
# Get Moutai company stock data
maotai_data = yf.download(symbol, start="2022-01-01", end="2023-11-01")
# Print the first few rows of the data
print(maotai_data.head())
In the above code, we used yfinance's download function to obtain stock data for Kweichow Moutai (600519.SS), with a time range from January 1, 2022 to November 1, 2023. The returned data is a Pandas DataFrame containing information such as Date, Open, High, Low, Close, Volume, and Adjusted Close (Adj Close).
For Pandas DataFrame content, please refer to:Pandas Data Structures - DataFrame
Executing the above code produces the following output:
# python3 mt.py
[*********************100%%**********************] 1 of 1 completed
Open High Low Close Adj Close Volume
Date
2022-01-04 2055.00000 2068.949951 2014.000000 2051.229980 1973.508057 3384262
2022-01-05 2045.00000 2065.000000 2018.000000 2024.000000 1947.309937 2839551
2022-01-06 2022.01001 2036.000000 1938.510010 1982.219971 1907.112793 5179475
2022-01-07 1975.00000 1988.880005 1939.319946 1942.000000 1868.416870 2981669
2022-01-10 1928.01001 1977.000000 1917.550049 1966.000000 1891.507568 2962670
Ticker Class
The yfinance Ticker class is used to obtain information and real-time data for a specific financial instrument.
TickerClass constructor:
- Usage:
yf.Ticker('AAPL') - Description: Creates a
Tickerobject representing a specific stock or financial asset. Pass the stock code inside the parentheses (e.g., 'AAPL').
historyMethods:
- Usage:
ticker.history(period='1d', interval='1m') - Description: Fetch historical price data.
periodThe parameter specifies the time span, which can be'1d'(one day),'1mo'(one month),'1y'(one year), etc.;intervalThe parameter specifies the time interval, which can be'1m'(one minute),'1d'(one day),'1wk'(one week), etc.
infoAttributes:
- Usage:
ticker.info - Description: Get basic information about the stock, such as company name, industry, market cap, etc.
dividendsAttributes:
- Usage:
ticker.dividends - Description: Get dividend data, returning a DataFrame containing dates and dividend amounts.
splitsAttributes:
- Usage:
ticker.splits - Description: Get stock split data, returning a DataFrame containing dates and split ratios.
recommendationsAttributes:
- Usage:
ticker.recommendations - Description: Get stock recommendations, returning a DataFrame containing dates and recommendation information.
major_holdersAttributes:
- Usage:
ticker.major_holders - Description: Get major holders information for the stock, returning a DataFrame containing major shareholders and their ownership percentages.
sustainabilityAttributes:
- Usage:
ticker.sustainability - Description: Get sustainability information for the stock, returning a DataFrame containing Environmental, Social, and Governance (ESG) metrics.
actionsAttributes:
- Usage:
ticker.actions - Description: Get corporate actions data for the stock, including splits, dividends, etc.
calendarAttributes:
- Usage:
ticker.calendar - Description: Get the company's financial calendar information, such as dates for reporting quarterly earnings, etc.
The following code uses the Ticker class from the yfinance library to obtain stock information for Microsoft Corporation (stock code: MSFT), including basic information, historical market data, dividends, stock splits, financial statements, etc.:
Example
# Create a Ticker object representing operations on Microsoft's stock data
msft = yf.Ticker("MSFT")
# Get all stock information
msft.info
# Get historical market data, here is the data for the past month
hist = msft.history(period="1mo")
# Display metadata of historical data (requires calling the history() function first)
msft.history_metadata
# Display corporate actions information (dividends, splits, capital gains)
msft.actions
msft.dividends
msft.splits
msft.capital_gains # Only applicable to mutual funds and exchange-traded funds (ETFs)
# Display shares outstanding
msft.get_shares_full(start="2022-01-01", end=None)
# Display financial statements:
# - Income statement
msft.income_stmt
msft.quarterly_income_stmt
# - Balance sheet
msft.balance_sheet
msft.quarterly_balance_sheet
# - Cash flow statement
msft.cashflow
msft.quarterly_cashflow
# For more options, please refer to `Ticker.get_income_stmt()`
# Display shareholder information
msft.major_holders
msft.institutional_holders
msft.mutualfund_holders
# Show future and historical earnings dates, returning up to 4 future quarters and 8 past quarters of data by default.
# Note: If more information is needed, you can use msft.get_earnings_dates(limit=XX), where XX is an increased limit parameter.
msft.earnings_dates
# Display International Securities Identification Number (ISIN) - *experimental feature*
# ISIN = International Securities Identification Number
msft.isin
# Display option expiration dates
msft.options
# Display news
msft.news
# Get options chain for a specific expiration date
opt = msft.option_chain('YYYY-MM-DD')
# Data can be accessed via opt.calls, opt.puts
Fetching Multiple Stock Data
The following code uses the yfinance library to initialize a Tickers object containing multiple stock codes, and uses that object to access information, historical data, and corporate actions for different stocks:
Example
# Initialize a Tickers object containing multiple stock codes
tickers = yf.Tickers('msft aapl goog')
# Usage example, accessing information for each stock
tickers.tickers['MSFT'].info # Get basic information for Microsoft (MSFT)
tickers.tickers['AAPL'].history(period="1mo") # Get historical data for Apple (AAPL) over the past month
tickers.tickers['GOOG'].actions # Get corporate actions information for Google (GOOG) (dividends, splits, etc.)
Download Historical Data
The following code uses theyfinancelibrary to download historical market data for the S&P 500 ETF (SPY) and Apple (AAPL) over the past month:
Example
# Use yfinance to download historical market data for the S&P 500 ETF (SPY) and Apple (AAPL)
data = yf.download("SPY AAPL", period="1mo")
period="1mo"The parameter indicates that the download time range is the past month.
More Financial Libraries
Here are some libraries mainly used for fetching financial data:
yfinance
- Official website: yfinance
- Introduction:yfinance is a library for fetching Yahoo Finance data. It provides a simple API that allows users to obtain financial data such as stocks, indices, etc.
- Installation:
pip install yfinance
Tushare
- Official website: Tushare
- Introduction:Tushare is an open financial data platform that provides interfaces for rich financial market data such as stocks, futures, funds, etc. It supports Python and provides an easy-to-use API.
- Installation:
pip install tushare
pandas-datareader
- Official website: pandas-datareader
- Introduction:pandas-datareader is a library that fetches financial data from multiple online data sources (such as Yahoo Finance, Google Finance, etc.).
- Installation:
pip install pandas-datareader - Official website: baostock
baostock
- Official website: baostock
- Introduction:baostock is a library that freely provides financial data such as A-shares, Hong Kong stocks, options, etc. It provides a Python interface for users to conveniently obtain data.
- Installation:
pip install baostock
alpha_vantage
- Official website: alpha_vantage
- Introduction:alpha_vantage provides a simple API that can be used to obtain financial data such as stocks, foreign exchange, etc. It also supports the calculation of some technical indicators.
- Installation:
pip install alpha_vantage
quandl
- Official website: Quandl
- Introduction:Quandl provides financial and economic data from various sources. It provides a Python library for users to conveniently obtain data.
- Installation:
pip install quandl
ccxt
- Official website: ccxt
- Introduction:ccxt is an open-source library for trading and obtaining financial data, supporting data acquisition from multiple exchanges.
- Installation:
pip install ccxt
AKShare
- Official website: AKShare
- Introduction:AKShare is a Python-based financial data interface library. It aims to provide a set of tools for financial products such as stocks, futures, options, funds, foreign exchange, bonds, indices, and cryptocurrencies, covering fundamental data, real-time and historical market data, and derived data, from data collection, data cleaning to data storage. It is mainly used for academic research purposes.
- Installation:
pip install akshare