Python Fetching Financial Data |
\n\nIn 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.
\n\nThe library used in the examples on this site for demonstration is yfinance.
Installation is as follows:
\n\npip install yfinance\n\nThe yfinance library uses the yf.download() function to download financial data.
Here is its basic syntax format:
\n\nyf.download(tickers, start=None, end=None, actions=False, threads=True)\n\nParameter Description:
\n\ntickers:
\n- \n
- Description: The ticker symbol for the financial instrument (stock, index, fund, etc.) whose data you want to download. \n
- Type: String (for a single symbol) or list (for multiple symbols). \n
- Example:
"AAPL",["AAPL", "GOOGL"]. \n
start:
\n- \n
- Description: The start date for downloading data. \n
- Type: String (date format:
"YYYY-MM-DD"). \n - Default:
None, which means starting from the earliest available date. \n - Example:
"2020-01-01". \n
end:
\n- \n
- Description: The end date for downloading data. \n
- Type: String (date format:
"YYYY-MM-DD"). \n - Default:
None, which means ending at the latest available date. \n - Example:
"2022-01-01". \n
actions:
\n- \n
- Description: Whether to include stock dividends and splits information. \n
- Type: Boolean. \n
- Default:
False. \n - Example:
actions=True. \n
threads:
\n- \n
- Description: Whether to use multithreading to download data. \n
- Type: Boolean. \n
- Default:
True. \n - Example:
threads=False. \n
In yfinance, Chinese A-share stock codes require an exchange suffix. The Shanghai Stock Exchange (SSE) uses .SS, and the Shenzhen Stock Exchange (SZSE) uses .SZ.
Below is a simple example of using yfinance to fetch stock data for Kweichow Moutai (600519.SS):
\n\nExample
\n\nimport yfinance as yf\n\n# Shanghai Stock Exchange, Moutai stock code\n\nsymbol="600519.SS"\n\n# Alternatively, Shenzhen Stock Exchange, Luzhou Laojiao stock code\n\n# luzhou_laojiao_szse = yf.Ticker('000568.SZ')\n\n# GetMoutai Company Stock Data\n\n maotai_data = yf.download(symbol, start="2022-01-01", end="2023-11-01", auto_adjust=False, progress=False)\n\n# Print the first few rows of data\n\nprint(maotai_data.head())\n\nIn the above code, we used yfinance's download function to retrieve stock data for Kweichow Moutai (600519.SS), covering the period 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 Adj Close.
For more information on Pandas DataFrame, refer to: Pandas Data Structure - DataFrame
\n\nExecuting the above code produces the following output:
\n\n# python3 mt.py[*********************100%%**********************] 1 of 1 completed Open High Low Close Adj Close VolumeDate 2022-01-04 2055.00000 2068.949951 2014.000000 2051.229980 1973.508057 33842622022-01-05 2045.00000 2065.000000 2018.000000 2024.000000 1947.309937 28395512022-01-06 2022.01001 2036.000000 1938.510010 1982.219971 1907.112793 51794752022-01-07 1975.00000 1988.880005 1939.319946 1942.000000 1868.416870 29816692022-01-10 1928.01001 1977.000000 1917.550049 1966.000000 1891.507568 2962670\n\nTicker Class
\n\nThe yfinance Ticker class is used to fetch information and real-time data for specific financial instruments.
Ticker Class Constructor:
- \n
- Usage:
yf.Ticker('AAPL')\n - Description: Creates a
Tickerobject representing a specific stock or financial asset. Pass the ticker symbol (e.g.,'AAPL') inside the parentheses. \n
history Method:
- \n
- Usage:
ticker.history(period='1d', interval='1m')\n - Description: Retrieves historical price data. The
periodparameter specifies the time span (e.g.,'1d'for one day,'1mo'for one month,'1y'for one year). Theintervalparameter specifies the time interval (e.g.,'1m'for one minute,'1d'for one day,'1wk'for one week). \n
info Attribute:
- \n
- Usage:
ticker.info\n - Description: Retrieves basic information about the stock, such as company name, industry, market cap, etc. \n
dividends Attribute:
- \n
- Usage:
ticker.dividends\n - Description: Retrieves dividend data, returning a DataFrame containing dates and dividend amounts. \n
splits Attribute:
- \n
- Usage:
ticker.splits\n - Description: Retrieves split data, returning a DataFrame containing dates and split ratios. \n
recommendations Attribute:
- \n
- Usage:
ticker.recommendations\n - Description: Retrieves analyst recommendations for the stock, returning a DataFrame containing dates and recommendation details. \n
major_holders Attribute:
- \n
- Usage:
ticker.major_holders\n - Description: Retrieves major holder information, returning a DataFrame containing major shareholders and their ownership percentages. \n
sustainability Attribute:
- \n
- Usage:
ticker.sustainability\n - Description: Retrieves sustainability information for the stock, returning a DataFrame containing Environmental, Social, and Governance (ESG) metrics. \n
actions Attribute:
- \n
- Usage:
ticker.actions\n - Description: Retrieves corporate action data, including splits and dividends. \n
calendar Attribute:
- \n
- Usage:
ticker.calendar\n - Description: Retrieves the company's financial calendar, such as dates for quarterly earnings reports. \n
The following code uses the Ticker class from the yfinance library to fetch stock information for Microsoft Corporation (ticker: MSFT), including basic info, historical market data, dividends, splits, financial statements, etc.:
Example
\n\nimport yfinance as yf\n\n# Create a Ticker object to operate on Microsoft's stock data\n\n msft = yf.Ticker("MSFT")\n\n# GetAll Stock Information\n\n msft.info\n\n# Get historical market data, here for the past month\n\n hist = msft.history(period="1mo")\n\n# Display metadata of historical data (requires calling history() function first)\n\n msft.history_metadata\n\n# Display corporate actions (dividends, stock splits, capital gains)\n\n msft.actions\n\n msft.dividends\n\n msft.splits\n\n msft.capital_gains# Only applicable to mutual funds and exchange-traded funds (ETFs)\n\n# Display number of shares\n\n msft.get_shares_full(start="2022-01-01", end=None)\n\n# Display financial statements:\n\n# - Income statement\n\n msft.income_stmt\n\n msft.quarterly_income_stmt\n\n# - Balance sheet\n\n msft.balance_sheet\n\n msft.quarterly_balance_sheet\n\n# - Cash flow statement\n\n msft.cashflow\n\n msft.quarterly_cashflow\n\n# To see more options, please refer to `Ticker.get_income_stmt()`\n\n# Display shareholder information\n\n msft.major_holders\n\n msft.institutional_holders\n\n msft.mutualfund_holders\n\n# Display future and historical earnings dates, returning up to 4 future quarters and 8 past quarters by default.\n\n# Note: If more information is needed, you can use msft.get_earnings_dates(limit=XX)οΌWhere XX is the additional limit parameter.\n\n msft.earnings_dates\n\n# Display International Securities Identification Number (ISIN) - *Experimental feature*\n\n# ISIN = International Securities Identification Number\n\n msft.isin\n\n# Display option expiration dates\n\n msft.options\n\n# Display news\n\n msft.news\n\n# Get option chain for a specific expiration date\n\n opt = msft.option_chain('YYYY-MM-DD')\n\n# Data can be accessed via opt.calls, opt.puts Get\n\nFetching Data for Multiple Stocks
\n\nThe following code initializes a Tickers object containing multiple stock symbols using the yfinance library and accesses information, historical data, and corporate actions for different stocks through this object:
Example
\n\nimport yfinance as yf\n\n# Initialize a Tickers object containing multiple stock tickers\n\n tickers = yf.Tickers('msft aapl goog')\n\n# Usage example, access information for each stock\n\n tickers.tickers['MSFT'].info# Get Microsoft Basic Information for Company (MSFT)\n\n tickers.tickers['AAPL'].history(period="1mo")# Get historical data for Apple Inc. (AAPL) for the past month\n\n tickers.tickers['GOOG'].actions# Get Google Corporate Actions Information for Company (GOOG) (Dividends, Stock Splits, etc.)\n\nDownloading Historical Data
\n\nThe following code uses the yfinance library to download one month of historical market data for the S&P 500 ETF (SPY) and Apple Inc. (AAPL):
\n\nExample
\n\nimport yfinance as yf\n\n# Use yfinance to download historical market data for S&P 500 ETF (SPY) and Apple Inc. (AAPL)\n\n data = yf.download("SPY AAPL", period="1mo")\n\nThe period="1mo" parameter indicates that the download time range covers the past month.
\n\n
More Financial Libraries
\n\nHere are some libraries primarily used for fetching financial data:
\n\nyfinance
\n- \n
- Official Website: yfinance \n
- Introduction: yfinance is a library for fetching data from Yahoo Finance. It provides a simple API that allows users to retrieve financial data for stocks, indices, and more. \n
- Installation:
pip install yfinance\n
Tushare
\n- \n
- Official Website: Tushare \n
- Introduction: Tushare is an open financial data platform offering rich APIs for stock, futures, funds, and other financial market data. It supports Python and provides an easy-to-use API. \n
- Installation:
pip install tushare\n
pandas-datareader
\n- \n
- Official Website: pandas-datareader \n
- Introduction: pandas-datareader is a library for fetching financial data from various online sources (such as Yahoo Finance, Google Finance, etc.). \n
- Installation:
pip install pandas-datareader\n - Official Website: baostock \n
baostock
\n- \n
- Official Website: baostock \n
- Introduction: baostock is a library that provides free access to A-shares, Hong Kong stocks, options, and other financial data. It offers a Python interface for convenient data retrieval. \n
- Installation:
pip install baostock\n
alpha_vantage
\n- \n
- Official Website: alpha_vantage \n
- Introduction: alpha_vantage provides a simple API to fetch financial data for stocks, forex, and more. It also supports calculations for some technical indicators. \n
- Installation:
pip install alpha_vantage\n
quandl
\n- \n
- Official Website: Quandl \n
- Introduction: Quandl provides financial and economic data from various sources. It offers a Python library for convenient data retrieval. \n
- Installation:
pip install quandl\n
ccxt
\n- \n
- Official Website: ccxt \n
- Introduction: ccxt is an open-source library for trading and fetching financial data, supporting data retrieval from multiple exchanges. \n
- Installation:
pip install ccxt\n
AKShare
\n- \n
- Official Website: AKShare \n
- Introduction: AKShare is a Python-based financial data interface library designed to provide a complete toolchain for collecting, cleaning, and storing fundamental data, real-time and historical quotes, and derived data for stocks, futures, options, funds, forex, bonds, indices, and cryptocurrencies. It is primarily intended for academic research purposes. \n
- Installation:
pip install akshare\n
YouTip