Horje
What is YFinance library?

In today’s data-driven world, access to accurate and timely financial data is crucial for investors, analysts, and anyone interested in the financial markets. One tool that has gained popularity for retrieving such data is yfinance. This Python library allows users to access historical market data from Yahoo Finance.

In this article, we will explore what yfinance is, how it works, and its various features and applications.

Overview of yfinance Libraries

yfinance is an open-source Python library that provides a simple way to download historical market data from Yahoo Finance. It was created by Ran Aroussi as a workaround to the Yahoo Finance API deprecation. yfinance stands out for its ease of use and comprehensive data retrieval capabilities, making it a go-to choice for many in the financial and data science communities.

Key Features of yfinance

  1. Historical Market Data: Users can download historical stock prices, including open, high, low, close, and adjusted close prices, as well as trading volumes.
  2. Corporate Actions: The library provides information on corporate actions such as dividends and stock splits, which are crucial for accurate financial analysis.
  3. Financial Statements: yfinance can retrieve financial statements, including balance sheets, income statements, and cash flow statements.
  4. Earnings Data: Users can access earnings data, including earnings dates, revenue, and earnings per share (EPS) information.
  5. Multiple Tickers: The library supports retrieving data for multiple tickers simultaneously, allowing for efficient data analysis across a portfolio.

How to Install yfinance?

Installing yfinance is straightforward and can be done using pip, Python’s package installer. Simply run the following command in your terminal or command prompt:

pip install yfinance

Downloading Historical Data using YFinance

One of the most common uses of yfinance is to download historical market data for a given ticker symbol.

  • yf.download(ticker, start, end): Downloads historical data for the specified ticker between the start and end dates.
  • The head() method displays the first few rows of the DataFrame.
Python
import yfinance as yf

# Define the ticker symbol
ticker = 'AAPL'

# Get historical market data
data = yf.download(ticker, start='2020-01-01', end='2023-01-01')

# Display the first few rows of the data
print(data.head())

Output:

DateOpenHighLowCloseAdj CloseVolume
2020-01-0274.05999875.15000273.79750175.08750272.960480135480400
2020-01-0374.28749875.14499774.12500074.35749872.251144146322800
2020-01-0673.44750274.98999873.18750074.94999772.826851118387200
2020-01-0774.95999975.22499874.37000374.59750472.484352108872000
2020-01-0874.29000176.11000174.29000175.79750173.650337132079200

Getting Real-Time Data using YFinance

You can also retrieve real-time stock price data using yfinance.

  • yf.Ticker(ticker): Creates a Ticker object for the specified ticker symbol.
  • history(period=”1d”): Retrieves historical data for the last trading day.
  • [‘Close’][0]: Extracts the closing price of the stock for the last trading day.
Python
import yfinance as yf

# Define the ticker symbol
ticker = 'AAPL'

# Get the ticker object
stock = yf.Ticker(ticker)

# Get real-time price data
price = stock.history(period="1d")['Close'][0]
print(f"Real-time price for {ticker}: {price}")

Output:

Real-time price for AAPL: 228.67999267578125

Accessing Financial Statements using YFinance

yfinance provides access to a company’s financial statements, such as balance sheets, income statements, and cash flow statements.

  • stock.balance_sheet: Retrieves the company’s balance sheet.
  • stock.financials: Retrieves the company’s income statement.
  • The head() method displays the first few rows of the DataFrame.
Python
import yfinance as yf

# Define the ticker symbol
ticker = 'AAPL'

# Get the ticker object
stock = yf.Ticker(ticker)

# Get the balance sheet
balance_sheet = stock.balance_sheet
print("Balance Sheet:")
print(balance_sheet.head())

# Get the income statement
income_statement = stock.financials
print("\nIncome Statement:")
print(income_statement.head())

Output:

Balance Sheet:

2023-09-302022-09-302021-09-302020-09-302019-09-30
Treasury Shares Number0.0NaNNaNNaNNaN
Ordinary Shares Number15,550,061,000.015,943,425,000.016,426,786,000.016,976,763,000.0NaN
Share Issued15,550,061,000.015,943,425,000.016,426,786,000.016,976,763,000.0NaN
Net Debt81,123,000,000.096,423,000,000.089,779,000,000.074,420,000,000.0NaN
Total Debt123,930,000,000.0132,480,000,000.0136,522,000,000.0122,278,000,000.0NaN

Income Statement:

2023-09-302022-09-302021-09-302020-09-30
Tax Effect Of Unusual Items0.00.00.00.0
Tax Rate For Calcs0.1470.1620.1330.144
Normalized EBITDA129,188,000,000.0133,138,000,000.0123,136,000,000.081,020,000,000.0
Net Income From Continuing Operation Net Minority Interest96,995,000,000.099,803,000,000.094,680,000,000.057,411,000,000.0
Reconciled Depreciation11,519,000,000.011,104,000,000.011,284,000,000.011,056,000,000.0


Getting Ticker Information using YFinance Library

Retrieve basic information about a stock ticker using the info attribute.

  • stock.info: Retrieves a dictionary containing various pieces of information about the company.
  • The information is accessed using dictionary keys, such as longName, sector, industry, marketCap, and trailingPE.
Python
import yfinance as yf

# Define the ticker symbol
ticker = 'AAPL'

# Get the ticker object
stock = yf.Ticker(ticker)

# Get basic information
info = stock.info
print(f"Company: {info['longName']}")
print(f"Sector: {info['sector']}")
print(f"Industry: {info['industry']}")
print(f"Market Cap: {info['marketCap']}")
print(f"P/E Ratio: {info['trailingPE']}")

Output:

Company: Apple Inc.
Sector: Technology
Industry: Consumer Electronics
Market Cap: 3506601984000
P/E Ratio: 35.56454

Retrieving Dividends Data using Yfinance

You can also access dividend data for a particular stock.

  • stock.dividends: Retrieves the historical dividends data for the stock.
  • The head() method displays the first few rows of the Series.
Python
import yfinance as yf

# Define the ticker symbol
ticker = 'AAPL'

# Get the ticker object
stock = yf.Ticker(ticker)

# Get dividends data
dividends = stock.dividends
print("Dividends:")
print(dividends.head())

Output:

Dividends:
Date
1987-05-11 00:00:00-04:00 0.000536
1987-08-10 00:00:00-04:00 0.000536
1987-11-17 00:00:00-05:00 0.000714
1988-02-12 00:00:00-05:00 0.000714
1988-05-16 00:00:00-04:00 0.000714
Name: Dividends, dtype: float64

Applications of YFinance

yfinance can be applied in various financial tasks:

  • Backtesting Trading Strategies: This involves using historical data to identify how your chosen indicators and trading techniques perform in actual trading.
  • Portfolio Management: Assist in tracking and evaluating the results of investing with the help of portfolio tracking software.
  • Market Analysis: Carry out market research to see trends in various markets and assess performance of the sectors.
  • Financial Modeling: Develop and analyze the numerical models of finance like analysis of the expectation and the valuation.

Conclusion

You can identify yfinance as being an advanced and multitalented resource that allows accessing an extensive amount of information concerning stock exchanges and business in general, as provided by Yahoo! Finance. In every case, whether you need to analyze historical data, pull the current price or extract the financial statements, of even get standard ticker details, yfinance provides a basic and effective way of doing this. When you incorporate yfinance into the tools you use for data analysis, your financial analysis and decision making gets a boost.

YFinance Library – FAQs

Is yfinance free to use?

Yes, yfinance is an open-source library and is free to use.

Can I get real-time stock prices with yfinance?

Yes, yfinance provides real-time stock prices and other financial metrics.

Does yfinance work with other Python libraries?

yfinance integrates seamlessly with Pandas and other Python libraries, making it highly versatile for data analysis and visualization.




Reffered: https://www.geeksforgeeks.org


AI ML DS

Related
How to choose Batch Size and Number of Epochs When Fitting a Model? How to choose Batch Size and Number of Epochs When Fitting a Model?
Image Segmentation Using Mean Shift Clustering Image Segmentation Using Mean Shift Clustering
Human Resource Management Analytics Dashboard in R Human Resource Management Analytics Dashboard in R
How to Make a Tree Plot Using Caret Package in R How to Make a Tree Plot Using Caret Package in R
How to Change the Value of k in KNN Using R? How to Change the Value of k in KNN Using R?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16