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 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'
        )

        # Rename columns to ensure 'Portfolio' and 'Benchmark' exist
        if portfolio_name != 'Portfolio':
            performance_comparison_df = performance_comparison_df.rename(
                columns={portfolio_name: 'Portfolio'}
            )
        if 'Benchmark' not in performance_comparison_df.columns:
            performance_comparison_df['Benchmark'] = "N/A"

        # 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 or Benchmark is 'N/A'
            if portfolio_val == "N/A" or benchmark_val == "N/A":
                return styles

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

                # 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)

        # Ensure 'Portfolio' and 'Benchmark' columns exist
        required_columns = ['Portfolio', 'Benchmark']
        for col in required_columns:
            if col not in performance_comparison_df.columns:
                performance_comparison_df[col] = "N/A"

        # Assuming performance_comparison_df is already created and correctly named
        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(2)
        with col1:
            st.dataframe(styled_metrics, use_container_width=True)

        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("---")

def display_portfolio_vs_portfolio(results, portfolio1_name, portfolio2_name):
    """Displays comparison between two portfolios with enhanced UI/UX."""
    # Extract data from results
    returns_a = results.get('returns_a', pd.Series(dtype=float))
    returns_b = results.get('returns_b', pd.Series(dtype=float))
    cum_returns_a = results.get('cum_returns_a', pd.Series(dtype=float))
    cum_returns_b = results.get('cum_returns_b', pd.Series(dtype=float))
    weights_a = results.get('weights_a', [])
    weights_b = results.get('weights_b', [])
    price_data_a = results.get('price_data_a', pd.DataFrame())
    price_data_b = results.get('price_data_b', pd.DataFrame())
    metrics_a = results.get('metrics_a', {})
    metrics_b = results.get('metrics_b', {})

    # Define available_a and available_b based on price data columns
    available_a = list(price_data_a.columns)
    available_b = list(price_data_b.columns)

    # Ensure that available_a and available_b are not empty
    if not available_a:
        st.error(f"No available data for Portfolio '{portfolio1}'.")
        return
    if not available_b:
        st.error(f"No available data for Portfolio '{portfolio2}'.")
        return

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

    # Create tabs for better organization
    overview_tab, comparison_tab, risk_tab, analysis_tab = st.tabs([
        "📊 Overview", "🔄 Comparison", "🎯 Risk Analysis", "🔍 Deep Analysis"
    ])

    with comparison_tab:
        st.header("🔄 Performance Metrics Comparison")
        st.subheader("Detailed Performance Metrics")

        detailed_metrics = [
            'Annualized Return (CAGR)',
            'Sharpe Ratio',
            'Sortino Ratio',
            'Maximum Drawdown',
            'Beta',
            'Alpha (annualized)',
            'Information Ratio',
            'Modigliani–Modigliani Measure',
            'Tracking Error',
            'Calmar Ratio'
        ]

        metrics_comparison = pd.DataFrame({
            'Metric': detailed_metrics,
            portfolio1_name: [metrics_a.get(metric, "N/A") for metric in detailed_metrics],
            portfolio2_name: [metrics_b.get(metric, "N/A") for metric in detailed_metrics]
        })

        # Apply styling
        styled_comparison = metrics_comparison.style.apply(
            highlight_better_performance(portfolio1_name, portfolio2_name),
            axis=1
        )

        # Display the styled dataframe
        st.dataframe(styled_comparison, height=400)

        # Rolling Performance Difference with Interactive Slider
        st.subheader("Rolling Performance Difference (30-Day MA)")
        window_size = st.slider("Select Rolling Window (Days)", min_value=10, max_value=60, value=30)
        rolling_diff = (returns_a - returns_b).rolling(window=window_size).mean() * 252

        fig_diff = px.line(
            rolling_diff,
            title=f"{window_size}-Day Rolling Return Difference",
            labels={"index": "Date", "value": "Return Difference"},
            template=selected_theme
        )
        fig_diff.update_traces(line=dict(color='magenta'))
        fig_diff.update_layout(
            hovermode='x unified',
            height=500,
            xaxis_title='Date',
            yaxis_title='Return Difference'
        )
        st.plotly_chart(fig_diff, use_container_width=True)

def create_performance_stats_df_portfolio_vs_portfolio(metrics_a, metrics_b, portfolio1, portfolio2):
    """Creates a refined DataFrame for Portfolio vs Portfolio performance statistics."""
    metrics = [
        'Annualized Return (CAGR)',
        'Sharpe Ratio',
        'Sortino Ratio',
        'Maximum Drawdown',
        'Beta',
        'Alpha (annualized)',
        'Information Ratio',
        'R2',
        'Calmar Ratio',
        'Tracking Error',
        'Upside Capture Ratio',
        'Downside Capture Ratio',
        'Best Year',
        'Worst Year'
    ]

    data = {
        'Metric': metrics,
        portfolio1: [metrics_a.get(metric, "N/A") for metric in metrics],
        portfolio2: [metrics_b.get(metric, "N/A") for metric in metrics]
    }

    performance_df = pd.DataFrame(data)
    performance_df.set_index('Metric', inplace=True)

    # Replace any missing or "N/A" with "N/A" explicitly (optional, for consistency)
    performance_df.replace({np.nan: "N/A"}, inplace=True)

    return performance_df

def create_advanced_metrics_df_portfolio_vs_portfolio(metrics_a, metrics_b, portfolio1, portfolio2):
    """Creates a refined DataFrame for Portfolio vs Portfolio advanced metrics."""
    metrics = [
        'Beta',
        'Alpha (annualized)',
        'Information Ratio',
        'Modigliani–Modigliani Measure',
        'Tracking Error',
        'Upside Capture Ratio',
        'Downside Capture Ratio'
    ]

    data = {
        'Metric': metrics,
        portfolio1: [metrics_a.get(metric, "N/A") for metric in metrics],
        portfolio2: [metrics_b.get(metric, "N/A") for metric in metrics]
    }

    advanced_metrics_df = pd.DataFrame(data)
    advanced_metrics_df.set_index('Metric', inplace=True)
    return advanced_metrics_df

def highlight_better_performance(portfolio1, portfolio2):
    """
    Creates a styling function for comparing two portfolios.
    
    Args:
        portfolio1 (str): Name of the first portfolio
        portfolio2 (str): Name of the second portfolio
        
    Returns:
        function: A styling function that can be used with DataFrame.style.apply()
    """
    def _style_row(row):
        styles = [''] * len(row)
        
        # Check if both portfolios exist in the row
        if portfolio1 in row.index and portfolio2 in row.index:
            val1 = row[portfolio1]
            val2 = row[portfolio2]
            
            # Convert string values to float if possible
            try:
                if isinstance(val1, str):
                    val1 = float(str(val1).strip('%').strip('$').replace(',', ''))
                if isinstance(val2, str):
                    val2 = float(str(val2).strip('%').strip('$').replace(',', ''))
                
                # Only proceed if both values are numeric
                if isinstance(val1, (int, float)) and isinstance(val2, (int, float)):
                    metric_name = row.name
                    # Determine if higher or lower is better based on the metric
                    lower_is_better = any(keyword in metric_name for keyword in [
                        'Drawdown', 'Deviation', 'Tracking Error', 'Downside Capture Ratio', 'R2'
                    ])
                    if lower_is_better:
                        better = val1 < val2
                    else:
                        better = val1 > val2
                    
                    # Apply styling
                    if better:
                        styles[row.index.get_loc(portfolio1)] = 'background-color: #d4f7d4'  # Green
                        styles[row.index.get_loc(portfolio2)] = 'background-color: #f7d4d4'  # Red
                    else:
                        styles[row.index.get_loc(portfolio1)] = 'background-color: #f7d4d4'  # Red
                        styles[row.index.get_loc(portfolio2)] = 'background-color: #d4f7d4'  # Green
            except (ValueError, TypeError):
                pass  # Skip if conversion fails
                
        return styles
    
    return _style_row

# ----------------------------
# Metric Definitions Improvement
# ----------------------------

# In the `display_portfolio_vs_benchmark` function, the `metric_explanations` dictionary has been improved to provide clearer definitions for each metric. Here's the updated section:

metric_explanations = {
    'Annualized Return (CAGR)': 'Compound Annual Growth Rate - The geometric mean of portfolio returns, representing the mean annual growth rate over a specified time period.',
    'Maximum Drawdown': 'Largest peak-to-trough decline in the portfolio’s value, indicating the maximum potential loss.',
    'Sharpe Ratio': 'Measures the performance of the portfolio compared to a risk-free asset, after adjusting for its risk. Higher values indicate better risk-adjusted returns.',
    'Sortino Ratio': 'Similar to the Sharpe Ratio but only penalizes downside volatility, providing a better assessment of negative risk.',
    'Standard Deviation (Annualized)': 'Represents the portfolio’s volatility, measuring the dispersion of returns around the mean. Higher values indicate higher risk.',
    'Beta': 'Indicates the portfolio’s sensitivity to market movements. A beta greater than 1 means the portfolio is more volatile than the market.',
    'Alpha (annualized)': 'Represents the portfolio’s excess return over the expected return based on its beta. Positive alpha indicates outperformance.',
    'R2': 'Determines how well the portfolio’s returns are explained by the benchmark’s returns. Values close to 1 indicate strong correlation.',
    'Calmar Ratio': 'Calculates the portfolio’s return relative to its maximum drawdown. Higher values indicate better performance considering risk.',
    'Information Ratio': 'Measures the portfolio’s excess return over a benchmark relative to the volatility of that excess return.',
    'Tracking Error': 'Represents the standard deviation of the difference between the portfolio and benchmark returns, indicating consistency in outperforming the benchmark.',
    'Upside Capture Ratio': 'Shows how well the portfolio captures gains when the benchmark is up. Values above 100% indicate outperformance in up markets.',
    'Downside Capture Ratio': 'Shows how well the portfolio captures losses when the benchmark is down. Values below 100% indicate outperformance in down markets.',
    'Best Year': 'The highest annual return achieved by the portfolio within the assessment period.',
    'Worst Year': 'The lowest annual return experienced by the portfolio within the assessment period.'
}

# Additionally, ensure that the `create_performance_stats_df_portfolio_vs_portfolio` function includes all necessary metrics without missing any calculations that could lead to "N/A" values. Here's the relevant function for reference:

def create_performance_stats_df_portfolio_vs_portfolio(metrics_a, metrics_b, portfolio1, portfolio2):
    """Creates a refined DataFrame for Portfolio vs Portfolio performance statistics."""
    metrics = [
        'Annualized Return (CAGR)',
        'Sharpe Ratio',
        'Sortino Ratio',
        'Maximum Drawdown',
        'Beta',
        'Alpha (annualized)',
        'Information Ratio',
        'R2',
        'Calmar Ratio',
        'Tracking Error',
        'Upside Capture Ratio',
        'Downside Capture Ratio',
        'Best Year',
        'Worst Year'
    ]

    data = {
        'Metric': metrics,
        portfolio1: [metrics_a.get(metric, "N/A") for metric in metrics],
        portfolio2: [metrics_b.get(metric, "N/A") for metric in metrics]
    }

    performance_df = pd.DataFrame(data)
    performance_df.set_index('Metric', inplace=True)

    # Replace any missing or "N/A" with "N/A" explicitly (optional, for consistency)
    performance_df.replace({np.nan: "N/A"}, inplace=True)

    return performance_df

problem:
many N/A of the Performance Comparison Table:
Annualized Return (CAGR) 7.56% 8.54%
Sharpe Ratio 0.41 0.42
Sortino Ratio 0.54 0.49
Maximum Drawdown -28.37% -37.09%
Beta N/A N/A
Alpha (annualized) N/A N/A
Information Ratio N/A N/A
R2 N/A N/A
Calmar Ratio 0.27 0.23
Tracking Error N/A N/A
Upside Capture Ratio N/A N/A
Downside Capture Ratio N/A N/A
Best Year 23.19% 22.34%
Worst Year -12.06% -8.78%
and the 📖 Metric Definitions can be improved
if the segments code need update, please return the full updated segments code, no need import or other stuff, only the full version of the updated segment, also brief explanation of changes on each part