problem:
@handle_exceptions
def run_portfolio_comparison(comparison_type, portfolio1, portfolio2=None):
    """
    Generalized function to run portfolio comparisons.

    Parameters:
    - comparison_type (str): "vs_benchmark" or "vs_portfolio"
    - portfolio1 (dict): Primary portfolio.
    - portfolio2 (dict, optional): Secondary portfolio for "vs_portfolio".

    Returns:
    - dict: Backtest results or error.
    """
    try:
        if comparison_type == "vs_benchmark":
            # Handle primary portfolio data
            available, missing, price_data = handle_portfolio_data(portfolio1)
            if not available:
                return {"error": "No valid tickers with available data."}
            
            # Adjust allocations based on available tickers
            allocations = adjust_allocations([portfolio1['allocations'][portfolio1['selected'].index(t)] for t in available])
            
            # Perform backtest for the portfolio
            returns, cum_returns = backtest(
                weights=np.array(allocations) / 100,
                prices=price_data[available],
                rebalance_freq=portfolio1['rebalance_freq'],
                broker_fee=portfolio1['broker_fee']
            )
            if cum_returns.empty:
                return {"error": "Cumulative returns are empty."}
            
            # Download benchmark data
            benchmark_data = download_data(
                [portfolio1['benchmark_symbol']],
                portfolio1['start_date'].strftime('%Y-%m-%d'),
                portfolio1['end_date'].strftime('%Y-%m-%d')
            )
            if benchmark_data.empty:
                return {"error": "Benchmark data could not be downloaded."}
            
            # Process benchmark data and handle potential errors
            try:
                benchmark_returns, benchmark_cum_returns, benchmark_metrics = process_benchmark(benchmark_data, returns, portfolio1)
            except ValueError as ve:
                return {"error": str(ve)}
            except Exception as e:
                return {"error": f"Benchmark processing failed: {e}"}
            
            # Calculate metrics for the portfolio without benchmark comparison
            portfolio_metrics = calculate_metrics(returns, cum_returns, portfolio1['rf_rate'])
            
            # Compile backtest results
            backtest_results = {
                'returns': returns,
                'cum_returns': cum_returns,
                'weights': allocations,
                'price_data': price_data[available],
                'available_selected': available,
                'metrics': portfolio_metrics,
                'benchmark_returns': benchmark_returns,
                'benchmark_cum_returns': benchmark_cum_returns,
                'benchmark_metrics': benchmark_metrics
            }
            
            return {"backtest_results": backtest_results}

        elif comparison_type == "vs_portfolio":
            # Determine overlapping date range between the two portfolios
            overlap_start = max(portfolio1['start_date'], portfolio2['start_date'])
            overlap_end = min(portfolio1['end_date'], portfolio2['end_date'])
            if overlap_start >= overlap_end:
                return {"error": "No overlapping date ranges."}
            
            # Handle data for both portfolios within the overlapping date range
            available_a, missing_a, price_data_a = handle_portfolio_data(portfolio1, (overlap_start, overlap_end))
            available_b, missing_b, price_data_b = handle_portfolio_data(portfolio2, (overlap_start, overlap_end))
            if not available_a or not available_b:
                return {"error": "One of the portfolios has no valid tickers with available data."}
            
            # Adjust allocations based on available tickers for both portfolios
            allocations_a = adjust_allocations([portfolio1['allocations'][portfolio1['selected'].index(t)] for t in available_a])
            allocations_b = adjust_allocations([portfolio2['allocations'][portfolio2['selected'].index(t)] for t in available_b])
            
            # Perform backtest for both portfolios
            returns_a, cum_returns_a = backtest(
                weights=np.array(allocations_a) / 100,
                prices=price_data_a[available_a],
                rebalance_freq=portfolio1['rebalance_freq'],
                broker_fee=portfolio1['broker_fee']
            )
            returns_b, cum_returns_b = backtest(
                weights=np.array(allocations_b) / 100,
                prices=price_data_b[available_b],
                rebalance_freq=portfolio2['rebalance_freq'],
                broker_fee=portfolio2['broker_fee']
            )
            if cum_returns_a.empty or cum_returns_b.empty:
                return {"error": "One of the cumulative returns is empty."}
            
            # Add error handling for metrics calculation
            if returns_a.empty or returns_b.empty:
                return {"error": "Unable to calculate returns for one or both portfolios"}
                
            # Calculate metrics with proper error handling
            try:
                metrics_a = calculate_metrics(returns_a, cum_returns_a, portfolio1['rf_rate'])
                metrics_b = calculate_metrics(returns_b, cum_returns_b, portfolio2['rf_rate'])
            except Exception as e:
                return {"error": f"Error calculating metrics: {str(e)}"}
                
            # Ensure no None values in metrics
            metrics_a = {k: 0.0 if v is None else v for k, v in metrics_a.items()}
            metrics_b = {k: 0.0 if v is None else v for k, v in metrics_b.items()}

            # Align two portfolios' returns
            common_index = cum_returns_a.index.intersection(cum_returns_b.index)
            if common_index.empty:
                return {"error": "No overlapping dates after backtesting."}
            returns_a = returns_a.loc[common_index]
            returns_b = returns_b.loc[common_index]
            cum_returns_a = cum_returns_a.loc[common_index]
            cum_returns_b = cum_returns_b.loc[common_index]
            
            # Compile backtest results
            backtest_results = {
                'returns_a': returns_a,
                'cum_returns_a': cum_returns_a,
                'weights_a': allocations_a,
                'price_data_a': price_data_a[available_a],
                'metrics_a': metrics_a,
                'returns_b': returns_b,
                'cum_returns_b': cum_returns_b,
                'weights_b': allocations_b,
                'price_data_b': price_data_b[available_b],
                'metrics_b': metrics_b
            }
            
            return {"backtest_results": backtest_results}
    except Exception as e:
        return {"error": f"An unexpected error occurred: {e}"}

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)

    with risk_tab:
        st.header("🎯 Risk Analysis")
        col1, col2 = st.columns([1,1])
        
        with col1:
             # Rolling Volatility with Threshold Highlighting
             st.subheader("📉 Rolling Volatility (30-Day)")
             rolling_vol = returns.rolling(window=30).std() * np.sqrt(252)
             rolling_vol_bench = benchmark_returns.rolling(window=30).std() * np.sqrt(252)
             
             fig_vol = go.Figure()
             fig_vol.add_trace(go.Scatter(
                 x=rolling_vol.index,
                 y=rolling_vol,
                 name="Portfolio Volatility",
                 line=dict(color='cyan', width=2)
             ))
             fig_vol.add_trace(go.Scatter(
                 x=rolling_vol_bench.index,
                 y=rolling_vol_bench,
                 name="Benchmark Volatility",
                 line=dict(color='orange', width=2, dash='dash')
             ))
             fig_vol.update_layout(
                 template=selected_theme,
                 hovermode='x unified',
                 height=400,
                 xaxis_title='Date',
                 yaxis_title='Annualized Volatility (%)',
                 legend=dict(x=0.01, y=0.99)
             )
             st.plotly_chart(fig_vol, use_container_width=True)
             st.subheader("📉 Top 10 Drawdowns Comparison")
             # Get drawdown details
             drawdowns_a = get_drawdown_details(cum_returns_a)
             drawdowns_b = get_drawdown_details(cum_returns_b)

             # Check if drawdown data is available
             if drawdowns_a and drawdowns_b:
                 # Convert to DataFrame and sort
                 drawdowns_a_df = pd.DataFrame(drawdowns_a).sort_values(by='Drawdown', ascending=True).head(10)
                 drawdowns_b_df = pd.DataFrame(drawdowns_b).sort_values(by='Drawdown', ascending=True).head(10)

                 # Combine for comparison
                 combined_drawdowns = pd.DataFrame({
                     "📅 Portfolio Start Date": drawdowns_a_df['Start'],
                     "📅 Portfolio End Date": drawdowns_a_df['End'],
                     "📉 Portfolio Drawdown (%)": drawdowns_a_df['Drawdown'],
                     f"📅 {portfolio_name} Benchmark Start Date": drawdowns_b_df['Start'],
                     f"📅 {portfolio_name} Benchmark End Date": drawdowns_b_df['End'],
                     f"📉 {portfolio_name} Benchmark Drawdown (%)": drawdowns_b_df['Drawdown']
                 })

                 # Display the comparison table
                 st.table(combined_drawdowns)

                 # Enhanced Comparative Bar Chart
                 fig_drawdown_comparison = go.Figure(data=[
                     go.Bar(
                         name='Portfolio',
                         x=drawdowns_a_df['Start'],
                         y=drawdowns_a_df['Drawdown'],
                         marker_color='cyan',
                         hovertemplate='%{y:.2f}% on %{x}<extra></extra>'
                     ),
                     go.Bar(
                         name='Benchmark',
                         x=drawdowns_b_df['Start'],
                         y=drawdowns_b_df['Drawdown'],
                         marker_color='orange',
                         hovertemplate='%{y:.2f}% on %{x}<extra></extra>'
                     )
                 ])
                 fig_drawdown_comparison.update_layout(
                     barmode='group',
                     title="📊 Top 10 Drawdowns Comparison",
                     xaxis_title='Date',
                     yaxis_title='Drawdown (%)',
                     template=selected_theme,
                     legend=dict(x=0.01, y=0.99),
                     height=600
                 )
                 st.plotly_chart(fig_drawdown_comparison, use_container_width=True)
             else:
                 st.write("⚠️ Insufficient drawdown data for comparison.")
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