This script sets up a comprehensive financial report generation system using Python. It begins by importing essential libraries, including yfinance
for fetching stock data, pandas
and numpy
for data manipulation, matplotlib
and seaborn
for data visualization, and fpdf
and reportlab
for PDF report generation. The data extraction step involves defining a function, fetch_data
, which retrieves historical stock prices for a specified symbol over a specified date range using the Yahoo Finance API.
The data cleaning step involves defining a function, clean_data
, which removes any missing values from the data. The financial analysis step involves defining a function, calculate_ratios
, which calculates daily returns, cumulative returns, a 20-day rolling mean, a 20-day rolling standard deviation, and a 50-day moving average. For data visualization, a function, plot_data
, is defined to create and save a plot of the adjusted close price and the 50-day moving average.
The report generation step includes two methods: one using the fpdf
library and another using the reportlab
library. The generate_pdf_fpdf
function defines a PDF class with methods for adding headers, chapter titles, body text, and charts. It creates a PDF report with the financial analysis and saved chart. Similarly, the generate_pdf_reportlab
function uses the reportlab
library to create a PDF report with key financial metrics and the saved chart.
Finally, the main function coordinates the entire process: fetching data for Apple Inc. (AAPL) from January 1, 2022, to January 1, 2023, cleaning the data, performing financial analysis, visualizing the data, and generating the PDF reports using both fpdf
and reportlab
. This setup allows for comprehensive data analysis, visualization, and reporting of stock financial metrics.