problem: enhance the 🎯 Risk Analysis by fixing all its bugs, there are many bugs on their graphs, and delete the Select Top N Assets for Risk Contribution as well
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
@handle_exceptions
def calculate_risk_contribution(returns: pd.DataFrame, weights: np.ndarray) -> np.ndarray:
    """
    Calculates the risk contribution of each asset in the portfolio.
    
    Parameters:
    - returns (pd.DataFrame): Asset returns DataFrame
    - weights (np.ndarray): Asset weights in the portfolio
    
    Returns:
    - np.ndarray: Risk contribution percentages for each asset
    """
    # Ensure returns is a DataFrame
    if isinstance(returns, pd.Series):
        returns = pd.DataFrame(returns)
    
    # Calculate covariance matrix
    cov_matrix = returns.cov().values
    
    # Ensure weights is a numpy array
    weights = np.array(weights).flatten()
    
    # Calculate portfolio volatility
    port_vol = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
    
    # Calculate marginal risk contribution
    mrc = np.dot(cov_matrix, weights) / port_vol if port_vol > 0 else np.zeros_like(weights)
    
    # Calculate component risk contribution
    rc = np.multiply(weights, mrc)
    
    # Normalize to get percentage contributions
    total_rc = np.sum(np.abs(rc))  # Use absolute values for normalization
    rc_pct = (rc / total_rc * 100) if total_rc > 0 else np.full_like(rc, 100/len(rc))
    
    return rc_pct


def calculate_diversification_index(risk_contributions: np.ndarray) -> float:
    """
    Calculates the diversification index based on risk contributions.
    
    The diversification index ranges from 0 to 1:
    - 1 indicates perfect diversification (equal risk contribution)
    - 0 indicates complete concentration in one asset
    
    Parameters:
    - risk_contributions (np.ndarray): Array of risk contributions in percentage
    
    Returns:
    - float: Diversification index between 0 and 1
    """
    # Convert percentages to decimals if needed
    rc = np.array(risk_contributions) / 100 if np.any(risk_contributions > 1) else np.array(risk_contributions)
    
    # Number of assets
    n = len(rc)
    if n == 0:
        return 0.0
    
    # Perfect diversification would have equal risk contribution of 1/n
    perfect_div = 1.0 / n
    
    # Calculate sum of squared deviations from perfect diversification
    squared_deviations = np.sum((rc - perfect_div) ** 2)
    
    # Maximum possible squared deviation (when one asset has 100% risk contribution)
    max_deviation = (n - 1) * perfect_div**2 + (1 - perfect_div)**2
    
    # Calculate diversification index
    if max_deviation == 0:
        return 1.0
    
    div_index = 1 - (squared_deviations / max_deviation)
    
    # Ensure the result is between 0 and 1
    return max(0.0, min(1.0, div_index))


def display_backtest_results(results, comparison_type, portfolio1_name, portfolio2_name=None):
    # ... existing code ...

    with risk_tab:
        st.header("🎯 Risk Analysis")
        col1, col2 = st.columns([1,1])
        
        with col1:
             # Rolling Volatility Plot
             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)
             
             # Drawdowns Comparison
             st.subheader("📉 Top 10 Drawdowns Comparison")
             drawdowns_portfolio = get_drawdown_details(cum_returns)
             drawdowns_benchmark = get_drawdown_details(benchmark_cum_returns)

             if drawdowns_portfolio and drawdowns_benchmark:
                 drawdowns_portfolio_df = pd.DataFrame(drawdowns_portfolio).sort_values(by='Drawdown', ascending=True).head(10)
                 drawdowns_benchmark_df = pd.DataFrame(drawdowns_benchmark).sort_values(by='Drawdown', ascending=True).head(10)

                 combined_drawdowns = pd.DataFrame({
                     "📅 Portfolio Start Date": drawdowns_portfolio_df['Start'],
                     "📅 Portfolio End Date": drawdowns_portfolio_df['End'],
                     "📉 Portfolio Drawdown (%)": drawdowns_portfolio_df['Drawdown'],
                     f"📅 {portfolio_name} Benchmark Start Date": drawdowns_benchmark_df['Start'],
                     f"📅 {portfolio_name} Benchmark End Date": drawdowns_benchmark_df['End'],
                     f"📉 {portfolio_name} Benchmark Drawdown (%)": drawdowns_benchmark_df['Drawdown']
                 })

                 st.table(combined_drawdowns)

                 fig_drawdown_comparison = go.Figure(data=[
                     go.Bar(
                         name='Portfolio',
                         x=drawdowns_portfolio_df['Start'],
                         y=drawdowns_portfolio_df['Drawdown'],
                         marker_color='cyan',
                         hovertemplate='%{y:.2f}% on %{x}<extra></extra>'
                     ),
                     go.Bar(
                         name='Benchmark',
                         x=drawdowns_benchmark_df['Start'],
                         y=drawdowns_benchmark_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.")
             
        with col2:
            st.subheader("🛡️ Risk Contribution Analysis")
            col3, col4 = st.columns([1,1])
             
            with col3:
                # Risk Contribution for Portfolio
                risk_contrib = calculate_risk_contribution(
                    price_data.pct_change().dropna(),
                    weights
                )
                 
                # Create DataFrame for plotting
                risk_contrib_df = pd.DataFrame({
                    'Asset': available_selected,
                    'Risk Contribution (%)': risk_contrib * 100
                }).sort_values(by='Risk Contribution (%)', ascending=False)
                 
                # Removed the "Select Top N Assets for Risk Contribution" slider and filtering
                
                fig_risk = px.bar(
                    risk_contrib_df,
                    x='Asset',
                    y='Risk Contribution (%)',
                    title=f"🔍 {portfolio_name} Risk Contribution",
                    labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
                    template=selected_theme,
                    color='Risk Contribution (%)',
                    color_continuous_scale='Blues',
                    hover_data=['Risk Contribution (%)']
                )
                fig_risk.update_layout(
                    xaxis_title='Asset',
                    yaxis_title='Risk Contribution (%)',
                    height=500
                )
                st.plotly_chart(fig_risk, use_container_width=True)
    
            with col4:
                 # Diversification Overview
                 st.subheader("📊 Diversification Overview")
                 diversification = calculate_diversification_index(risk_contrib)
                 st.metric("🔢 Diversification Index", f"{diversification:.2f}/1.00", help="Higher values indicate better diversification.")
                 
                 # Enhanced Diversification Gauge
                 fig_diversification = go.Figure(go.Indicator(
                     mode = "gauge+number",
                     value = diversification,
                     title = {'text': "🎯 Diversification Index"},
                     gauge = {
                         'axis': {'range': [0, 1]},
                         'bar': {'color': "darkblue"},
                         'steps' : [
                             {'range': [0, 0.3], 'color': "lightcoral"},
                             {'range': [0.3, 0.7], 'color': "lightsalmon"},
                             {'range': [0.7, 1], 'color': "lightgreen"}],
                         'threshold': {
                             'line': {'color': "black", 'width': 4},
                             'thickness': 0.75,
                             'value': diversification}
                     }
                 ))
                 fig_diversification.update_layout(template=selected_theme, height=400)
                 st.plotly_chart(fig_diversification, use_container_width=True)
                 
                 st.markdown("💡 **Interpretation:** A Diversification Index closer to 1.00 signifies a well-diversified portfolio, reducing unsystematic risk.")
    
        # Interactive Summary Recommendations
        create_summary_recommendations('risk', metrics=metrics)