Home / AI / Mastering Finance Analytics: From Yahoo Data Extraction to Customized PDF Reports

Mastering Finance Analytics: From Yahoo Data Extraction to Customized PDF Reports

Analyzing stock data is crucial for making informed decisions in the financial sector. This tutorial provides a detailed guide on creating a financial analysis and reporting tool using Python. You will learn how to obtain historical market data from Yahoo Finance and calculate important technical indicators such as Simple Moving Averages, Bollinger Bands, MACD, and RSI. The tutorial includes instructions on creating insightful visualizations and compiling them into customized multi-page PDF reports. If you are a data enthusiast, financial analyst, or Python developer eager to expand your skills, this tutorial will help you convert raw market data into meaningful 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

We import essential Python libraries for financial data analysis and visualization. Here, yfinance is used to fetch stock market data, pandas for data manipulation, matplotlib and numpy for creating and handling numerical plots, and PdfPages for compiling multiple 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.clip(lower=0)
    loss = delta.clip(upper=0).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

This function computes key technical indicators—including SMAs, Bollinger Bands, MACD, and RSI—for stock price data contained in the input DataFrame. It updates the DataFrame with additional columns for each indicator, enabling in-depth technical analysis of historical 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)
    plt.close(fig)

This function creates a visually appealing cover page using matplotlib and adds it as the first page of the PDF report using the provided PdfPages object. It then closes the figure to free up resources.

<div class="dm-code-snippet" style=

Deje un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *