Automate Stock Analysis with Python and Yfinance: Generate Excel Reports

In this article, we will explore how to analyze stocks using Python and Excel. We will fetch historical data for three popular stocks—Realty Income (O), McDonald’s (MCD), and Johnson & Johnson (JNJ) — calculate returns, factor in dividends, and visualize the results in an Excel report. By the end of this guide, you will have a fully automated stock analysis tool that you can use for your own investments.

Close prices of [O, MCD, JNJ] for the period of 2020 to 2023.

Why Python and Excel?

Python is a powerful programming language that excels at data analysis and automation. Excel, on the other hand, is a widely-used tool for data visualization and reporting. By combining the two, we can leverage the strengths of both platforms: Python for data processing and Excel for presentation.

Step 1: Fetching Historical Data

We start by fetching historical stock data using the yfinance  library. This library provides an easy way to access financial data from Yahoo Finance. We define the stock tickers and download the closing prices from January 1, 2020, to January 1, 2023. The Close  column contains the daily closing prices for each stock.


Step 2: Calculating Daily and Cumulative Returns

Next, we calculate the daily returns, which show the percentage change in stock prices each day. We then use these daily returns to calculate the cumulative returns, which represent the total growth of an investment over time.

Example of Cumulative Returns

Suppose a stock has the following daily returns:

  • Day 1: 0.02 (2%)
  • Day 2: 0.03 (3%)
  • Day 3: -0.01 (-1%)

We convert these returns into growth factors by adding 1:

  • Day 1: 1.02
  • Day 2: 1.03
  • Day 3: 0.99

The cumulative return after three days is calculated as:

This means the investment has grown by 4.01% over the three-day period.


Step 3: Fetching Dividend Data

Dividends are payments made by a company to its shareholders. We fetch dividend data for each stock using the yfinance library.


Step 4: Adjusting Cumulative Returns for Dividends

To include dividends in our analysis, we convert the dividend data into daily returns and add them to the stock returns. We then recalculate the cumulative returns.


Step 5: Calculating Moving Averages

Moving averages help smooth out short-term fluctuations and identify trends. We calculate the 50-day moving average for each stock.


Step 6: Aggregating Dividends by Month and Year

To better analyze dividend payments, we aggregate the data by month and year.


Step 7: Creating an Excel Workbook

We use the openpyxl  library to create an Excel workbook and add the processed data to separate sheets. This includes raw stock data, cumulative returns, moving averages, monthly dividends, and yearly dividends.


Step 8: Visualizing the Data

We create a line chart of the stock prices over time and embed it in the Excel workbook.


Step 9: Saving the Excel File

Finally, we save the Excel file with a unique timestamp to avoid overwriting previous reports.


What You Will Get

  1. Excel File:
    • A file named YYMMDDHHMMSS__Stock_Analysis.xlsx  with five sheets:
      • Stock Data: Raw closing prices
      • Cumulative Returns: Cumulative returns (with dividends)
      • Moving Averages: 50-day moving averages
      • Monthly Dividends: Dividend data aggregated by month
      • Yearly Dividends: Dividend data aggregated by year
    • A plot of the stock prices embedded in the Stock Data sheet.
  2. Console Output:
    • Confirmation messages for each step (e.g., Excel file saved as 231015123045__Stock_Analysis.xlsx).

The YouTube video for the article is here:

The full code is available both below and in GitHub.

Enjoy your day! 🙂

Tagged with: , , , , , ,