Generative AI

Guide that is coded Code Analytics for issuing Yahoo Financial Data, Currency Processing, and Construction of PDF Custom Reports

Exception and analyzing the stock data is the key to introducing decisions to financial decisions. This lesson provides the full guide to create an integrated financial analysis and reporting tool in Python. We will learn to pull the history market data from the Yahoo Finance and important technologies such as simple travel ratings, Bollinger Bands, Macd, and RSI. The guide moves with you by producing understanding and separates them from PDF custom reports. Whether you are a data lover, a financial analyst, or Python developer looks to grow your tools, this lesson will equip you with skills helping the green market data into effective recognition.

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 the keynics of the Python information for financial data analysis and navigation. Here, the YFinance is used to download stock market data, pandas delicate data, matplotlib and a numpy construction and management of numbers, and the PDfpages to cover multiple sites with one 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 > 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

This work includes important technologies – including SMASs, Bollinger Bands, Macd, and RSI-for stock price contained in the installation data data. Reviewing the databame in the formal columns in each index, enabling the deep technological analysis of historical stock.

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 work creates a lovely cover page by using matplotlib and adds it as the first PDF report page with a given PDFTE item. Then to close the number to free the resources.

def plot_price_chart(ticker, df):
    """
    Generates a price chart with SMA and Bollinger Bands for a given ticker.
    """
    fig, ax = plt.subplots(figsize=(14, 7))
    ax.plot(df.index, df['Close'], label="Close Price", linewidth=1.5)
    ax.plot(df.index, df['SMA20'], label="SMA (20)", linewidth=1.2)
    ax.plot(df.index, df['SMA50'], label="SMA (50)", linewidth=1.2)
    ax.plot(df.index, df['UpperBand'], label="Upper Bollinger Band", linestyle="--")
    ax.plot(df.index, df['LowerBand'], label="Lower Bollinger Band", linestyle="--")
    ax.fill_between(df.index, df['LowerBand'], df['UpperBand'], color="lightgray", alpha=0.3)
    ax.set_title(f'{ticker}: Price & Moving Averages with Bollinger Bands')
    ax.set_xlabel('Date')
    ax.set_ylabel('Price')
    ax.legend()
    ax.grid(True)
    return fig

This work produces a wide range of stocks that includes the nearest value, 20 SMAs and 50 days, and Bollinger bands. Returns the Mattplotlib number or resumed in the PDF report.

def plot_macd_chart(ticker, df):
    """
    Generates a MACD plot for the given ticker.
    """
    fig, ax = plt.subplots(figsize=(14, 5))
    ax.plot(df.index, df['MACD'], label="MACD", linewidth=1.5)
    ax.plot(df.index, df['Signal'], label="Signal Line", linewidth=1.5)
    ax.set_title(f'{ticker}: MACD')
    ax.set_xlabel('Date')
    ax.set_ylabel('MACD')
    ax.legend()
    ax.grid(True)
    return fig

This work produces a MACD chart of the cell specified by planning a macd and its signal line over time. Returns the matplotlib number that can be included in a large PDF report or displayed independently.

def plot_rsi_chart(ticker, df):
    """
    Generates an RSI plot for the given ticker.
    """
    fig, ax = plt.subplots(figsize=(14, 5))
    ax.plot(df.index, df['RSI'], label="RSI", linewidth=1.5)
    ax.axhline(70, color="red", linestyle="--", linewidth=1, label="Overbought (70)")
    ax.axhline(30, color="green", linestyle="--", linewidth=1, label="Oversold (30)")
    ax.set_title(f'{ticker}: RSI')
    ax.set_xlabel('Date')
    ax.set_ylabel('RSI')
    ax.legend()
    ax.grid(True)
    return fig

This work produces the RSI chart with the stock storage, planning RSI prices and horizontal reference lines at high (70) and the Oviersold (30). Returns the matplotlib number that can be included in the final report for financial analysis.

def main():
    tickers = []
    for i in range(5):
        ticker = input(f"Enter ticker #{i+1}: ").upper().strip()
        tickers.append(ticker)
   
    pdf_filename = "financial_report.pdf"
   
    with PdfPages(pdf_filename) as pdf:
        create_cover_page(pdf)


        for ticker in tickers:
            print(f"Downloading data for {ticker} from Yahoo Finance...")
            df = yf.download(ticker, period='1y')
           
            if df.empty:
                print(f"No data found for {ticker}. Skipping to the next ticker.")
                continue
           
            df = compute_indicators(df)
           
            fig_price = plot_price_chart(ticker, df)
            pdf.savefig(fig_price)
            plt.close(fig_price)
           
            fig_macd = plot_macd_chart(ticker, df)
            pdf.savefig(fig_macd)
            plt.close(fig_macd)
           
            fig_rsi = plot_rsi_chart(ticker, df)
            pdf.savefig(fig_rsi)
            plt.close(fig_rsi)
   
    print(f"PDF report generated and saved as '{pdf_filename}'.")

Here, the main function moves the user to submit a single-year stock tickets, to download each year of each data from Yahoo, and compatible charts, as well as the RSI charts, and RSIs, and RSIs. Then it includes all the charts in the PDF report called Financial_report.PDF “and print a confirmation message when the report is saved.

if __name__ == "__main__":
    main()

Finally, this block tests whether the text is done directly rather than being submitted as module. If so, it costs the main function ().

In conclusion, show how to change financial analysis using the Python. You learn how to remove important data, calculate technical indicators, and produce complete visual reports in the PDF format with a lot of page. This integrated approach is moving the analysis process and provides a strong approach to market styles and monitoring the stock. As you continue to customize and expansion, you can continue to improve your analysis strength and make additional financial decisions.


Here is the Colab Notebook. Also, don't forget to follow Sane and join ours Telegraph station including LinkedIn Grtopic. Don't forget to join ours 85k + ml subreddit.

🔥 [Register Now] Summit of the Minicon Virtual in Agentic AI: Free Registration + Certificate of Before Hour 4 Hour Court (May 21, 9 AM


Sana Hassan, a contact in MarktechPost with a student of the Dual-degree student in the IIit Madras, loves to use technology and ai to deal with the real challenges of the world. I'm very interested in solving practical problems, brings a new view of ai solution to AI and real solutions.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button