The Python Code for Fetching Stock Data from Yahoo Finance

in #yfinance7 days ago (edited)

image.png

  1. yfinance Library
    yfinance is a Python library used to fetch financial data from Yahoo Finance.
    In this code, yfinance is used to retrieve historical stock prices.

  2. List of Stock Tickers

image.png

The list contains stock tickers of various companies and indices: NVDA (NVIDIA); PLUG (Plug Power); SMCI (Super Micro Computer); AMZN (Amazon); F (Ford); AAPL (Apple); TSLA (Tesla); ^GSPC (S&P 500 index, representing the broader market).

3.Fetching Historical Data for Tesla (TSLA)

image.png

The function yf.download is used to download historical stock data.

Specifically:
'TSLA': The stock ticker for Tesla.
'2008-01-01' and '2023-12-31': The date range for fetching data (from January 1, 2008, to December 31, 2023).

The result is a DataFrame containing Tesla's historical data, including columns like:
Open: Opening price.
High: Highest price of the day.
Low: Lowest price of the day.
Close: Closing price.
Volume: Number of shares traded.

4.Initializing a DataFrame

image.png

df: A blank DataFrame is created with the same index (trading dates) as Tesla’s data.
Purpose: To store the closing prices of all stocks.

5.Loop to Fetch Stock Data

image.png

for loop iterates through each stock ticker in the list:
yf.download(i, '2008-01-01', '2023-12-31'):
Fetches historical data for the stock ticker i within the specified date range.
x["Close"]:
Extracts the "Close" column (closing price) from the resulting DataFrame.
df[i] = x["Close"]:
Adds the closing prices of the stock to the DataFrame df, naming the column after the stock ticker.

6.Displaying the Data

image.png