Downloading and Exporting Stock Market Data with yfinance, pandas, and Python
In this blog post, we will demonstrate how to download historical stock prices using the
yfinance library and Python, and then export the data to an Excel file. We will create a list of stock tickers, define a time range, download the closing prices for each ticker within that time range, and store the closing prices in a DataFrame. Finally, we will export the DataFrame to an Excel file.
import yfinance as yf import pandas as pd from datetime import datetime, timedelta import os
We begin by importing the necessary libraries:
yfinance library allows us to download financial data from Yahoo Finance, while
pandas helps us manage the data efficiently.
Section 1: Define Tickers and Time Range
## Define the list of tickers tickers = ['SPY','BND','GLD','QQQ','VTI'] ## Set the end date to today end_date = datetime.today() print(end_date) ## Set the start date to 2 years ago start_date = end_date - timedelta(days = 2*365) print(start_date)
In this section, we define a list of stock tickers that we want to download historical prices for. We then set the end date to the current date and the start date to two years ago using the
Section 2: Download Close Prices
## Create an empty DataFrame to store the close prices close_df = pd.DataFrame() ## Download the close prices for each ticker for ticker in tickers: data = yf.download(ticker, start = start_date, end = end_date) close_df[ticker] = data['Close'] ## Display the DataFrame print(close_df)
In this section, we create an empty DataFrame called
close_df to store the closing prices for each stock ticker. We then loop through each ticker in the
tickers list and download the historical data using the
yf.download() function. We add the closing prices to the
close_df DataFrame and print the result.
Section 3: Set Output Folder and Export Data
## Set the output folder path output_folder = r"C:\Users\Ryan\Documents\YouTube Videos\Python Tutorials\Retrieve Stock Prices and Export to Excel" ## Export the DataFrame to Excel output_file = os.path.join(output_folder, 'stock_prices.xlsx') close_df.to_excel(output_file)
In this final section, we set the output folder path where we want to save the Excel file containing the historical stock prices. We then use the
to_excel() function from the
pandas library to export the
close_df DataFrame to an Excel file.
In this blog post, we demonstrated how to download historical stock prices using the
yfinance library and Python, and then export the data to an Excel file. By creating a list of stock tickers, defining a time range, downloading the closing prices for each ticker within that time range, and exporting the data to an Excel file, we can easily analyze stock performance and gain insights into market trends.