The user wants a Python script to scrape financial data and calculate key financial ratios.
This is a multi-step task involving:
- Selecting a data source: Yahoo Finance is the most common free source for this type of data.
yfinance is the standard library for Python.
- Scraping/Fetching Data: Using the library to get financial statements (Balance Sheet, Income Statement, Cash Flow).
- Calculating Ratios: defining formulas for common ratios (e.g., P/E, ROE, Current Ratio, Debt-to-Equity).
- Structuring the Output: Presenting the data clearly, perhaps in a pandas DataFrame.
Potential Risks & Safety Policy Check:
- Malicious scraping: Is scraping Yahoo Finance malicious? Generally, no, as long as rate limits are respected.
yfinance handles this reasonably well, but I should warn about rate limiting.
- Financial Advice: The script provides calculation, not advice. I must include a disclaimer that this is for educational purposes and not financial advice.
Plan:
- Import libraries:
yfinance and pandas.
- Define a class or functions: A class structure is cleaner for holding the ticker object and methods.
- Fetch Data: Get the ticker object.
- Extract Metrics: Pull specific line items (Net Income, Total Assets, Total Liabilities, etc.).
- Calculate Ratios:
- Liquidity: Current Ratio.
- Profitability: Gross Margin, Operating Margin, Net Profit Margin, ROE, ROA.
- Valuation: P/E Ratio (often provided, but can be calculated), P/B Ratio.
- Leverage: Debt-to-Equity.
- Error Handling: Handle cases where data might be missing (try-except blocks or
.get()).
- Example Usage: Run the script for a major stock (e.g., AAPL).
Refinement on "Scraping":
While the user asked to "scrape," using an API wrapper like yfinance is much more robust and Pythonic than writing a raw BeautifulSoup parser for Yahoo Finance, which breaks frequently due to HTML changes. I will use yfinance but explain that it acts as a scraper/API wrapper.
Code Structure:
import yfinance as yf
import pandas as pd
def get_financial_data(ticker_symbol):
ticker = yf.Ticker(ticker_symbol)
# ... extraction logic ...
# ... calculation logic ...
return df
Specific Ratios to include:
- Current Ratio = Current Assets / Current Liabilities
- Debt-to-Equity (D/E) = Total Liabilities / Shareholder Equity
- Return on Equity (ROE) = Net Income / Shareholder Equity
- Gross Margin = Gross Profit / Revenue
- Price-to-Earnings (P/E) = Price / EPS (or use info dict)
Self-Correction during drafting:
Some data points in yfinance are in the .info dictionary (like Market Cap, PE), while others are in .financials or .balance_sheet. Mixing these requires handling timeframes (TTM vs. specific year). I'll stick to the most recent annual report data for calculation consistency, or TTM where available in .info.
Decision: I will prioritize calculated ratios based on the most recent annual report for consistency, and pull valuation metrics directly from the info object (which is usually TTM).
Disclaimer: Crucial.
Dependencies: The user needs to install yfinance and pandas.
Step-by-Step Guide:
- Prerequisites (install packages).
- The Code.
- Explanation of the code.
- Disclaimer.
Let's write the code.
ticker.info['currentPrice']
ticker.balance_sheet -> index: 'Total Assets', 'Total Liab', etc.
ticker.financials -> index: 'Total Revenue', 'Net Income', etc.
Check: yfinance returns MultiIndex columns sometimes. Need to access the latest column (usually .iloc[:, 0]).
Let's refine the retrieval logic:
balance_sheet = ticker.balance_sheet
latest_balance = balance_sheet.iloc[:, 0]
This gets the most recent year.
Safety:
Ensure no credential harvesting (not applicable here).
Ensure no harmful code execution (not applicable here).
Output format: Standard python script with comments.
Here is a complete Python script to accomplish this. It uses the yfinance library to access Yahoo Finance data, which is the standard method for retrieving historical market data and financial statements programmatically.
Prerequisites
You will need to install the yfinance and pandas libraries:
pip install yfinance pandas
The Python Script
This script defines a class FinancialAnalyzer that fetches the income statement, balance sheet, and cash flow statement. It then calculates Liquidity, Profitability, and Leverage ratios.
import yfinance as yf
import pandas as pd
class FinancialAnalyzer:
def __init__(self, ticker_symbol):
self.ticker = ticker_symbol
self.stock = yf.Ticker(ticker_symbol)
# Retrieve financial statements
# Note: yfinance returns dataframes where columns are dates (newest first)
self.income_stmt = self.stock.financials
self.balance_sheet = self.stock.balance_sheet
self.cash_flow = self.stock.cashflow
# Extract the most recent annual data (column 0)
# Using .get() with a default of 0 to handle missing data safely
try:
self.latest_income = self.income_stmt.iloc[:, 0]
self.latest_balance = self.balance_sheet.iloc[:, 0]
except IndexError:
print(f"Error: Could not retrieve full financial data for {ticker_symbol}.")
self.latest_income = pd.Series()
self.latest_balance = pd.Series()
def get_price_data(self):
"""Fetches current market cap and stock price."""
info = self.stock.info
return {
"Current Price": info.get("currentPrice", None),
"Market Cap": info.get("marketCap", None),
"Trailing PE": info.get("trailingPE", None)
}
def calculate_ratios(self):
"""
Calculates key ratios based on the most recent annual report.
Returns a dictionary of ratios.
"""
ratios = {}
# Helper to safely get a value from the statements
def get_value(series, key):
try:
return series.loc[key]
except KeyError:
return 0
# --- Extract Raw Data ---
# Income Statement
revenue = get_value(self.latest_income, "Total Revenue")
net_income = get_value(self.latest_income, "Net Income")
ebit = get_value(self.latest_income, "EBIT")
# Balance Sheet
total_assets = get_value(self.latest_balance, "Total Assets")
total_liab = get_value(self.latest_balance, "Total Liabilities Net Minority Interest")
current_assets = get_value(self.latest_balance, "Current Assets")
current_liab = get_value(self.latest_balance, "Current Liabilities")
inventory = get_value(self.latest_balance, "Inventory")
total_equity = total_assets - total_liab
# --- Calculations ---
# 1. Liquidity Ratios
if current_liab != 0:
ratios["Current Ratio"] = current_assets / current_liab
# Quick Ratio excludes inventory
ratios["Quick Ratio"] = (current_assets - inventory) / current_liab
else:
ratios["Current Ratio"] = "N/A"
ratios["Quick Ratio"] = "N/A"
# 2. Profitability Ratios
if revenue != 0:
ratios["Gross Margin"] = f"{(get_value(self.latest_income, 'Gross Profit') / revenue) * 100:.2f}%"
ratios["Net Profit Margin"] = f"{(net_income / revenue) * 100:.2f}%"
if total_equity != 0:
ratios["Return on Equity (ROE)"] = f"{(net_income / total_equity) * 100:.2f}%"
if total_assets != 0:
ratios["Return on Assets (ROA)"] = f"{(net_income / total_assets) * 100:.2f}%"
# 3. Leverage Ratios
if total_equity != 0:
ratios["Debt-to-Equity"] = total_liab / total_equity
return ratios
def analyze(self):
"""Runs all analysis and prints a report."""
print(f"\n--- Financial Analysis: {self.ticker} ---")
# Print Market Data
price_data = self.get_price_data()
print("\n[Market Data]")
for key, value in price_data.items():
print(f"{key}: {value}")
# Print Calculated Ratios
ratios = self.calculate_ratios()
print("\n[Key Financial Ratios (Most Recent Annual)]")
for key, value in ratios.items():
print(f"{key}: {value}")
# --- Execution ---
if __name__ == "__main__":
# You can change 'AAPL' to any valid ticker symbol (e.g., 'MSFT', 'TSLA', 'AMZN')
ticker_symbol = "AAPL"
analyzer = FinancialAnalyzer(ticker_symbol)
analyzer.analyze()
Explanation of the Code
yfinance Library: This is the engine of the script. yf.Ticker(ticker) creates an object that allows us to download market data and financial statements.
- Financial Statements: The script accesses
stock.financials (Income Statement) and stock.balance_sheet. These are returned as Pandas DataFrames where the index is the line item name (e.g., "Total Revenue") and the columns represent different years.
- Data Extraction: We use
iloc[:, 0] to grab the most recent year of data (column 0).
- Ratio Formulas:
- Current Ratio: Measures ability to pay short-term obligations (
Current Assets / Current Liabilities).
- Quick Ratio: A stricter liquidity measure excluding inventory (
(Current Assets - Inventory) / Current Liabilities).
- Net Profit Margin: How much net profit is generated per dollar of revenue (
Net Income / Revenue).
- ROE (Return on Equity): Profitability relative to shareholder equity (
Net Income / Equity).
- Debt-to-Equity: Financial leverage (
Total Liabilities / Equity).
Important Notes
- Data Delays: Yahoo Finance data is generally accurate but can have delays or discrepancies compared to official SEC filings (like 10-Ks).
- Missing Data: Not all companies report the same line items. If a specific company lacks "Inventory" or "EBIT" in the scraped data, the script handles it by catching the KeyError or returning 0.
- Disclaimer: This script is for educational purposes. Always verify financial data from official sources before making investment decisions.