1
Skills & Agents

Analyze Financial Statements

Published Oct 27, 2025 Original by Pedram Navid Shared by partonside Source
Optimised for: Claude 4.5 Opus Claude 4.5 Sonnet
v1.0 Oct 27, 2025 · 16:23 by partonside
Add version
---
SKILL.md
---

# Financial Ratio Calculator Skill

This skill provides comprehensive financial ratio analysis for evaluating company performance, profitability, liquidity, and valuation.

## Capabilities

Calculate and interpret:
- **Profitability Ratios**: ROE, ROA, Gross Margin, Operating Margin, Net Margin
- **Liquidity Ratios**: Current Ratio, Quick Ratio, Cash Ratio
- **Leverage Ratios**: Debt-to-Equity, Interest Coverage, Debt Service Coverage
- **Efficiency Ratios**: Asset Turnover, Inventory Turnover, Receivables Turnover
- **Valuation Ratios**: P/E, P/B, P/S, EV/EBITDA, PEG
- **Per-Share Metrics**: EPS, Book Value per Share, Dividend per Share

## How to Use

1. **Input Data**: Provide financial statement data (income statement, balance sheet, cash flow)
2. **Select Ratios**: Specify which ratios to calculate or use "all" for comprehensive analysis
3. **Interpretation**: The skill will calculate ratios and provide industry-standard interpretations

## Input Format

Financial data can be provided as:
- CSV with financial line items
- JSON with structured financial statements
- Text description of key financial figures
- Excel files with financial statements

## Output Format

Results include:
- Calculated ratios with values
- Industry benchmark comparisons (when available)
- Trend analysis (if multiple periods provided)
- Interpretation and insights
- Excel report with formatted results

## Example Usage

"Calculate key financial ratios for this company based on the attached financial statements"

"What's the P/E ratio if the stock price is $50 and annual earnings are $2.50 per share?"

"Analyze the liquidity position using the balance sheet data"

## Scripts

- `calculate_ratios.py`: Main calculation engine for all financial ratios
- `interpret_ratios.py`: Provides interpretation and benchmarking

## Best Practices

1. Always validate data completeness before calculations
2. Handle missing values appropriately (use industry averages or exclude)
3. Consider industry context when interpreting ratios
4. Include period comparisons for trend analysis
5. Flag unusual or concerning ratios

## Limitations

- Requires accurate financial data
- Industry benchmarks are general guidelines
- Some ratios may not apply to all industries
- Historical data doesn't guarantee future performance

---
calculate_ratios.py
---
"""
Financial ratio calculation module.
Provides functions to calculate key financial metrics and ratios.
"""

import json
from typing import Dict, Any, Optional, List


class FinancialRatioCalculator:
    """Calculate financial ratios from financial statement data."""

    def __init__(self, financial_data: Dict[str, Any]):
        """
        Initialize with financial statement data.

        Args:
            financial_data: Dictionary containing income_statement, balance_sheet,
                          cash_flow, and market_data
        """
        self.income_statement = financial_data.get('income_statement', {})
        self.balance_sheet = financial_data.get('balance_sheet', {})
        self.cash_flow = financial_data.get('cash_flow', {})
        self.market_data = financial_data.get('market_data', {})
        self.ratios = {}

    def safe_divide(self, numerator: float, denominator: float, default: float = 0.0) -> float:
        """Safely divide two numbers, returning default if denominator is zero."""
        if denominator == 0:
            return default
        return numerator / denominator

    def calculate_profitability_ratios(self) -> Dict[str, float]:
        """Calculate profitability ratios."""
        ratios = {}

        # ROE (Return on Equity)
        net_income = self.income_statement.get('net_income', 0)
        shareholders_equity = self.balance_sheet.get('shareholders_equity', 0)
        ratios['roe'] = self.safe_divide(net_income, shareholders_equity)

        # ROA (Return on Assets)
        total_assets = self.balance_sheet.get('total_assets', 0)
        ratios['roa'] = self.safe_divide(net_income, total_assets)

        # Gross Margin
        revenue = self.income_statement.get('revenue', 0)
        cogs = self.income_statement.get('cost_of_goods_sold', 0)
        gross_profit = revenue - cogs
        ratios['gross_margin'] = self.safe_divide(gross_profit, revenue)

        # Operating Margin
        operating_income = self.income_statement.get('operating_income', 0)
        ratios['operating_margin'] = self.safe_divide(operating_income, revenue)

        # Net Margin
        ratios['net_margin'] = self.safe_divide(net_income, revenue)

        return ratios

    def calculate_liquidity_ratios(self) -> Dict[str, float]:
        """Calculate liquidity ratios."""
        ratios = {}

        current_assets = self.balance_sheet.get('current_assets', 0)
        current_liabilities = self.balance_sheet.get('current_liabilities', 0)

        # Current Ratio
        ratios['current_ratio'] = self.safe_divide(current_assets, current_liabilities)

        # Quick Ratio (Acid Test)
        inventory = self.balance_sheet.get('inventory', 0)
        quick_assets = current_assets - inventory
        ratios['quick_ratio'] = self.safe_divide(quick_assets, current_liabilities)

        # Cash Ratio
        cash = self.balance_sheet.get('cash_and_equivalents', 0)
        ratios['cash_ratio'] = self.safe_divide(cash, current_liabilities)

        return ratios

    def calculate_leverage_ratios(self) -> Dict[str, float]:
        """Calculate leverage/solvency ratios."""
        ratios = {}

        total_debt = self.balance_sheet.get('total_debt', 0)
        shareholders_equity = self.balance_sheet.get('shareholders_equity', 0)

        # Debt-to-Equity Ratio
        ratios['debt_to_equity'] = self.safe_divide(total_debt, shareholders_equity)

        # Interest Coverage Ratio
        ebit = self.income_statement.get('ebit', 0)
        interest_expense = self.income_statement.get('interest_expense', 0)
        ratios['interest_coverage'] = self.safe_divide(ebit, interest_expense)

        # Debt Service Coverage Ratio
        net_operating_income = self.income_statement.get('operating_income', 0)
        total_debt_service = interest_expense + self.balance_sheet.get('current_portion_long_term_debt', 0)
        ratios['debt_service_coverage'] = self.safe_divide(net_operating_income, total_debt_service)

        return ratios

    def calculate_efficiency_ratios(self) -> Dict[str, float]:
        """Calculate efficiency/activity ratios."""
        ratios = {}

        revenue = self.income_statement.get('revenue', 0)
        total_assets = self.balance_sheet.get('total_assets', 0)

        # Asset Turnover
        ratios['asset_turnover'] = self.safe_divide(revenue, total_assets)

        # Inventory Turnover
        cogs = self.income_statement.get('cost_of_goods_sold', 0)
        inventory = self.balance_sheet.get('inventory', 0)
        ratios['inventory_turnover'] = self.safe_divide(cogs, inventory)

        # Receivables Turnover
        accounts_receivable = self.balance_sheet.get('accounts_receivable', 0)
        ratios['receivables_turnover'] = self.safe_divide(revenue, accounts_receivable)

        # Days Sales Outstanding
        ratios['days_sales_outstanding'] = self.safe_divide(365, ratios['receivables_turnover'])

        return ratios

    def calculate_valuation_ratios(self) -> Dict[str, float]:
        """Calculate valuation ratios."""
        ratios = {}

        share_price = self.market_data.get('share_price', 0)
        shares_outstanding = self.market_data.get('shares_outstanding', 0)
        market_cap = share_price * shares_outstanding

        # P/E Ratio
        net_income = self.income_statement.get('net_income', 0)
        eps = self.safe_divide(net_income, shares_outstanding)
        ratios['pe_ratio'] = self.safe_divide(share_price, eps)
        ratios['eps'] = eps

        # P/B Ratio
        book_value = self.balance_sheet.get('shareholders_equity', 0)
        book_value_per_share = self.safe_divide(book_value, shares_outstanding)
        ratios['pb_ratio'] = self.safe_divide(share_price, book_value_per_share)
        ratios['book_value_per_share'] = book_value_per_share

        # P/S Ratio
        revenue = self.income_statement.get('revenue', 0)
        ratios['ps_ratio'] = self.safe_divide(market_cap, revenue)

        # EV/EBITDA
        ebitda = self.income_statement.get('ebitda', 0)
        total_debt = self.balance_sheet.get('total_debt', 0)
        cash = self.balance_sheet.get('cash_and_equivalents', 0)
        enterprise_value = market_cap + total_debt - cash
        ratios['ev_to_ebitda'] = self.safe_divide(enterprise_value, ebitda)

        # PEG Ratio (if growth rate available)
        earnings_growth = self.market_data.get('earnings_growth_rate', 0)
        if earnings_growth > 0:
            ratios['peg_ratio'] = self.safe_divide(ratios['pe_ratio'], earnings_growth * 100)

        return ratios

    def calculate_all_ratios(self) -> Dict[str, Any]:
        """Calculate all financial ratios."""
        return {
            'profitability': self.calculate_profitability_ratios(),
            'liquidity': self.calculate_liquidity_ratios(),
            'leverage': self.calculate_leverage_ratios(),
            'efficiency': self.calculate_efficiency_ratios(),
            'valuation': self.calculate_valuation_ratios()
        }

    def interpret_ratio(self, ratio_name: str, value: float) -> str:
        """Provide interpretation for a specific ratio."""
        interpretations = {
            'current_ratio': lambda v: (
                "Strong liquidity" if v > 2 else
                "Adequate liquidity" if v > 1.5 else
                "Potential liquidity concerns" if v > 1 else
                "Liquidity issues"
            ),
            'debt_to_equity': lambda v: (
                "Low leverage" if v < 0.5 else
                "Moderate leverage" if v < 1 else
                "High leverage" if v < 2 else
                "Very high leverage"
            ),
            'roe': lambda v: (
                "Excellent returns" if v > 0.20 else
                "Good returns" if v > 0.15 else
                "Average returns" if v > 0.10 else
                "Below average returns" if v > 0 else
                "Negative returns"
            ),
            'pe_ratio': lambda v: (
                "Potentially undervalued" if 0 < v < 15 else
                "Fair value" if 15 <= v < 25 else
                "Growth premium" if 25 <= v < 40 else
                "High valuation" if v >= 40 else
                "N/A (negative earnings)" if v <= 0 else "N/A"
            )
        }

        if ratio_name in interpretations:
            return interpretations[ratio_name](value)
        return "No interpretation available"

    def format_ratio(self, name: str, value: float, format_type: str = "ratio") -> str:
        """Format ratio value for display."""
        if format_type == "percentage":
            return f"{value * 100:.2f}%"
        elif format_type == "times":
            return f"{value:.2f}x"
        elif format_type == "days":
            return f"{value:.1f} days"
        elif format_type == "currency":
            return f"${value:.2f}"
        else:
            return f"{value:.2f}"


def calculate_ratios_from_data(financial_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    Main function to calculate all ratios from financial data.

    Args:
        financial_data: Dictionary with financial statement data

    Returns:
        Dictionary with calculated ratios and interpretations
    """
    calculator = FinancialRatioCalculator(financial_data)
    ratios = calculator.calculate_all_ratios()

    # Add interpretations
    interpretations = {}
    for category, category_ratios in ratios.items():
        interpretations[category] = {}
        for ratio_name, value in category_ratios.items():
            interpretations[category][ratio_name] = {
                'value': value,
                'formatted': calculator.format_ratio(ratio_name, value),
                'interpretation': calculator.interpret_ratio(ratio_name, value)
            }

    return {
        'ratios': ratios,
        'interpretations': interpretations,
        'summary': generate_summary(ratios)
    }


def generate_summary(ratios: Dict[str, Any]) -> str:
    """Generate a text summary of the financial analysis."""
    summary_parts = []

    # Profitability summary
    prof = ratios.get('profitability', {})
    if prof.get('roe', 0) > 0:
        summary_parts.append(f"ROE of {prof['roe']*100:.1f}% indicates {'strong' if prof['roe'] > 0.15 else 'moderate'} shareholder returns.")

    # Liquidity summary
    liq = ratios.get('liquidity', {})
    if liq.get('current_ratio', 0) > 0:
        summary_parts.append(f"Current ratio of {liq['current_ratio']:.2f} suggests {'good' if liq['current_ratio'] > 1.5 else 'potential'} liquidity {'position' if liq['current_ratio'] > 1.5 else 'concerns'}.")

    # Leverage summary
    lev = ratios.get('leverage', {})
    if lev.get('debt_to_equity', 0) >= 0:
        summary_parts.append(f"Debt-to-equity of {lev['debt_to_equity']:.2f} indicates {'conservative' if lev['debt_to_equity'] < 0.5 else 'moderate' if lev['debt_to_equity'] < 1 else 'high'} leverage.")

    # Valuation summary
    val = ratios.get('valuation', {})
    if val.get('pe_ratio', 0) > 0:
        summary_parts.append(f"P/E ratio of {val['pe_ratio']:.1f} suggests the stock is trading at {'a discount' if val['pe_ratio'] < 15 else 'fair value' if val['pe_ratio'] < 25 else 'a premium'}.")

    return " ".join(summary_parts) if summary_parts else "Insufficient data for summary."


# Example usage
if __name__ == "__main__":
    # Sample financial data
    sample_data = {
        'income_statement': {
            'revenue': 1000000,
            'cost_of_goods_sold': 600000,
            'operating_income': 200000,
            'ebit': 180000,
            'ebitda': 250000,
            'interest_expense': 20000,
            'net_income': 150000
        },
        'balance_sheet': {
            'total_assets': 2000000,
            'current_assets': 800000,
            'cash_and_equivalents': 200000,
            'accounts_receivable': 150000,
            'inventory': 250000,
            'current_liabilities': 400000,
            'total_debt': 500000,
            'current_portion_long_term_debt': 50000,
            'shareholders_equity': 1500000
        },
        'cash_flow': {
            'operating_cash_flow': 180000,
            'investing_cash_flow': -100000,
            'financing_cash_flow': -50000
        },
        'market_data': {
            'share_price': 50,
            'shares_outstanding': 100000,
            'earnings_growth_rate': 0.10
        }
    }

    results = calculate_ratios_from_data(sample_data)
    print(json.dumps(results, indent=2))

---
interpret_ratios.py
---
"""
Financial ratio interpretation module.
Provides industry benchmarks and contextual analysis.
"""

from typing import Dict, Any, List, Optional


class RatioInterpreter:
    """Interpret financial ratios with industry context."""

    # Industry benchmark ranges (simplified for demonstration)
    BENCHMARKS = {
        'technology': {
            'current_ratio': {'excellent': 2.5, 'good': 1.8, 'acceptable': 1.2, 'poor': 1.0},
            'debt_to_equity': {'excellent': 0.3, 'good': 0.5, 'acceptable': 1.0, 'poor': 2.0},
            'roe': {'excellent': 0.25, 'good': 0.18, 'acceptable': 0.12, 'poor': 0.08},
            'gross_margin': {'excellent': 0.70, 'good': 0.50, 'acceptable': 0.35, 'poor': 0.20},
            'pe_ratio': {'undervalued': 15, 'fair': 25, 'growth': 35, 'expensive': 50}
        },
        'retail': {
            'current_ratio': {'excellent': 2.0, 'good': 1.5, 'acceptable': 1.0, 'poor': 0.8},
            'debt_to_equity': {'excellent': 0.5, 'good': 0.8, 'acceptable': 1.5, 'poor': 2.5},
            'roe': {'excellent': 0.20, 'good': 0.15, 'acceptable': 0.10, 'poor': 0.05},
            'gross_margin': {'excellent': 0.40, 'good': 0.30, 'acceptable': 0.20, 'poor': 0.10},
            'pe_ratio': {'undervalued': 12, 'fair': 18, 'growth': 25, 'expensive': 35}
        },
        'financial': {
            'current_ratio': {'excellent': 1.5, 'good': 1.2, 'acceptable': 1.0, 'poor': 0.8},
            'debt_to_equity': {'excellent': 1.0, 'good': 2.0, 'acceptable': 4.0, 'poor': 6.0},
            'roe': {'excellent': 0.15, 'good': 0.12, 'acceptable': 0.08, 'poor': 0.05},
            'pe_ratio': {'undervalued': 10, 'fair': 15, 'growth': 20, 'expensive': 30}
        },
        'manufacturing': {
            'current_ratio': {'excellent': 2.2, 'good': 1.7, 'acceptable': 1.3, 'poor': 1.0},
            'debt_to_equity': {'excellent': 0.4, 'good': 0.7, 'acceptable': 1.2, 'poor': 2.0},
            'roe': {'excellent': 0.18, 'good': 0.14, 'acceptable': 0.10, 'poor': 0.06},
            'gross_margin': {'excellent': 0.35, 'good': 0.25, 'acceptable': 0.18, 'poor': 0.12},
            'pe_ratio': {'undervalued': 14, 'fair': 20, 'growth': 28, 'expensive': 40}
        },
        'healthcare': {
            'current_ratio': {'excellent': 2.3, 'good': 1.8, 'acceptable': 1.4, 'poor': 1.0},
            'debt_to_equity': {'excellent': 0.3, 'good': 0.6, 'acceptable': 1.0, 'poor': 1.8},
            'roe': {'excellent': 0.22, 'good': 0.16, 'acceptable': 0.11, 'poor': 0.07},
            'gross_margin': {'excellent': 0.65, 'good': 0.45, 'acceptable': 0.30, 'poor': 0.20},
            'pe_ratio': {'undervalued': 18, 'fair': 28, 'growth': 40, 'expensive': 55}
                }
    }

    def __init__(self, industry: str = 'general'):
        """
        Initialize interpreter with industry context.

        Args:
            industry: Industry sector for benchmarking
        """
        self.industry = industry.lower()
        self.benchmarks = self.BENCHMARKS.get(self.industry, self._get_general_benchmarks())

    def _get_general_benchmarks(self) -> Dict[str, Any]:
        """Get general industry-agnostic benchmarks."""
        return {
            'current_ratio': {'excellent': 2.0, 'good': 1.5, 'acceptable': 1.0, 'poor': 0.8},
            'debt_to_equity': {'excellent': 0.5, 'good': 1.0, 'acceptable': 1.5, 'poor': 2.5},
            'roe': {'excellent': 0.20, 'good': 0.15, 'acceptable': 0.10, 'poor': 0.05},
            'gross_margin': {'excellent': 0.40, 'good': 0.30, 'acceptable': 0.20, 'poor': 0.10},
            'pe_ratio': {'undervalued': 15, 'fair': 22, 'growth': 30, 'expensive': 45}
        }

    def interpret_ratio(self, ratio_name: str, value: float) -> Dict[str, Any]:
        """
        Interpret a single ratio with context.

        Args:
            ratio_name: Name of the ratio
            value: Calculated ratio value

        Returns:
            Dictionary with interpretation details
        """
        interpretation = {
            'value': value,
            'rating': 'N/A',
            'message': '',
            'recommendation': '',
            'benchmark_comparison': {}
        }

        if ratio_name in self.benchmarks:
            benchmark = self.benchmarks[ratio_name]
            interpretation['benchmark_comparison'] = benchmark

            # Determine rating based on benchmarks
            if ratio_name in ['current_ratio', 'roe', 'gross_margin']:
                # Higher is better
                if value >= benchmark['excellent']:
                    interpretation['rating'] = 'Excellent'
                    interpretation['message'] = f"Performance significantly exceeds industry standards"
                elif value >= benchmark['good']:
                    interpretation['rating'] = 'Good'
                    interpretation['message'] = f"Above average performance for {self.industry} industry"
                elif value >= benchmark['acceptable']:
                    interpretation['rating'] = 'Acceptable'
                    interpretation['message'] = f"Meets industry standards"
                else:
                    interpretation['rating'] = 'Poor'
                    interpretation['message'] = f"Below industry standards - attention needed"

            elif ratio_name == 'debt_to_equity':
                # Lower is better
                if value <= benchmark['excellent']:
                    interpretation['rating'] = 'Excellent'
                    interpretation['message'] = f"Very conservative capital structure"
                elif value <= benchmark['good']:
                    interpretation['rating'] = 'Good'
                    interpretation['message'] = f"Healthy leverage level"
                elif value <= benchmark['acceptable']:
                    interpretation['rating'] = 'Acceptable'
                    interpretation['message'] = f"Moderate leverage"
                else:
                    interpretation['rating'] = 'Poor'
                    interpretation['message'] = f"High leverage - potential risk"

            elif ratio_name == 'pe_ratio':
                # Context-dependent
                if value > 0:
                    if value < benchmark['undervalued']:
                        interpretation['rating'] = 'Potentially Undervalued'
                        interpretation['message'] = f"Trading below typical {self.industry} multiples"
                    elif value < benchmark['fair']:
                        interpretation['rating'] = 'Fair Value'
                        interpretation['message'] = f"In line with industry averages"
                    elif value < benchmark['growth']:
                        interpretation['rating'] = 'Growth Premium'
                        interpretation['message'] = f"Market pricing in growth expectations"
                    else:
                        interpretation['rating'] = 'Expensive'
                        interpretation['message'] = f"High valuation relative to industry"

        # Add specific recommendations
        interpretation['recommendation'] = self._get_recommendation(ratio_name, interpretation['rating'])

        return interpretation

    def _get_recommendation(self, ratio_name: str, rating: str) -> str:
        """Generate actionable recommendations based on ratio and rating."""
        recommendations = {
            'current_ratio': {
                'Poor': "Consider improving working capital management, reducing short-term debt, or increasing liquid assets",
                'Acceptable': "Monitor liquidity closely and consider building additional cash reserves",
                'Good': "Maintain current liquidity management practices",
                'Excellent': "Strong liquidity position - consider productive use of excess cash"
            },
            'debt_to_equity': {
                'Poor': "High leverage increases financial risk - consider debt reduction strategies",
                'Acceptable': "Monitor debt levels and ensure adequate interest coverage",
                'Good': "Balanced capital structure - maintain current approach",
                'Excellent': "Conservative leverage - may consider strategic use of debt for growth"
            },
            'roe': {
                'Poor': "Focus on improving operational efficiency and profitability",
                'Acceptable': "Explore opportunities to enhance returns through operational improvements",
                'Good': "Solid returns - continue current strategies",
                'Excellent': "Outstanding performance - ensure sustainability of high returns"
            },
            'pe_ratio': {
                'Potentially Undervalued': "May present buying opportunity if fundamentals are solid",
                'Fair Value': "Reasonably priced relative to industry peers",
                'Growth Premium': "Ensure growth prospects justify premium valuation",
                'Expensive': "Consider valuation risk - ensure fundamentals support high multiple"
            }
        }

        if ratio_name in recommendations and rating in recommendations[ratio_name]:
            return recommendations[ratio_name][rating]

        return "Continue monitoring this metric"

    def analyze_trend(self, ratio_name: str, values: List[float], periods: List[str]) -> Dict[str, Any]:
        """
        Analyze trend in a ratio over time.

        Args:
            ratio_name: Name of the ratio
            values: List of ratio values
            periods: List of period labels

        Returns:
            Trend analysis dictionary
        """
        if len(values) < 2:
            return {'trend': 'Insufficient data', 'message': 'Need at least 2 periods for trend analysis'}

        # Calculate trend
        first_value = values[0]
        last_value = values[-1]
        change = last_value - first_value
        pct_change = (change / abs(first_value)) * 100 if first_value != 0 else 0

        # Determine trend direction
        if abs(pct_change) < 5:
            trend = 'Stable'
        elif pct_change > 0:
            trend = 'Improving' if ratio_name != 'debt_to_equity' else 'Deteriorating'
        else:
            trend = 'Deteriorating' if ratio_name != 'debt_to_equity' else 'Improving'

        return {
            'trend': trend,
            'change': change,
            'pct_change': pct_change,
            'message': f"{ratio_name} has {'increased' if change > 0 else 'decreased'} by {abs(pct_change):.1f}% from {periods[0]} to {periods[-1]}",
            'values': list(zip(periods, values))
        }

    def generate_report(self, ratios: Dict[str, Any]) -> str:
        """
        Generate a comprehensive interpretation report.

        Args:
            ratios: Dictionary of calculated ratios

        Returns:
            Formatted report string
        """
        report_lines = [
            f"Financial Analysis Report - {self.industry.title()} Industry Context",
            "=" * 70,
            ""
        ]

        for category, category_ratios in ratios.items():
            report_lines.append(f"\n{category.upper()} ANALYSIS")
            report_lines.append("-" * 40)

            for ratio_name, value in category_ratios.items():
                if isinstance(value, (int, float)):
                    interpretation = self.interpret_ratio(ratio_name, value)
                    report_lines.append(f"\n{ratio_name.replace('_', ' ').title()}:")
                    report_lines.append(f"  Value: {value:.2f}")
                    report_lines.append(f"  Rating: {interpretation['rating']}")
                    report_lines.append(f"  Analysis: {interpretation['message']}")
                    report_lines.append(f"  Action: {interpretation['recommendation']}")

        return "\n".join(report_lines)


def perform_comprehensive_analysis(
    ratios: Dict[str, Any],
    industry: str = 'general',
    historical_data: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """
    Perform comprehensive ratio analysis with interpretations.

    Args:
        ratios: Calculated financial ratios
        industry: Industry sector for benchmarking
        historical_data: Optional historical ratio data for trend analysis

    Returns:
        Complete analysis with interpretations and recommendations
    """
    interpreter = RatioInterpreter(industry)
    analysis = {
        'current_analysis': {},
        'trend_analysis': {},
        'overall_health': {},
        'recommendations': []
    }

    # Analyze current ratios
    for category, category_ratios in ratios.items():
        analysis['current_analysis'][category] = {}
        for ratio_name, value in category_ratios.items():
            if isinstance(value, (int, float)):
                analysis['current_analysis'][category][ratio_name] = interpreter.interpret_ratio(ratio_name, value)

    # Perform trend analysis if historical data provided
    if historical_data:
        for ratio_name, historical_values in historical_data.items():
            if 'values' in historical_values and 'periods' in historical_values:
                analysis['trend_analysis'][ratio_name] = interpreter.analyze_trend(
                    ratio_name,
                    historical_values['values'],
                    historical_values['periods']
                )

    # Generate overall health assessment
    analysis['overall_health'] = _assess_overall_health(analysis['current_analysis'])

    # Generate key recommendations
    analysis['recommendations'] = _generate_key_recommendations(analysis)

    # Add formatted report
    analysis['report'] = interpreter.generate_report(ratios)

    return analysis


def _assess_overall_health(current_analysis: Dict[str, Any]) -> Dict[str, str]:
    """Assess overall financial health based on ratio analysis."""
    ratings = []
    for category, category_analysis in current_analysis.items():
        for ratio_name, ratio_analysis in category_analysis.items():
            if 'rating' in ratio_analysis:
                ratings.append(ratio_analysis['rating'])

    # Simple scoring system
    score_map = {
        'Excellent': 4,
        'Good': 3,
        'Acceptable': 2,
        'Poor': 1,
        'Fair Value': 3,
        'Potentially Undervalued': 3,
        'Growth Premium': 2,
        'Expensive': 1
    }

    scores = [score_map.get(rating, 2) for rating in ratings]
    avg_score = sum(scores) / len(scores) if scores else 0

    if avg_score >= 3.5:
        health = "Excellent"
        message = "Company shows strong financial health across most metrics"
    elif avg_score >= 2.5:
        health = "Good"
        message = "Overall healthy financial position with some areas for improvement"
    elif avg_score >= 1.5:
        health = "Fair"
        message = "Mixed financial indicators - attention needed in several areas"
    else:
        health = "Poor"
        message = "Significant financial challenges requiring immediate attention"

    return {
        'status': health,
        'message': message,
        'score': f"{avg_score:.1f}/4.0"
    }


def _generate_key_recommendations(analysis: Dict[str, Any]) -> List[str]:
    """Generate prioritized recommendations based on analysis."""
    recommendations = []

    # Check for critical issues
    for category, category_analysis in analysis['current_analysis'].items():
        for ratio_name, ratio_analysis in category_analysis.items():
            if ratio_analysis.get('rating') == 'Poor':
                recommendations.append(f"Priority: Address {ratio_name.replace('_', ' ')} - {ratio_analysis.get('recommendation', '')}")

    # Add trend-based recommendations
    for ratio_name, trend in analysis.get('trend_analysis', {}).items():
        if trend.get('trend') == 'Deteriorating':
            recommendations.append(f"Monitor: {ratio_name.replace('_', ' ')} showing negative trend")

    # Add general recommendations if healthy
    if not recommendations:
        recommendations.append("Continue current financial management practices")
        recommendations.append("Consider strategic growth opportunities")

    return recommendations[:5]  # Return top 5 recommendations