import pandas as pd
import matplotlib
# Set non-interactive backend for headless operation - must be before pyplot import
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# Ensure matplotlib is in non-interactive mode
plt.ioff()
import seaborn as sns
import numpy as np
from datetime import datetime
import os
import glob

def setup_plotting_style():
    """Set up a professional plotting style."""
    plt.style.use('default')
    sns.set_palette("husl")
    plt.rcParams['figure.figsize'] = (15, 10)
    plt.rcParams['font.size'] = 10
    plt.rcParams['axes.labelsize'] = 12
    plt.rcParams['axes.titlesize'] = 14
    plt.rcParams['legend.fontsize'] = 10
    plt.rcParams['xtick.labelsize'] = 9
    plt.rcParams['ytick.labelsize'] = 9

def detect_ticker_symbol():
    """Detect the ticker symbol from the most recent XLSX file."""
    try:
        # Check downloaded_files folder for recent files
        xlsx_files = glob.glob("./downloaded_files/*.xlsx")
        if xlsx_files:
            # Get the most recent file
            latest_file = max(xlsx_files, key=os.path.getmtime)
            filename = os.path.basename(latest_file)
            
            # Extract ticker from filename like "financials_export_brkb_2025_08_02_221804.xlsx"
            if 'financials_export_' in filename:
                parts = filename.split('_')
                if len(parts) >= 3:
                    ticker = parts[2].upper()
                    # Handle special cases like BRK.B
                    if ticker == 'BRKB':
                        ticker = 'BRK.B'
                    return ticker
        
        # Fallback: try to detect from data patterns
        return "TICKER"
    except:
        return "TICKER"

def load_data():
    """Load both annual and quarterly CSV data."""
    try:
        # Load annual data from data directory
        annual_path = os.path.join('data', 'owner_earnings_financials_annual.csv')
        annual_df = pd.read_csv(annual_path)
        print(f"[OK] Loaded annual data: {len(annual_df)} years")
        
        # Load quarterly data from data directory
        quarterly_path = os.path.join('data', 'owner_earnings_financials_quarterly.csv')
        quarterly_df = pd.read_csv(quarterly_path)
        print(f"[OK] Loaded quarterly data: {len(quarterly_df)} quarters")
        
        return annual_df, quarterly_df
    
    except FileNotFoundError as e:
        print(f"[ERROR] Error loading CSV files: {e}")
        print("[INFO] Make sure to run owner_earnings_fixed.py first to generate the CSV files")
        print("[INFO] CSV files should be in the 'data/' directory")
        return None, None

def prepare_quarterly_data(df):
    """Prepare quarterly data for plotting."""
    # Convert period to datetime for better plotting
    df = df.copy()
    df['year'] = df['Period'].str[:4].astype(int)
    df['quarter'] = df['Period'].str[-1].astype(int)
    
    # Create a proper date column
    df['date'] = pd.to_datetime(df[['year']].assign(month=(df['quarter']-1)*3+1, day=1))
    
    # Convert to millions for better readability
    financial_cols = ['net_income', 'depreciation', 'capex', 'working_capital_change', 'owner_earnings']
    for col in financial_cols:
        df[f'{col}_millions'] = df[col] / 1_000_000
    
    # Sort by date for proper chronological plotting
    df = df.sort_values('date')
    
    return df

def prepare_annual_data(df):
    """Prepare annual data for plotting."""
    df = df.copy()
    df['date'] = pd.to_datetime(df['Period'], format='%Y')
    
    # Convert to millions for better readability
    financial_cols = ['net_income', 'depreciation', 'capex', 'working_capital_change', 'owner_earnings']
    for col in financial_cols:
        df[f'{col}_millions'] = df[col] / 1_000_000
    
    return df

def create_owner_earnings_comparison(annual_df, quarterly_df, ticker):
    """Create a comparison chart of annual vs quarterly owner earnings."""
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 12))
    
    # Annual chart
    annual_df.plot(x='date', y='owner_earnings_millions', kind='line', 
                   ax=ax1, marker='o', linewidth=2, markersize=6, color='#1f77b4')
    ax1.axhline(y=0, color='red', linestyle='--', alpha=0.7)
    ax1.set_title(f'{ticker} Annual Owner Earnings (2015-2024)', fontweight='bold', fontsize=16)
    ax1.set_ylabel('Owner Earnings ($ Millions)')
    ax1.set_xlabel('Year')
    ax1.grid(True, alpha=0.3)
    ax1.legend(['Owner Earnings', 'Break-even'], loc='upper left')
    
    # Add annotations for key points
    max_annual = annual_df.loc[annual_df['owner_earnings_millions'].idxmax()]
    min_annual = annual_df.loc[annual_df['owner_earnings_millions'].idxmin()]
    
    ax1.annotate(f'Best: ${max_annual["owner_earnings_millions"]:.0f}M\n({max_annual["Period"]})', 
                xy=(max_annual['date'], max_annual['owner_earnings_millions']),
                xytext=(10, 10), textcoords='offset points',
                bbox=dict(boxstyle='round,pad=0.3', facecolor='lightgreen', alpha=0.7),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
    
    ax1.annotate(f'Worst: ${min_annual["owner_earnings_millions"]:.0f}M\n({min_annual["Period"]})', 
                xy=(min_annual['date'], min_annual['owner_earnings_millions']),
                xytext=(10, -20), textcoords='offset points',
                bbox=dict(boxstyle='round,pad=0.3', facecolor='lightcoral', alpha=0.7),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
    
    # Quarterly chart
    quarterly_df.plot(x='date', y='owner_earnings_millions', kind='line', 
                      ax=ax2, marker='s', linewidth=1.5, markersize=4, color='#ff7f0e', alpha=0.8)
    ax2.axhline(y=0, color='red', linestyle='--', alpha=0.7)
    ax2.set_title(f'{ticker} Quarterly Owner Earnings (2015-2025)', fontweight='bold', fontsize=16)
    ax2.set_ylabel('Owner Earnings ($ Millions)')
    ax2.set_xlabel('Date')
    ax2.grid(True, alpha=0.3)
    ax2.legend(['Owner Earnings', 'Break-even'], loc='upper left')
    
    # Add annotations for quarterly extremes
    max_quarterly = quarterly_df.loc[quarterly_df['owner_earnings_millions'].idxmax()]
    min_quarterly = quarterly_df.loc[quarterly_df['owner_earnings_millions'].idxmin()]
    
    ax2.annotate(f'Best: ${max_quarterly["owner_earnings_millions"]:.0f}M\n({max_quarterly["Period"]})', 
                xy=(max_quarterly['date'], max_quarterly['owner_earnings_millions']),
                xytext=(10, 10), textcoords='offset points',
                bbox=dict(boxstyle='round,pad=0.3', facecolor='lightgreen', alpha=0.7),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
    
    ax2.annotate(f'Worst: ${min_quarterly["owner_earnings_millions"]:.0f}M\n({min_quarterly["Period"]})', 
                xy=(min_quarterly['date'], min_quarterly['owner_earnings_millions']),
                xytext=(10, -20), textcoords='offset points',
                bbox=dict(boxstyle='round,pad=0.3', facecolor='lightcoral', alpha=0.7),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
    
    plt.tight_layout()
    return fig

def create_components_breakdown(annual_df, quarterly_df, ticker):
    """Create waterfall charts showing the components of owner earnings."""
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 14))
    
    # Annual components waterfall
    create_annual_waterfall_chart(ax1, annual_df, ticker)
    
    # Quarterly components (most recent 20 quarters for readability)
    # Since data is now sorted chronologically, get the last 20 quarters
    quarterly_recent = quarterly_df.tail(20).copy()
    
    # Create waterfall chart for quarterly data
    create_waterfall_chart(ax2, quarterly_recent, ticker)
    
    # Rotate x-axis labels for better readability
    ax2.tick_params(axis='x', rotation=45)
    
    plt.tight_layout()
    return fig
    
    plt.tight_layout()
    return fig

def create_annual_waterfall_chart(ax, df, ticker):
    """Create a waterfall chart showing annual owner earnings components."""
    
    # Get the last 5 years for better visibility
    recent_years = df.tail(5).copy()
    
    # Set up the chart dimensions
    n_years = len(recent_years)
    bar_width = 0.15
    
    # Create positions for each year
    year_positions = np.arange(n_years)
    
    # Colors for each component
    colors = {
        'Net Income': '#2E86AB',
        'Depreciation': '#A23B72', 
        'CapEx': '#F18F01',
        'WC Changes': '#C73E1D',
        'Owner Earnings': '#4CAF50'
    }
    
    # Create grouped waterfall charts for each year
    for i, (_, year) in enumerate(recent_years.iterrows()):
        period = year['Period']
        
        # Component values
        net_income = year['net_income_millions']
        depreciation = year['depreciation_millions']
        capex = year['capex_millions']
        wc_change = year['working_capital_change_millions']
        owner_earnings = year['owner_earnings_millions']
        
        # Calculate cumulative positions for waterfall
        cumulative = [0]
        cumulative.append(net_income)
        cumulative.append(cumulative[-1] + depreciation)
        cumulative.append(cumulative[-1] + capex)
        cumulative.append(cumulative[-1] + wc_change)
        
        # X position for this year's bars
        x_base = i
        
        # Net Income (starts from 0)
        ax.bar(x_base - 2*bar_width, net_income, bar_width, 
               bottom=0, color=colors['Net Income'], alpha=0.8, 
               edgecolor='black', linewidth=0.3,
               label='Net Income' if i == 0 else "")
        
        # Depreciation (stacks on Net Income)
        ax.bar(x_base - bar_width, depreciation, bar_width,
               bottom=cumulative[1], color=colors['Depreciation'], alpha=0.8,
               edgecolor='black', linewidth=0.3,
               label='+ Depreciation' if i == 0 else "")
        
        # CapEx (negative, stacks on previous)
        ax.bar(x_base, capex, bar_width,
               bottom=cumulative[2], color=colors['CapEx'], alpha=0.8,
               edgecolor='black', linewidth=0.3,
               label='- CapEx' if i == 0 else "")
        
        # Working Capital Changes (can be positive or negative)
        wc_color = colors['WC Changes'] if wc_change < 0 else '#90EE90'
        ax.bar(x_base + bar_width, wc_change, bar_width,
               bottom=cumulative[3], color=wc_color, alpha=0.8,
               edgecolor='black', linewidth=0.3,
               label='WC Changes' if i == 0 else "")
        
        # Owner Earnings (final result)
        oe_color = colors['Owner Earnings'] if owner_earnings >= 0 else '#F44336'
        ax.bar(x_base + 2*bar_width, owner_earnings, bar_width,
               bottom=0, color=oe_color, alpha=0.8,
               edgecolor='black', linewidth=0.5,
               label='Owner Earnings' if i == 0 else "")
        
        # Add value labels for Owner Earnings (in billions for annual)
        oe_billions = owner_earnings / 1000
        ax.text(x_base + 2*bar_width, owner_earnings/2, f'${oe_billions:.1f}B',
               ha='center', va='center', fontweight='bold', fontsize=9, rotation=90)
        
        # Add connecting line to show the flow to final result
        if owner_earnings >= 0:
            ax.plot([x_base + bar_width + bar_width/2, x_base + 2*bar_width - bar_width/2], 
                   [cumulative[4], owner_earnings/2], 'k--', alpha=0.3, linewidth=1)
    
    # Formatting
    ax.set_xticks(year_positions)
    ax.set_xticklabels([str(int(y['Period'])) for _, y in recent_years.iterrows()])
    ax.set_title(f'{ticker} Annual Owner Earnings Waterfall - Recent Years', fontweight='bold', fontsize=16)
    ax.set_ylabel('Amount ($ Millions)')
    ax.legend(loc='upper left', fontsize=10)
    ax.grid(True, alpha=0.3, axis='y')
    ax.axhline(y=0, color='black', linestyle='-', alpha=0.8)

def create_waterfall_chart(ax, df, ticker):
    """Create a waterfall chart showing owner earnings components for recent quarters."""
    
    # Get the last 8 quarters for quarterly granularity
    recent_quarters = df.tail(8).copy()
    
    # Set up the chart dimensions
    n_quarters = len(recent_quarters)
    n_components = 5  # Net Income, Depreciation, CapEx, WC Changes, Owner Earnings
    bar_width = 0.15
    
    # Create positions for each quarter
    quarter_positions = np.arange(n_quarters)
    
    # Colors for each component
    colors = {
        'Net Income': '#2E86AB',
        'Depreciation': '#A23B72', 
        'CapEx': '#F18F01',
        'WC Changes': '#C73E1D',
        'Owner Earnings': '#4CAF50'
    }
    
    # Create grouped waterfall charts for each quarter
    for i, (_, quarter) in enumerate(recent_quarters.iterrows()):
        period = quarter['Period']
        
        # Component values
        net_income = quarter['net_income_millions']
        depreciation = quarter['depreciation_millions']
        capex = quarter['capex_millions']
        wc_change = quarter['working_capital_change_millions']
        owner_earnings = quarter['owner_earnings_millions']
        
        # Calculate cumulative positions for waterfall
        cumulative = [0]
        cumulative.append(net_income)
        cumulative.append(cumulative[-1] + depreciation)
        cumulative.append(cumulative[-1] + capex)
        cumulative.append(cumulative[-1] + wc_change)
        
        # X position for this quarter's bars
        x_base = i
        
        # Net Income (starts from 0)
        ax.bar(x_base - 2*bar_width, net_income, bar_width, 
               bottom=0, color=colors['Net Income'], alpha=0.8, 
               edgecolor='black', linewidth=0.3,
               label='Net Income' if i == 0 else "")
        
        # Depreciation (stacks on Net Income)
        ax.bar(x_base - bar_width, depreciation, bar_width,
               bottom=cumulative[1], color=colors['Depreciation'], alpha=0.8,
               edgecolor='black', linewidth=0.3,
               label='+ Depreciation' if i == 0 else "")
        
        # CapEx (negative, stacks on previous)
        ax.bar(x_base, capex, bar_width,
               bottom=cumulative[2], color=colors['CapEx'], alpha=0.8,
               edgecolor='black', linewidth=0.3,
               label='- CapEx' if i == 0 else "")
        
        # Working Capital Changes (can be positive or negative)
        wc_color = colors['WC Changes'] if wc_change < 0 else '#90EE90'
        ax.bar(x_base + bar_width, wc_change, bar_width,
               bottom=cumulative[3], color=wc_color, alpha=0.8,
               edgecolor='black', linewidth=0.3,
               label='WC Changes' if i == 0 else "")
        
        # Owner Earnings (final result)
        oe_color = colors['Owner Earnings'] if owner_earnings >= 0 else '#F44336'
        ax.bar(x_base + 2*bar_width, owner_earnings, bar_width,
               bottom=0, color=oe_color, alpha=0.8,
               edgecolor='black', linewidth=0.5,
               label='Owner Earnings' if i == 0 else "")
        
        # Add value labels for Owner Earnings
        ax.text(x_base + 2*bar_width, owner_earnings/2, f'${owner_earnings:,.0f}M',
               ha='center', va='center', fontweight='bold', fontsize=8, rotation=90)
        
        # Add connecting line to show the flow to final result
        if owner_earnings >= 0:
            ax.plot([x_base + bar_width + bar_width/2, x_base + 2*bar_width - bar_width/2], 
                   [cumulative[4], owner_earnings/2], 'k--', alpha=0.3, linewidth=1)
    
    # Formatting
    ax.set_xticks(quarter_positions)
    ax.set_xticklabels([q['Period'] for _, q in recent_quarters.iterrows()], rotation=45, ha='right')
    ax.set_title(f'{ticker} Owner Earnings Waterfall - Recent Quarters', fontweight='bold', fontsize=14)
    ax.set_ylabel('Amount ($ Millions)')
    ax.legend(loc='upper left', fontsize=9)
    ax.grid(True, alpha=0.3, axis='y')
    ax.axhline(y=0, color='black', linestyle='-', alpha=0.8)

def create_volatility_analysis(quarterly_df, ticker):
    """Create charts showing the volatility and trends in owner earnings."""
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(16, 12))
    
    # 1. Rolling average to show trend
    quarterly_df['rolling_4q'] = quarterly_df['owner_earnings_millions'].rolling(window=4, center=True).mean()
    quarterly_df['rolling_8q'] = quarterly_df['owner_earnings_millions'].rolling(window=8, center=True).mean()
    
    ax1.plot(quarterly_df['date'], quarterly_df['owner_earnings_millions'], 
             'o-', alpha=0.6, label='Quarterly', linewidth=1, markersize=3)
    ax1.plot(quarterly_df['date'], quarterly_df['rolling_4q'], 
             '-', linewidth=2, label='4Q Rolling Avg', color='red')
    ax1.plot(quarterly_df['date'], quarterly_df['rolling_8q'], 
             '-', linewidth=2, label='8Q Rolling Avg', color='green')
    ax1.axhline(y=0, color='black', linestyle='--', alpha=0.7)
    ax1.set_title(f'{ticker} Owner Earnings Trend Analysis', fontweight='bold')
    ax1.set_ylabel('Owner Earnings ($ Millions)')
    ax1.legend()
    ax1.grid(True, alpha=0.3)
    
    # 2. Year-over-year comparison (same quarter)
    quarterly_df['year'] = quarterly_df['date'].dt.year
    quarterly_df['quarter'] = quarterly_df['date'].dt.quarter
    
    # Create pivot for YoY comparison
    pivot_data = quarterly_df.pivot(index='quarter', columns='year', values='owner_earnings_millions')
    recent_years = [col for col in pivot_data.columns if col >= 2020]  # Focus on recent years
    
    for year in recent_years:
        if year in pivot_data.columns:
            ax2.plot([1,2,3,4], pivot_data[year], 'o-', label=f'{year}', linewidth=2, markersize=6)
    
    ax2.axhline(y=0, color='black', linestyle='--', alpha=0.7)
    ax2.set_title('Year-over-Year Quarterly Comparison', fontweight='bold')
    ax2.set_xlabel('Quarter')
    ax2.set_ylabel('Owner Earnings ($ Millions)')
    ax2.set_xticks([1,2,3,4])
    ax2.set_xticklabels(['Q1', 'Q2', 'Q3', 'Q4'])
    ax2.legend()
    ax2.grid(True, alpha=0.3)
    
    # 3. Distribution histogram
    ax3.hist(quarterly_df['owner_earnings_millions'], bins=20, alpha=0.7, color='skyblue', edgecolor='black')
    ax3.axvline(x=quarterly_df['owner_earnings_millions'].mean(), color='red', 
                linestyle='--', label=f"Mean: ${quarterly_df['owner_earnings_millions'].mean():.0f}M")
    ax3.axvline(x=quarterly_df['owner_earnings_millions'].median(), color='green', 
                linestyle='--', label=f"Median: ${quarterly_df['owner_earnings_millions'].median():.0f}M")
    ax3.set_title('Distribution of Quarterly Owner Earnings', fontweight='bold')
    ax3.set_xlabel('Owner Earnings ($ Millions)')
    ax3.set_ylabel('Frequency')
    ax3.legend()
    ax3.grid(True, alpha=0.3)
    
    # 4. Positive vs Negative quarters
    positive_quarters = quarterly_df[quarterly_df['owner_earnings_millions'] > 0]
    negative_quarters = quarterly_df[quarterly_df['owner_earnings_millions'] <= 0]
    
    summary_data = {
        'Positive Quarters': [len(positive_quarters), positive_quarters['owner_earnings_millions'].mean()],
        'Negative Quarters': [len(negative_quarters), negative_quarters['owner_earnings_millions'].mean()]
    }
    
    categories = list(summary_data.keys())
    counts = [summary_data[cat][0] for cat in categories]
    avg_values = [summary_data[cat][1] for cat in categories]
    
    x_pos = np.arange(len(categories))
    
    bars1 = ax4.bar(x_pos - 0.2, counts, 0.4, label='Count', color='lightblue', alpha=0.8)
    ax4_twin = ax4.twinx()
    bars2 = ax4_twin.bar(x_pos + 0.2, avg_values, 0.4, label='Avg Value ($M)', color='lightcoral', alpha=0.8)
    
    ax4.set_title('Positive vs Negative Quarters Summary', fontweight='bold')
    ax4.set_xlabel('Quarter Type')
    ax4.set_ylabel('Number of Quarters', color='blue')
    ax4_twin.set_ylabel('Average Value ($ Millions)', color='red')
    ax4.set_xticks(x_pos)
    ax4.set_xticklabels(categories)
    
    # Add value labels on bars
    for bar, count in zip(bars1, counts):
        ax4.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, 
                str(count), ha='center', va='bottom')
    
    for bar, avg_val in zip(bars2, avg_values):
        ax4_twin.text(bar.get_x() + bar.get_width()/2, bar.get_height() + (20 if avg_val > 0 else -40), 
                     f'${avg_val:.0f}M', ha='center', va='bottom' if avg_val > 0 else 'top')
    
    plt.tight_layout()
    return fig

def save_and_show_plots(figures, filenames, ticker):
    """Save plots to files and display them."""
    # Ensure we're using non-interactive backend
    matplotlib.use('Agg')
    plt.ioff()
    
    # Create charts directory if it doesn't exist
    charts_dir = "charts"
    if not os.path.exists(charts_dir):
        os.makedirs(charts_dir)
        print(f"[DIR] Created directory: {charts_dir}/")
    
    for fig, filename in zip(figures, filenames):
        # Use the filename as-is since it's already properly formatted
        filepath = os.path.join(charts_dir, f"{filename}.png")
        fig.savefig(filepath, dpi=300, bbox_inches='tight', facecolor='white')
        print(f"[CHART] Saved chart: {filepath}")
        # Close the figure to free memory
        plt.close(fig)
    
    # Don't show interactive plots in GUI mode - just save them
    # plt.show()
    print("\n[OK] All charts displayed and saved!")

def main():
    """Main function to create all visualizations."""
    # Detect ticker symbol
    ticker = detect_ticker_symbol()
    
    print(f"{ticker} Owner Earnings Visualization Tool")
    print("=" * 50)
    
    # Set up plotting style
    setup_plotting_style()
    
    # Load data
    annual_df, quarterly_df = load_data()
    if annual_df is None or quarterly_df is None:
        return
    
    # Prepare data
    print("[ANALYSIS] Preparing data for visualization...")
    annual_df = prepare_annual_data(annual_df)
    quarterly_df = prepare_quarterly_data(quarterly_df)
    
    print(f"[CHARTS] Creating visualizations...")
    
    # Create all charts
    figures = []
    filenames = []
    
    # 1. Owner earnings comparison
    fig1 = create_owner_earnings_comparison(annual_df, quarterly_df, ticker)
    figures.append(fig1)
    filenames.append(f"{ticker.lower().replace('.', '')}_owner_earnings_comparison")
    
    # 2. Components breakdown
    fig2 = create_components_breakdown(annual_df, quarterly_df, ticker)
    figures.append(fig2)
    filenames.append(f"{ticker.lower().replace('.', '')}_earnings_components_breakdown")
    
    # 3. Volatility analysis
    fig3 = create_volatility_analysis(quarterly_df, ticker)
    figures.append(fig3)
    filenames.append(f"{ticker.lower().replace('.', '')}_volatility_analysis")
    
    # Save and show all plots
    save_and_show_plots(figures, filenames, ticker)
    
    # Print summary statistics
    print(f"\n[SUMMARY] {ticker} SUMMARY STATISTICS:")
    print(f"Annual Data Range: {annual_df['Period'].min()} to {annual_df['Period'].max()}")
    print(f"Quarterly Data Range: {quarterly_df['Period'].min()} to {quarterly_df['Period'].max()}")
    print(f"Best Annual Owner Earnings: ${annual_df['owner_earnings_millions'].max():.0f}M ({annual_df.loc[annual_df['owner_earnings_millions'].idxmax(), 'Period']})")
    print(f"Worst Annual Owner Earnings: ${annual_df['owner_earnings_millions'].min():.0f}M ({annual_df.loc[annual_df['owner_earnings_millions'].idxmin(), 'Period']})")
    print(f"Best Quarterly Owner Earnings: ${quarterly_df['owner_earnings_millions'].max():.0f}M ({quarterly_df.loc[quarterly_df['owner_earnings_millions'].idxmax(), 'Period']})")
    print(f"Worst Quarterly Owner Earnings: ${quarterly_df['owner_earnings_millions'].min():.0f}M ({quarterly_df.loc[quarterly_df['owner_earnings_millions'].idxmin(), 'Period']})")
    
    positive_quarters = len(quarterly_df[quarterly_df['owner_earnings_millions'] > 0])
    total_quarters = len(quarterly_df)
    print(f"Positive Quarters: {positive_quarters}/{total_quarters} ({positive_quarters/total_quarters*100:.1f}%)")

if __name__ == "__main__":
    main()
