Discounted Cash Flow Analysis

60 minintermediate

3. Discounted Cash Flow Analysis

Discounted Cash Flow (DCF) analysis is one of the most theoretically rigorous and widely used valuation methodologies in finance. It is grounded in the fundamental principle that the value of any asset equals the present value of its expected future cash flows. DCF analysis provides a framework for determining the intrinsic value of a company by forecasting its future free cash flows and discounting them to their present value using an appropriate discount rate. This section provides a comprehensive exploration of DCF methodology, from its theoretical foundations to practical implementation challenges.

Theoretical Foundation: The Time Value of Money

The theoretical foundation of DCF analysis rests on the concept of the time value of money - the principle that a dollar received today is worth more than a dollar received in the future because money can be invested to earn returns. This principle is fundamental to all financial valuation and reflects the opportunity cost of capital. When we discount future cash flows, we are adjusting them for the time value of money and the risk associated with receiving those cash flows.

The mathematical expression of the time value of money is the present value formula:

#x27; in math mode at position 1: $̲$PV = \frac{CF}…" style="color:#cc0000">$PV = \frac{CF}{(1+r)^n}$

Where:

#x27; in math mode at position 1: $̲$FCF = EBIT(1-t…" style="color:#cc0000">$FCF = EBIT(1-t) + D\&A - CapEx - \Delta NWC$ = Present value
  • #x27; in math mode at position 1: $̲$WACC = \frac{E…" style="color:#cc0000">$WACC = \frac{E}{V}r_e + \frac{D}{V}r_d(1-t)$ = Future cash flow
  • #x27; in math mode at position 1: $̲$TV = \frac{FCF…" style="color:#cc0000">$TV = \frac{FCF_{n+1}}{WACC - g}$ = Discount rate (required rate of return)
  • #x27; in math mode at position 1: $̲$TV = Metric_n …" style="color:#cc0000">$TV = Metric_n \times Multiple$ = Number of periods

    This formula captures two essential components of valuation: the timing of cash flows and the risk-adjusted discount rate. The discount rate reflects both the time value of money (the risk-free rate) and a risk premium that compensates investors for the uncertainty associated with the cash flows.

    Discounted Cash Flow (DCF) Analysis: A valuation methodology that estimates the intrinsic value of an asset by discounting its expected future cash flows to their present value using an appropriate discount rate. DCF analysis is based on the principle that the value of an asset equals the present value of all future cash flows it will generate.

    The DCF model is particularly powerful because it:

    However, DCF models are also sensitive to assumptions, particularly growth rates, discount rates, and terminal value assumptions. Understanding these sensitivities is crucial for proper DCF implementation.

    DCF Model Structure: Components and Framework

    A complete DCF model consists of several key components that work together to estimate enterprise value and equity value. Understanding the structure and interrelationships of these components is essential for building robust DCF models.

    Free Cash Flow Projections

    The foundation of any DCF model is the projection of future free cash flows. Free cash flow represents the cash available to all providers of capital (both debt and equity holders) after the company has made all necessary investments to maintain and grow its business. Free cash flow is calculated as:

    #x27; in math mode at position 1: $̲$FCF = EBIT(1-t…" style="color:#cc0000">$FCF = EBIT(1-t) + D\&A - CapEx - \Delta NWC$

    Where:

    This formula captures the cash flow available to capital providers by starting with operating profit, adjusting for taxes, adding back non-cash expenses (depreciation and amortization), and subtracting cash investments (capital expenditures and working capital changes).

    Free cash flow projections typically cover a projection period of 5 to 10 years, during which detailed forecasts can be made based on company-specific factors. Beyond this projection period, a terminal value is used to capture the value of cash flows extending into perpetuity.

    Discount Rate: Weighted Average Cost of Capital (WACC)

    The discount rate used in DCF analysis is the Weighted Average Cost of Capital (WACC), which represents the blended cost of all sources of capital (both debt and equity). WACC reflects the opportunity cost of capital and the risk associated with the company's cash flows.

    WACC is calculated as:

    #x27; in math mode at position 1: $̲$WACC = \frac{E…" style="color:#cc0000">$WACC = \frac{E}{V}r_e + \frac{D}{V}r_d(1-t)$

    Where:

    WACC represents a weighted average because it reflects the proportion of each type of capital in the company's capital structure. The weights (#x27; in math mode at position 1: $̲$r_e = r_f + \b…" style="color:#cc0000">$r_e = r_f + \beta(E[R_m] - r_f) + s \times SMB + h \times HML$ and #x27; in math mode at position 1: $̲$r_e = \frac{D_…" style="color:#cc0000">$r_e = \frac{D_1}{P_0} + g$ ) should be based on market values, not book values, to reflect the true cost of capital.

    Terminal Value: Capturing Perpetual Cash Flows

    Terminal value represents the present value of all cash flows beyond the explicit projection period. Since it's impractical to forecast cash flows indefinitely, terminal value provides a way to capture the value of the business as a going concern. There are two primary methods for calculating terminal value:

    1. Perpetuity Growth Model (Gordon Growth Model):

    #x27; in math mode at position 1: $̲$TV = \frac{FCF…" style="color:#cc0000">$TV = \frac{FCF_{n+1}}{WACC - g}$

    Where:

    This method assumes that cash flows will grow at a constant rate forever. The growth rate should be conservative and typically should not exceed the long-term growth rate of the economy (usually 2-3%).

    2. Exit Multiple Method:

    #x27; in math mode at position 1: $̲$TV = Metric_n …" style="color:#cc0000">$TV = Metric_n \times Multiple$

    Where:

    This method assumes the company will be sold at the end of the projection period at a multiple of a financial metric, similar to how comparable companies are valued.

    The perpetuity growth model is theoretically more sound as it's based on DCF principles, while the exit multiple method is more market-based. Many practitioners use both methods and triangulate the results.

    Enterprise Value and Equity Value

    The DCF model produces an enterprise value, which represents the value of the entire business (both debt and equity). To arrive at equity value, we must adjust for net debt:

    #x27; in math mode at position 1: $̲$Equity\ Value …" style="color:#cc0000">$Equity\ Value = Enterprise\ Value - Net\ Debt$

    Where:

    Enterprise value represents the value of the operating business, while equity value represents the value available to equity holders after debt obligations are satisfied.

    Let's visualize the complete DCF model structure:

    Python exercise

    #| label: dcf-model-structure
    #| fig-cap: "DCF Model Structure: Components and Value Breakdown"
    #| fig-width: 16
    #| fig-height: 10
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # DCF Model Parameters
    projection_years = 5
    fcf_year_1 = 10_000_000  # $10M initial FCF
    fcf_growth = np.array([0.15, 0.12, 0.10, 0.08, 0.06])  # Declining growth rates
    wacc = 0.10  # 10% WACC
    terminal_growth = 0.03  # 3% terminal growth
    
    # Calculate projected FCFs
    fcfs = np.zeros(projection_years)
    fcfs[0] = fcf_year_1
    for i in range(1, projection_years):
        fcfs[i] = fcfs[i-1] * (1 + fcf_growth[i])
    
    # Calculate present value of projected FCFs
    pv_fcfs = np.zeros(projection_years)
    for i in range(projection_years):
        pv_fcfs[i] = fcfs[i] / ((1 + wacc) ** (i + 1))
    
    # Calculate terminal value
    terminal_fcf = fcfs[-1] * (1 + terminal_growth)
    terminal_value = terminal_fcf / (wacc - terminal_growth)
    pv_terminal_value = terminal_value / ((1 + wacc) ** projection_years)
    
    # Calculate enterprise value
    enterprise_value = np.sum(pv_fcfs) + pv_terminal_value
    
    # Adjust for net debt to get equity value
    net_debt = 30_000_000  # $30M net debt
    equity_value = enterprise_value - net_debt
    
    # Create comprehensive visualization
    fig = plt.figure(figsize=(16, 10))
    gs = fig.add_gridspec(2, 3, hspace=0.35, wspace=0.3)
    fig.suptitle('DCF Model Structure: Complete Breakdown', fontsize=18, fontweight='bold', y=0.98)
    
    # Plot 1: Projected Free Cash Flows
    ax1 = fig.add_subplot(gs[0, 0])
    years = np.arange(1, projection_years + 1)
    bars1 = ax1.bar(years, fcfs / 1_000_000, color='#2E86AB', alpha=0.8, edgecolor='black', linewidth=1.5)
    ax1.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax1.set_ylabel('Free Cash Flow ($ Millions)', fontsize=11, fontweight='bold')
    ax1.set_title('Projected Free Cash Flows', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3, axis='y')
    ax1.set_xticks(years)
    for i, (bar, fcf) in enumerate(zip(bars1, fcfs)):
        height = bar.get_height()
        growth_pct = fcf_growth[i] * 100
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                 f'${fcf/1_000_000:.1f}M\n({growth_pct:.1f}%)', 
                 ha='center', va='bottom', fontweight='bold', fontsize=9)
    
    # Plot 2: Present Value of FCFs
    ax2 = fig.add_subplot(gs[0, 1])
    bars2 = ax2.bar(years, pv_fcfs / 1_000_000, color='#A23B72', alpha=0.8, edgecolor='black', linewidth=1.5)
    ax2.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax2.set_ylabel('Present Value ($ Millions)', fontsize=11, fontweight='bold')
    ax2.set_title('Present Value of Projected FCFs', fontsize=12, fontweight='bold')
    ax2.grid(True, alpha=0.3, axis='y')
    ax2.set_xticks(years)
    for bar, pv in zip(bars2, pv_fcfs):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                 f'${pv/1_000_000:.1f}M', ha='center', va='bottom', fontweight='bold', fontsize=9)
    
    # Plot 3: Value Components
    ax3 = fig.add_subplot(gs[0, 2])
    components = ['PV of\nProjected FCFs', 'PV of\nTerminal Value', 'Enterprise\nValue']
    values = [np.sum(pv_fcfs), pv_terminal_value, enterprise_value]
    colors = ['#F18F01', '#06A77D', '#7209B7']
    bars3 = ax3.bar(components, [v / 1_000_000 for v in values], color=colors, alpha=0.8, edgecolor='black', linewidth=2)
    ax3.set_ylabel('Value ($ Millions)', fontsize=11, fontweight='bold')
    ax3.set_title('Enterprise Value Components', fontsize=12, fontweight='bold')
    ax3.grid(True, alpha=0.3, axis='y')
    for bar, val in zip(bars3, values):
        height = bar.get_height()
        pct = (val / enterprise_value) * 100
        ax3.text(bar.get_x() + bar.get_width()/2., height,
                 f'${val/1_000_000:.1f}M\n({pct:.1f}%)', ha='center', va='bottom', fontweight='bold', fontsize=10)
    
    # Plot 4: Cash Flow Timeline
    ax4 = fig.add_subplot(gs[1, :2])
    years_extended = np.arange(1, projection_years + 2)
    fcfs_extended = np.append(fcfs, terminal_fcf)
    ax4.plot(years_extended[:-1], fcfs_extended[:-1] / 1_000_000, 'o-', linewidth=2.5, 
            markersize=10, color='#2E86AB', label='Projected FCFs', zorder=3)
    ax4.axvline(x=projection_years, color='r', linestyle='--', linewidth=2, alpha=0.7, label='Terminal Period Start')
    ax4.plot([projection_years, projection_years + 1], 
             [fcfs[-1] / 1_000_000, terminal_fcf / 1_000_000], 
             'o--', linewidth=2, markersize=8, color='#F18F01', label='Terminal FCF', zorder=3)
    ax4.fill_between(years_extended[:-1], 0, fcfs_extended[:-1] / 1_000_000, alpha=0.3, color='#2E86AB')
    ax4.set_xlabel('Year', fontsize=12, fontweight='bold')
    ax4.set_ylabel('Free Cash Flow ($ Millions)', fontsize=12, fontweight='bold')
    ax4.set_title('DCF Cash Flow Timeline', fontsize=13, fontweight='bold')
    ax4.grid(True, alpha=0.3)
    ax4.legend(loc='best', fontsize=10)
    ax4.set_xticks(years_extended)
    
    # Plot 5: Value Breakdown Summary
    ax5 = fig.add_subplot(gs[1, 2])
    ax5.axis('off')
    summary_text = f"""
    DCF MODEL SUMMARY
    
    Projection Period: {projection_years} years
    WACC: {wacc*100:.1f}%
    Terminal Growth: {terminal_growth*100:.1f}%
    
    VALUE BREAKDOWN:
      PV of Projected FCFs:  ${np.sum(pv_fcfs)/1_000_000:.1f}M
      PV of Terminal Value:  ${pv_terminal_value/1_000_000:.1f}M
      ─────────────────────────────
      Enterprise Value:      ${enterprise_value/1_000_000:.1f}M
      
      Less: Net Debt:        ${net_debt/1_000_000:.1f}M
      ─────────────────────────────
      Equity Value:          ${equity_value/1_000_000:.1f}M
    
    TERMINAL VALUE:
      Terminal FCF:          ${terminal_fcf/1_000_000:.1f}M
      Terminal Value:         ${terminal_value/1_000_000:.1f}M
      PV of Terminal Value:  ${pv_terminal_value/1_000_000:.1f}M
      
      Terminal Value %:      {(pv_terminal_value/enterprise_value)*100:.1f}%
    """
    ax5.text(0.1, 0.5, summary_text, fontsize=10, fontfamily='monospace', 
             verticalalignment='center', fontweight='bold',
             bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
    
    plt.tight_layout()
    display(fig)
    plt.close()
    
    print(f"\n📊 **DCF Model Structure Analysis**")
    print(f"{'='*70}")
    print(f"Enterprise Value:              ${enterprise_value:,.0f}")
    print(f"  - PV of Projected FCFs:      ${np.sum(pv_fcfs):,.0f} ({(np.sum(pv_fcfs)/enterprise_value)*100:.1f}%)")
    print(f"  - PV of Terminal Value:       ${pv_terminal_value:,.0f} ({(pv_terminal_value/enterprise_value)*100:.1f}%)")
    print(f"{'='*70}")
    print(f"Less: Net Debt:                 ${net_debt:,.0f}")
    print(f"{'='*70}")
    print(f"Equity Value:                   ${equity_value:,.0f}")
    print(f"{'='*70}")
    print(f"✅ Key Insight: Terminal value represents {(pv_terminal_value/enterprise_value)*100:.1f}% of enterprise value,")
    print(f"   highlighting the importance of terminal value assumptions in DCF models.")
    
    
    
    
    
    
    

    Cash Flow Projections: Building the Foundation

    Accurate cash flow projections are the foundation of a reliable DCF model. Projections require a deep understanding of the company's business model, industry dynamics, competitive position, and growth drivers. The projection process involves forecasting each component of free cash flow.

    Revenue Forecasting

    Revenue forecasting is typically the starting point for cash flow projections. Revenue growth depends on multiple factors:

    Revenue forecasting methods include:

    Revenue projections should be realistic and reflect the company's competitive position and industry dynamics. High growth rates are difficult to sustain, and projections should typically show growth rates declining toward a sustainable long-term rate.

    Expense Projections

    Expense projections involve forecasting operating expenses, which typically include:

    Expense projections should consider:

    A common approach is to forecast expenses as a percentage of revenue, adjusted for expected changes in operating leverage and efficiency. This approach captures the relationship between revenue and expenses while allowing for margin expansion or contraction.

    Working Capital Projections

    Working capital represents the investment required to operate the business and includes:

    The change in net working capital (

    #x27; in math mode at position 1: $̲$CapEx = Mainte…" style="color:#cc0000">$CapEx = Maintenance\ CapEx + Growth\ CapEx$ ) represents the cash investment required to support business growth. Working capital typically grows with revenue, and the relationship can be expressed as:

    #x27; in math mode at position 1: $̲$\Delta NWC = W…" style="color:#cc0000">$\Delta NWC = WC\% \times \Delta Revenue$

    Where:

    Working capital requirements vary by industry. Retail companies typically have high inventory requirements, while service companies may have minimal working capital needs. Understanding industry norms is important for accurate projections.

    Capital Expenditure Projections

    Capital expenditures (CapEx) represent investments in long-term assets such as property, plant, and equipment. CapEx is necessary to:

    CapEx projections typically separate maintenance CapEx (required to maintain operations) from growth CapEx (required to support growth):

    #x27; in math mode at position 1: $̲$CapEx = Mainte…" style="color:#cc0000">$CapEx = Maintenance\ CapEx + Growth\ CapEx$

    Where:

    Capital intensity varies significantly by industry. Capital-intensive industries (e.g., manufacturing, utilities) require substantial CapEx, while asset-light industries (e.g., software, services) require minimal CapEx.

    Let's visualize the cash flow projection process:

    Python exercise

    #| label: cash-flow-projection-process
    #| fig-cap: "Cash Flow Projection Process: Building the Foundation of DCF Analysis"
    #| fig-width: 16
    #| fig-height: 12
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Company parameters - starting point
    base_revenue = 50_000_000  # $50M base revenue
    revenue_growth = np.array([0.12, 0.10, 0.08, 0.07, 0.06])  # Declining growth
    ebitda_margin = 0.25  # 25% EBITDA margin
    tax_rate = 0.25  # 25% tax rate
    depreciation_rate = 0.05  # 5% of revenue
    capex_rate = 0.08  # 8% of revenue
    nwc_rate = 0.15  # 15% of revenue
    
    # Project revenue
    revenues = np.zeros(5)
    revenues[0] = base_revenue
    for i in range(1, 5):
        revenues[i] = revenues[i-1] * (1 + revenue_growth[i])
    
    # Calculate EBITDA
    ebitdas = revenues * ebitda_margin
    
    # Calculate EBIT (EBITDA - D&A)
    depreciation = revenues * depreciation_rate
    ebit = ebitdas - depreciation
    
    # Calculate NOPAT (Net Operating Profit After Tax)
    nopat = ebit * (1 - tax_rate)
    
    # Calculate CapEx
    capex = revenues * capex_rate
    
    # Calculate change in NWC
    nwc = revenues * nwc_rate
    delta_nwc = np.zeros(5)
    delta_nwc[0] = nwc[0]
    for i in range(1, 5):
        delta_nwc[i] = nwc[i] - nwc[i-1]
    
    # Calculate Free Cash Flow
    fcfs = nopat + depreciation - capex - delta_nwc
    
    # Create comprehensive visualization
    fig = plt.figure(figsize=(16, 12))
    gs = fig.add_gridspec(3, 3, hspace=0.35, wspace=0.3)
    fig.suptitle('Cash Flow Projection Process: Building the Foundation', fontsize=18, fontweight='bold', y=0.98)
    
    # Plot 1: Revenue Projection
    ax1 = fig.add_subplot(gs[0, 0])
    years = np.arange(1, 6)
    bars1 = ax1.bar(years, revenues / 1_000_000, color='#2E86AB', alpha=0.8, edgecolor='black', linewidth=1.5)
    ax1.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax1.set_ylabel('Revenue ($ Millions)', fontsize=11, fontweight='bold')
    ax1.set_title('Revenue Projection', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3, axis='y')
    ax1.set_xticks(years)
    for i, (bar, rev, growth) in enumerate(zip(bars1, revenues, revenue_growth)):
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                 f'${rev/1_000_000:.1f}M\n({growth*100:.1f}%)', 
                 ha='center', va='bottom', fontweight='bold', fontsize=9)
    
    # Plot 2: EBITDA and EBIT
    ax2 = fig.add_subplot(gs[0, 1])
    x = np.arange(len(years))
    width = 0.35
    bars2a = ax2.bar(x - width/2, ebitdas / 1_000_000, width, label='EBITDA', color='#A23B72', alpha=0.8, edgecolor='black')
    bars2b = ax2.bar(x + width/2, ebit / 1_000_000, width, label='EBIT', color='#F18F01', alpha=0.8, edgecolor='black')
    ax2.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax2.set_ylabel('Value ($ Millions)', fontsize=11, fontweight='bold')
    ax2.set_title('EBITDA and EBIT', fontsize=12, fontweight='bold')
    ax2.set_xticks(x)
    ax2.set_xticklabels(years)
    ax2.legend(loc='best', fontsize=9)
    ax2.grid(True, alpha=0.3, axis='y')
    
    # Plot 3: NOPAT Calculation
    ax3 = fig.add_subplot(gs[0, 2])
    bars3 = ax3.bar(years, nopat / 1_000_000, color='#06A77D', alpha=0.8, edgecolor='black', linewidth=1.5)
    ax3.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax3.set_ylabel('NOPAT ($ Millions)', fontsize=11, fontweight='bold')
    ax3.set_title('Net Operating Profit After Tax', fontsize=12, fontweight='bold')
    ax3.grid(True, alpha=0.3, axis='y')
    ax3.set_xticks(years)
    for bar, nop in zip(bars3, nopat):
        height = bar.get_height()
        ax3.text(bar.get_x() + bar.get_width()/2., height,
                 f'${nop/1_000_000:.1f}M', ha='center', va='bottom', fontweight='bold', fontsize=9)
    
    # Plot 4: CapEx and Depreciation
    ax4 = fig.add_subplot(gs[1, 0])
    bars4a = ax4.bar(x - width/2, capex / 1_000_000, width, label='CapEx', color='#7209B7', alpha=0.8, edgecolor='black')
    bars4b = ax4.bar(x + width/2, depreciation / 1_000_000, width, label='D&A', color='#4CC9F0', alpha=0.8, edgecolor='black')
    ax4.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax4.set_ylabel('Value ($ Millions)', fontsize=11, fontweight='bold')
    ax4.set_title('Capital Expenditures and Depreciation', fontsize=12, fontweight='bold')
    ax4.set_xticks(x)
    ax4.set_xticklabels(years)
    ax4.legend(loc='best', fontsize=9)
    ax4.grid(True, alpha=0.3, axis='y')
    
    # Plot 5: Change in Net Working Capital
    ax5 = fig.add_subplot(gs[1, 1])
    colors_delta = ['#D00000' if d < 0 else '#06A77D' for d in delta_nwc]
    bars5 = ax5.bar(years, delta_nwc / 1_000_000, color=colors_delta, alpha=0.8, edgecolor='black', linewidth=1.5)
    ax5.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax5.set_ylabel('Change in NWC ($ Millions)', fontsize=11, fontweight='bold')
    ax5.set_title('Change in Net Working Capital', fontsize=12, fontweight='bold')
    ax5.grid(True, alpha=0.3, axis='y')
    ax5.axhline(y=0, color='black', linestyle='-', linewidth=1)
    ax5.set_xticks(years)
    for bar, delta in zip(bars5, delta_nwc):
        height = bar.get_height()
        ax5.text(bar.get_x() + bar.get_width()/2., height,
                 f'${delta/1_000_000:.2f}M', ha='center', 
                 va='bottom' if delta >= 0 else 'top', fontweight='bold', fontsize=9)
    
    # Plot 6: Free Cash Flow
    ax6 = fig.add_subplot(gs[1, 2])
    colors_fcf = ['#D00000' if f < 0 else '#06A77D' for f in fcfs]
    bars6 = ax6.bar(years, fcfs / 1_000_000, color=colors_fcf, alpha=0.8, edgecolor='black', linewidth=2)
    ax6.set_xlabel('Year', fontsize=11, fontweight='bold')
    ax6.set_ylabel('Free Cash Flow ($ Millions)', fontsize=11, fontweight='bold')
    ax6.set_title('Free Cash Flow (Final Result)', fontsize=12, fontweight='bold')
    ax6.grid(True, alpha=0.3, axis='y')
    ax6.axhline(y=0, color='black', linestyle='-', linewidth=1)
    ax6.set_xticks(years)
    for bar, fcf in zip(bars6, fcfs):
        height = bar.get_height()
        ax6.text(bar.get_x() + bar.get_width()/2., height,
                 f'${fcf/1_000_000:.1f}M', ha='center', 
                 va='bottom' if fcf >= 0 else 'top', fontweight='bold', fontsize=10)
    
    # Plot 7: FCF Bridge (Waterfall)
    ax7 = fig.add_subplot(gs[2, :])
    year_idx = 2  # Show Year 3 as example
    components = ['NOPAT', '+ D&A', '- CapEx', '- ΔNWC', '= FCF']
    values_bridge = [nopat[year_idx], depreciation[year_idx], -capex[year_idx], -delta_nwc[year_idx], fcfs[year_idx]]
    cumulative = np.cumsum([0] + values_bridge[:-1])
    colors_bridge = ['#06A77D', '#4CC9F0', '#7209B7', '#F18F01', '#2E86AB']
    bars7 = ax7.bar(components, [v / 1_000_000 for v in values_bridge], 
                    bottom=[c / 1_000_000 for c in cumulative],
                    color=colors_bridge, alpha=0.8, edgecolor='black', linewidth=1.5)
    ax7.set_ylabel('Value ($ Millions)', fontsize=12, fontweight='bold')
    ax7.set_title(f'Free Cash Flow Bridge - Year {year_idx + 1}', fontsize=13, fontweight='bold')
    ax7.grid(True, alpha=0.3, axis='y')
    ax7.axhline(y=0, color='black', linestyle='-', linewidth=1)
    for i, (bar, val, cum) in enumerate(zip(bars7, values_bridge, cumulative)):
        height = bar.get_height()
        y_pos = (cum + val/2) / 1_000_000
        ax7.text(bar.get_x() + bar.get_width()/2., y_pos,
                 f'${val/1_000_000:.1f}M', ha='center', va='center', fontweight='bold', fontsize=10)
    
    plt.tight_layout()
    display(fig)
    plt.close()
    
    print(f"\n📊 **Cash Flow Projection Analysis**")
    print(f"{'='*70}")
    print(f"Year 1 Revenue:                 ${revenues[0]:,.0f}")
    print(f"Year 5 Revenue:                 ${revenues[4]:,.0f}")
    print(f"5-Year Revenue CAGR:            {(revenues[4]/revenues[0])**(1/5)-1:.1%}")
    print(f"{'='*70}")
    print(f"Year 1 FCF:                     ${fcfs[0]:,.0f}")
    print(f"Year 5 FCF:                     ${fcfs[4]:,.0f}")
    print(f"5-Year FCF CAGR:                {(fcfs[4]/fcfs[0])**(1/5)-1:.1%}")
    print(f"{'='*70}")
    print(f"Average FCF Margin:             {np.mean(fcfs/revenues):.1%}")
    print(f"✅ Key Insight: FCF projections require careful modeling of revenue growth,")
    print(f"   operating margins, capital intensity, and working capital requirements.")
    
    
    
    
    
    
    

    Discount Rate Calculation: Cost of Capital

    The discount rate (WACC) is a critical input in DCF analysis, as small changes in WACC can significantly impact valuation. WACC calculation requires estimating the cost of equity and the cost of debt, and determining the appropriate capital structure weights.

    Cost of Equity: Capital Asset Pricing Model (CAPM)

    The cost of equity represents the return required by equity investors to compensate them for the risk of investing in the company's stock. The most common method for estimating the cost of equity is the Capital Asset Pricing Model (CAPM):

    #x27; in math mode at position 1: $̲$r_e = r_f + \b…" style="color:#cc0000">$r_e = r_f + \beta(E[R_m] - r_f)$

    Where:

    Risk-Free Rate: Typically the yield on long-term government bonds (10-year Treasury bonds in the U.S.). The risk-free rate should match the projection period (long-term for DCF models).

    Beta: Measures the sensitivity of the company's stock returns to market returns. Beta is typically estimated using historical stock price data, regressing company returns against market returns. Beta can also be estimated using comparable companies or industry averages.

    Market Risk Premium: The excess return that investors expect from the market over the risk-free rate. Historical market risk premiums are typically in the range of 5-7%, though forward-looking estimates may differ.

    CAPM has limitations:

    Despite these limitations, CAPM remains widely used because of its simplicity and theoretical foundation.

    Alternative Cost of Equity Models

    Build-Up Method: Adds various risk premiums to the risk-free rate:

    #x27; in math mode at position 1: $̲$r_e = r_f + ER…" style="color:#cc0000">$r_e = r_f + ERP + Size\ Premium + Industry\ Premium + Company\ Premium$

    Where risk premiums might include:

    Fama-French Three-Factor Model: Extends CAPM to include size and value factors:

    #x27; in math mode at position 1: $̲$r_e = r_f + \b…" style="color:#cc0000">$r_e = r_f + \beta(E[R_m] - r_f) + s \times SMB + h \times HML$

    Where:

    Dividend Growth Model: For companies with stable dividends:

    #x27; in math mode at position 1: $̲$r_e = \frac{D_…" style="color:#cc0000">$r_e = \frac{D_1}{P_0} + g$

    Where:

    Cost of Debt

    The cost of debt represents the interest rate the company pays on its debt. For companies with publicly traded debt, the cost of debt can be observed directly as the yield to maturity on the company's bonds. For companies without publicly traded debt, the cost of debt can be estimated as:

    #x27; in math mode at position 1: $̲$r_d = r_f + Cr…" style="color:#cc0000">$r_d = r_f + Credit\ Spread$

    Where:

    The cost of debt is tax-advantaged because interest payments are tax-deductible. The after-tax cost of debt is:

    #x27; in math mode at position 1: $̲$r_d^{after-tax…" style="color:#cc0000">$r_d^{after-tax} = r_d(1-t)$

    Where #x27; in math mode at position 1: $̲$TV = \frac{FCF…" style="color:#cc0000">$TV = \frac{FCF_{n+1}}{WACC - g}$ is the tax rate.

    WACC Calculation and Capital Structure

    WACC calculation requires determining the appropriate capital structure (the mix of debt and equity). The capital structure used in WACC should reflect:

    The capital structure weights should be based on market values, not book values, because market values reflect the true cost of capital. Market values can be volatile, so many practitioners use target capital structures or average market values over time.

    Let's visualize WACC calculation and its components:

    Python exercise

    #| label: wacc-calculation-components
    #| fig-cap: "WACC Calculation: Components and Sensitivity Analysis"
    #| fig-width: 16
    #| fig-height: 12
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # WACC Components
    risk_free_rate = 0.035  # 3.5% risk-free rate
    beta = 1.2  # Beta
    market_return = 0.10  # 10% expected market return
    market_risk_premium = market_return - risk_free_rate  # 6.5%
    
    # Cost of equity (CAPM)
    cost_of_equity = risk_free_rate + beta * market_risk_premium
    
    # Cost of debt
    credit_spread = 0.025  # 2.5% credit spread
    cost_of_debt = risk_free_rate + credit_spread
    tax_rate = 0.25  # 25% tax rate
    after_tax_cost_of_debt = cost_of_debt * (1 - tax_rate)
    
    # Capital structure
    equity_value = 100_000_000  # $100M equity
    debt_value = 40_000_000  # $40M debt
    total_value = equity_value + debt_value
    equity_weight = equity_value / total_value
    debt_weight = debt_value / total_value
    
    # WACC calculation
    wacc = (equity_weight * cost_of_equity) + (debt_weight * after_tax_cost_of_debt)
    
    # Create comprehensive visualization
    fig = plt.figure(figsize=(16, 12))
    gs = fig.add_gridspec(3, 3, hspace=0.35, wspace=0.3)
    fig.suptitle('WACC Calculation: Components and Analysis', fontsize=18, fontweight='bold', y=0.98)
    
    # Plot 1: Cost of Equity Components (CAPM)
    ax1 = fig.add_subplot(gs[0, 0])
    capm_components = ['Risk-Free\nRate', 'Beta × MRP', 'Cost of\nEquity']
    capm_values = [risk_free_rate * 100, (beta * market_risk_premium) * 100, cost_of_equity * 100]
    colors_capm = ['#2E86AB', '#A23B72', '#F18F01']
    bars1 = ax1.bar(capm_components, capm_values, color=colors_capm, alpha=0.8, edgecolor='black', linewidth=2)
    ax1.set_ylabel('Rate (%)', fontsize=11, fontweight='bold')
    ax1.set_title('Cost of Equity (CAPM)', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3, axis='y')
    for bar, val in zip(bars1, capm_values):
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                 f'{val:.2f}%', ha='center', va='bottom', fontweight='bold', fontsize=10)
    
    # Plot 2: Cost of Debt Components
    ax2 = fig.add_subplot(gs[0, 1])
    debt_components = ['Risk-Free\nRate', 'Credit\nSpread', 'Pre-Tax\nCost', 'Tax Shield', 'After-Tax\nCost']
    debt_values = [risk_free_rate * 100, credit_spread * 100, cost_of_debt * 100, 
                   (cost_of_debt - after_tax_cost_of_debt) * 100, after_tax_cost_of_debt * 100]
    colors_debt = ['#2E86AB', '#A23B72', '#F18F01', '#06A77D', '#7209B7']
    bars2 = ax2.bar(debt_components, debt_values, color=colors_debt, alpha=0.8, edgecolor='black', linewidth=2)
    ax2.set_ylabel('Rate (%)', fontsize=11, fontweight='bold')
    ax2.set_title('Cost of Debt', fontsize=12, fontweight='bold')
    ax2.grid(True, alpha=0.3, axis='y')
    for bar, val in zip(bars2, debt_values):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                 f'{val:.2f}%', ha='center', va='bottom', fontweight='bold', fontsize=9)
    
    # Plot 3: Capital Structure
    ax3 = fig.add_subplot(gs[0, 2])
    capital_components = ['Equity', 'Debt']
    capital_values = [equity_value / 1_000_000, debt_value / 1_000_000]
    colors_capital = ['#2E86AB', '#A23B72']
    bars3 = ax3.bar(capital_components, capital_values, color=colors_capital, alpha=0.8, edgecolor='black', linewidth=2)
    ax3.set_ylabel('Value ($ Millions)', fontsize=11, fontweight='bold')
    ax3.set_title('Capital Structure', fontsize=12, fontweight='bold')
    ax3.grid(True, alpha=0.3, axis='y')
    for bar, val, weight in zip(bars3, capital_values, [equity_weight, debt_weight]):
        height = bar.get_height()
        ax3.text(bar.get_x() + bar.get_width()/2., height,
                 f'${val:.1f}M\n({weight*100:.1f}%)', ha='center', va='bottom', fontweight='bold', fontsize=10)
    
    # Plot 4: WACC Components (Weighted)
    ax4 = fig.add_subplot(gs[1, 0])
    wacc_components = ['Equity\nComponent', 'Debt\nComponent', 'WACC']
    wacc_component_values = [(equity_weight * cost_of_equity) * 100, 
                              (debt_weight * after_tax_cost_of_debt) * 100, wacc * 100]
    colors_wacc = ['#2E86AB', '#A23B72', '#F18F01']
    bars4 = ax4.bar(wacc_components, wacc_component_values, color=colors_wacc, alpha=0.8, edgecolor='black', linewidth=2)
    ax4.set_ylabel('Weighted Cost (%)', fontsize=11, fontweight='bold')
    ax4.set_title('WACC Components', fontsize=12, fontweight='bold')
    ax4.grid(True, alpha=0.3, axis='y')
    for bar, val in zip(bars4, wacc_component_values):
        height = bar.get_height()
        ax4.text(bar.get_x() + bar.get_width()/2., height,
                 f'{val:.2f}%', ha='center', va='bottom', fontweight='bold', fontsize=10)
    
    # Plot 5: Beta Sensitivity
    ax5 = fig.add_subplot(gs[1, 1])
    beta_range = np.linspace(0.5, 2.0, 50)
    cost_of_equity_range = risk_free_rate + beta_range * market_risk_premium
    wacc_range_beta = (equity_weight * cost_of_equity_range) + (debt_weight * after_tax_cost_of_debt)
    ax5.plot(beta_range, wacc_range_beta * 100, 'b-', linewidth=2.5, label='WACC')
    ax5.axvline(x=beta, color='r', linestyle='--', linewidth=2, label=f'Base Beta: {beta:.2f}', alpha=0.7)
    ax5.axhline(y=wacc * 100, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax5.set_xlabel('Beta', fontsize=11, fontweight='bold')
    ax5.set_ylabel('WACC (%)', fontsize=11, fontweight='bold')
    ax5.set_title('WACC Sensitivity to Beta', fontsize=12, fontweight='bold')
    ax5.grid(True, alpha=0.3)
    ax5.legend(loc='best', fontsize=9)
    
    # Plot 6: Capital Structure Sensitivity
    ax6 = fig.add_subplot(gs[1, 2])
    debt_ratio_range = np.linspace(0.0, 0.7, 50)
    wacc_range_structure = []
    for dr in debt_ratio_range:
        ew = 1 - dr
        dw = dr
        w = (ew * cost_of_equity) + (dw * after_tax_cost_of_debt)
        wacc_range_structure.append(w)
    ax6.plot(debt_ratio_range * 100, [w * 100 for w in wacc_range_structure], 'g-', linewidth=2.5, label='WACC')
    ax6.axvline(x=debt_weight * 100, color='r', linestyle='--', linewidth=2, 
                label=f'Current Debt Ratio: {debt_weight*100:.1f}%', alpha=0.7)
    ax6.axhline(y=wacc * 100, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax6.set_xlabel('Debt Ratio (%)', fontsize=11, fontweight='bold')
    ax6.set_ylabel('WACC (%)', fontsize=11, fontweight='bold')
    ax6.set_title('WACC Sensitivity to Capital Structure', fontsize=12, fontweight='bold')
    ax6.grid(True, alpha=0.3)
    ax6.legend(loc='best', fontsize=9)
    
    # Plot 7: WACC Summary
    ax7 = fig.add_subplot(gs[2, :])
    ax7.axis('off')
    summary_text = f"""
    WACC CALCULATION SUMMARY
    
    COST OF EQUITY (CAPM):
      Risk-Free Rate:              {risk_free_rate*100:.2f}%
      Beta:                         {beta:.2f}
      Market Risk Premium:          {market_risk_premium*100:.2f}%
      ─────────────────────────────────────
      Cost of Equity:               {cost_of_equity*100:.2f}%
    
    COST OF DEBT:
      Risk-Free Rate:               {risk_free_rate*100:.2f}%
      Credit Spread:                {credit_spread*100:.2f}%
      ─────────────────────────────────────
      Pre-Tax Cost of Debt:         {cost_of_debt*100:.2f}%
      Tax Rate:                     {tax_rate*100:.1f}%
      Tax Shield:                   {(cost_of_debt - after_tax_cost_of_debt)*100:.2f}%
      ─────────────────────────────────────
      After-Tax Cost of Debt:       {after_tax_cost_of_debt*100:.2f}%
    
    CAPITAL STRUCTURE:
      Equity Value:                 ${equity_value/1_000_000:.1f}M ({equity_weight*100:.1f}%)
      Debt Value:                   ${debt_value/1_000_000:.1f}M ({debt_weight*100:.1f}%)
      Total Value:                  ${total_value/1_000_000:.1f}M
    
    WACC CALCULATION:
      Equity Component:             {(equity_weight * cost_of_equity)*100:.2f}%
      Debt Component:               {(debt_weight * after_tax_cost_of_debt)*100:.2f}%
      ─────────────────────────────────────
      WACC:                         {wacc*100:.2f}%
    """
    ax7.text(0.1, 0.5, summary_text, fontsize=10, fontfamily='monospace', 
             verticalalignment='center', fontweight='bold',
             bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
    
    plt.tight_layout()
    display(fig)
    plt.close()
    
    print(f"\n📊 **WACC Calculation Analysis**")
    print(f"{'='*70}")
    print(f"Cost of Equity (CAPM):          {cost_of_equity*100:.2f}%")
    print(f"  = {risk_free_rate*100:.2f}% + {beta:.2f} × {market_risk_premium*100:.2f}%")
    print(f"{'='*70}")
    print(f"After-Tax Cost of Debt:         {after_tax_cost_of_debt*100:.2f}%")
    print(f"  = {cost_of_debt*100:.2f}% × (1 - {tax_rate*100:.1f}%)")
    print(f"{'='*70}")
    print(f"WACC:                            {wacc*100:.2f}%")
    print(f"  = {equity_weight*100:.1f}% × {cost_of_equity*100:.2f}% + {debt_weight*100:.1f}% × {after_tax_cost_of_debt*100:.2f}%")
    print(f"{'='*70}")
    print(f"✅ Key Insight: WACC is sensitive to beta, capital structure, and market conditions.")
    print(f"   Small changes in these inputs can significantly impact valuation.")
    
    
    
    
    
    
    

    Terminal Value Methods: Capturing Long-Term Value

    Terminal value often represents a significant portion of total DCF value (sometimes 50-70% or more), making it a critical component of DCF analysis. Understanding terminal value methods and their assumptions is essential for robust valuation.

    Perpetuity Growth Model: Theoretical Foundation

    The perpetuity growth model assumes that cash flows will grow at a constant rate forever. This method is theoretically sound because it's based on DCF principles and provides a consistent framework for terminal value calculation.

    The perpetuity growth model formula is:

    #x27; in math mode at position 1: $̲$TV = \frac{FCF…" style="color:#cc0000">$TV = \frac{FCF_{n+1}}{WACC - g}$

    Key considerations for the growth rate (#x27; in math mode at position 1: $̲$TV = EBITDA_n …" style="color:#cc0000">$TV = EBITDA_n \times EV/EBITDA_{multiple}$ ):

    The growth rate assumption is critical because small changes can significantly impact terminal value. A growth rate that is too high can lead to unrealistic valuations, while a growth rate that is too low may undervalue the company.

    Exit Multiple Method: Market-Based Approach

    The exit multiple method assumes the company will be sold at the end of the projection period at a multiple of a financial metric, similar to how comparable companies are valued. This method is more market-based and can provide a reality check on perpetuity growth model results.

    The exit multiple method formula is:

    #x27; in math mode at position 1: $̲$TV = EBITDA_n …" style="color:#cc0000">$TV = EBITDA_n \times EV/EBITDA_{multiple}$

    Common multiples used include:

    The multiple should be based on:

    The exit multiple method has the advantage of being based on observable market data, but it assumes that market multiples will remain constant, which may not be realistic.

    Terminal Value Best Practices

    Best practices for terminal value calculation include:

    1. Use both methods: Calculate terminal value using both perpetuity growth and exit multiple methods, then triangulate
    2. Sensitivity analysis: Test how changes in assumptions affect terminal value
    3. Reality checks: Compare terminal value assumptions to historical performance and industry norms
    4. Consistency: Ensure terminal value assumptions are consistent with projection period assumptions
    5. Documentation: Clearly document all assumptions and rationale

    Terminal value often represents a large portion of total value, so it's important to validate assumptions carefully and consider multiple scenarios.

    Let's visualize terminal value calculation and sensitivity:

    Python exercise

    #| label: terminal-value-calculation-sensitivity
    #| fig-cap: "Terminal Value Calculation: Methods and Sensitivity Analysis"
    #| fig-width: 16
    #| fig-height: 12
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Base parameters
    final_year_fcf = 15_000_000  # $15M FCF in final projection year
    wacc = 0.10  # 10% WACC
    terminal_growth = 0.03  # 3% terminal growth
    final_year_ebitda = 25_000_000  # $25M EBITDA in final year
    ev_ebitda_multiple = 8.0  # 8x EV/EBITDA multiple
    projection_years = 5
    
    # Perpetuity Growth Model
    terminal_fcf = final_year_fcf * (1 + terminal_growth)
    terminal_value_perpetuity = terminal_fcf / (wacc - terminal_growth)
    pv_terminal_value_perpetuity = terminal_value_perpetuity / ((1 + wacc) ** projection_years)
    
    # Exit Multiple Method
    terminal_value_exit = final_year_ebitda * ev_ebitda_multiple
    pv_terminal_value_exit = terminal_value_exit / ((1 + wacc) ** projection_years)
    
    # Create comprehensive visualization
    fig = plt.figure(figsize=(16, 12))
    gs = fig.add_gridspec(3, 3, hspace=0.35, wspace=0.3)
    fig.suptitle('Terminal Value Calculation: Methods and Sensitivity', fontsize=18, fontweight='bold', y=0.98)
    
    # Plot 1: Terminal Value Methods Comparison
    ax1 = fig.add_subplot(gs[0, 0])
    methods = ['Perpetuity\nGrowth', 'Exit\nMultiple']
    tv_values = [pv_terminal_value_perpetuity, pv_terminal_value_exit]
    colors = ['#2E86AB', '#A23B72']
    bars1 = ax1.bar(methods, [v / 1_000_000 for v in tv_values], color=colors, alpha=0.8, edgecolor='black', linewidth=2)
    ax1.set_ylabel('PV of Terminal Value ($ Millions)', fontsize=11, fontweight='bold')
    ax1.set_title('Terminal Value Methods', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3, axis='y')
    for bar, val in zip(bars1, tv_values):
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                 f'${val/1_000_000:.1f}M', ha='center', va='bottom', fontweight='bold', fontsize=11)
    
    # Plot 2: Terminal Growth Rate Sensitivity
    ax2 = fig.add_subplot(gs[0, 1])
    growth_range = np.linspace(0.01, 0.05, 50)
    tv_growth_sensitivity = []
    for g in growth_range:
        if g < wacc:  # Growth must be less than WACC
            tv_fcf = final_year_fcf * (1 + g)
            tv = tv_fcf / (wacc - g)
            pv_tv = tv / ((1 + wacc) ** projection_years)
            tv_growth_sensitivity.append(pv_tv)
        else:
            tv_growth_sensitivity.append(np.nan)
    ax2.plot(growth_range * 100, [v / 1_000_000 for v in tv_growth_sensitivity], 'b-', linewidth=2.5)
    ax2.axvline(x=terminal_growth * 100, color='r', linestyle='--', linewidth=2, 
                label=f'Base Growth: {terminal_growth*100:.1f}%', alpha=0.7)
    ax2.axhline(y=pv_terminal_value_perpetuity / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax2.set_xlabel('Terminal Growth Rate (%)', fontsize=11, fontweight='bold')
    ax2.set_ylabel('PV of Terminal Value ($ Millions)', fontsize=11, fontweight='bold')
    ax2.set_title('Sensitivity to Terminal Growth Rate', fontsize=12, fontweight='bold')
    ax2.grid(True, alpha=0.3)
    ax2.legend(loc='best', fontsize=9)
    
    # Plot 3: WACC Sensitivity
    ax3 = fig.add_subplot(gs[0, 2])
    wacc_range = np.linspace(0.08, 0.15, 50)
    tv_wacc_sensitivity = []
    for w in wacc_range:
        if w > terminal_growth:  # WACC must be greater than growth
            tv_fcf = final_year_fcf * (1 + terminal_growth)
            tv = tv_fcf / (w - terminal_growth)
            pv_tv = tv / ((1 + w) ** projection_years)
            tv_wacc_sensitivity.append(pv_tv)
        else:
            tv_wacc_sensitivity.append(np.nan)
    ax3.plot(wacc_range * 100, [v / 1_000_000 for v in tv_wacc_sensitivity], 'g-', linewidth=2.5)
    ax3.axvline(x=wacc * 100, color='r', linestyle='--', linewidth=2, 
                label=f'Base WACC: {wacc*100:.1f}%', alpha=0.7)
    ax3.axhline(y=pv_terminal_value_perpetuity / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax3.set_xlabel('WACC (%)', fontsize=11, fontweight='bold')
    ax3.set_ylabel('PV of Terminal Value ($ Millions)', fontsize=11, fontweight='bold')
    ax3.set_title('Sensitivity to WACC', fontsize=12, fontweight='bold')
    ax3.grid(True, alpha=0.3)
    ax3.legend(loc='best', fontsize=9)
    
    # Plot 4: Exit Multiple Sensitivity
    ax4 = fig.add_subplot(gs[1, 0])
    multiple_range = np.linspace(5.0, 12.0, 50)
    tv_multiple_sensitivity = [final_year_ebitda * m / ((1 + wacc) ** projection_years) for m in multiple_range]
    ax4.plot(multiple_range, [v / 1_000_000 for v in tv_multiple_sensitivity], 'm-', linewidth=2.5)
    ax4.axvline(x=ev_ebitda_multiple, color='r', linestyle='--', linewidth=2, 
                label=f'Base Multiple: {ev_ebitda_multiple:.1f}x', alpha=0.7)
    ax4.axhline(y=pv_terminal_value_exit / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax4.set_xlabel('EV/EBITDA Multiple', fontsize=11, fontweight='bold')
    ax4.set_ylabel('PV of Terminal Value ($ Millions)', fontsize=11, fontweight='bold')
    ax4.set_title('Sensitivity to Exit Multiple', fontsize=12, fontweight='bold')
    ax4.grid(True, alpha=0.3)
    ax4.legend(loc='best', fontsize=9)
    
    # Plot 5: Two-Way Sensitivity (Growth vs WACC)
    ax5 = fig.add_subplot(gs[1, 1])
    growth_grid = np.linspace(0.015, 0.045, 20)
    wacc_grid = np.linspace(0.085, 0.125, 20)
    growth_mesh, wacc_mesh = np.meshgrid(growth_grid, wacc_grid)
    tv_mesh = np.zeros_like(growth_mesh)
    for i in range(len(wacc_grid)):
        for j in range(len(growth_grid)):
            if wacc_grid[i] > growth_grid[j]:
                tv_fcf = final_year_fcf * (1 + growth_grid[j])
                tv = tv_fcf / (wacc_grid[i] - growth_grid[j])
                tv_mesh[i, j] = tv / ((1 + wacc_grid[i]) ** projection_years)
            else:
                tv_mesh[i, j] = np.nan
    contour = ax5.contourf(growth_mesh * 100, wacc_mesh * 100, tv_mesh / 1_000_000, levels=20, cmap='viridis')
    ax5.axvline(x=terminal_growth * 100, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax5.axhline(y=wacc * 100, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax5.plot(terminal_growth * 100, wacc * 100, 'ro', markersize=10, label='Base Case')
    ax5.set_xlabel('Terminal Growth Rate (%)', fontsize=11, fontweight='bold')
    ax5.set_ylabel('WACC (%)', fontsize=11, fontweight='bold')
    ax5.set_title('Two-Way Sensitivity: Growth vs WACC', fontsize=12, fontweight='bold')
    plt.colorbar(contour, ax=ax5, label='PV of Terminal Value ($M)')
    ax5.legend(loc='best', fontsize=9)
    
    # Plot 6: Terminal Value as % of Total Value
    ax6 = fig.add_subplot(gs[1, 2])
    # Assume PV of projected FCFs
    pv_projected_fcfs = 50_000_000  # $50M for illustration
    enterprise_value_perpetuity = pv_projected_fcfs + pv_terminal_value_perpetuity
    enterprise_value_exit = pv_projected_fcfs + pv_terminal_value_exit
    tv_pct_perpetuity = (pv_terminal_value_perpetuity / enterprise_value_perpetuity) * 100
    tv_pct_exit = (pv_terminal_value_exit / enterprise_value_exit) * 100
    
    components = ['PV of\nProjected FCFs', 'PV of\nTerminal Value']
    values_perpetuity = [pv_projected_fcfs / 1_000_000, pv_terminal_value_perpetuity / 1_000_000]
    colors_pie = ['#F18F01', '#2E86AB']
    bars6 = ax6.bar(components, values_perpetuity, color=colors_pie, alpha=0.8, edgecolor='black', linewidth=2)
    ax6.set_ylabel('Value ($ Millions)', fontsize=11, fontweight='bold')
    ax6.set_title(f'Terminal Value: {tv_pct_perpetuity:.1f}% of Enterprise Value', fontsize=12, fontweight='bold')
    ax6.grid(True, alpha=0.3, axis='y')
    for bar, val, pct in zip(bars6, values_perpetuity, [100-tv_pct_perpetuity, tv_pct_perpetuity]):
        height = bar.get_height()
        ax6.text(bar.get_x() + bar.get_width()/2., height,
                 f'${val:.1f}M\n({pct:.1f}%)', ha='center', va='bottom', fontweight='bold', fontsize=10)
    
    # Plot 7: Summary
    ax7 = fig.add_subplot(gs[2, :])
    ax7.axis('off')
    summary_text = f"""
    TERMINAL VALUE CALCULATION SUMMARY
    
    PERPETUITY GROWTH MODEL:
      Final Year FCF:               ${final_year_fcf/1_000_000:.1f}M
      Terminal Growth Rate:          {terminal_growth*100:.1f}%
      WACC:                         {wacc*100:.1f}%
      ─────────────────────────────────────
      Terminal FCF:                 ${terminal_fcf/1_000_000:.1f}M
      Terminal Value:               ${terminal_value_perpetuity/1_000_000:.1f}M
      PV of Terminal Value:         ${pv_terminal_value_perpetuity/1_000_000:.1f}M
    
    EXIT MULTIPLE METHOD:
      Final Year EBITDA:            ${final_year_ebitda/1_000_000:.1f}M
      EV/EBITDA Multiple:           {ev_ebitda_multiple:.1f}x
      ─────────────────────────────────────
      Terminal Value:               ${terminal_value_exit/1_000_000:.1f}M
      PV of Terminal Value:         ${pv_terminal_value_exit/1_000_000:.1f}M
    
    COMPARISON:
      Difference:                   ${abs(pv_terminal_value_perpetuity - pv_terminal_value_exit)/1_000_000:.1f}M
      % Difference:                {abs(pv_terminal_value_perpetuity - pv_terminal_value_exit)/pv_terminal_value_perpetuity*100:.1f}%
    
    ASSUMPTIONS VALIDATION:
      Terminal Growth < WACC:       {terminal_growth < wacc} ✓
      Growth Rate Reasonable:        {terminal_growth <= 0.03} ✓ (≤ long-term GDP)
      Multiple Reasonable:           {5 <= ev_ebitda_multiple <= 12} ✓
    """
    ax7.text(0.1, 0.5, summary_text, fontsize=10, fontfamily='monospace', 
             verticalalignment='center', fontweight='bold',
             bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
    
    plt.tight_layout()
    display(fig)
    plt.close()
    
    print(f"\n📊 **Terminal Value Analysis**")
    print(f"{'='*70}")
    print(f"Perpetuity Growth Model:")
    print(f"  Terminal Value:               ${terminal_value_perpetuity/1_000_000:.1f}M")
    print(f"  PV of Terminal Value:         ${pv_terminal_value_perpetuity/1_000_000:.1f}M")
    print(f"{'='*70}")
    print(f"Exit Multiple Method:")
    print(f"  Terminal Value:               ${terminal_value_exit/1_000_000:.1f}M")
    print(f"  PV of Terminal Value:         ${pv_terminal_value_exit/1_000_000:.1f}M")
    print(f"{'='*70}")
    print(f"Terminal Value as % of Enterprise Value: {tv_pct_perpetuity:.1f}%")
    print(f"{'='*70}")
    print(f"✅ Key Insight: Terminal value often represents 50-70% of total DCF value,")
    print(f"   making terminal value assumptions critical. Both methods should be used")
    print(f"   and results triangulated.")
    
    
    
    
    
    
    

    Sensitivity Analysis: Understanding Value Drivers

    DCF models are sensitive to assumptions, and understanding these sensitivities is crucial for proper interpretation and use of DCF results. Sensitivity analysis helps identify the key value drivers and assess the impact of changes in assumptions on valuation.

    Key Value Drivers

    The key value drivers in a DCF model typically include:

    1. Revenue growth rate: Higher growth increases value
    2. Operating margins: Higher margins increase value
    3. WACC: Lower WACC increases value
    4. Terminal growth rate: Higher terminal growth increases value
    5. Capital intensity: Lower capital intensity increases value

    Understanding which assumptions have the greatest impact on value helps focus analysis on the most important factors and provides insight into valuation risks.

    Sensitivity Analysis Methods

    One-Way Sensitivity: Vary one assumption at a time to see its impact on value. This helps identify which assumptions are most critical.

    Two-Way Sensitivity (Tornado Diagram): Vary two assumptions simultaneously to see their combined impact. This helps understand interactions between assumptions.

    Scenario Analysis: Create multiple scenarios (base case, optimistic, pessimistic) with different sets of assumptions. This helps assess the range of possible values.

    Monte Carlo Simulation: Use probability distributions for assumptions and run thousands of simulations to generate a distribution of possible values. This provides a probabilistic view of valuation.

    Interpreting Sensitivity Results

    Sensitivity analysis results should be interpreted carefully:

    Sensitivity analysis helps identify valuation risks and provides a framework for understanding the confidence level in DCF results.

    Let's create a comprehensive sensitivity analysis:

    Python exercise

    #| label: comprehensive-sensitivity-analysis
    #| fig-cap: "Comprehensive Sensitivity Analysis: Understanding DCF Value Drivers"
    #| fig-width: 16
    #| fig-height: 14
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Base case DCF parameters
    base_fcf = 10_000_000  # $10M base FCF
    base_growth = 0.10  # 10% growth
    base_wacc = 0.10  # 10% WACC
    base_terminal_growth = 0.03  # 3% terminal growth
    projection_years = 5
    
    # Base case DCF calculation
    def calculate_dcf(fcf, growth, wacc, terminal_growth, years):
        # Project FCFs
        fcfs = np.zeros(years)
        fcfs[0] = fcf
        for i in range(1, years):
            fcfs[i] = fcfs[i-1] * (1 + growth)
        
        # PV of projected FCFs
        pv_fcfs = sum(fcfs[i] / ((1 + wacc) ** (i + 1)) for i in range(years))
        
        # Terminal value
        terminal_fcf = fcfs[-1] * (1 + terminal_growth)
        if wacc > terminal_growth:
            terminal_value = terminal_fcf / (wacc - terminal_growth)
            pv_terminal = terminal_value / ((1 + wacc) ** years)
        else:
            pv_terminal = 0
        
        return pv_fcfs + pv_terminal
    
    base_enterprise_value = calculate_dcf(base_fcf, base_growth, base_wacc, base_terminal_growth, projection_years)
    
    # Create comprehensive visualization
    fig = plt.figure(figsize=(16, 14))
    gs = fig.add_gridspec(4, 3, hspace=0.4, wspace=0.3)
    fig.suptitle('Comprehensive DCF Sensitivity Analysis', fontsize=18, fontweight='bold', y=0.99)
    
    # Plot 1: Growth Rate Sensitivity
    ax1 = fig.add_subplot(gs[0, 0])
    growth_range = np.linspace(0.05, 0.15, 50)
    ev_growth_sensitivity = [calculate_dcf(base_fcf, g, base_wacc, base_terminal_growth, projection_years) 
                             for g in growth_range]
    ax1.plot(growth_range * 100, [v / 1_000_000 for v in ev_growth_sensitivity], 'b-', linewidth=2.5)
    ax1.axvline(x=base_growth * 100, color='r', linestyle='--', linewidth=2, 
                label=f'Base: {base_growth*100:.1f}%', alpha=0.7)
    ax1.axhline(y=base_enterprise_value / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax1.set_xlabel('Growth Rate (%)', fontsize=11, fontweight='bold')
    ax1.set_ylabel('Enterprise Value ($ Millions)', fontsize=11, fontweight='bold')
    ax1.set_title('Sensitivity to Growth Rate', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3)
    ax1.legend(loc='best', fontsize=9)
    
    # Plot 2: WACC Sensitivity
    ax2 = fig.add_subplot(gs[0, 1])
    wacc_range = np.linspace(0.08, 0.14, 50)
    ev_wacc_sensitivity = [calculate_dcf(base_fcf, base_growth, w, base_terminal_growth, projection_years) 
                           for w in wacc_range]
    ax2.plot(wacc_range * 100, [v / 1_000_000 for v in ev_wacc_sensitivity], 'g-', linewidth=2.5)
    ax2.axvline(x=base_wacc * 100, color='r', linestyle='--', linewidth=2, 
                label=f'Base: {base_wacc*100:.1f}%', alpha=0.7)
    ax2.axhline(y=base_enterprise_value / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax2.set_xlabel('WACC (%)', fontsize=11, fontweight='bold')
    ax2.set_ylabel('Enterprise Value ($ Millions)', fontsize=11, fontweight='bold')
    ax2.set_title('Sensitivity to WACC', fontsize=12, fontweight='bold')
    ax2.grid(True, alpha=0.3)
    ax2.legend(loc='best', fontsize=9)
    
    # Plot 3: Terminal Growth Sensitivity
    ax3 = fig.add_subplot(gs[0, 2])
    terminal_growth_range = np.linspace(0.01, 0.05, 50)
    ev_terminal_sensitivity = []
    for tg in terminal_growth_range:
        if base_wacc > tg:
            ev = calculate_dcf(base_fcf, base_growth, base_wacc, tg, projection_years)
            ev_terminal_sensitivity.append(ev)
        else:
            ev_terminal_sensitivity.append(np.nan)
    ax3.plot(terminal_growth_range * 100, [v / 1_000_000 if not np.isnan(v) else 0 for v in ev_terminal_sensitivity], 
             'm-', linewidth=2.5)
    ax3.axvline(x=base_terminal_growth * 100, color='r', linestyle='--', linewidth=2, 
                label=f'Base: {base_terminal_growth*100:.1f}%', alpha=0.7)
    ax3.axhline(y=base_enterprise_value / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    ax3.set_xlabel('Terminal Growth Rate (%)', fontsize=11, fontweight='bold')
    ax3.set_ylabel('Enterprise Value ($ Millions)', fontsize=11, fontweight='bold')
    ax3.set_title('Sensitivity to Terminal Growth', fontsize=12, fontweight='bold')
    ax3.grid(True, alpha=0.3)
    ax3.legend(loc='best', fontsize=9)
    
    # Plot 4: Tornado Diagram (Two-Way Sensitivity)
    ax4 = fig.add_subplot(gs[1, 0])
    # Vary growth and WACC
    growth_variations = [-0.02, -0.01, 0, 0.01, 0.02]
    wacc_variations = [-0.01, -0.005, 0, 0.005, 0.01]
    tornado_data = []
    labels = []
    for g_var in growth_variations:
        for w_var in wacc_variations:
            ev = calculate_dcf(base_fcf, base_growth + g_var, base_wacc + w_var, base_terminal_growth, projection_years)
            tornado_data.append(ev)
            labels.append(f'G{int(g_var*100):+d}%\nW{int(w_var*100):+d}%')
    
    tornado_data = np.array(tornado_data)
    sorted_idx = np.argsort(tornado_data)
    tornado_data_sorted = tornado_data[sorted_idx]
    labels_sorted = [labels[i] for i in sorted_idx]
    
    bars4 = ax4.barh(range(len(tornado_data_sorted)), [v / 1_000_000 for v in tornado_data_sorted], 
                     color='#2E86AB', alpha=0.8, edgecolor='black', linewidth=1)
    ax4.set_yticks(range(len(tornado_data_sorted)))
    ax4.set_yticklabels(labels_sorted, fontsize=8)
    ax4.set_xlabel('Enterprise Value ($ Millions)', fontsize=11, fontweight='bold')
    ax4.set_title('Tornado Diagram: Growth vs WACC', fontsize=12, fontweight='bold')
    ax4.grid(True, alpha=0.3, axis='x')
    ax4.axvline(x=base_enterprise_value / 1_000_000, color='r', linestyle='--', linewidth=2, alpha=0.7)
    
    # Plot 5: Scenario Analysis
    ax5 = fig.add_subplot(gs[1, 1])
    scenarios = ['Pessimistic', 'Base Case', 'Optimistic']
    scenario_growths = [0.05, base_growth, 0.15]
    scenario_waccs = [0.12, base_wacc, 0.08]
    scenario_evs = [calculate_dcf(base_fcf, g, w, base_terminal_growth, projection_years) 
                    for g, w in zip(scenario_growths, scenario_waccs)]
    colors_scenarios = ['#D00000', '#F18F01', '#06A77D']
    bars5 = ax5.bar(scenarios, [v / 1_000_000 for v in scenario_evs], color=colors_scenarios, 
                    alpha=0.8, edgecolor='black', linewidth=2)
    ax5.set_ylabel('Enterprise Value ($ Millions)', fontsize=11, fontweight='bold')
    ax5.set_title('Scenario Analysis', fontsize=12, fontweight='bold')
    ax5.grid(True, alpha=0.3, axis='y')
    for bar, val, g, w in zip(bars5, scenario_evs, scenario_growths, scenario_waccs):
        height = bar.get_height()
        ax5.text(bar.get_x() + bar.get_width()/2., height,
                 f'${val/1_000_000:.1f}M\nG:{g*100:.0f}% W:{w*100:.1f}%', 
                 ha='center', va='bottom', fontweight='bold', fontsize=9)
    
    # Plot 6: Value Driver Impact
    ax6 = fig.add_subplot(gs[1, 2])
    # Calculate impact of ±10% change in each driver
    drivers = ['Growth\nRate', 'WACC', 'Terminal\nGrowth', 'Base FCF']
    base_impacts = []
    # Growth impact
    ev_high_growth = calculate_dcf(base_fcf, base_growth * 1.1, base_wacc, base_terminal_growth, projection_years)
    ev_low_growth = calculate_dcf(base_fcf, base_growth * 0.9, base_wacc, base_terminal_growth, projection_years)
    base_impacts.append((ev_high_growth - ev_low_growth) / base_enterprise_value * 100)
    
    # WACC impact
    ev_high_wacc = calculate_dcf(base_fcf, base_growth, base_wacc * 1.1, base_terminal_growth, projection_years)
    ev_low_wacc = calculate_dcf(base_fcf, base_growth, base_wacc * 0.9, base_terminal_growth, projection_years)
    base_impacts.append((ev_low_wacc - ev_high_wacc) / base_enterprise_value * 100)  # Inverted (lower WACC = higher value)
    
    # Terminal growth impact
    ev_high_term = calculate_dcf(base_fcf, base_growth, base_wacc, base_terminal_growth * 1.1, projection_years)
    ev_low_term = calculate_dcf(base_fcf, base_growth, base_wacc, base_terminal_growth * 0.9, projection_years)
    base_impacts.append((ev_high_term - ev_low_term) / base_enterprise_value * 100)
    
    # Base FCF impact
    ev_high_fcf = calculate_dcf(base_fcf * 1.1, base_growth, base_wacc, base_terminal_growth, projection_years)
    ev_low_fcf = calculate_dcf(base_fcf * 0.9, base_growth, base_wacc, base_terminal_growth, projection_years)
    base_impacts.append((ev_high_fcf - ev_low_fcf) / base_enterprise_value * 100)
    
    bars6 = ax6.barh(drivers, base_impacts, color='#7209B7', alpha=0.8, edgecolor='black', linewidth=2)
    ax6.set_xlabel('Impact on Enterprise Value (%)', fontsize=11, fontweight='bold')
    ax6.set_title('Value Driver Impact (±10% Change)', fontsize=12, fontweight='bold')
    ax6.grid(True, alpha=0.3, axis='x')
    for bar, impact in zip(bars6, base_impacts):
        width = bar.get_width()
        ax6.text(width, bar.get_y() + bar.get_height()/2.,
                 f'{impact:+.1f}%', ha='left', va='center', fontweight='bold', fontsize=10)
    
    # Plot 7: Two-Way Sensitivity Heatmap (Growth vs WACC)
    ax7 = fig.add_subplot(gs[2, :2])
    growth_grid = np.linspace(0.05, 0.15, 20)
    wacc_grid = np.linspace(0.08, 0.14, 20)
    growth_mesh, wacc_mesh = np.meshgrid(growth_grid, wacc_grid)
    ev_mesh = np.zeros_like(growth_mesh)
    for i in range(len(wacc_grid)):
        for j in range(len(growth_grid)):
            ev_mesh[i, j] = calculate_dcf(base_fcf, growth_grid[j], wacc_grid[i], base_terminal_growth, projection_years)
    contour = ax7.contourf(growth_mesh * 100, wacc_mesh * 100, ev_mesh / 1_000_000, levels=20, cmap='RdYlGn')
    ax7.axvline(x=base_growth * 100, color='white', linestyle='--', linewidth=2, alpha=0.7)
    ax7.axhline(y=base_wacc * 100, color='white', linestyle='--', linewidth=2, alpha=0.7)
    ax7.plot(base_growth * 100, base_wacc * 100, 'wo', markersize=12, markeredgecolor='black', 
             markeredgewidth=2, label='Base Case')
    ax7.set_xlabel('Growth Rate (%)', fontsize=12, fontweight='bold')
    ax7.set_ylabel('WACC (%)', fontsize=12, fontweight='bold')
    ax7.set_title('Two-Way Sensitivity: Growth Rate vs WACC', fontsize=13, fontweight='bold')
    plt.colorbar(contour, ax=ax7, label='Enterprise Value ($M)')
    ax7.legend(loc='best', fontsize=10)
    
    # Plot 8: Summary Statistics
    ax8 = fig.add_subplot(gs[2, 2])
    ax8.axis('off')
    summary_text = f"""
    SENSITIVITY ANALYSIS SUMMARY
    
    BASE CASE:
      Enterprise Value:             ${base_enterprise_value/1_000_000:.1f}M
      Growth Rate:                  {base_growth*100:.1f}%
      WACC:                         {base_wacc*100:.1f}%
      Terminal Growth:              {base_terminal_growth*100:.1f}%
    
    VALUE DRIVER IMPACT (±10%):
      Growth Rate:                  {base_impacts[0]:+.1f}%
      WACC:                         {base_impacts[1]:+.1f}%
      Terminal Growth:              {base_impacts[2]:+.1f}%
      Base FCF:                     {base_impacts[3]:+.1f}%
    
    SCENARIO ANALYSIS:
      Pessimistic:                  ${scenario_evs[0]/1_000_000:.1f}M
      Base Case:                    ${scenario_evs[1]/1_000_000:.1f}M
      Optimistic:                   ${scenario_evs[2]/1_000_000:.1f}M
      Range:                        ${(scenario_evs[2]-scenario_evs[0])/1_000_000:.1f}M
    
    KEY INSIGHTS:
      • Growth rate has the largest impact
      • WACC sensitivity is significant
      • Terminal value assumptions critical
      • Use multiple scenarios for robustness
    """
    ax8.text(0.1, 0.5, summary_text, fontsize=9, fontfamily='monospace', 
             verticalalignment='center', fontweight='bold',
             bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
    
    # Plot 9: Monte Carlo Simulation (simplified)
    ax9 = fig.add_subplot(gs[3, :])
    # Simplified Monte Carlo: random variations
    np.random.seed(42)
    n_simulations = 1000
    monte_carlo_evs = []
    for _ in range(n_simulations):
        g = np.random.normal(base_growth, 0.02)  # ±2% std dev
        w = np.random.normal(base_wacc, 0.01)  # ±1% std dev
        tg = np.random.normal(base_terminal_growth, 0.005)  # ±0.5% std dev
        g = max(0.01, min(0.20, g))  # Constrain growth
        w = max(0.05, min(0.20, w))  # Constrain WACC
        tg = max(0.01, min(0.05, tg))  # Constrain terminal growth
        if w > tg:
            ev = calculate_dcf(base_fcf, g, w, tg, projection_years)
            monte_carlo_evs.append(ev)
    
    ax9.hist([v / 1_000_000 for v in monte_carlo_evs], bins=50, color='#2E86AB', alpha=0.7, edgecolor='black', linewidth=1)
    ax9.axvline(x=base_enterprise_value / 1_000_000, color='r', linestyle='--', linewidth=2, 
                label=f'Base Case: ${base_enterprise_value/1_000_000:.1f}M', alpha=0.7)
    ax9.axvline(x=np.mean(monte_carlo_evs) / 1_000_000, color='g', linestyle='--', linewidth=2, 
                label=f'Mean: ${np.mean(monte_carlo_evs)/1_000_000:.1f}M', alpha=0.7)
    ax9.axvline(x=np.percentile(monte_carlo_evs, 5) / 1_000_000, color='orange', linestyle=':', linewidth=2, 
                label=f'5th Percentile: ${np.percentile(monte_carlo_evs, 5)/1_000_000:.1f}M', alpha=0.7)
    ax9.axvline(x=np.percentile(monte_carlo_evs, 95) / 1_000_000, color='orange', linestyle=':', linewidth=2, 
                label=f'95th Percentile: ${np.percentile(monte_carlo_evs, 95)/1_000_000:.1f}M', alpha=0.7)
    ax9.set_xlabel('Enterprise Value ($ Millions)', fontsize=12, fontweight='bold')
    ax9.set_ylabel('Frequency', fontsize=12, fontweight='bold')
    ax9.set_title('Monte Carlo Simulation: Distribution of Enterprise Values', fontsize=13, fontweight='bold')
    ax9.grid(True, alpha=0.3, axis='y')
    ax9.legend(loc='best', fontsize=9)
    
    plt.tight_layout()
    display(fig)
    plt.close()
    
    print(f"\n📊 **Comprehensive Sensitivity Analysis**")
    print(f"{'='*70}")
    print(f"Base Case Enterprise Value:      ${base_enterprise_value/1_000_000:.1f}M")
    print(f"{'='*70}")
    print(f"Value Driver Impact (±10% change):")
    for driver, impact in zip(drivers, base_impacts):
        print(f"  {driver:20s}: {impact:+.1f}%")
    print(f"{'='*70}")
    print(f"Monte Carlo Results ({n_simulations} simulations):")
    print(f"  Mean:                        ${np.mean(monte_carlo_evs)/1_000_000:.1f}M")
    print(f"  Std Dev:                      ${np.std(monte_carlo_evs)/1_000_000:.1f}M")
    print(f"  5th-95th Percentile Range:    ${np.percentile(monte_carlo_evs, 5)/1_000_000:.1f}M - ${np.percentile(monte_carlo_evs, 95)/1_000_000:.1f}M")
    print(f"{'='*70}")
    print(f"✅ Key Insight: Sensitivity analysis reveals that growth rate and WACC are")
    print(f"   the most critical value drivers. Monte Carlo simulation provides a")
    print(f"   probabilistic view of valuation uncertainty.")
    
    
    
    
    
    
    

    DCF Implementation Challenges and Best Practices

    DCF analysis is powerful but challenging to implement correctly. Understanding common challenges and best practices helps build more robust and reliable DCF models.

    Common Challenges

    1. Forecasting Uncertainty: Future cash flows are inherently uncertain, and projections may be inaccurate. This is particularly challenging for high-growth companies or companies in rapidly changing industries.

    2. Discount Rate Estimation: WACC estimation involves multiple assumptions (risk-free rate, beta, market risk premium, cost of debt), each of which introduces uncertainty.

    3. Terminal Value Dominance: Terminal value often represents a large portion of total value, making the model sensitive to terminal value assumptions.

    4. Cyclical Companies: Companies with cyclical cash flows are difficult to value using DCF because projections may not capture the full cycle.

    5. Distressed Companies: Companies in financial distress may have negative cash flows, making DCF analysis challenging.

    Best Practices

    1. Use Multiple Scenarios: Create base case, optimistic, and pessimistic scenarios to assess valuation range.

    2. Validate Assumptions: Compare assumptions to historical performance, industry norms, and analyst estimates.

    3. Sensitivity Analysis: Perform comprehensive sensitivity analysis to understand value drivers and risks.

    4. Reality Checks: Compare DCF results to market prices and other valuation methods.

    5. Documentation: Clearly document all assumptions, data sources, and methodologies.

    6. Regular Updates: Update DCF models as new information becomes available.

    7. Professional Judgment: DCF models provide structure, but professional judgment is essential for interpreting results.

    Summary

    DCF analysis is a powerful and theoretically sound valuation methodology that provides a framework for determining intrinsic value based on expected future cash flows. The methodology requires careful attention to cash flow projections, discount rate estimation, and terminal value calculation. Understanding the theoretical foundations, practical implementation challenges, and best practices enables analysts to build robust DCF models that provide valuable insights into company valuation.

    Key takeaways:

    1. Theoretical Foundation: DCF is based on the time value of money and present value principles
    2. Model Structure: DCF models consist of cash flow projections, discount rate (WACC), and terminal value
    3. Cash Flow Projections: Accurate projections require understanding business model, industry dynamics, and growth drivers
    4. Discount Rate: WACC reflects the blended cost of all sources of capital
    5. Terminal Value: Often represents a large portion of total value and requires careful consideration
    6. Sensitivity Analysis: Essential for understanding value drivers and valuation risks
    7. Best Practices: Multiple scenarios, validation, documentation, and professional judgment are essential

    DCF analysis, when implemented correctly, provides a rigorous framework for valuation that can withstand scrutiny and serve as a foundation for investment decisions.

    In Module 6: Equity Valuation

    1. Introduction
    2. Fundamental Analysis
    3. Valuation Models and Methods
    4. Discounted Cash Flow Analysis
    5. Relative Valuation Techniques
    6. Valuation in Practice
    7. Special Valuation Cases
    8. Valuation Challenges
    9. Advanced Valuation Topics
    10. End-of-Module Assessment