You’ll be using the yfinance Python library to get the current and historical stock market price data from Yahoo Finance.

Installing Required Libraries

Yahoo Finance is one of the widely used platforms that provides stock market data. You can easily download the dataset from their website, but if you want to access it directly from a Python program, you can use the yfinance library. To install yfinance using pip, you need to run the following command at a command prompt:

The yfinance Python library is free to use and it does not require an API key.

Get Current Stock Price Data

You need to have the ticker of the stock for which you want to extract the data. In the following example, we’ll be finding the market price and previous close price for GOOGL.

This produces the following output:

This example uses the regularMarketPrice and regularMarketPreviousClose properties to get the required data. The yfinance library provides numerous other properties that you can explore. These include zip, sector, fullTimeEmployees, longBusinessSummary, city, phone, state, and country. You can get the complete list of the available properties using this code:

Get Historical Stock Price Data

You can get all the historical price data by providing the start date, end date, and ticker.

This produces the following output:

The above code will fetch the stock price data from 2020-01-01 to 2022-01-01.

If you want to pull data of multiple tickers at once, you can do so by providing the tickers in the form of a space-separated string.

Transforming Data for Analysis

In the above dataset, Date is the index of the dataset and not a column. To perform any data analysis on this data, you need to convert this index into a column. Below is how you can do that:

This produces the following output:

This transformed data is the same as the data you would have downloaded from Yahoo Finance.

Storing the Received Data in a CSV File

You can export a DataFrame object to a CSV file using the to_csv() method. Since the above data is already in the form of a pandas DataFrame, you can export the data into a CSV file using the following code:

Pandas is the widely used data-analysis Python library. If you’re not much comfortable with this library, you should get started with basic operations using Pandas.

Visualize the Data

The yfinance Python library is one of the most convenient libraries to set up, fetch data, and perform data analysis tasks with. You can use this data to visualize results and capture insights using libraries like Matplotlib, Seaborn, or Bokeh.

You can even display these visualizations directly on a webpage using PyScript.