Javatpoint Logo
Javatpoint Logo

Python yfinance Module

There are many instances when we have to get financial data or statements of a blogging site or even a browser sometimes. One of the famous browsers that allow us to collect its financial data is Yahoo, and actually, there are many instances when we need to perform this task. In this tutorial, we are going to learn about the yfinance module in Python, and we will learn how we can get financial data from Yahoo using this module and what kind of data we can collect from it.

yfinance Module in Python

The yfinance is one of the famous modules in Python, which is used to collect online data, and with it, we can collect the financial data of Yahoo. With the help of the yfinance module, we retrieve and collect the company's financial information (such as financial ratios, etc.) as well as the histories of marketing data by using its functions. But, before we start learning more about this module and its implementation as well as applications, we have to install the yfinance module in our system (as it is not a built-in module in Python). Once the installation process is done, we will proceed to the implementation part of the yfinance module.

Installation

In this section, we will learn how we can install the yfinance module in our system so that we can import it into a program and use its functions. We have to follow the following steps to install the yfinance module on our device:

Step 1: Open the command prompt terminal of the device and locate the directory (using mkdir) where Python is installed in the system.

Step 2: Now write the following command in the terminal to install the yfinance module with pip installer:


Python yfinance Module

Step 3: When we will press the enter key, the pip installer will start installing the yfinance module in the system at the defined path.

Python yfinance Module

As we can see, the yfinance module is successfully installed in our system, and now we can start working with it by importing it into a Python program.

Implementation

Now, we will use the yfinance module in our Python program so that we can collect the financial data from Yahoo using it and understand its implementation. When we are using the yfinance module in our program, we have to pass the ticker as an argument inside the function (Here, Ticker is referred to as the ticker of a company).

Note: A ticker is basically a stock symbol or unique series of alphabets for the company names, and it is assigned to add an extra security layer for trading purposes. Look at the following examples of tickers that we will use in the yfinance module:

  • Ticker for Google is "GOOGL"
  • The ticker for Facebook is "FB"
  • and, Ticker for Amazon is "AMZN", etc.

Now, let's use the yfinance module in various example programs so that we can understand its function and implementation easily. Look at the following example programs using the yfinance module in them for collecting data:

Example 1:

Look at the following Python program where we will retrieve the financial data of Facebook from Yahoo finance:

Output:

{'zip': '94025', 'sector': 'Communication Services', 'fullTimeEmployees': 63404, 'longBusinessSummary': "Facebook, Inc. develops products that enable people to connect and share with friends and family through mobile devices, personal computers, virtual reality headsets, and in-home devices worldwide. The company's products include Facebook that enables people to connect, share, discover, and communicate with each other on mobile devices and personal computers; Instagram, a community for sharing photos, videos, and private messages; Messenger, a messaging application for people to connect with friends, family, groups, and businesses across platforms and devices; and WhatsApp, a messaging application that is used by people and businesses to communicate in a private way. It also provides Facebook Reality Labs, an augmented and virtual reality product that help people feel connected, anytime, and anywhere. Facebook, Inc. was founded in 2004 and is headquartered in Menlo Park, California.", 'city': 'Menlo Park', 'phone': '650-543-4800', 'state': 'CA', 'country': 'United States', 'companyOfficers': [], 'website': 'http://investor.fb.com', 'maxAge': 1, 'address1': '1601 Willow Road', 'industry': 'Internet Content & Information', 'ebitdaMargins': 0.49698, 'profitMargins': 0.37175998, 'grossMargins': 0.80977, 'operatingCashflow': 49358000128, 'revenueGrowth': 0.556, 'operatingMargins': 0.42523, 'ebitda': 52079001600, 'targetLowPrice': 225, 'recommendationKey': 'buy', 'grossProfits': 69273000000, 'freeCashflow': 22740000768, 'targetMedianPrice': 425, 'currentPrice': 330.05, 'earningsGrowth': 1.006, 'currentRatio': 5.425, 'returnOnAssets': 0.17950001, 'numberOfAnalystOpinions': 50, 'targetMeanPrice': 417.22, 'debtToEquity': 9.089, 'returnOnEquity': 0.31332, 'targetHighPrice': 500, 'totalCash': 64079998976, 'totalDebt': 12563000320, 'totalRevenue': 104789999616, 'totalCashPerShare': 22.728, 'financialCurrency': 'USD', 'revenuePerShare': 36.82, 'quickRatio': 5.095, 'recommendationMean': 1.9, 'exchange': 'NMS', 'shortName': 'Facebook, Inc.', 'longName': 'Facebook, Inc.', 'exchangeTimezone

Explanation:

We have firstly imported the yfinance module as yahooFin in the program to use its functionality. Then, we have used the yahooFin with the FB Ticker function to collect all the financial information of the Facebook page from Yahoo. After retrieving the financial information from the Facebook page of Yahoo, we have printed this information in the output when the program is executed.

As we can see in the output, we have printed all the financial data as a whole Python dictionary.

Collecting Financial Key Metrics from Yahoo:

Other than retrieving the financial information from Yahoo sites (as we have performed in example 1), we can even collect various financial key metrics. These financial key metrics can be Price Earnings Ratio, Company Beta and Company Sector etc., from the whole Python dictionary that we printed in the above first example. Let's retrieve the financial key metrics by using the yfinance module.

Example 2:

Look at the following Python program where we will retrieve the financial key metrics from the Yahoo using yfinance module:

Output:

The Company Sector Metric key we collected from the page:  Communication Services
The Price Earnings Ratio (PER) we got from the financial data of page:  26.211199
The Company Beta key we retrieved from page:  1.295305

Explanation:

Instead of retrieving complete financial data information from the page, we have retrieved only a limited set of financial key metrics in this program. We have firstly initialized three variables (keyPer, comSecKey and comBetaKey) and stored the values of financial key metrics from the financial data we have collected from the Facebook page. We have retrieved Price Earning Ratio, Company Beta and Company Sector financial metric keys in this example and stored them in the respective variable. After storing the financial metric keys, we have printed them in the output as a result, and as we can see in the output, details are successfully printed.

Splitting the financial metric keys:

In the first and second examples, we have printed the financial data and metric keys from Yahoo as they are some dictionary values. But we can even split these values by means of key-value pair, and then we can print the split result. In the following example, we will print the financial metric keys values by splitting them, and we will split them by looping over them.

Example 3:

Look at the following Python program, where we will split the financial metric keys into key-value pairs:

Output:

Items from the financial data of the Facebook page in the key-value page: 
zip : 94025
sector : Communication Services
fullTimeEmployees : 63404
longBusinessSummary : Facebook, Inc. develops products that enable people to connect and share with friends and family through mobile devices, personal computers, virtual reality headsets, and in-home devices worldwide. The company's products include Facebook that enables people to connect, share, discover, and communicate with each other on mobile devices and personal computers; Instagram, a community for sharing photos, videos, and private messages; Messenger, a messaging application for people to connect with friends, family, groups, and businesses across platforms and devices; and WhatsApp, a messaging application that is used by people and businesses to communicate in a private way. It also provides Facebook Reality Labs, an augmented and virtual reality product that help people feel connected, anytime, and anywhere. Facebook, Inc. was founded in 2004 and is headquartered in Menlo Park, California.
city : Menlo Park
phone : 650-543-4800
state : CA
country : United States
companyOfficers : []
website : http://investor.fb.com
maxAge : 1
address1 : 1601 Willow Road
industry : Internet Content & Information
ebitdaMargins : 0.49698
profitMargins : 0.37175998
grossMargins : 0.80977
operatingCashflow : 49358000128
revenueGrowth : 0.556
operatingMargins : 0.42523
ebitda : 52079001600

Explanation:

After retrieving information from the Facebook financial data from Yahoo, we have used for loop on it. With the help of for loop, we have looped over the data, and then we split the data items into key-value pairs. In last, we have printed these key-value pairs in the output as a result of the program.

Retrieving Historical Market Prices:

We can even retrieve the historical market prices from Yahoo financial data, and then we can even print this information in the output.

Example 4:

Let's first look at the following example, and then we will understand more about retrieving historical market prices:

Output:

Historical Market Prices data from the Facebook page financial data of Yahoo: 
                  Open        High         Low       Close     Volume  \
Date                                                                    
2012-05-18   42.049999   45.000000   38.000000   38.230000  573576400   
2012-05-21   36.529999   36.660000   33.000000   34.029999  168192700   
2012-05-22   32.610001   33.590000   30.940001   31.000000  101786600   
2012-05-23   31.370001   32.500000   31.360001   32.000000   73600000   
2012-05-24   32.950001   33.209999   31.770000   33.029999   50237200   
...                ...         ...         ...         ...        ...   
2021-10-04  335.529999  335.940002  322.700012  326.230011   42885000   
2021-10-05  328.579987  335.179993  326.160004  332.959991   35377900   
2021-10-06  329.739990  334.380005  325.799988  333.640015   26443000   
2021-10-07  337.000000  338.839996  328.980011  329.220001   28307500   
2021-10-08  331.510010  333.399994  328.709991  330.049988   15934300   

            Dividends  Stock Splits  
Date                                 
2012-05-18          0             0  
2012-05-21          0             0  
2012-05-22          0             0  
2012-05-23          0             0  
2012-05-24          0             0  
...               ...           ...  
2021-10-04          0             0  
2021-10-05          0             0  
2021-10-06          0             0  
2021-10-07          0             0  
2021-10-08          0             0  

[2364 rows x 7 columns]

Explanation:

In this example, we have imported the historical market prices from Facebook's financial data from the Yahoo page we retrieved in the program. We have retrieved the historical market prices from Facebook's financial data using the history() function with the FB Ticker, and then we have stored the information inside the variable we have initialized, i.e., maxHisMP. In last, we have printed this historical market prices information in the output as a result of the program. We can see the information regarding the history of market prices for the maximum period available in the Yahoo financial data.

Note: The 'max' we have defined in the history function with the FB ticker is used to collect the history of market prices available for the maximum time period in Yahoo. The max keyword will retrieve the history of daily price changes for Facebook available in Yahoo.

Now, we have learned that how we can bring the history of market prices from Yahoo's financial data using its history() function. But here is a thing that we can even minimize our data which we are getting from history() to reduce its complexity. We can do this by giving a fixed time argument inside the history() function and retrieve only a small amount of data from Yahoo.

Here, we are going to perform this function in two ways which are following:

1. Collecting fixed time data since Last '1 day' or '5 day' or '1 month' or '3 month' etc., by providing fixed time argument inside the history function. Let's understand this by using the fixed time argument inside a program and then retrieving market prices from Yahoo.

Example 5:

Look at the following Python program where we will retrieve the last 3 month's history of market prices from Facebook:

Output:

Historical Market Prices data of last 3 months from the Facebook page of Yahoo: 
                  Open        High         Low       Close    Volume  \
Date                                                                   
2021-07-09  345.320007  350.709991  345.269989  350.420013  13018700   
2021-07-12  351.230011  354.190002  349.640015  353.160004  10018600   
2021-07-13  351.500000  358.489990  348.799988  352.089996  11456000   
2021-07-14  354.559998  355.200012  346.730011  347.630005  13894200   
2021-07-15  349.230011  349.230011  340.220001  344.459991  14781600   
...                ...         ...         ...         ...       ...   
2021-10-04  335.529999  335.940002  322.700012  326.230011  42885000   
2021-10-05  328.579987  335.179993  326.160004  332.959991  35377900   
2021-10-06  329.739990  334.380005  325.799988  333.640015  26443000   
2021-10-07  337.000000  338.839996  328.980011  329.220001  28307500   
2021-10-08  331.510010  333.399994  328.709991  330.049988  15934300   

            Dividends  Stock Splits  
Date                                 
2021-07-09          0             0  
2021-07-12          0             0  
2021-07-13          0             0  
2021-07-14          0             0  
2021-07-15          0             0  
...               ...           ...  
2021-10-04          0             0  
2021-10-05          0             0  
2021-10-06          0             0  
2021-10-07          0             0  
2021-10-08          0             0  

[65 rows x 7 columns]

Explanation:

We have used the same logic as we have used in the previous example program and collected the data of historical market prices from the Facebook page of Yahoo. But, in this program, instead of collecting the maximum data, we have limited our data by giving the argument '3mo' inside the history function so that it will only retrieve the history of market prices for the last three months only. And then, we printed this last three months market prices history in the output as a result.

As we can see in the output, the history of market prices of the Facebook page in Yahoo since only last three months have been printed.

Note: When we have to collect the data from a past fixed time, then we cannot give any duration argument in the history function because it will not be a valid argument. We have the following valid fixed time period arguments for the history function of the yfinance module: max, ytd, 10y, 5y, 2y, 1y, 6mo, 3mo, 1mo, 5d and 1d. We cannot give any other time period argument inside the history() function as it will be treated as an invalid argument, and no data of market prices history will be retrieved.

2. Collecting fixed data from the history() function by giving start time and end time as the arguments of this history() function. We can retrieve the data of the time period which we want by defining starting and end time variables and then using these variables as the arguments of the history() function. Let's understand this by using these defined time arguments inside a program and then retrieving market prices history from Yahoo.

Example 6:

Look at the following Python program where we will retrieve history of market prices from Facebook for a user defined period of time:

Output:

Historical Market Prices data of the time period we defined from the financial data of Facebook page: 
                  Open        High         Low       Close    Volume  \
Date                                                                   
2021-04-26  303.339996  305.799988  301.559998  303.040009  16172600   
2021-04-27  304.279999  305.339996  301.109985  303.570007  15309300   
2021-04-28  307.359985  310.920013  305.369995  307.100006  33907200   
2021-04-29  330.119995  331.809998  321.609985  329.510010  56526800   
2021-04-30  326.140015  329.820007  324.500000  325.079987  26332400   
...                ...         ...         ...         ...       ...   
2021-07-30  354.000000  360.730011  352.940002  356.299988  15966700   
2021-08-02  358.100006  359.399994  350.739990  351.950012  13180400   
2021-08-03  352.730011  353.769989  347.700012  351.239990  12406100   
2021-08-04  352.420013  360.480011  351.510010  358.920013  14180600   
2021-08-05  359.640015  363.899994  356.899994  362.970001  10247200   

            Dividends  Stock Splits  
Date                                 
2021-04-26          0             0  
2021-04-27          0             0  
2021-04-28          0             0  
2021-04-29          0             0  
2021-04-30          0             0  
...               ...           ...  
2021-07-30          0             0  
2021-08-02          0             0  
2021-08-03          0             0  
2021-08-04          0             0  
2021-08-05          0             0  

[72 rows x 7 columns]

Explanation:

We have imported the yfinance as well as datetime module in this program so that we can use the datetime() function of it. Then, we defined two variables where we set start and end dates in them using the datetime function of the datetime module. Then, we used these variables inside the history() function as the start and end date of retrieving data from Yahoo. We have used the start and end keyword inside the history() to set the starting date and ending date for collecting the data. That's how we will retrieve a user fixed time's market prices history from Yahoo. In last, we have printed the minimized data in the output as a result.

We can see in the output that we have got the fixed time (which we set in the program) history of market prices from Yahoo.

Conclusion

In this tutorial, we have discussed how we can use the yfinance module in a Python program to retrieve simply Yahoo's financial data or various aspects of financial data of Yahoo by using functions given in the module and then we can print this data for further use.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA