```python
# Relevant code segments related to the KeyError: 'Portfolio'

def display_backtest_results(results, comparison_type, portfolio1_name, portfolio2_name=None):
    # Do not pre-format metrics here
    if comparison_type == "Portfolio vs Benchmark":
        display_portfolio_vs_benchmark(results, portfolio1_name)
    elif comparison_type == "Portfolio vs Portfolio":
        display_portfolio_vs_portfolio(results, portfolio1_name, portfolio2_name)

def display_portfolio_vs_benchmark(results, portfolio_name):
    # Extract data from results
    returns = results['returns']
    cum_returns = results['cum_returns']
    weights = results['weights']
    price_data = results['price_data']
    available_selected = results['available_selected']
    metrics = results['metrics']
    benchmark_metrics = results.get('benchmark_metrics', {})
    benchmark_returns = results.get('benchmark_returns', pd.Series(dtype=float))
    benchmark_cum_returns = results.get('benchmark_cum_returns', pd.Series(dtype=float))

    # Define a consistent theme for all plots
    THEMES = {
        'plotly_dark': 'plotly_dark',
        'plotly_light': 'plotly_white'
    }
    selected_theme = THEMES.get('plotly_dark')  # Change as needed

    # Create tabs for better organization
    main_tab, metrics_tab, risk_tab, analysis_tab, insights_tab = st.tabs([
        "📈 Main Charts", "📊 Performance Metrics", "🎯 Risk Analysis", "🔍 Deep Analysis", "🧠 Metric-Based Insights"
    ])

    with main_tab:
        st.header("🔹 Portfolio vs Benchmark Overview")
        col1, col2 = st.columns([2, 1])
        with col1:
            st.subheader("Portfolio Composition")
            fig_composition = px.pie(
                values=weights,
                names=price_data.columns,
                title="Current Portfolio Allocation",
                template=selected_theme,
                hole=0.4
            )
            fig_composition.update_traces(textinfo='percent+label')
            st.plotly_chart(fig_composition, use_container_width=True)

        with col2:
            st.subheader("Key Performance Indicators")
            # Format metrics here, ensuring numerical operations are valid
            annualized_cagr = metrics.get('Annualized Return (CAGR)', None)
            if isinstance(annualized_cagr, (int, float)) and not np.isnan(annualized_cagr):
                annualized_return = f"{annualized_cagr:.2f}%"
            else:
                annualized_return = "N/A"

            # Similarly format other metrics
            total_return = f"{(cum_returns.iloc[-1] - 1) * 100:.2f}%" if not cum_returns.empty else "N/A"
            sharpe_ratio = f"{metrics.get('Sharpe Ratio', 'N/A'):.2f}" if 'Sharpe Ratio' in metrics and not np.isnan(metrics.get('Sharpe Ratio', np.nan)) else "N/A"
            max_drawdown = f"{metrics.get('Maximum Drawdown', 0):.2f}%" if 'Maximum Drawdown' in metrics and not np.isnan(metrics.get('Maximum Drawdown', np.nan)) else "N/A"

            metrics_display = {
                "Total Return": total_return,
                "Annualized Return": annualized_return,
                "Sharpe Ratio": sharpe_ratio,
                "Max Drawdown": max_drawdown
            }
            for metric, value in metrics_display.items():
                st.metric(metric, value)

    # Performance Metrics Tab
    with metrics_tab:
        st.header("📊 Key Performance Metrics")
        st.subheader("Performance Comparison Table")

        # Define metrics separately
        common_metrics = [
            'Annualized Return (CAGR)',
            'Maximum Drawdown',
            'Sharpe Ratio',
            'Sortino Ratio',
            'Standard Deviation (Annualized)',
            'Beta',
            'Alpha (annualized)',
            'R2',
            'Calmar Ratio',
            'Information Ratio',
            'Tracking Error',
            'Upside Capture Ratio',
            'Downside Capture Ratio',
            'Best Year',
            'Worst Year'
        ]

        # Filter metrics
        filtered_portfolio_metrics = {k: v for k, v in metrics.items() if k in common_metrics}
        filtered_benchmark_metrics = {k: v for k, v in benchmark_metrics.items() if k in common_metrics}

        # Create DataFrame for Portfolio vs Benchmark Metrics
        performance_comparison_df = create_performance_stats_df_portfolio_vs_portfolio(
            metrics_a=filtered_portfolio_metrics,
            metrics_b=filtered_benchmark_metrics,
            portfolio1=portfolio_name,
            portfolio2='Benchmark'
        )

        # Define which metrics are percentage-based
        percentage_metrics = [
            'Annualized Return (CAGR)',
            'Maximum Drawdown',
            'Standard Deviation (Annualized)',
            'Alpha (annualized)',
            'Tracking Error',
            'Upside Capture Ratio',
            'Downside Capture Ratio',
            'Best Year',
            'Worst Year'
        ]

        # Style the metrics table
        def highlight_better(row):
            styles = [''] * len(row)
            portfolio_val = row["Portfolio"]
            benchmark_val = row["Benchmark"]

            # Skip if Portfolio is 'N/A'
            if portfolio_val == "N/A" or benchmark_val == "N/A":
                return styles

            try:
                # Convert string values to float if possible
                if isinstance(portfolio_val, str):
                    portfolio_num = float(portfolio_val.strip('%').strip('$').replace(',', ''))
                else:
                    portfolio_num = portfolio_val

                if isinstance(benchmark_val, str):
                    benchmark_num = float(benchmark_val.strip('%').strip('$').replace(',', ''))
                else:
                    benchmark_num = benchmark_val

                # Determine if higher is better or lower is better based on metric name
                metric_name = row.name
                lower_is_better = any(keyword in metric_name for keyword in [
                    'Drawdown', 'Deviation', 'Tracking Error', 'Downside Capture Ratio'
                ])
                if lower_is_better:
                    better = portfolio_num < benchmark_num
                else:
                    better = portfolio_num > benchmark_num

                # Apply styling
                if better:
                    styles[0] = 'background-color: #d4f7d4'  # Portfolio Green
                    styles[1] = 'background-color: #f7d4d4'  # Benchmark Red
                else:
                    styles[0] = 'background-color: #f7d4d4'  # Portfolio Red
                    styles[1] = 'background-color: #d4f7d4'  # Benchmark Green
            except (ValueError, TypeError):
                pass  # Skip if conversion fails

            return styles

        def custom_formatter(x, metric):
            try:
                # Attempt to convert to float after stripping possible symbols
                if x == "N/A":
                    return "N/A"
                value = float(str(x).strip('%').strip('$').replace(',', ''))
                if metric in percentage_metrics:
                    return f"{value:.2f}%"
                else:
                    return f"{value:.2f}"
            except (ValueError, TypeError):
                return "N/A"  # Return 'N/A' if conversion fails

        # Apply formatter row-wise to access metric name
        def row_formatter(row):
            metric = row.name
            formatted = {}
            for col in ['Portfolio', 'Benchmark']:
                formatted[col] = custom_formatter(row[col], metric)
            return pd.Series(formatted)

        # Assuming performance_comparison_df is already created
        formatted_metrics = performance_comparison_df.apply(row_formatter, axis=1)
        performance_comparison_df[['Portfolio', 'Benchmark']] = formatted_metrics[['Portfolio', 'Benchmark']]

        # Apply the highlight function to style the rows
        styled_metrics = performance_comparison_df.style.apply(
            highlight_better,
            axis=1
        ).format({
            'Portfolio': lambda x: x,
            'Benchmark': lambda x: x
        })

        # Add metric explanations
        metric_explanations = {
            'Annualized Return (CAGR)': 'Compound Annual Growth Rate - The geometric mean of portfolio returns',
            'Maximum Drawdown': 'Largest peak-to-trough decline',
            'Sharpe Ratio': 'Risk-adjusted return relative to risk-free rate',
            'Sortino Ratio': 'Risk-adjusted return focusing on downside volatility',
            'Standard Deviation (Annualized)': 'Measure of portfolio volatility',
            'Beta': 'Portfolio sensitivity to market movements',
            'Alpha (annualized)': 'Excess return compared to benchmark',
            'R2': 'How well portfolio returns are explained by benchmark',
            'Calmar Ratio': 'Return relative to maximum drawdown',
            'Information Ratio': 'Risk-adjusted excess returns vs benchmark',
            'Tracking Error': 'Standard deviation of portfolio vs benchmark difference',
            'Upside Capture Ratio': 'Performance relative to benchmark in up markets',
            'Downside Capture Ratio': 'Performance relative to benchmark in down markets',
            'Best Year': 'Highest annual return',
            'Worst Year': 'Lowest annual return'
        }

        # Display the metrics table
        col1, col2 = st.columns([3, 1])
        with col1:
            st.dataframe(styled_metrics, height=600)

        with col2:
            with st.expander("📖 Metric Definitions", expanded=True):
                for metric, explanation in metric_explanations.items():
                    st.markdown(f"**{metric}**")
                    st.markdown(f"_ {explanation}_")
                    st.markdown("---")

        # Interactive Summary Recommendations
        create_summary_recommendations('comparison', metrics=metrics)
```

fix the above issues and if the segments code need update, please return the full updated segments code, no need import xyz or other stuff, only the full version of the updated segment