Scrape financial ratios from Yahoo Finance including cash flow statement and balance sheet. Calculate the Altman Z-Score for bankruptcy risk prediction by combining multiple fields and handle missing data gracefully.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a comprehensive request to create a web scraper for financial data from Yahoo Finance and calculate the Altman Z-Score. Let me break this down:
Scraping Yahoo Finance for financial ratios
Getting cash flow statement data
Getting balance sheet data
Calculating Altman Z-Score
Handling missing data gracefully
The Altman Z-Score formula is:
Z = 1.2X1 + 1.4X2 + 3.3X3 + 0.6X4 + 1.0*X5
Where:
X1 = Working Capital / Total Assets
X2 = Retained Earnings / Total Assets
X3 = EBIT / Total Assets
X4 = Market Value of Equity / Book Value of Total Liabilities
X5 = Sales / Total Assets
Interpretation:
Z > 2.99: Safe Zone (Low bankruptcy risk)
1.81 < Z < 2.99: Gray Zone (Moderate risk)
Z < 1.81: Distress Zone (High bankruptcy risk)
I'll create a comprehensive solution using:
yfinance for Yahoo Finance data
requests and BeautifulSoup for web scraping additional data
pandas for data manipulation
Error handling for missing data
Let me write a complete solution:
Financial Data Scraper and Altman Z-Score Calculator
I'll create a comprehensive solution to scrape financial data from Yahoo Finance and calculate the Altman Z-Score with robust error handling.
python
import pandas as pd
import numpy as np
import yfinance as yf
from datetime import datetime
import logging
from typing import Dict, Tuple, Optional
import warnings
warnings.filterwarnings('ignore')
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class FinancialDataScraper:
"""Scrape financial data from Yahoo Finance"""
def __init__(self, ticker: str):
self.ticker = ticker.upper()
self.stock = yf.Ticker(self.ticker)
self.info = None
self.financials = None
self.quarterly_financials = None
self.balance_sheet = None
self.quarterly_balance_sheet = None
self.cash_flow = None
self.quarterly_cash_flow = None
def fetch_all_data(self) -> bool:
"""Fetch all required financial data"""
try:
logger.info(f"Fetching data for {self.ticker}...")
self.info = self.stock.info
self.financials = self.stock.financials
self.quarterly_financials = self.stock.quarterly_financials
self.balance_sheet = self.stock.balance_sheet
self.quarterly_balance_sheet = self.stock.quarterly_balance_sheet
self.cash_flow = self.stock.cashflow
self.quarterly_cash_flow = self.stock.quarterly_cashflow
logger.info(f"Successfully fetched data for {self.ticker}")
return True
except Exception as e:
logger.error(f"Error fetching data for {self.ticker}: {str(e)}")
return False
def get_financial_ratios(self) -> Dict:
"""Extract key financial ratios"""
try:
ratios = {
'ticker': self.ticker,
'timestamp': datetime.now().isoformat(),
'data_source': 'Yahoo Finance'
}
# Price and Market Cap
ratios['current_price'] = self.info.get('currentPrice', np.nan)
ratios['market_cap'] = self.info.get('marketCap', np.nan)
ratios['shares_outstanding'] = self.info.get('sharesOutstanding', np.nan)
# Profitability Ratios
ratios['pe_ratio'] = self.info.get('trailingPE', np.nan)
ratios['forward_pe'] = self.info.get('forwardPE', np.nan)
ratios['profit_margin'] = self.info.get('profitMargins', np.nan)
ratios['operating_margin'] = self.info.get('operatingMargins', np.nan)
ratios['gross_margin'] = self.info.get('grossMargins', np.nan)
# Liquidity Ratios
ratios['current_ratio'] = self.info.get('currentRatio', np.nan)
ratios['quick_ratio'] = self.info.get('quickRatio', np.nan)
# Leverage Ratios
ratios['debt_to_equity'] = self.info.get('debtToEquity', np.nan)
ratios['total_debt'] = self.info.get('totalDebt', np.nan)
# ROI Metrics
ratios['roe'] = self.info.get('returnOnEquity', np.nan)
ratios['roa'] = self.info.get('returnOnAssets', np.nan)
# Dividend and Yield
ratios['dividend_yield'] = self.info.get('dividendYield', np.nan)
ratios['payout_ratio'] = self.info.get('payoutRatio', np.nan)
return ratios
except Exception as e:
logger.error(f"Error extracting financial ratios: {str(e)}")
return {}
def get_balance_sheet_data(self) -> Dict:
"""Extract balance sheet data"""
balance_sheet_data = {}
try:
if self.balance_sheet is not None and not self.balance_sheet.empty:
latest = self.balance_sheet.iloc[:, 0]
# Assets
balance_sheet_data['total_assets'] = latest.get(
'Total Assets', np.nan
)
balance_sheet_data['current_assets'] = latest.get(
'Current Assets', np.nan
)
balance_sheet_data['cash'] = latest.get(
'Cash And Cash Equivalents', np.nan
)
# Liabilities
balance_sheet_data['total_liabilities'] = latest.get(
'Total Liab', np.nan
)
balance_sheet_data['current_liabilities'] = latest.get(
'Current Liabilities', np.nan
)
balance_sheet_data['long_term_debt'] = latest.get(
'Long Term Debt', np.nan
)
# Equity
balance_sheet_data['total_equity'] = latest.get(
'Total Stockholder Equity', np.nan
)
balance_sheet_data['retained_earnings'] = latest.get(
'Retained Earnings', np.nan
)
balance_sheet_data['common_stock'] = latest.get(
'Common Stock', np.nan
)
logger.info("Successfully extracted balance sheet data")
except Exception as e:
logger.error(f"Error extracting balance sheet data: {str(e)}")
return balance_sheet_data
def get_income_statement_data(self) -> Dict:
"""Extract income statement data"""
income_data = {}
try:
if self.financials is not None and not self.financials.empty:
latest = self.financials.iloc[:, 0]
income_data['total_revenue'] = latest.get(
'Total Revenue', np.nan
)
income_data['cost_of_revenue'] = latest.get(
'Cost Of Revenue', np.nan
)
income_data['operating_income'] = latest.get(
'Operating Income', np.nan
)
income_data['ebit'] = latest.get(
'EBIT', np.nan
)
income_data['net_income'] = latest.get(
'Net Income', np.nan
)
income_data['interest_expense'] = latest.get(
'Interest Expense', np.nan
)
logger.info("Successfully extracted income statement data")
except Exception as e:
logger.error(f"Error extracting income statement data: {str(e)}")
return income_data
def get_cash_flow_data(self) -> Dict:
"""Extract cash flow statement data"""
cash_flow_data = {}
try:
if self.cash_flow is not None and not self.cash_flow.empty:
latest = self.cash_flow.iloc[:, 0]
cash_flow_data['operating_cash_flow'] = latest.get(
'Operating Cash Flow', np.nan
)
cash_flow_data['investing_cash_flow'] = latest.get(
'Investing Cash Flow', np.nan
)
cash_flow_data['financing_cash_flow'] = latest.get(
'Financing Cash Flow', np.nan
)
cash_flow_data['free_cash_flow'] = latest.get(
'Free Cash Flow', np.nan
)
cash_flow_data['capital_expenditure'] = latest.get(
'Capital Expenditure', np.nan
)
logger.info("Successfully extracted cash flow data")
except Exception as e:
logger.error(f"Error extracting cash flow data: {str(e)}")
return cash_flow_data
class AltmanZScoreCalculator:
"""Calculate Altman Z-Score for bankruptcy risk prediction"""
# Z-Score Thresholds
SAFE_ZONE_THRESHOLD = 2.99
GRAY_ZONE_LOWER = 1.81
GRAY_ZONE_UPPER = 2.99
DISTRESS_ZONE_THRESHOLD = 1.81
# Altman Z-Score Coefficients
COEFFICIENTS = {
'x1': 1.2, # Working Capital / Total Assets
'x2': 1.4, # Retained Earnings / Total Assets
'x3': 3.3, # EBIT / Total Assets
'x4': 0.6, # Market Value of Equity / Book Value of Total Liabilities
'x5': 1.0 # Sales / Total Assets
}
def __init__(self, ticker: str = None, market_price: float = None):
self.ticker = ticker
self.market_price = market_price
self.z_score = None
self.components = {}
self.missing_fields = []
self.warnings = []
def calculate(self, financial_data: Dict) -> bool:
"""Calculate Altman Z-Score"""
try:
logger.info(f"Calculating Altman Z-Score for {self.ticker}...")
# Extract required fields
total_assets = financial_data.get('total_assets')
current_assets = financial_data.get('current_assets')
current_liabilities = financial_data.get('current_liabilities')
retained_earnings = financial_data.get('retained_earnings')
ebit = financial_data.get('ebit')
total_liabilities = financial_data.get('total_liabilities')
total_revenue = financial_data.get('total_revenue')
market_cap = financial_data.get('market_cap')
# Validate critical data
if not self._validate_data(
total_assets, total_liabilities, ebit, total_revenue
):
return False
# Calculate X1: Working Capital / Total Assets
self.components['x1'] = self._calculate_x1(
current_assets, current_liabilities, total_assets
)
# Calculate X2: Retained Earnings / Total Assets
self.components['x2'] = self._calculate_x2(
retained_earnings, total_assets
)
# Calculate X3: EBIT / Total Assets
self.components['x3'] = self._calculate_x3(
ebit, total_assets
)
# Calculate X4: Market Value of Equity / Book Value of Total Liabilities
self.components['x4'] = self._calculate_x4(
market_cap, total_liabilities
)
# Calculate X5: Sales / Total Assets
self.components['x5'] = self._calculate_x5(
total_revenue, total_assets
)
# Calculate final Z-Score
self.z_score = (
self.COEFFICIENTS['x1'] * self.components['x1'] +
self.COEFFICIENTS['x2'] * self.components['x2'] +
self.COEFFICIENTS['x3'] * self.components['x3'] +
self.COEFFICIENTS['x4'] * self.components['x4'] +
self.COEFFICIENTS['x5'] * self.components['x5']
)
logger.info(f"Z-Score calculated: {self.z_score:.4f}")
return True
except Exception as e:
logger.error(f"Error calculating Z-Score: {str(e)}")
return False
def _validate_data(self, total_assets, total_liabilities, ebit, revenue):
"""Validate critical financial data"""
has_errors = False
if pd.isna(total_assets) or total_assets == 0:
self.missing_fields.append('total_assets')
has_errors = True
if pd.isna(total_liabilities):
self.missing_fields.append('total_liabilities')
has_errors = True
if pd.isna(ebit):
self.missing_fields.append('ebit')
self.warnings.append(
"EBIT not available, using operating income as fallback"
)
if pd.isna(revenue):
self.missing_fields.append('total_revenue')
has_errors = True
if has_errors:
logger.warning(
f"Missing critical fields: {', '.join(self.missing_fields)}"
)
return False
return True
def _calculate_x1(self, current_assets, current_liabilities,
total_assets) -> float:
"""Calculate X1: Working Capital / Total Assets"""
try:
if pd.isna(current_assets) or pd.isna(current_liabilities):
self.warnings.append("Using balance sheet data for X1")
return 0 # Conservative approach
working_capital = current_assets - current_liabilities
x1 = working_capital / total_assets
return x1
except Exception as e:
logger.warning(f"Error calculating X1: {str(e)}")
return 0
def _calculate_x2(self, retained_earnings, total_assets) -> float:
"""Calculate X2: Retained Earnings / Total Assets"""
try:
if pd.isna(retained_earnings):
self.warnings.append("Retained earnings not available for X2")
return 0
x2 = retained_earnings / total_assets
return x2
except Exception as e:
logger.warning(f"Error calculating X2: {str(e)}")
return 0
def _calculate_x3(self, ebit, total_assets) -> float:
"""Calculate X3: EBIT / Total Assets"""
try:
if pd.isna(ebit):
self.warnings.append("EBIT not available for X3")
return 0
x3 = ebit / total_assets
return x3
except Exception as e:
logger.warning(f"Error calculating X3: {str(e)}")
return 0
def _calculate_x4(self, market_value_equity, book_value_liabilities) -> float:
"""Calculate X4: Market Value of Equity / Book Value of Total Liabilities"""
try:
if pd.isna(market_value_equity):
self.warnings.append(
"Market cap not available, X4 may be underestimated"
)
return 0
if pd.isna(book_value_liabilities) or book_value_liabilities == 0:
return 0
x4 = market_value_equity / book_value_liabilities
return x4
except Exception as e:
logger.warning(f"Error calculating X4: {str(e)}")
return 0
def _calculate_x5(self, sales, total_assets) -> float:
"""Calculate X5: Sales / Total Assets"""
try:
if pd.isna(sales):
self.warnings.append("Sales not available for X5")
return 0
x5 = sales / total_assets
return x5
except Exception as e:
logger.warning(f"Error calculating X5: {str(e)}")
return 0
def get_risk_classification(self) -> str:
"""Classify bankruptcy risk based on Z-Score"""
if self.z_score is None:
return "CALCULATION_FAILED"
if self.z_score > self.SAFE_ZONE_THRESHOLD:
return "SAFE_ZONE"
elif self.z_score >= self.GRAY_ZONE_LOWER:
return "GRAY_ZONE"
else:
return "DISTRESS_ZONE"
def get_risk_description(self) -> str:
"""Get detailed risk description"""
classification = self.get_risk_classification()
descriptions = {
"SAFE_ZONE": "Low bankruptcy risk. Company is financially healthy.",
"GRAY_ZONE": "Moderate bankruptcy risk. Close monitoring recommended.",
"DISTRESS_ZONE": "High bankruptcy risk. Caution advised.",
"CALCULATION_FAILED": "Unable to calculate Z-Score due to missing data."
}
return descriptions.get(classification, "Unknown classification")
def generate_report(self) -> Dict:
"""Generate comprehensive Z-Score report"""
return {
'ticker': self.ticker,
'z_score': round(self.z_score, 4) if self.z_score else None,
'risk_classification': self.get_risk_classification(),
'risk_description': self.get_risk_description(),
'components': {
'x1_working_capital_ratio': round(
self.components.get('x1', 0), 4
),
'x2_retained_earnings_ratio': round(
self.components.get('x2', 0), 4
),
'x3_ebit_ratio': round(
self.components.get('x3', 0), 4
),
'x4_market_to_book_ratio': round(
self.components.get('x4', 0), 4
),
'x5_asset_turnover': round(
self.components.get('x5', 0), 4
),
},
'weighted_components': {
f'x1_contribution': round(
self.COEFFICIENTS['x1'] * self.components.get('x1', 0), 4
),
f'x2_contribution': round(
self.COEFFICIENTS['x2'] * self.components.get('x2', 0), 4
),
f'x3_contribution': round(
self.COEFFICIENTS['x3'] * self.components.get('x3', 0), 4
),
f'x4_contribution': round(
self.COEFFICIENTS['x4'] * self.components.get('x4', 0), 4
),
f'x5_contribution': round(
self.COEFFICIENTS['x5'] * self.components.get('x5', 0), 4
),
},
'missing_fields': self.missing_fields,
'warnings': self.warnings,
'timestamp': datetime.now().isoformat()
}
class FinancialAnalyzer:
"""Main analyzer combining scraper and Z-Score calculator"""
def __init__(self, ticker: str):
self.ticker = ticker
self.scraper = FinancialDataScraper(ticker)
self.calculator = AltmanZScoreCalculator(ticker)
self.all_data = {}
def analyze(self) -> Dict:
"""Perform complete financial analysis"""
try:
# Fetch data
if not self.scraper.fetch_all_data():
return {'error': f'Failed to fetch data for {self.ticker}'}
# Extract all financial data
self.all_data.update(self.scraper.get_financial_ratios())
self.all_data.update(self.scraper.get_balance_sheet_data())
self.all_data.update(self.scraper.get_income_statement_data())
self.all_data.update(self.scraper.get_cash_flow_data())
# Calculate Z-Score
if self.calculator.calculate(self.all_data):
return {
'status': 'success',
'ticker': self.ticker,
'z_score_report': self.calculator.generate_report(),
'financial_data': self.all_data
}
else:
return {
'status': 'failure',
'ticker': self.ticker,
'error': 'Z-Score calculation failed',
'missing_fields': self.calculator.missing_fields
}
except Exception as e:
logger.error(f"Analysis failed for {self.ticker}: {str(e)}")
return {
'status': 'error',
'ticker': self.ticker,
'error': str(e)
}
def export_to_dataframe(self) -> pd.DataFrame:
"""Export all data to DataFrame"""
df = pd.DataFrame([self.all_data])
return df
def export_to_csv(self, filename: str):
"""Export data to CSV"""
df = self.export_to_dataframe()
df.to_csv(filename, index=False)
logger.info(f"Data exported to {filename}")
# Example usage and demonstration
def main():
"""Main function demonstrating usage"""
# List of tickers to analyze
tickers = ['AAPL', 'MSFT', 'TSLA', 'BAC', 'GE']
all_results = []
z_score_reports = []
for ticker in tickers:
print(f"\n{'='*60}")
print(f"Analyzing {ticker}")
print(f"{'='*60}")
analyzer = FinancialAnalyzer(ticker)
result = analyzer.analyze()
if result['status'] == 'success':
report = result['z_score_report']
all_results.append(result)
z_score_reports.append(report)
# Display results
print(f"\nZ-Score: {report['z_score']}")
print(f"Classification: {report['risk_classification']}")
print(f"Description: {report['risk_description']}")
print("\n--- Z-Score Components ---")
for key, value in report['components'].items():
print(f"{key}: {value}")
print("\n--- Contributions to Z-Score ---")
for key, value in report['weighted_components'].items():
print(f"{key}: {value}")
if report['warnings']:
print("\n--- Warnings ---")
for warning in report['warnings']:
print(f"⚠ {warning}")
else:
print(f"Error: {result.get('error', 'Unknown error')}")
if 'missing_fields' in result:
print(f"Missing fields: {result['missing_fields']}")
# Create comparison DataFrame
if z_score_reports:
print(f"\n{'='*60}")
print("Z-SCORE COMPARISON")
print(f"{'='*60}\n")
comparison_data = []
for report in z_score_reports:
comparison_data.append({
'Ticker': report['ticker'],
'Z-Score': report['z_score'],
'Classification': report['risk_classification'],
'Working Capital': report['components']['x1_working_capital_ratio'],
'Retained Earnings': report['components']['x2_retained_earnings_ratio'],
'EBIT': report['components']['x3_ebit_ratio'],
'Market to Book': report['components']['x4_market_to_book_ratio'],
'Asset Turnover': report['components']['x5_asset_turnover'],
})
comparison_df = pd.DataFrame(comparison_data)
print(comparison_df.to_string(index=False))
# Save to CSV
comparison_df.to_csv('altman_zscore_analysis.csv', index=False)
print("\nResults saved to 'altman_zscore_analysis.csv'")
# Additional analysis
print(f"\n{'='*60}")
print("RISK DISTRIBUTION")
print(f"{'='*60}\n")
risk_counts = comparison_df['Classification'].value_counts()
print(risk_counts)
# Identify highest and lowest risk
print(f"\nHighest Risk (Lowest Z-Score): "
f"{comparison_df.loc[comparison_df['Z-Score'].idxmin(), 'Ticker']} "
f"({comparison_df['Z-Score'].min():.4f})")
print(f"Lowest Risk (Highest Z-Score): "
f"{comparison_df.loc[comparison_df['Z-Score'].idxmax(), 'Ticker']} "
f"({comparison_df['Z-Score'].max():.4f})")
if __name__ == "__main__":
main()