Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 3, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 3, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 3, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 3, 2025

      SteelSeries reveals new Arctis Nova 3 Wireless headset series for Xbox, PlayStation, Nintendo Switch, and PC

      June 3, 2025

      The Witcher 4 looks absolutely amazing in UE5 technical presentation at State of Unreal 2025

      June 3, 2025

      Razer’s having another go at making it so you never have to charge your wireless gaming mouse, and this time it might have nailed it

      June 3, 2025

      Alienware’s rumored laptop could be the first to feature NVIDIA’s revolutionary Arm-based APU

      June 3, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      easy-live2d – About Make your Live2D as easy to control as a pixi sprite! Live2D Web SDK based on Pixi.js.

      June 3, 2025
      Recent

      easy-live2d – About Make your Live2D as easy to control as a pixi sprite! Live2D Web SDK based on Pixi.js.

      June 3, 2025

      From Kitchen To Conversion

      June 3, 2025

      Perficient Included in Forrester’s AI Technical Services Landscape, Q2 2025

      June 3, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      SteelSeries reveals new Arctis Nova 3 Wireless headset series for Xbox, PlayStation, Nintendo Switch, and PC

      June 3, 2025
      Recent

      SteelSeries reveals new Arctis Nova 3 Wireless headset series for Xbox, PlayStation, Nintendo Switch, and PC

      June 3, 2025

      The Witcher 4 looks absolutely amazing in UE5 technical presentation at State of Unreal 2025

      June 3, 2025

      Razer’s having another go at making it so you never have to charge your wireless gaming mouse, and this time it might have nailed it

      June 3, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»FinData Explorer: A Step-by-Step Tutorial Using BeautifulSoup, yfinance, matplotlib, ipywidgets, and fpdf for Financial Data Extraction, Interactive Visualization, and Dynamic PDF Report Generation

    FinData Explorer: A Step-by-Step Tutorial Using BeautifulSoup, yfinance, matplotlib, ipywidgets, and fpdf for Financial Data Extraction, Interactive Visualization, and Dynamic PDF Report Generation

    February 25, 2025

    In this tutorial, we will guide you through building an advanced financial data reporting tool on Google Colab by combining multiple Python libraries. You’ll learn how to scrape live financial data from web pages, retrieve historical stock data using yfinance, and visualize trends with matplotlib. Also, the tutorial demonstrates how to integrate an interactive UI using ipywidgets, culminating in a dynamic PDF report generated with FPDF.

    Copy CodeCopiedUse a different Browser
    !pip install fpdf beautifulsoup4 yfinance ipywidgets

    First, we install the necessary libraries for our project: fpdf for generating PDF reports, beautifulsoup4 for web scraping, yfinance for retrieving historical financial data, and ipywidgets for creating interactive UI elements in the notebook.

    Copy CodeCopiedUse a different Browser
    import requests
    from bs4 import BeautifulSoup
    from fpdf import FPDF
    import yfinance as yf
    import matplotlib.pyplot as plt
    import ipywidgets as widgets
    from IPython.display import display, FileLink

    Here, we import a range of libraries to build a comprehensive financial data tool.

    Copy CodeCopiedUse a different Browser
    def generate_report(b):
        symbol = symbol_text.value.upper().strip()
        start_date = start_date_picker.value
        end_date = end_date_picker.value
       
        output_area.clear_output()  # Clear previous outputs
       
        if not (symbol and start_date and end_date):
            with output_area:
                print("Please provide valid inputs for stock symbol and both dates.")
            return
       
        with output_area:
            print(f"Generating report for {symbol} from {start_date} to {end_date}...")
       
        # 1. Retrieve current price using yfinance
        try:
            stock = yf.Ticker(symbol)
            current_price = stock.info.get('regularMarketPrice', 'N/A')
        except Exception as e:
            current_price = "Error retrieving price"
            with output_area:
                print("Error retrieving current price:", e)
       
        # 2. Fetch historical data using yfinance
        try:
            hist = stock.history(start=start_date, end=end_date)
        except Exception as e:
            hist = None
            with output_area:
                print("Error fetching historical data:", e)
       
        # 3. Plot historical closing prices
        if hist is not None and not hist.empty:
            plt.figure(figsize=(10, 5))
            plt.plot(hist.index, hist['Close'], marker='o', linestyle='-', label="Close Price")
            plt.title(f"{symbol} Historical Closing Prices")
            plt.xlabel("Date")
            plt.ylabel("Close Price (USD)")
            plt.grid(True)
            plt.xticks(rotation=45)
            plt.tight_layout()
            graph_filename = "graph.png"
            plt.savefig(graph_filename)
            plt.show()
        else:
            graph_filename = None
            with output_area:
                print("No historical data available for the selected date range.")
       
        # 4. Create a PDF report using FPDF
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", "B", 16)
        pdf.cell(0, 10, f"Financial Report for {symbol}", ln=True, align="C")
        pdf.ln(10)
       
        pdf.set_font("Arial", size=12)
        pdf.cell(0, 10, f"Current Price: {current_price}", ln=True)
        pdf.cell(0, 10, f"Date Range: {start_date} to {end_date}", ln=True)
        pdf.ln(10)
       
        if graph_filename:
            pdf.cell(0, 10, "Historical Closing Prices:", ln=True)
            # Adjust the image width to fit the page layout
            pdf.image(graph_filename, w=180)
       
        pdf_filename = "financial_report.pdf"
        pdf.output(pdf_filename)
       
        # 5. Display the download link for the PDF report
        with output_area:
            print(f"PDF Report generated: {pdf_filename}")
            display(FileLink(pdf_filename))
    

    With the above function, we retrieve user inputs for the stock symbol and date range, then scrape the current financial data from Yahoo Finance while fetching historical data via yfinance. It plots the historical closing prices using matplotlib, generates a PDF report embedding the scraped data and the graph using FPDF, and finally displays a download link for the PDF report.

    Copy CodeCopiedUse a different Browser
    # Create UI widgets
    symbol_text = widgets.Text(
        value="AAPL",
        description="Stock Symbol:",
        placeholder="e.g., AAPL"
    )
    start_date_picker = widgets.DatePicker(
        description='Start Date'
    )
    end_date_picker = widgets.DatePicker(
        description='End Date'
    )
    generate_button = widgets.Button(
        description="Generate Report",
        button_style='success'
    )
    output_area = widgets.Output()
    
    
    generate_button.on_click(generate_report)
    
    
    display(widgets.VBox([symbol_text, start_date_picker, end_date_picker, generate_button, output_area]))
    

    Finally, this code block sets up an interactive user interface using ipywidgets. It creates input fields for a stock symbol, date pickers for a start and end date, and a button to trigger the report generation. The UI elements are then organized vertically using a VBox layout, and an output area is provided to display feedback and the generated PDF download link.

    Output and PDF Sample

    In conclusion, by following this tutorial, you have successfully integrated web scraping, data analysis, interactive UI design, and PDF report generation into a single Google Colab notebook. This step-by-step process illustrates how to harness the power of Python’s diverse libraries to create a robust, user-friendly financial data tool.


    Here is the Colab Notebook for the above project. Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 80k+ ML SubReddit.

    🚨 Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets

    The post FinData Explorer: A Step-by-Step Tutorial Using BeautifulSoup, yfinance, matplotlib, ipywidgets, and fpdf for Financial Data Extraction, Interactive Visualization, and Dynamic PDF Report Generation appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleConvergence Releases Proxy Lite: A Mini, Open-Weights Version of Proxy Assistant Performing Pretty Well on UI Navigation Tasks
    Next Article Enhancing Instruction Tuning in LLMs: A Diversity-Aware Data Selection Strategy Using Sparse Autoencoders

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    June 3, 2025
    Machine Learning

    Distillation Scaling Laws

    June 3, 2025
    Leave A Reply Cancel Reply

    Hostinger

    Continue Reading

    Zypper ottimizza le prestazioni con download paralleli sperimentali

    Linux

    Nearly 1 Million Vulnerable Fortinet, SonicWall Devices Exposed to the Web

    Development

    EA has canceled yet another game, shuttered its developer, and started more layoffs

    News & Updates

    Rest Assured – Schema to use cannot be null

    Development

    Highlights

    Development

    CERT-UA Warns of Escalating Cyberattacks Targeting Ukraine’s Defense Sector with DarkCrystal RAT

    March 21, 2025

    The Government Computer Emergency Response Team (CERT-UA) issued an important warning about a series of…

    New Qilin Ransomware Attack Uses VPN Credentials, Steals Chrome Data

    August 23, 2024

    CVE-2025-3496 – D-Link Bluetooth/RS-232 Buffer Overflow Vulnerability

    May 12, 2025

    Overwatch 2 joins up with Street Fighter 6 in this dream-come-true collaboration

    May 10, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.