Accessing and interpreting stock data is crucial for making well-informed decisions in the financial sector. This tutorial provides a step-by-step guide for creating an all-in-one financial analysis and reporting tool using Python. We’ll explore how to retrieve historical market data from Yahoo Finance and calculate pivotal technical metrics like Simple Moving Averages, Bollinger Bands, MACD, and RSI. The tutorial also covers how to create meaningful visualizations and integrate them into custom multi-page PDF reports. If you’re a data enthusiast, financial analyst, or Python developer looking to broaden your skills, this tutorial will enable you to convert raw market data into valuable insights.
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
Essential Python libraries are imported for financial data analysis and visualization. The library yfinance is utilized for obtaining stock market data, pandas for data manipulation, matplotlib and numpy for crafting and managing numerical plots, and PdfPages for merging several plots into a single PDF report.
def compute_indicators(df):
"""
Computes technical indicators for the DataFrame:
- 20-day and 50-day Simple Moving Averages (SMA)
- Bollinger Bands (using 20-day SMA ±2 standard deviations)
- MACD (12-day EMA minus 26-day EMA) and its 9-day Signal Line
- RSI (Relative Strength Index) over a 14-day lookback period
"""
df['SMA20'] = df['Close'].rolling(window=20).mean()
df['SMA50'] = df['Close'].rolling(window=50).mean()
df['STD20'] = df['Close'].rolling(window=20).std()
df['UpperBand'] = df['SMA20'] + 2 * df['STD20']
df['LowerBand'] = df['SMA20'] - 2 * df['STD20']
df['EMA12'] = df['Close'].ewm(span=12, adjust=False).mean()
df['EMA26'] = df['Close'].ewm(span=26, adjust=False).mean()
df['MACD'] = df['EMA12'] - df['EMA26']
df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
delta = df['Close'].diff()
gain = delta.copy()
loss = delta.copy()
gain[gain 0] = 0
loss = loss.abs()
avg_gain = gain.rolling(window=14).mean()
avg_loss = loss.rolling(window=14).mean()
rs = avg_gain / avg_loss
df['RSI'] = 100 - (100 / (1 + rs))
return df
The function calculates essential technical indicators for stock prices present in the input DataFrame, including SMAs, Bollinger Bands, MACD, and RSI. It adds new columns for each indicator to the DataFrame, facilitating detailed technical evaluation of past stock performance.
def create_cover_page(pdf):
"""
Creates and saves a cover page into the PDF report.
"""
fig = plt.figure(figsize=(11.69, 8.27))
plt.axis('off')
plt.text(0.5, 0.7, "Financial Analysis Report", fontsize=24, ha='center')
plt.text(0.5, 0.62, "Analysis of 5 Stocks from Yahoo Finance", fontsize=16, ha='center')
plt.text(0.5, 0.5, "Includes Technical Indicators: SMA, Bollinger Bands, MACD, RSI", fontsize=12, ha='center')
plt.text(0.5, 0.4, "Generated with Python and matplotlib", fontsize=10, ha='center')
pdf.savefig(fig)