Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

I have a Python script for a portfolio optimizer using Streamlit. The script includes…

  1. User

    I have a Python script for a portfolio optimizer using Streamlit. The script includes functionality to compare two portfolios. However, there are some bugs in the "Portfolio vs Portfolio" comparison section. I need help identifying and fixing these bugs. Below is the relevant code snippet for the "Portfolio vs Portfolio" comparison.

    elif step == "Run Backtest":
        st.title("📊 Run Backtest")
        if st.session_state.portfolios:
            with st.form("compare_form"):
                st.subheader("🔍 Select Portfolios to Compare")
                comparison_type = st.selectbox(
                    "Comparison Type",
                    ["Portfolio vs Benchmark", "Portfolio vs Portfolio"]
                )
                portfolio_names = [p['name'] for p in st.session_state.portfolios]
                if comparison_type == "Portfolio vs Benchmark":
                    portfolio1 = st.selectbox("Select Portfolio", portfolio_names)
                else:
                    portfolio1 = st.selectbox("Select First Portfolio", portfolio_names, key="p1")
                    portfolio2 = st.selectbox("Select Second Portfolio", portfolio_names, key="p2")
                run = st.form_submit_button("Run Backtest")
    
            if run:
                with st.spinner("Running backtest..."):
                    if comparison_type == "Portfolio vs Benchmark":
                        # Code for Portfolio vs Benchmark comparison
                        pass
                    elif comparison_type == "Portfolio vs Portfolio":
                        if portfolio1 == portfolio2:
                            st.error("Please select two different portfolios for comparison.")
                        else:
                            portfolio_a = next(p for p in st.session_state.portfolios if p['name'] == portfolio1)
                            portfolio_b = next(p for p in st.session_state.portfolios if p['name'] == portfolio2)
    
                            overlap_start = max(portfolio_a['start_date'], portfolio_b['start_date'])
                            overlap_end = min(portfolio_a['end_date'], portfolio_b['end_date'])
    
                            if overlap_start >= overlap_end:
                                st.error("The selected portfolios do not have overlapping date ranges.")
                                st.stop()
    
                            price_data_a = download_data(
                                portfolio_a['selected'],
                                overlap_start,
                                overlap_end
                            )
                            price_data_b = download_data(
                                portfolio_b['selected'],
                                overlap_start,
                                overlap_end
                            )
    
                            if price_data_a.empty:
                                st.error(f"No price data available for portfolio '{portfolio_a['name']}' in the overlapping period.")
                                st.stop()
                            if price_data_b.empty:
                                st.error(f"No price data available for portfolio '{portfolio_b['name']}' in the overlapping period.")
                                st.stop()
    
                            # Backtest Portfolio A
                            available_a = [ticker for ticker in portfolio_a['selected'] if ticker in price_data_a.columns]
                            missing_a = list(set(portfolio_a['selected']) - set(available_a))
                            if missing_a:
                                st.warning(f"Excluded tickers from '{portfolio_a['name']}': {', '.join(missing_a)}")
                            if not available_a:
                                st.error(f"No valid tickers for portfolio '{portfolio_a['name']}' in the overlapping period.")
                                st.stop()
                            allocs_a = [portfolio_a['allocations'][i] for i, ticker in enumerate(portfolio_a['selected']) if ticker in available_a]
                            if not np.isclose(sum(allocs_a), 100.0, atol=1e-4):
                                st.warning(f"Allocations for '{portfolio_a['name']}' do not sum to 100%. Adjusting allocations proportionally.")
                                allocs_a = [a / sum(allocs_a) * 100 for a in allocs_a]
                            weights_a = np.array(allocs_a) / 100
                            returns_a, cum_returns_a = backtest(weights_a, price_data_a[available_a],
                                                               portfolio_a['rebalance_freq'], portfolio_a['broker_fee'], debug=False)
    
                            # Backtest Portfolio B
                            available_b = [ticker for ticker in portfolio_b['selected'] if ticker in price_data_b.columns]
                            missing_b = list(set(portfolio_b['selected']) - set(available_b))
                            if missing_b:
                                st.warning(f"Excluded tickers from '{portfolio_b['name']}': {', '.join(missing_b)}")
                            if not available_b:
                                st.error(f"No valid tickers for portfolio '{portfolio_b['name']}' in the overlapping period.")
                                st.stop()
                            allocs_b = [portfolio_b['allocations'][i] for i, ticker in enumerate(portfolio_b['selected']) if ticker in available_b]
                            if not np.isclose(sum(allocs_b), 100.0, atol=1e-4):
                                st.warning(f"Allocations for '{portfolio_b['name']}' do not sum to 100%. Adjusting allocations proportionally.")
                                allocs_b = [a / sum(allocs_b) * 100 for a in allocs_b]
                            weights_b = np.array(allocs_b) / 100
                            returns_b, cum_returns_b = backtest(weights_b, price_data_b[available_b],
                                                               portfolio_b['rebalance_freq'], portfolio_b['broker_fee'], debug=False)
    
                            if cum_returns_a.empty or cum_returns_b.empty:
                                st.error("One of the portfolios has empty cumulative returns. Check the data and allocations.")
                                st.stop()
    
                            # Align date ranges between the two portfolios
                            common_index = cum_returns_a.index.intersection(cum_returns_b.index)
                            if common_index.empty:
                                st.error("No overlapping dates between the two portfolios after backtesting.")
                                st.stop()
                            returns_a = returns_a.loc[common_index]
                            cum_returns_a = cum_returns_a.loc[common_index]
                            returns_b = returns_b.loc[common_index]
                            cum_returns_b = cum_returns_b.loc[common_index]
    
                            # Calculate metrics without using one portfolio as the benchmark for the other
                            metrics_a = calculate_portfolio_metrics(
                                returns_a, cum_returns_a, portfolio_a['rf_rate'], benchmark_returns=None
                            )
                            metrics_b = calculate_portfolio_metrics(
                                returns_b, cum_returns_b, portfolio_b['rf_rate'], benchmark_returns=None
                            )
    
                            # Dashboard Header with Key Stats
                            with st.container():
                                st.markdown("### 🔑 Key Metrics")
                                key_metrics_a = {
                                    'Annualized Return (CAGR)': metrics_a.get('Annualized Return (CAGR)', "N/A"),
                                    'Sharpe Ratio': metrics_a.get('Sharpe Ratio', "N/A"),
                                    'Maximum Drawdown': metrics_a.get('Maximum Drawdown', "N/A")
                                }
                                key_metrics_b = {
                                    'Annualized Return (CAGR)': metrics_b.get('Annualized Return (CAGR)', "N/A"),
                                    'Sharpe Ratio': metrics_b.get('Sharpe Ratio', "N/A"),
                                    'Maximum Drawdown': metrics_b.get('Maximum Drawdown', "N/A")
                                }
                                cols = st.columns(len(key_metrics_a))
                                for col, (metric, value) in zip(cols, key_metrics_a.items()):
                                    with col:
                                        st.metric(label=f"{portfolio_a['name']} {metric}", value=value)
                                for col, (metric, value) in zip(cols, key_metrics_b.items()):
                                    with col:
                                        st.metric(label=f"{portfolio_b['name']} {metric}", value=value)
    
                            # Create Tabs for Organized Sections
                            tabs = st.tabs(["Overview", "Performance Statistics", "Advanced Metrics", "Drawdowns", "Visualizations"])
    
                            with tabs[0]:
                                st.header("📈 Portfolio Performance Overview")
                                st.write(f"**Portfolio A Name:** {portfolio_a['name']}")
                                st.write(f"**Portfolio B Name:** {portfolio_b['name']}")
                                st.write(f"**Start Date:** {portfolio_a['start_date']}")
                                st.write(f"**End Date:** {portfolio_a['end_date']}")
    
                            with tabs[1]:
                                st.header("📊 Performance Statistics")
                                with st.expander("🛠️ Basic Metrics", expanded=True):
                                    performance_data_stats = {
                                        'Metric': [
                                            'Start Balance',
                                            'End Balance',
                                            'Annualized Return (CAGR)',
                                            'Standard Deviation (Annualized)',
                                            'Best Year',
                                            'Worst Year',
                                            'Maximum Drawdown',
                                            'Sharpe Ratio',
                                            'Sortino Ratio',
                                            'Benchmark Correlation'
                                        ],
                                        portfolio_a['name']: [
                                            metrics_a['Start Balance'],
                                            metrics_a['End Balance'],
                                            metrics_a['Annualized Return (CAGR)'],
                                            metrics_a['Standard Deviation (Annualized)'],
                                            metrics_a['Best Year'],
                                            metrics_a['Worst Year'],
                                            metrics_a['Maximum Drawdown'],
                                            metrics_a['Sharpe Ratio'],
                                            metrics_a['Sortino Ratio'],
                                            metrics_a['Benchmark Correlation']
                                        ],
                                        portfolio_b['name']: [
                                            metrics_b['Start Balance'],
                                            metrics_b['End Balance'],
                                            metrics_b['Annualized Return (CAGR)'],
                                            metrics_b['Standard Deviation (Annualized)'],
                                            metrics_b['Best Year'],
                                            metrics_b['Worst Year'],
                                            metrics_b['Maximum Drawdown'],
                                            metrics_b['Sharpe Ratio'],
                                            metrics_b['Sortino Ratio'],
                                            metrics_b['Benchmark Correlation']
                                        ]
                                    }
                                    performance_df_stats = pd.DataFrame(performance_data_stats).set_index('Metric')
                                    st.table(performance_df_stats)
    
                            with tabs[2]:
                                st.header("📉 Advanced Metrics")
                                with st.expander("📈 Advanced Metrics", expanded=False):
                                    performance_data_advanced = {
                                        'Metric': list(metrics_a.keys()),
                                        portfolio_a['name']: list(metrics_a.values()),
                                        portfolio_b['name']: list(metrics_b.values())
                                    }
                                    performance_df_advanced = pd.DataFrame(performance_data_advanced).set_index('Metric')
                                    st.table(performance_df_advanced)
    
                            with tabs[3]:
                                st.header("📉 Drawdowns")
                                st.markdown("### 📉 Detailed Drawdowns")
                                st.markdown(f"#### 📉 Drawdowns for {portfolio_a['name']}")
                                drawdowns_a = get_drawdown_details(cum_returns_a)
                                if drawdowns_a:
                                    drawdowns_a_df = pd.DataFrame(drawdowns_a)
                                    st.table(drawdowns_a_df)
                                else:
                                    st.write("No drawdowns detected.")
    
                                st.markdown(f"#### 📉 Drawdowns for {portfolio_b['name']}")
                                drawdowns_b = get_drawdown_details(cum_returns_b)
                                if drawdowns_b:
                                    drawdowns_b_df = pd.DataFrame(drawdowns_b)
                                    st.table(drawdowns_b_df)
                                else:
                                    st.write("No drawdowns detected.")
    
                            with tabs[4]:
                                st.header("📊 Visualizations")
                                # Growth Comparison
                                fig_growth = px.line(title='Growth Comparison')
                                fig_growth.add_scatter(x=cum_returns_a.index, y=cum_returns_a, mode='lines', name=portfolio_a['name'])
                                fig_growth.add_scatter(x=cum_returns_b.index, y=cum_returns_b, mode='lines', name=portfolio_b['name'])
                                st.plotly_chart(fig_growth, use_container_width=True)
    
                                # Drawdown Comparison
                                portfolio_drawdown_series_a = (cum_returns_a / cum_returns_a.expanding().max() - 1) * 100
                                portfolio_drawdown_series_b = (cum_returns_b / cum_returns_b.expanding().max() - 1) * 100
                                fig_drawdown = px.line(title='Drawdown Comparison')
                                fig_drawdown.add_scatter(x=portfolio_drawdown_series_a.index, y=portfolio_drawdown_series_a, mode='lines', name=portfolio_a['name'])
                                fig_drawdown.add_scatter(x=portfolio_drawdown_series_b.index, y=portfolio_drawdown_series_b, mode='lines', name=portfolio_b['name'])
                                st.plotly_chart(fig_drawdown, use_container_width=True)
    
                                # Box Plot for Returns Distribution
                                st.subheader("📦 Returns Distribution Box Plot")
                                fig_box_plot_a = px.box(returns_a, title=f'Returns Distribution Box Plot for {portfolio_a["name"]}', labels={'value': 'Returns', 'variable': 'Asset'})
                                fig_box_plot_b = px.box(returns_b, title=f'Returns Distribution Box Plot for {portfolio_b["name"]}', labels={'value': 'Returns', 'variable': 'Asset'})
                                st.plotly_chart(fig_box_plot_a, use_container_width=True)
                                st.plotly_chart(fig_box_plot_b, use_container_width=True)
    
                                # Heatmap of Correlations Between Assets
                                st.subheader("🔥 Correlation Heatmap of Assets")
                                plot_correlation_heatmap(price_data_a[available_a].pct_change().dropna())
                                plot_correlation_heatmap(price_data_b[available_b].pct_change().dropna())
    
                                # Portfolio Allocation Pie Chart
                                st.subheader("🥧 Portfolio Allocation Pie Chart")
                                plot_allocation_pie(weights_a, available_a, title=f"{portfolio_a['name']} Allocation")
                                plot_allocation_pie(weights_b, available_b, title=f"{portfolio_b['name']} Allocation")
    
                                # Final Score
                                st.markdown("### 📝 Final Score")
                                score_a = calculate_final_score(metrics_a, metrics_b)
                                score_b = calculate_final_score(metrics_b, metrics_a)
                                st.write(f"**{portfolio_a['name']}:** {score_a:.2f} / 100")
                                st.write(f"**{portfolio_b['name']}:** {score_b:.2f} / 100")
    
                                # Store results
                                st.session_state.backtest_results = {
                                    'returns_a': returns_a,
                                    'cum_returns_a': cum_returns_a,
                                    'weights_a': weights_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': weights_b,
                                    'price_data_b': price_data_b[available_b],
                                    'metrics_b': metrics_b,
                                    'performance_df_stats': performance_df_stats,
                                    'performance_df_advanced': performance_df_advanced,
                                    'benchmark_cum_returns': pd.Series(dtype=float)
                                }
                                st.success("Backtest completed!")
    

    Issues:

    1. The "Portfolio vs Portfolio" comparison section seems to have some bugs, especially in the alignment of date ranges and the calculation of metrics.
    2. The visualizations for the "Portfolio vs Portfolio" comparison are not displaying correctly.

    Tasks:

    1. Identify and fix the bugs in the "Portfolio vs Portfolio" comparison section.
    2. Ensure that the date ranges are correctly aligned between the two portfolios.
    3. Verify that the metrics and visualizations are correctly calculated and displayed.

    Please help me fix these issues.


    Note: The code provided is a snippet from a larger script. If additional context or code is needed to resolve the issues, please let me know.

  2. Assistant

    To address the issues you've raised in the "Portfolio vs Portfolio" comparison section, let's focus on the three tasks: identifying and fixing bugs, ensuring the correct alignment of date ranges, and verifying the metrics and visualizations. Here’s a breakdown of the code snippet with proposed changes:

    1. Ensure Correct Date Range Alignment

    Make sure the overlapping date range is correctly computed and that you are using it consistently in the backtesting and metrics calculations. The overlap is already calculated right, but we should ensure that all downstream processes respect it.

    2. Fix Metric Calculations

    There seem to be some redundant calls or possible issues with metric calculations. It’s vital to ensure that you compare metrics in a consistent manner and adequately handle any edge cases such as empty data frames.

    3. Visualization Issues

    Verify that the plots and tables are correctly retrieving and formatting data. You might also want to add checks to ensure data isn't empty before generating plots.

    Here’s a revised version of your code with suggested bug fixes and improvements:

    # Check for valid conditions when running the backtest
    elif step == "Run Backtest":
        st.title("📊 Run Backtest")
        if st.session_state.portfolios:
            with st.form("compare_form"):
                st.subheader("🔍 Select Portfolios to Compare")
                comparison_type = st.selectbox(
                    "Comparison Type",
                    ["Portfolio vs Benchmark", "Portfolio vs Portfolio"]
                )
                portfolio_names = [p['name'] for p in st.session_state.portfolios]
                if comparison_type == "Portfolio vs Benchmark":
                    portfolio1 = st.selectbox("Select Portfolio", portfolio_names)
                else:
                    portfolio1 = st.selectbox("Select First Portfolio", portfolio_names, key="p1")
                    portfolio2 = st.selectbox("Select Second Portfolio", portfolio_names, key="p2")
                run = st.form_submit_button("Run Backtest")
    
            if run:
                with st.spinner("Running backtest..."):
                    if comparison_type == "Portfolio vs Benchmark":
                        # Code for Portfolio vs Benchmark comparison
                        pass
                    elif comparison_type == "Portfolio vs Portfolio":
                        if portfolio1 == portfolio2:
                            st.error("Please select two different portfolios for comparison.")
                        else:
                            portfolio_a = next(p for p in st.session_state.portfolios if p['name'] == portfolio1)
                            portfolio_b = next(p for p in st.session_state.portfolios if p['name'] == portfolio2)
    
                            # Compute overlapping dates
                            overlap_start = max(portfolio_a['start_date'], portfolio_b['start_date'])
                            overlap_end = min(portfolio_a['end_date'], portfolio_b['end_date'])
    
                            if overlap_start >= overlap_end:
                                st.error("The selected portfolios do not have overlapping date ranges.")
                                st.stop()
    
                            # Fetch price data
                            price_data_a = download_data(portfolio_a['selected'], overlap_start, overlap_end)
                            price_data_b = download_data(portfolio_b['selected'], overlap_start, overlap_end)
    
                            # Handle price data availability
                            if price_data_a.empty or price_data_b.empty:
                                st.error("No price data available for one or both portfolios in the overlapping period.")
                                st.stop()
    
                            # Backtest logic for Portfolio A
                            # Clean and validate available assets
                            available_a = [ticker for ticker in portfolio_a['selected'] if ticker in price_data_a.columns]
                            missing_a = list(set(portfolio_a['selected']) - set(available_a))
                            if missing_a:
                                st.warning(f"Excluded tickers from '{portfolio_a['name']}': {', '.join(missing_a)}")
                            if not available_a:
                                st.error(f"No valid tickers for portfolio '{portfolio_a['name']}' in the overlapping period.")
                                st.stop()
                            allocs_a = np.array([portfolio_a['allocations'][i] for i, ticker in enumerate(portfolio_a['selected']) if ticker in available_a])
                            if not np.isclose(sum(allocs_a), 100.0, atol=1e-4):
                                st.warning(f"Allocations for '{portfolio_a['name']}' do not sum to 100%. Adjusting allocations proportionally.")
                                allocs_a = (allocs_a / sum(allocs_a)) * 100
                            weights_a = allocs_a / 100
                            
                            # Backtest Portfolio B
                            available_b = [ticker for ticker in portfolio_b['selected'] if ticker in price_data_b.columns]
                            missing_b = list(set(portfolio_b['selected']) - set(available_b))
                            if missing_b:
                                st.warning(f"Excluded tickers from '{portfolio_b['name']}': {', '.join(missing_b)}")
                            if not available_b:
                                st.error(f"No valid tickers for portfolio '{portfolio_b['name']}' in the overlapping period.")
                                st.stop()
                            allocs_b = np.array([portfolio_b['allocations'][i] for i, ticker in enumerate(portfolio_b['selected']) if ticker in available_b])
                            if not np.isclose(sum(allocs_b), 100.0, atol=1e-4):
                                st.warning(f"Allocations for '{portfolio_b['name']}' do not sum to 100%. Adjusting allocations proportionally.")
                                allocs_b = (allocs_b / sum(allocs_b)) * 100
                            weights_b = allocs_b / 100
    
                            # Backtest both portfolios
                            returns_a, cum_returns_a = backtest(weights_a, price_data_a[available_a], portfolio_a['rebalance_freq'], portfolio_a['broker_fee'])
                            returns_b, cum_returns_b = backtest(weights_b, price_data_b[available_b], portfolio_b['rebalance_freq'], portfolio_b['broker_fee'])
    
                            # Ensure non-empty cumulative returns
                            if cum_returns_a.empty or cum_returns_b.empty:
                                st.error("One of the portfolios has empty cumulative returns. Check the data and allocations.")
                                st.stop()
    
                            # Align date ranges between the portfolios
                            common_index = cum_returns_a.index.intersection(cum_returns_b.index)
                            if common_index.empty:
                                st.error("No overlapping dates between the two portfolios after backtesting.")
                                st.stop()
                            returns_a = returns_a.loc[common_index]
                            cum_returns_a = cum_returns_a.loc[common_index]
                            returns_b = returns_b.loc[common_index]
                            cum_returns_b = cum_returns_b.loc[common_index]
    
                            # Calculate metrics
                            metrics_a = calculate_portfolio_metrics(returns_a, cum_returns_a, portfolio_a['rf_rate'], None)
                            metrics_b = calculate_portfolio_metrics(returns_b, cum_returns_b, portfolio_b['rf_rate'], None)
    
                            # Display Key Metrics
                            with st.container():
                                st.markdown("### 🔑 Key Metrics")
                                key_metrics_a = {
                                    'Annualized Return (CAGR)': metrics_a.get('Annualized Return (CAGR', "N/A"),
                                    'Sharpe Ratio': metrics_a.get('Sharpe Ratio', "N/A"),
                                    'Maximum Drawdown': metrics_a.get('Maximum Drawdown', "N/A")
                                }
                                key_metrics_b = {
                                    'Annualized Return (CAGR)': metrics_b.get('Annualized Return (CAGR', "N/A"),
                                    'Sharpe Ratio': metrics_b.get('Sharpe Ratio', "N/A"),
                                    'Maximum Drawdown': metrics_b.get('Maximum Drawdown', "N/A")
                                }
                                
                                # Display metrics for both portfolios
                                cols = st.columns(len(key_metrics_a))
                                for col, (metric, value) in zip(cols, key_metrics_a.items()):
                                    with col:
                                        st.metric(label=f"{portfolio_a['name']} {metric}", value=value)
                                for col, (metric, value) in zip(cols, key_metrics_b.items()):
                                    with col:
                                        st.metric(label=f"{portfolio_b['name']} {metric}", value=value)
    
                            # Create Tabs for Organized Sections
                            tabs = st.tabs(["Overview", "Performance Statistics", "Advanced Metrics", "Drawdowns", "Visualizations"])
    
                            with tabs[0]:
                                st.header("📈 Portfolio Performance Overview")
                                st.write(f"**Portfolio A Name:** {portfolio_a['name']}")
                                st.write(f"**Portfolio B Name:** {portfolio_b['name']}")
                                st.write(f"**Start Date:** {overlap_start} to {overlap_end}")
    
                            # Performance Statistics Tab
                            with tabs[1]:
                                st.header("📊 Performance Statistics")
                                performance_data_stats = {
                                    'Metric': ['Start Balance', 'End Balance', 'Annualized Return (CAGR)', 'Standard Deviation (Annualized)', 'Best Year', 'Worst Year', 'Maximum Drawdown', 'Sharpe Ratio', 'Sortino Ratio', 'Benchmark Correlation'],
                                    portfolio_a['name']: [
                                        metrics_a.get('Start Balance', "N/A"),
                                        metrics_a.get('End Balance', "N/A"),
                                        metrics_a.get('Annualized Return (CAGR)', "N/A"),
                                        metrics_a.get('Standard Deviation (Annualized)', "N/A"),
                                        metrics_a.get('Best Year', "N/A"),
                                        metrics_a.get('Worst Year', "N/A"),
                                        metrics_a.get('Maximum Drawdown', "N/A"),
                                        metrics_a.get('Sharpe Ratio', "N/A"),
                                        metrics_a.get('Sortino Ratio', "N/A"),
                                        metrics_a.get('Benchmark Correlation', "N/A")
                                    ],
                                    portfolio_b['name']: [
                                        metrics_b.get('Start Balance', "N/A"),
                                        metrics_b.get('End Balance', "N/A"),
                                        metrics_b.get('Annualized Return (CAGR)', "N/A"),
                                        metrics_b.get('Standard Deviation (Annualized)', "N/A"),
                                        metrics_b.get('Best Year', "N/A"),
                                        metrics_b.get('Worst Year', "N/A"),
                                        metrics_b.get('Maximum Drawdown', "N/A"),
                                        metrics_b.get('Sharpe Ratio', "N/A"),
                                        metrics_b.get('Sortino Ratio', "N/A"),
                                        metrics_b.get('Benchmark Correlation', "N/A")
                                    ]
                                }
                                performance_df_stats = pd.DataFrame(performance_data_stats).set_index('Metric')
                                st.table(performance_df_stats)
    
                            with tabs[2]:
                                st.header("📉 Advanced Metrics")
                                advanced_metrics_data = {
                                    'Metric': list(metrics_a.keys()),
                                    portfolio_a['name']: list(metrics_a.values()),
                                    portfolio_b['name']: list(metrics_b.values())
                                }
                                advanced_metrics_df = pd.DataFrame(advanced_metrics_data).set_index('Metric')
                                st.table(advanced_metrics_df)
    
                            # Drawdown and Visualizations Tabs
                            with tabs[3]:
                                st.header("📉 Drawdowns")
                                st.markdown(f"#### 📉 Drawdowns for {portfolio_a['name']}")
                                drawdowns_a = get_drawdown_details(cum_returns_a)
                                if drawdowns_a:
                                    drawdowns_a_df = pd.DataFrame(drawdowns_a)
                                    st.table(drawdowns_a_df)
                                else:
                                    st.write("No drawdowns detected for Portfolio A.")
    
                                st.markdown(f"#### 📉 Drawdowns for {portfolio_b['name']}")
                                drawdowns_b = get_drawdown_details(cum_returns_b)
                                if drawdowns_b:
                                    drawdowns_b_df = pd.DataFrame(drawdowns_b)
                                    st.table(drawdowns_b_df)
                                else:
                                    st.write("No drawdowns detected for Portfolio B.")
    
                            with tabs[4]:
                                st.header("📊 Visualizations")
                                # Growth Comparison Plot
                                fig_growth = px.line(title='Growth Comparison')
                                fig_growth.add_scatter(x=cum_returns_a.index, y=cum_returns_a, mode='lines', name=portfolio_a['name'])
                                fig_growth.add_scatter(x=cum_returns_b.index, y=cum_returns_b, mode='lines', name=portfolio_b['name'])
                                st.plotly_chart(fig_growth, use_container_width=True)
    
                                # Drawdown Comparison Plot
                                fig_drawdown = px.line(title='Drawdown Comparison')
                                portfolio_drawdown_a = (cum_returns_a / cum_returns_a.expanding().max() - 1) * 100
                                portfolio_drawdown_b = (cum_returns_b / cum_returns_b.expanding().max() - 1) * 100
                                fig_drawdown.add_scatter(x=portfolio_drawdown_a.index, y=portfolio_drawdown_a, mode='lines', name=portfolio_a['name'])
                                fig_drawdown.add_scatter(x=portfolio_drawdown_b.index, y=portfolio_drawdown_b, mode='lines', name=portfolio_b['name'])
                                st.plotly_chart(fig_drawdown, use_container_width=True)
    
                                # Box Plot for Returns Distribution
                                st.subheader("📦 Returns Distribution Box Plot")
                                if not returns_a.empty:
                                    fig_box_plot_a = px.box(returns_a, title=f'Returns Distribution Box Plot for {portfolio_a["name"]}', labels={'value': 'Returns', 'variable': 'Asset'})
                                    st.plotly_chart(fig_box_plot_a, use_container_width=True)
                                if not returns_b.empty:
                                    fig_box_plot_b = px.box(returns_b, title=f'Returns Distribution Box Plot for {portfolio_b["name"]}', labels={'value': 'Returns', 'variable': 'Asset'})
                                    st.plotly_chart(fig_box_plot_b, use_container_width=True)
    
                                # Correlation Heatmap
                                st.subheader("🔥 Correlation Heatmap of Assets")
                                if not price_data_a[available_a].empty:
                                    plot_correlation_heatmap(price_data_a[available_a].pct_change().dropna())
                                if not price_data_b[available_b].empty:
                                    plot_correlation_heatmap(price_data_b[available_b].pct_change().dropna())
    
                                # Portfolio Allocation Pie Chart
                                st.subheader("🥧 Portfolio Allocation Pie Chart")
                                plot_allocation_pie(weights_a, available_a, title=f"{portfolio_a['name']} Allocation")
                                plot_allocation_pie(weights_b, available_b, title=f"{portfolio_b['name']} Allocation")
    
                                # Final Score
                                st.markdown("### 📝 Final Score")
                                score_a = calculate_final_score(metrics_a, metrics_b)
                                score_b = calculate_final_score(metrics_b, metrics_a)
                                st.write(f"**{portfolio_a['name']}:** {score_a:.2f} / 100")
                                st.write(f"**{portfolio_b['name']}:** {score_b:.2f} / 100")
    
                                # Store results
                                st.session_state.backtest_results = {
                                    'returns_a': returns_a,
                                    'cum_returns_a': cum_returns_a,
                                    'weights_a': weights_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': weights_b,
                                    'price_data_b': price_data_b[available_b],
                                    'metrics_b': metrics_b,
                                    'performance_df_stats': performance_df_stats,
                                    'performance_df_advanced': advanced_metrics_df,
                                    'benchmark_cum_returns': pd.Series(dtype=float)
                                }
                                st.success("Backtest completed!")
    

    Key Changes Made:

    1. Unified Handling of Date Ranges: I explicitly emphasized the starting and ending dates when referencing overlaps.
    2. Safety Checks for Empty Data: Added checks to handle cases where data might be empty before performing operations.
    3. Restructured and Organized Data Display: Further clarified how metrics are displayed and ensured metrics retrieval is consistent.
    4. Visualizations: Added checks for empty returns and price data before generating plots. This prevents crashes due to missing data.
    5. Console Logging: Optional logging can be added for additional debugging if necessary.

    Feel free to test the modified code and make any tweaks based on your overall application architecture or specific requirements. If you have further issues, let me know!