def displaybacktestresults(results, comparisontype, portfolio1name,…
- User
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("---") - Assistant