How to Use yfinance API with Python
Last Updated :
16 Jul, 2024
The yfinance API is a powerful tool for accessing financial data from Yahoo Finance. It allows users to download historical market data, retrieve financial information, and perform various financial analyses. This API is widely used in finance, investment, and trading applications for its ease of use and comprehensive data coverage. In this article, we will explore the use yfinance API in Python with detailed examples.
What is yfinance?
yfinance is a Python library designed for accessing and retrieving financial data from Yahoo Finance. It simplifies the process of fetching historical market data, financial statements, and other relevant information for stocks, indices, and securities. Widely utilized in finance, investment, and trading applications, yfinance offers comprehensive data coverage and ease of integration, making it a popular choice among developers and financial analysts alike.
Setting Up yfinance API
To use yfinance, you need to install it first. This can be done using pip:
pip install yfinance
After installation, you can import the library in your Python script:
Python
Fetching Financial Data
With yfinance, you can fetch historical market data and financial information about stocks, indices, and other securities. The primary method for this is the Ticker object.
Example 1: Fetching Historical Market Data of Apple Inc
In this example, we are using the yfinance library in Python to fetch comprehensive financial data for the ticker symbol "AAPL" (Apple Inc.). We begin by creating a Ticker object for "AAPL" and then use it to retrieve historical market data for the last year (period="1y"). The fetched data includes daily Open, High, Low, Close prices, and Volume. Additionally, we fetch basic financial statements (financials) and stock actions (actions) such as dividends and splits related to Apple's stock.
Python
import yfinance as yf
# Define the ticker symbol
ticker_symbol = "AAPL"
# Create a Ticker object
ticker = yf.Ticker(ticker_symbol)
# Fetch historical market data
historical_data = ticker.history(period="1y") # data for the last year
print("Historical Data:")
print(historical_data)
# Fetch basic financials
financials = ticker.financials
print("\nFinancials:")
print(financials)
# Fetch stock actions like dividends and splits
actions = ticker.actions
print("\nStock Actions:")
print(actions)
Output
Example 2: Fetching Historical Market Data of Microsoft
In this example, we use yfinance to fetch historical market data for Microsoft Corporation (MSFT). We create a Ticker object for "MSFT" and fetch data for the last month (period="1mo"). The fetched data includes daily Open, High, Low, Close prices, and Volume. The summary output displays these key data points in a concise format, making it easier to analyze short-term trends for Microsoft's stock.
Python
import yfinance as yf
# Define the ticker symbol
ticker_symbol = "MSFT"
# Create a Ticker object
ticker = yf.Ticker(ticker_symbol)
# Fetch historical market data for the last 30 days
historical_data = ticker.history(period="1mo") # data for the last month
# Display a summary of the fetched data
print(f"Summary of Historical Data for {ticker_symbol}:")
print(historical_data[['Open', 'High', 'Low', 'Close', 'Volume']])
Output
Conclusion
In conclusion, the yfinance API proves invaluable for accessing detailed financial data from Yahoo Finance directly into Python applications. It simplifies the process of fetching historical market data, financial statements, and stock actions for various securities such as stocks and indices. By leveraging yfinance, users can efficiently perform financial analyses and gain insights crucial for finance, investment, and trading decisions.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read