top of page
Writer's pictureErika Jakobi

Python’s Application in Financial Analysis – Yfinance Library

Updated: May 8



Author: Pedram Safaeifar

Date of Publication: 28/01/2023




This post may contain affiliate links, which means I may receive a small commission, at no cost to you, if you make a purchase through a link


Python is a powerful programming language that has various applications in financial analysis.

Python is a powerful programming language that has various applications in financial analysis. Thanks to multiple free and powerful dictionaries, Python can play a significant role in financial analysis. Apart from that, it helps stakeholders to observe and make data-driven decisions. Financial modeling, Data analysis, Automation, Visualization and algorithm trading are all the products of implementing Python in economic analysis. However, in this article, I will introduce you to one of the most comprehensive and useful libraries that can help us in fundamental and technical analysis. Yahoo Finance is a well-known service that provides a large variety of financial data. 'yfinance' is the name of a library in Python that contains Yahoo Finance information. It can help us diversify our portfolio efficiently, study the relationship between symbols, and to facilitate the process of data gathering and decision-making. You may get a variety of data from Yahoo Finance using the yfinance library, including:

  • Historical stock prices: Include daily or weekly performance information for a specific stock or index and historical prices for a particular stock, index, or currency pair.

  • Financial statements: Retrieving the balance sheet, income statement, and statement of cash flows for a particular stock.

  • Market information: Such as the market capitalization and trade volume, for a particular sector or industry.

  • Company information: Information about a specific company, including the company's name, ticker symbol, industry, sector, and stakeholders.

Now we see how Python can practically help us with the financial analysis.


Diversifying Portfolio

Financial modeling, Data analysis, Automation, Visualization and algorithm trading are all the products of implementing Python in economic analysis.

One of the implementations of this system is to diversify the portfolio better. Since we would like to try not to put all the eggs in a basket, we may do it unintentionally. A common strategy in all investment activities is avoiding similar assets to decrease the risk of unforeseen events. We may think that we have diversified our portfolio, but sometimes our decision is more of a gut feeling than a mathematical fact. Imagine in your portfolio, you have shares of Google and Walt Disney. We are trying to figure out how our portfolio is diversified. We continue with the analysis of this example in Python.

  • If you are not familiar with Python, there is no problem. Here we go through the analysis step by step.

  • If you do not have a Jupyter Notebook installed, I recommend using Google Colab.


First, we install the library.

!pip install yfinance


Then, we load the libraries.

import yfinance as yf import matplotlib.pyplot as plt import pandas as pd


Then, we continue with importing data and extracting close prices.

# Fetch the stock data for GOOG and DIS goog = yf.Ticker("GOOG").history(period="1y") dis = yf.Ticker("DIS").history(period="1y") # Extract the Close column for each stock goog_close = goog['Close'] dis_close = dis['Close']


Now, we calculate the correlation between these two prices.

# Calculate the correlation between the two stocks correlation = goog_close.corr(dis_close)


And printing.

# Print the correlation print(f"Correlation between GOOG and DIS: {correlation:.2f}")

Correlation between GOOG and DIS.










# Plot the closing prices of the two stocks plt.plot(goog_close, label='GOOG') plt.plot(dis_close, label='DIS') plt.legend() plt.show()


Here we notice that the correlation between two stocks (0.9) and the fluctuation in their plots also confirms this correlation. This finding suggests that Walt Disney and Google are potentially behaving similarly if an unpredicted situation happens. Therefore, we shouldn’t solely rely on this pair to diversify our portfolio. This procedure can be applied to other assets to understand the portfolio's volatility better.


Fundamental Analysis

Another practical utilization of yfinance relates to fundamental analysis.

Another practical utilization of yfinance relates to fundamental analysis. There is a ton of fundamental financial information for each company and finding them individually and processing each one by one seem to be exhausting. This library can save us from this torment and frustration. Imagine we would like to do a fundamental analysis of Apple. So, let’s see in the following how it goes.


We retrieve Apple's revenues and earnings data with just a few lines of scripts.

import yfinance as yf import pandas as pd

Funamental Analysis: Retrieve Apple's revenues and earnings data.









aapl = yf.Ticker('aapl') info = aapl.info aapl.earnings


Here, with the following code we can access a more detailed list of Income Statement records.

aapl.get_financials().head(10)


The Income Statement









Imagine if we want more information about a company's stakeholders. This code shows us the holders of Apple.

aapl.institutional_holders


We can study the underlying relationship between the prices of stocks and accurately investigate the financial records such as balance sheet, stakeholders, cash flow, etc.

In fact, the amount of financial data we are able to gather with this library is quite large and comprehensive. For instance, all of these categories of information are accessible in the library, and they are at the operator's disposal.




Conclusion

Python is a powerful programming language with a variety of abilities. In fact, multiple libraries can be utilized for a financial analysis, and 'yfinance' is one of them. Thus, using this library, we can study the underlying relationship between the prices of stocks and accurately investigate the financial records such as balance sheet, stakeholders, cash flow, etc. Therefore, it can help decision-makers for more precise and faster decisions. However, it is worth mentioning yfinance is an unofficial library and it increases the probability of poor maintenance when a failure and problem occurs. Moreover, it might not be a perfect solution for real-time analysis.


Binance offers a secure platform with cutting-edge security features and regulatory compliance, ensuring the protection of your transactions.


 

Reference List:


Comentários


bottom of page