### Extracted Code Segments

#### 1. **Code Segment from `display_portfolio_vs_benchmark` Function**
   - **Location:** `display_portfolio_vs_benchmark` function in `portfolio_optimizer.py`
   - **Relevance:** This segment is directly related to the problem of refining and enhancing the Performance Comparison Table. It includes the creation of the comparison metrics table and the styling of the table to handle numeric and non-numeric values.
   - **Context:** The code creates a DataFrame for performance metrics comparison and applies custom formatting and highlighting to numeric cells.

```python
# Create comparison metrics table assuming both metrics and benchmark_metrics have same keys
portfolio_metrics_df = pd.DataFrame(metrics.items(), columns=['Metric', 'Portfolio'])
benchmark_metrics_df = pd.DataFrame(benchmark_metrics.items(), columns=['Metric', 'Benchmark'])
metrics_comparison = pd.merge(portfolio_metrics_df, benchmark_metrics_df, on='Metric', how='outer')

# Define a custom formatter to handle numeric and non-numeric values
def custom_formatter(x):
    try:
        # Attempt to convert to float after stripping possible symbols
        value = float(str(x).strip('%').strip('$').replace(',', ''))
        return f"{value:.2f}%"
    except (ValueError, TypeError):
        return x  # Return the original value if conversion fails

# Style the metrics table
def highlight_better(row):
    styles = [''] * len(row)
    portfolio_val = row["Portfolio"]
    benchmark_val = row["Benchmark"]
    # Skip if either is N/A
    if portfolio_val == "N/A" or benchmark_val == "N/A":
        return styles
    # Convert to float if possible
    try:
        portfolio_num = float(str(portfolio_val).strip('%').strip('$').replace(',', ''))
        benchmark_num = float(str(benchmark_val).strip('%').strip('$').replace(',', ''))
    except:
        return styles
    # Determine if higher is better or lower is better based on metric name
    if any(keyword in row['Metric'] for keyword in ['Drawdown', 'Deviation']):
        better = portfolio_num < benchmark_num
    else:
        better = portfolio_num > benchmark_num
    styles[1] = 'background-color: #d4f7d4' if better else 'background-color: #f7d4d4'
    return styles

styled_metrics = metrics_comparison.style.apply(highlight_better, axis=1)

# Apply the custom formatter only to numeric cells
styled_metrics = styled_metrics.format(
    custom_formatter,
    subset=pd.IndexSlice[:, ['Portfolio', 'Benchmark']]
)

st.dataframe(styled_metrics, height=400)
```

#### 2. **Code Segment from `calculate_metrics` Function**
   - **Location:** `calculate_metrics` function in `portfolio_optimizer.py`
   - **Relevance:** This segment is crucial for calculating comprehensive portfolio metrics, which are essential for the Performance Comparison Table. It handles missing values and ensures that metrics are calculated correctly.
   - **Context:** The function calculates various metrics for the portfolio and benchmark, handling cases where data might be missing or incomplete.

```python
def calculate_metrics(
    returns: pd.Series, 
    cum_returns: pd.Series, 
    rf: float = 0.02, 
    benchmark_returns: pd.Series = None
) -> dict:
    metrics = {}
    metrics['Start Balance'] = "$10,000.00"
    if not cum_returns.empty and not returns.empty:
        end_balance = 10000 * cum_returns.iloc[-1]
        years = (cum_returns.index[-1] - cum_returns.index[0]).days / 365.25
        try:
            cagr = (end_balance / 10000) ** (1 / years) - 1 if years > 0 else np.nan
        except:
            cagr = np.nan
        metrics.update({
            'End Balance': f"${end_balance:,.2f}",
            'Annualized Return (CAGR)': f"{cagr * 100:.2f}%" if not np.isnan(cagr) else "N/A",
            'Best Year': f"{returns.resample('Y').apply(lambda x: (1 + x).prod() - 1).max() * 100:.2f}%" if not returns.empty else "N/A",
            'Worst Year': f"{returns.resample('Y').apply(lambda x: (1 + x).prod() - 1).min() * 100:.2f}%" if not returns.empty else "N/A",
            'Arithmetic Mean (Monthly)': f"{returns.mean() * 100:.2f}%",
            'Arithmetic Mean (Annualized)': f"{returns.mean() * 252 * 100:.2f}%",
            'Geometric Mean (Monthly)': f"{(np.exp(np.log1p(returns).mean()) - 1) * 100:.2f}%" if not returns.empty else "N/A",
            'Geometric Mean (Annualized)': f"{(np.exp(np.log1p(returns).mean() * 252) - 1) * 100:.2f}%" if not returns.empty else "N/A",
            'Standard Deviation (Monthly)': f"{returns.std() * 100:.2f}%",
            'Standard Deviation (Annualized)': f"{returns.std() * np.sqrt(252) * 100:.2f}%",
            'Downside Deviation (Monthly)': f"{returns[returns < 0].std() * 100:.2f}%" if not returns.empty else "N/A",
            'Maximum Drawdown': f"{drawdown(cum_returns) * 100:.2f}%" if not cum_returns.empty else "N/A",
            'Sharpe Ratio': f"{calculate_sharpe_ratio(returns, rf):.2f}" if not cum_returns.empty else "N/A",
            'Sortino Ratio': f"{calculate_sortino_ratio(returns, rf):.2f}" if not cum_returns.empty else "N/A",
            'Gain/Loss Ratio': f"{calculate_gain_loss_ratio(returns):.2f}" if not cum_returns.empty else "N/A",
            'Skewness': f"{skew(returns):.2f}" if not returns.empty else "N/A",
            'Excess Kurtosis': f"{kurtosis(returns):.2f}" if not returns.empty else "N/A",
            'Safe Withdrawal Rate': f"{calculate_safe_withdrawal_rate(returns):.6f}%" if not returns.empty else "N/A",
            'Perpetual Withdrawal Rate': f"{calculate_perpetual_withdrawal_rate(returns):.6f}%" if not returns.empty else "N/A",
            'Positive Periods': calculate_positive_periods(returns) if not returns.empty else "N/A"
        })
    else:
        # Assign "N/A" to all metrics if cum_returns or returns are empty
        metrics.update({
            'End Balance': "N/A",
            'Annualized Return (CAGR)': "N/A",
            'Best Year': "N/A",
            'Worst Year': "N/A",
            'Arithmetic Mean (Monthly)': "N/A",
            'Arithmetic Mean (Annualized)': "N/A",
            'Geometric Mean (Monthly)': "N/A",
            'Geometric Mean (Annualized)': "N/A",
            'Standard Deviation (Monthly)': "N/A",
            'Standard Deviation (Annualized)': "N/A",
            'Downside Deviation (Monthly)': "N/A",
            'Maximum Drawdown': "N/A",
            'Sharpe Ratio': "N/A",
            'Sortino Ratio': "N/A",
            'Gain/Loss Ratio': "N/A",
            'Skewness': "N/A",
            'Excess Kurtosis': "N/A",
            'Safe Withdrawal Rate': "N/A",
            'Perpetual Withdrawal Rate': "N/A",
            'Positive Periods': "N/A"
        })
    
    if benchmark_returns is not None and not benchmark_returns.empty:
        # Calculate benchmark-relative metrics
        correlation = returns.corr(benchmark_returns)
        beta = calculate_beta(returns, benchmark_returns)
        alpha = calculate_alpha(returns, benchmark_returns, rf)
        r2 = calculate_r_squared(returns, benchmark_returns)
        treynor = calculate_treynor_ratio(returns, benchmark_returns, rf)
        calmar = calculate_calmar_ratio(returns, cum_returns)
        m2 = calculate_modigliani_miller(returns, benchmark_returns, rf)
        info_ratio = calculate_information_ratio(returns, benchmark_returns)
        tracking_error = calculate_tracking_error(returns, benchmark_returns)
        active_return = calculate_active_return(returns, benchmark_returns)
        upside_capture = calculate_capture_ratio(returns, benchmark_returns, upside=True)
        downside_capture = calculate_capture_ratio(returns, benchmark_returns, upside=False)
        
        metrics.update({
            'Benchmark Correlation': f"{correlation:.2f}" if not np.isnan(correlation) else "N/A",
            'Beta': f"{beta:.2f}" if not np.isnan(beta) else "N/A",
            'Alpha (annualized)': f"{alpha * 100:.2f}%" if not np.isnan(alpha) else "N/A",
            'R2': f"{r2 * 100:.2f}%" if not np.isnan(r2) else "N/A",
            'Treynor Ratio': f"{treynor:.2f}" if not np.isnan(treynor) else "N/A",
            'Calmar Ratio': f"{calmar:.2f}" if not np.isnan(calmar) else "N/A",
            'Modigliani–Modigliani Measure': f"{m2 * 100:.2f}%" if not np.isnan(m2) else "N/A",
            'Information Ratio': f"{info_ratio:.2f}" if not np.isnan(info_ratio) else "N/A",
            'Tracking Error': f"{tracking_error * 100:.2f}%" if not np.isnan(tracking_error) else "N/A",
            'Active Return': f"{active_return:.2f}%" if not np.isnan(active_return) else "N/A",
            'Upside Capture Ratio': f"{upside_capture:.2f}%" if not np.isnan(upside_capture) else "N/A",
            'Downside Capture Ratio': f"{downside_capture:.2f}%" if not np.isnan(downside_capture) else "N/A"
        })
    else:
        # Assign "N/A" to all benchmark metrics
        metrics.update({
            'Benchmark Correlation': "N/A",
            'Beta': "N/A",
            'Alpha (annualized)': "N/A",
            'R2': "N/A",
            'Treynor Ratio': "N/A",
            'Calmar Ratio': "N/A",
            'Modigliani–Modigliani Measure': "N/A",
            'Information Ratio': "N/A",
            'Tracking Error': "N/A",
            'Active Return': "N/A",
            'Upside Capture Ratio': "N/A",
            'Downside Capture Ratio': "N/A"
        })
    
    return metrics
```

### Explanation

1. **`display_portfolio_vs_benchmark` Function:**
   - This function is responsible for displaying the performance comparison between a portfolio and a benchmark.
   - The segment creates a DataFrame for performance metrics comparison and applies custom formatting and highlighting to numeric cells.
   - The `custom_formatter` function ensures that numeric values are formatted correctly, even if they contain symbols like '%' or '$'.
   - The `highlight_better` function applies conditional formatting to highlight which values are better (higher or lower) based on the metric type.

2. **`calculate_metrics` Function:**
   - This function calculates various performance metrics for a portfolio, including returns, risk metrics, and benchmark-relative metrics.
   - It handles cases where data might be missing or incomplete by assigning "N/A" to metrics that cannot be calculated.
   - The function ensures that all metrics are calculated correctly and consistently, which is crucial for the Performance Comparison Table.

These segments are essential for addressing the problem of refining and enhancing the Performance Comparison Table, ensuring that it handles missing values and formats data correctly.

Problem: 📊 Metric-Based Insights is missing, too many N/A in the Performance Comparison Table, also some of them are not %data but still have % on the cell, refine and enhance it
if the segments code need update, please return the full updated segments code