The first requirement is to ensure that yfinance is installed. If using Google Colab, install the required libraries:
!pipinstallyfinanceplotlypandas
After installing the yfinance library, the next step is to import the libraries and load the data. The yfinance library has the alias yf.
import yfinance as yfimport plotly.express as pximport pandas as pd
To fetch data from yfinance, choose the stock ticker and the date range. In this case, we are going to examine Boeing, a company with the ticker "BA", for the date range of January 1, 2023 to December 31, 2025. This will provide all the available data for 2025.
The download function has the parameters ticker, start, and end. Note that the format for the dates are "YYYY-MM-DD", so January 1, 2023 is written as "2023-01-01".
# Step 1: Fetch Boeing stock dataticker ='BA'# Ticker symbol for Boeingstart_date ='2023-01-01'end_date ='2025-12-31'# Fetch historical databoeing_data = yf.download(ticker,start=start_date,end=end_date)# Step 2: Prepare the data# Reset the index to make the 'Date' column accessibleboeing_data.reset_index(inplace=True)
By default, the yfinance returns the Date as a row name and not a column. The line reset_index(inplace=True) makes the Date a column. You must run only once and directly after you run yf.download().