def createsummaryrecommendations(context, metrics=None): """ Creates context-specific…
- User
def create_summary_recommendations(context, metrics=None): """ Creates context-specific summary and recommendations with enhanced UI/UX.
code - Assistant
def create_summary_recommendations(context, metrics=None): """ Creates context-specific summary and recommendations with enhanced UI/UX.
Parameters:
- context (str): The tab context ('overview', 'comparison', 'risk', 'deep')
- metrics (dict): Optional metrics to base recommendations on
"""
st.markdown("---") # Visual separator
# Create an expandable container for recommendations
with st.expander("📋 Summary & Recommendations", expanded=True):
summaries = {
'overview': {
'title': "Portfolio Overview",
'sections': {
'Summary': [
"🎯 Portfolio Performance Overview",
"📊 Key Metrics Analysis",
"💼 Asset Allocation Review"
],
'Key Recommendations': [
"📈 Consider rebalancing if allocations have drifted",
"🔄 Review diversification across sectors",
"💰 Analyze fee impact on returns",
"⚖️ Assess risk-return alignment",
"📅 Schedule next portfolio review"
]
}
},
'comparison': {
'title': "Comparative Analysis",
'sections': {
'Performance Review': [
"📊 Relative Performance Analysis",
"⚖️ Risk-Adjusted Returns",
"🔗 Correlation Insights"
],
'Strategic Actions': [
"🎯 Address performance gaps",
"🛡️ Optimize risk management",
"📈 Improve benchmark tracking",
"💼 Review asset allocation",
"⚡ Consider rebalancing needs"
]
}
},
'risk': {
'title': "Risk Assessment",
'sections': {
'Risk Analysis': [
"📉 Value at Risk (VaR) Review",
"🎯 Stress Test Results",
"📊 Volatility Assessment"
],
'Risk Management': [
"🛡️ Implement hedging strategies",
"⚖️ Adjust position sizing",
"🎯 Set stop-loss levels",
"📈 Optimize risk-return balance",
"🔄 Review risk tolerance alignment"
]
}
},
'deep': {
'title': "Deep Analysis",
'sections': {
'Analysis Results': [
"📊 Factor Analysis Findings",
"📈 Attribution Results",
"🔍 Advanced Metrics Review"
],
'Strategic Recommendations': [
"🎯 Optimize factor exposure",
"💼 Address style drift",
"📈 Enhance portfolio efficiency",
"⚡ Consider strategic reallocations",
"🔄 Review investment strategy"
]
}
}
}
if context in summaries:
current_summary = summaries[context]
# Display title with icon
st.markdown(f"### {current_summary['title']} 📑")
# Create columns for sections
cols = st.columns(len(current_summary['sections']))
# Display sections in columns
for col, (section_title, items) in zip(cols, current_summary['sections'].items()):
with col:
st.markdown(f"**{section_title}**")
for item in items:
st.markdown(f"{item}")
# Add call to action section
st.markdown("---")
st.markdown("### ⚡ Next Steps")
next_steps = {
"Priority Actions": "Review and implement key recommendations",
"Timeline": "Set implementation deadlines",
"Follow-up": "Schedule review of changes",
"Documentation": "Record actions and outcomes"
}
for step, description in next_steps.items():
st.markdown(f"**{step}:** {description}")
def display_portfolio_vs_benchmark(results, portfolio_name): # ... [previous code] ...
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_benchmark(
metrics_portfolio=filtered_portfolio_metrics,
metrics_benchmark=filtered_benchmark_metrics,
portfolio_name=portfolio_name
)
# 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"]
# Hide row if both are "N/A"
if portfolio_val == "N/A" and benchmark_val == "N/A":
return ['display: none'] * len(row)
# 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, 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.'
}
# 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("---")
# Interactive Summary Recommendations
create_summary_recommendations('comparison', metrics=metrics)
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 risk_tab:
st.header("🎯 Risk Analysis")
col1, col2 = st.columns([1,1])
with col1:
# Rolling Volatility Comparison with Interactive Layers
st.subheader("Rolling Volatility Comparison (30-Day)")
rolling_vol_a = returns_a.rolling(window=30).std() * np.sqrt(252)
rolling_vol_b = returns_b.rolling(window=30).std() * np.sqrt(252)
fig_vol = go.Figure()
fig_vol.add_trace(go.Scatter(
x=rolling_vol_a.index,
y=rolling_vol_a,
name=f"{portfolio1} Volatility",
line=dict(color='cyan', width=2)
))
fig_vol.add_trace(go.Scatter(
x=rolling_vol_b.index,
y=rolling_vol_b,
name=f"{portfolio2} Volatility",
line=dict(color='orange', width=2, dash='dash')
))
fig_vol.update_layout(
template=selected_theme,
hovermode='x unified',
height=500,
xaxis_title='Date',
yaxis_title='Annualized Volatility',
legend=dict(x=0.01, y=0.99)
)
st.plotly_chart(fig_vol, use_container_width=True)
with col2:
# Rolling Correlation Comparison with Interactive Features
st.subheader("Rolling Correlation (30-Day) Between Portfolios")
rolling_corr = returns_a.rolling(window=30).corr(returns_b)
fig_corr = px.line(
rolling_corr,
title="30-Day Rolling Correlation",
labels={"index": "Date", "value": "Correlation"},
template=selected_theme
)
fig_corr.update_traces(line=dict(color='purple'))
fig_corr.update_layout(
hovermode='x unified',
height=500,
xaxis_title='Date',
yaxis_title='Correlation'
)
st.plotly_chart(fig_corr, use_container_width=True)
st.subheader("Risk Contribution Analysis")
col3, col4 = st.columns([1,1])
with col3:
# Calculate risk contributions for portfolio1
risk_contrib_a = calculate_risk_contribution(
price_data_a[available_a].pct_change().dropna(),
weights_a
)
# Create DataFrame for plotting
risk_contrib_df_a = pd.DataFrame({
'Asset': available_a,
'Risk Contribution (%)': risk_contrib_a * 100
}).sort_values(by='Risk Contribution (%)', ascending=False)
fig_risk_a = px.bar(
risk_contrib_df_a,
x='Asset',
y='Risk Contribution (%)',
title=f"{portfolio1} Risk Contribution",
labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
template=selected_theme,
color='Risk Contribution (%)',
color_continuous_scale='Blues'
)
fig_risk_a.update_layout(
xaxis_title='Asset',
yaxis_title='Risk Contribution (%)',
height=500
)
st.plotly_chart(fig_risk_a, use_container_width=True)
with col4:
# Calculate risk contributions for portfolio2
risk_contrib_b = calculate_risk_contribution(
price_data_b[available_b].pct_change().dropna(),
weights_b
)
# Create DataFrame for plotting
risk_contrib_df_b = pd.DataFrame({
'Asset': available_b,
'Risk Contribution (%)': risk_contrib_b * 100
}).sort_values(by='Risk Contribution (%)', ascending=False)
fig_risk_b = px.bar(
risk_contrib_df_b,
x='Asset',
y='Risk Contribution (%)',
title=f"{portfolio2} Risk Contribution",
labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
template=selected_theme,
color='Risk Contribution (%)',
color_continuous_scale='Oranges'
)
fig_risk_b.update_layout(
xaxis_title='Asset',
yaxis_title='Risk Contribution (%)',
height=500
)
st.plotly_chart(fig_risk_b, use_container_width=True)
st.markdown("### 📉 Top 10 Drawdowns Comparison Between Portfolios")
# 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({
f"{portfolio1} Date": drawdowns_a_df['Date'],
f"{portfolio1} Drawdown (%)": drawdowns_a_df['Drawdown'],
f"{portfolio2} Date": drawdowns_b_df['Date'],
f"{portfolio2} Drawdown (%)": drawdowns_b_df['Drawdown']
})
# Display the comparison table
st.table(combined_drawdowns)
# Add a comparative bar chart
fig_drawdown_comparison = go.Figure(data=[
go.Bar(
name=portfolio1,
x=drawdowns_a_df['Date'],
y=drawdowns_a_df['Drawdown'],
marker_color='cyan'
),
go.Bar(
name=portfolio2,
x=drawdowns_b_df['Date'],
y=drawdowns_b_df['Drawdown'],
marker_color='orange'
)
])
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)
)
st.plotly_chart(fig_drawdown_comparison, use_container_width=True)
else:
st.write("Insufficient drawdown data for comparison.")
@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_portfolio_vs_benchmark(results, portfolio_name): # ... [previous code] ...
# Diversification Metrics
with risk_tab:
st.header("🎯 Risk Analysis")
col1, col2 = st.columns([1,1])
with col2:
# 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.")
# Optional: Display 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.5], 'color': "lightcoral"},
{'range': [0.5, 1], 'color': "lightgreen"}],
'threshold': {
'line': {'color': "black", 'width': 4},
'thickness': 0.75,
'value': diversification}
}
))
fig_diversification.update_layout(template=selected_theme, height=300)
st.plotly_chart(fig_diversification, use_container_width=True)
def display_backtest_results(results, comparison_type, portfolio1_name, portfolio2_name=None): # ... [previous code] ...
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
portfolio_drawdowns = get_drawdown_details(cum_returns)
benchmark_drawdowns = get_drawdown_details(benchmark_cum_returns)
# Check if drawdown data is available
if portfolio_drawdowns and benchmark_drawdowns:
# Convert to DataFrame and sort
portfolio_drawdowns_df = pd.DataFrame(portfolio_drawdowns).sort_values(by='Drawdown', ascending=True).head(10)
benchmark_drawdowns_df = pd.DataFrame(benchmark_drawdowns).sort_values(by='Drawdown', ascending=True).head(10)
# Combine for comparison
# Here, you can choose to display Start and End dates separately
combined_drawdowns = pd.DataFrame({
"Portfolio Start Date": portfolio_drawdowns_df['Start'],
"Portfolio End Date": portfolio_drawdowns_df['End'],
"Portfolio Drawdown (%)": portfolio_drawdowns_df['Drawdown'],
"Benchmark Start Date": benchmark_drawdowns_df['Start'],
"Benchmark End Date": benchmark_drawdowns_df['End'],
"Benchmark Drawdown (%)": benchmark_drawdowns_df['Drawdown']
})
# Display the comparison table
st.table(combined_drawdowns)
# Add a comparative bar chart
fig_drawdown_comparison = go.Figure(data=[
go.Bar(
name='Portfolio',
x=portfolio_drawdowns_df['Start'],
y=portfolio_drawdowns_df['Drawdown'],
marker_color='cyan'
),
go.Bar(
name='Benchmark',
x=benchmark_drawdowns_df['Start'],
y=benchmark_drawdowns_df['Drawdown'],
marker_color='orange'
)
])
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)
)
st.plotly_chart(fig_drawdown_comparison, use_container_width=True)
else:
st.write("Insufficient drawdown data for comparison.")
with col2:
# Risk Contribution Analysis with Interactive Filters
st.subheader("Risk Contribution Analysis")
col3, col4 = st.columns([1,1])
with col3:
# Risk Contribution for Portfolio
risk_contrib = calculate_risk_contribution(price_data[available_selected].pct_change().dropna(), weights)
risk_contrib_df = pd.DataFrame({
'Asset': price_data.columns,
'Risk Contribution (%)': risk_contrib * 100
}).sort_values(by='Risk Contribution (%)', ascending=False)
fig_risk = px.bar(
risk_contrib_df,
x='Asset',
y='Risk Contribution (%)',
title="Risk Contribution by Asset",
labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
template=selected_theme,
color='Risk Contribution (%)',
color_continuous_scale='Viridis'
)
fig_risk.update_layout(
xaxis_title='Asset',
yaxis_title='Risk Contribution (%)',
height=400
)
st.plotly_chart(fig_risk, use_container_width=True)
with col4:
# Diversification Index
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.")
# Optional: Display 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.5], 'color': "lightcoral"},
{'range': [0.5, 1], 'color': "lightgreen"}],
'threshold': {
'line': {'color': "black", 'width': 4},
'thickness': 0.75,
'value': diversification}
}
))
fig_diversification.update_layout(template=selected_theme, height=300)
st.plotly_chart(fig_diversification, use_container_width=True)
def plot_drawdown_comparison(cum_returns_portfolio: pd.Series, cum_returns_benchmark: pd.Series, portfolio_name='Portfolio', benchmark_name='Benchmark') -> None: """Plots an enhanced drawdown comparison between portfolio and benchmark with improved visuals."""
# Calculate drawdowns for portfolio
portfolio_drawdown = (cum_returns_portfolio / cum_returns_portfolio.expanding().max() - 1) * 100
# Calculate drawdowns for benchmark
benchmark_drawdown = (cum_returns_benchmark / cum_returns_benchmark.expanding().max() - 1) * 100
fig_drawdown = go.Figure()
# Add portfolio drawdown
fig_drawdown.add_trace(go.Scatter(
x=portfolio_drawdown.index,
y=portfolio_drawdown,
mode='lines',
name=portfolio_name,
line=dict(color='red', width=2)
))
# Add benchmark drawdown if available
if not cum_returns_benchmark.empty:
fig_drawdown.add_trace(go.Scatter(
x=benchmark_drawdown.index,
y=benchmark_drawdown,
mode='lines',
name=benchmark_name,
line=dict(color='blue', width=2, dash='dash')
))
# Update layout with better formatting
fig_drawdown.update_layout(
title='📉 Drawdown Comparison',
hovermode='x unified',
yaxis=dict(
showgrid=True,
zeroline=True,
title='Drawdown (%)',
tickformat='.1f'
),
xaxis=dict(
showgrid=True,
title='Date'
),
legend=dict(
x=0.01,
y=0.99,
bgcolor='rgba(255, 255, 255, 0.8)'
),
height=500,
template='plotly_white'
)
st.plotly_chart(fig_drawdown, use_container_width=True)
def calculate_final_score(primary_metrics: dict, comparison_metrics: dict) -> float: metrics_to_compare = [ 'Annualized Return (CAGR)', 'Sharpe Ratio', 'Sortino Ratio', 'Treynor Ratio', 'Calmar Ratio', 'Alpha (annualized)', 'Information Ratio', 'Modigliani–Modigliani Measure', 'Upside Capture Ratio', 'Gain/Loss Ratio' ] metric_weights = { 'Annualized Return (CAGR)': 15, 'Sharpe Ratio': 15, 'Sortino Ratio': 10, 'Treynor Ratio': 10, 'Calmar Ratio': 10, 'Alpha (annualized)': 10, 'Information Ratio': 10, 'Modigliani–Modigliani Measure': 10, 'Upside Capture Ratio': 5, 'Gain/Loss Ratio': 5 }
score = 0
total = 0
for metric in metrics_to_compare:
primary = primary_metrics.get(metric, "N/A")
comparison = comparison_metrics.get(metric, "N/A")
# Handle numpy types and convert to native Python types
if isinstance(primary, (np.float64, np.float32)):
primary = float(primary)
if isinstance(comparison, (np.float64, np.float32)):
comparison = float(comparison)
if primary != "N/A" and comparison != "N/A":
try:
# Convert string values to float if necessary
primary_val = float(str(primary).strip('%')) if isinstance(primary, str) else primary
comparison_val = float(str(comparison).strip('%')) if isinstance(comparison, str) else comparison
weight = metric_weights.get(metric, 1)
if abs(comparison_val) < 1e-10: # Better way to check for near-zero values
st.warning(f"Comparison metric '{metric}' is too close to zero. Skipping this metric.")
continue
if primary_val > comparison_val:
score += weight * (primary_val / comparison_val)
else:
score += weight * (primary_val / comparison_val) * 0.5 # Partial credit
total += weight
except (ValueError, TypeError) as e:
st.warning(f"Error processing metric '{metric}': {str(e)}")
continue
return (score / total) * 100 if total > 0 else 0.0
def create_performance_stats_df_portfolio_vs_benchmark(metrics_portfolio, metrics_benchmark, portfolio_name): """Creates a refined DataFrame for Portfolio vs Benchmark 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,
'Portfolio': [metrics_portfolio.get(metric, "N/A") for metric in metrics],
'Benchmark': [metrics_benchmark.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
@handle_exceptions def create_summary_recommendations(context, metrics=None): """ Creates context-specific summary and recommendations with enhanced UI/UX.
Parameters:
- context (str): The tab context ('overview', 'comparison', 'risk', 'deep')
- metrics (dict): Optional metrics to base recommendations on
"""
st.markdown("---") # Visual separator
# Create an expandable container for recommendations
with st.expander("📋 Summary & Recommendations", expanded=True):
summaries = {
'overview': {
'title': "Portfolio Overview",
'sections': {
'Summary': [
"🎯 Portfolio Performance Overview",
"📊 Key Metrics Analysis",
"💼 Asset Allocation Review"
],
'Key Recommendations': [
"📈 Consider rebalancing if allocations have drifted",
"🔄 Review diversification across sectors",
"💰 Analyze fee impact on returns",
"⚖️ Assess risk-return alignment",
"📅 Schedule next portfolio review"
]
}
},
'comparison': {
'title': "Comparative Analysis",
'sections': {
'Performance Review': [
"📊 Relative Performance Analysis",
"⚖️ Risk-Adjusted Returns",
"🔗 Correlation Insights"
],
'Strategic Actions': [
"🎯 Address performance gaps",
"🛡️ Optimize risk management",
"📈 Improve benchmark tracking",
"💼 Review asset allocation",
"⚡ Consider rebalancing needs"
]
}
},
'risk': {
'title': "Risk Assessment",
'sections': {
'Risk Analysis': [
"📉 Value at Risk (VaR) Review",
"🎯 Stress Test Results",
"📊 Volatility Assessment"
],
'Risk Management': [
"🛡️ Implement hedging strategies",
"⚖️ Adjust position sizing",
"🎯 Set stop-loss levels",
"📈 Optimize risk-return balance",
"🔄 Review risk tolerance alignment"
]
}
},
'deep': {
'title': "Deep Analysis",
'sections': {
'Analysis Results': [
"📊 Factor Analysis Findings",
"📈 Attribution Results",
"🔍 Advanced Metrics Review"
],
'Strategic Recommendations': [
"🎯 Optimize factor exposure",
"💼 Address style drift",
"📈 Enhance portfolio efficiency",
"⚡ Consider strategic reallocations",
"🔄 Review investment strategy"
]
}
}
}
if context in summaries:
current_summary = summaries[context]
# Display title with icon
st.markdown(f"### {current_summary['title']} 📑")
# Create columns for sections
cols = st.columns(len(current_summary['sections']))
# Display sections in columns
for col, (section_title, items) in zip(cols, current_summary['sections'].items()):
with col:
st.markdown(f"**{section_title}**")
for item in items:
st.markdown(f"{item}")
# Add call to action section
st.markdown("---")
st.markdown("### ⚡ Next Steps")
next_steps = {
"Priority Actions": "Review and implement key recommendations",
"Timeline": "Set implementation deadlines",
"Follow-up": "Schedule review of changes",
"Documentation": "Record actions and outcomes"
}
for step, description in next_steps.items():
st.markdown(f"**{step}:** {description}")
problem: enhance the 📋 Summary & Recommendations, also hide the row in Performance Comparison Table if both column is N/A, enhance the top10 comparison graph and Risk Contribution Analysis and Diversification Overview
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
Here are the enhanced code segments based on your requirements:
Enhanced create_summary_recommendations Function:
Changes:
@handle_exceptions
def create_summary_recommendations(context, metrics=None):
"""
Creates context-specific summary and recommendations with enhanced UI/UX.
Parameters:
- context (str): The tab context ('overview', 'comparison', 'risk', 'deep')
- metrics (dict): Optional metrics to base recommendations on
"""
st.markdown("---") # Visual separator
# Create an expandable container for recommendations
with st.expander("📋 Summary & Recommendations", expanded=True):
summaries = {
'overview': {
'title': "📈 Portfolio Overview",
'sections': {
'Summary': [
"🎯 **Portfolio Performance Overview**: A high-level view of your portfolio's performance.",
"📊 **Key Metrics Analysis**: Examination of essential performance metrics.",
"💼 **Asset Allocation Review**: Assessment of how assets are distributed across different categories."
],
'Key Recommendations': [
"📈 **Rebalancing**: Consider rebalancing if asset allocations have drifted significantly from targets.",
"🔄 **Diversification**: Enhance diversification across sectors to mitigate unsystematic risks.",
"💰 **Fee Analysis**: Analyze the impact of fees on overall returns and explore lower-cost alternatives.",
"⚖️ **Risk-Return Alignment**: Ensure that the portfolio's risk profile aligns with your investment objectives.",
"📅 **Next Review**: Schedule the next portfolio review to stay on track with your financial goals."
]
}
},
'comparison': {
'title': "🔍 Comparative Analysis",
'sections': {
'Performance Review': [
"📊 **Relative Performance**: Analyzing how the portfolio performs against benchmarks.",
"⚖️ **Risk-Adjusted Returns**: Evaluating returns in the context of the risk taken.",
"🔗 **Correlation Insights**: Understanding the relationship between portfolio and benchmark movements."
],
'Strategic Actions': [
"🎯 **Performance Gaps**: Address areas where the portfolio underperforms benchmarks.",
"🛡️ **Risk Management**: Optimize strategies to manage and mitigate risks effectively.",
"📈 **Benchmark Tracking**: Improve alignment with benchmark indices for consistent performance.",
"💼 **Asset Allocation Review**: Reassess asset distribution to enhance performance.",
"⚡ **Rebalancing Needs**: Consider rebalancing to maintain target allocations."
]
}
},
'risk': {
'title': "🛡️ Risk Assessment",
'sections': {
'Risk Analysis': [
"📉 **Value at Risk (VaR)**: Review potential losses in extreme scenarios.",
"🎯 **Stress Testing**: Assess portfolio resilience under various economic conditions.",
"📊 **Volatility Assessment**: Measure the portfolio's price fluctuations over time."
],
'Risk Management': [
"🛡️ **Hedging Strategies**: Implement techniques to protect against adverse market movements.",
"⚖️ **Position Sizing**: Adjust the size of positions to manage exposure effectively.",
"🎯 **Stop-Loss Levels**: Set thresholds to limit potential losses on investments.",
"📈 **Risk-Return Optimization**: Balance risk-taking with expected returns for optimal performance.",
"🔄 **Risk Tolerance Alignment**: Ensure that portfolio risk aligns with your personal or organizational risk tolerance."
]
}
},
'deep': {
'title': "🔬 Deep Analysis",
'sections': {
'Analysis Results': [
"📊 **Factor Analysis**: Insights into the factors driving portfolio performance.",
"📈 **Attribution Results**: Breakdown of returns to identify sources of performance.",
"🔍 **Advanced Metrics Review**: Examination of complex metrics for in-depth understanding."
],
'Strategic Recommendations': [
"🎯 **Factor Optimization**: Adjust exposures to key factors for better performance.",
"💼 **Style Drift Management**: Address any unintended shifts in investment style.",
"📈 **Portfolio Efficiency**: Enhance the efficiency of the portfolio to maximize returns.",
"⚡ **Strategic Reallocations**: Make informed reallocations based on deep analysis.",
"🔄 **Investment Strategy Review**: Regularly review and refine your investment strategy."
]
}
}
}
if context in summaries:
current_summary = summaries[context]
# Display title with icon
st.markdown(f"### {current_summary['title']} 📑")
# Create columns for sections
sections = current_summary['sections']
num_sections = len(sections)
cols = st.columns(num_sections)
# Display sections in columns
for col, (section_title, items) in zip(cols, sections.items()):
with col:
st.markdown(f"**{section_title}**")
for item in items:
st.markdown(f"- {item}")
# Add dynamic recommendations based on metrics
if metrics:
st.markdown("## 🛠️ Personalized Recommendations")
personalized_recs = []
# Example: If Sharpe Ratio is low
if 'Sharpe Ratio' in metrics and isinstance(metrics['Sharpe Ratio'], (int, float)):
if metrics['Sharpe Ratio'] < 1:
personalized_recs.append("⚖️ **Improve Sharpe Ratio**: Consider strategies to enhance risk-adjusted returns, such as optimizing asset allocation or reducing high-risk investments.")
# Example: If Maximum Drawdown is high
if 'Maximum Drawdown' in metrics and isinstance(metrics['Maximum Drawdown'], (int, float)):
if metrics['Maximum Drawdown'] > -20:
personalized_recs.append("🛡️ **Mitigate Drawdowns**: Implement hedging strategies or diversify into less volatile assets to reduce potential drawdowns.")
# Add more conditional recommendations as needed
if personalized_recs:
for rec in personalized_recs:
st.markdown(f"- {rec}")
else:
st.markdown("- 🎉 Your portfolio metrics are within healthy ranges. Keep up the good work!")
# Add call to action section
st.markdown("---")
st.markdown("### ⚡ Next Steps")
next_steps = {
"📌 Priority Actions": "Review and implement the key recommendations listed above.",
"🗓️ Timeline": "Set specific deadlines for each action item to ensure timely execution.",
"🔄 Follow-up": "Schedule a follow-up review to assess the impact of implemented changes.",
"📝 Documentation": "Record all actions taken and outcomes achieved for future reference."
}
for step, description in next_steps.items():
st.markdown(f"**{step}:** {description}")
Updated create_performance_stats_df_portfolio_vs_benchmark Function to Hide Rows with Both "N/A":
Changes:
def create_performance_stats_df_portfolio_vs_benchmark(metrics_portfolio, metrics_benchmark, portfolio_name):
"""Creates a refined DataFrame for Portfolio vs Benchmark 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,
'Portfolio': [metrics_portfolio.get(metric, "N/A") for metric in metrics],
'Benchmark': [metrics_benchmark.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)
# Filter out rows where both Portfolio and Benchmark are "N/A"
performance_df = performance_df[~((performance_df['Portfolio'] == "N/A") & (performance_df['Benchmark'] == "N/A"))]
return performance_df
Enhanced Top 10 Drawdowns Comparison Graph in display_portfolio_vs_portfolio:
Changes:
Enhanced Risk Contribution Analysis and Diversification Overview in display_portfolio_vs_benchmark:
Changes:
Additional Enhancements for Hiding Rows in Performance Comparison Table:
Explanation:
create_performance_stats_df_portfolio_vs_benchmark function now filters out rows with both "N/A", ensure that the styling does not attempt to hide already filtered rows.# In display_portfolio_vs_benchmark function after creating performance_comparison_df
# Removed the 'highlight_better' function's hiding logic since rows with both "N/A" are already filtered
# Apply the highlight function to style the rows
styled_metrics = performance_comparison_df.style.apply(
highlight_better, # Assumes this function now only handles styling without hiding
axis=1
).format({
'Portfolio': lambda x: x,
'Benchmark': lambda x: x
})
Note: Ensure that the highlight_better function no longer needs to handle hiding rows, as filtering is performed earlier.
These enhancements improve the user experience by providing more interactive and insightful visualizations, ensuring that irrelevant data is hidden for clarity, and offering personalized recommendations based on portfolio metrics.
Not yet included in a published release.
def display_portfolio_vs_portfolio(results, portfolio1_name, portfolio2_name):
"""Displays comparison between two portfolios with enhanced UI/UX."""
# ... [previous code] ...
with risk_tab:
st.header("🎯 Risk Analysis")
col1, col2 = st.columns([1,1])
with col1:
# Rolling Volatility Comparison with Interactive Layers
st.subheader("📉 Rolling Volatility Comparison (30-Day)")
rolling_vol_a = returns_a.rolling(window=30).std() * np.sqrt(252)
rolling_vol_b = returns_b.rolling(window=30).std() * np.sqrt(252)
fig_vol = go.Figure()
fig_vol.add_trace(go.Scatter(
x=rolling_vol_a.index,
y=rolling_vol_a,
name=f"{portfolio1_name} Volatility",
line=dict(color='cyan', width=2)
))
fig_vol.add_trace(go.Scatter(
x=rolling_vol_b.index,
y=rolling_vol_b,
name=f"{portfolio2_name} Volatility",
line=dict(color='orange', width=2, dash='dash')
))
fig_vol.update_layout(
template=selected_theme,
hovermode='x unified',
height=500,
xaxis_title='Date',
yaxis_title='Annualized Volatility (%)',
legend=dict(x=0.01, y=0.99)
)
st.plotly_chart(fig_vol, use_container_width=True)
with col2:
# Rolling Correlation Comparison with Interactive Features
st.subheader("🔄 Rolling Correlation (30-Day) Between Portfolios")
rolling_corr = returns_a.rolling(window=30).corr(returns_b)
fig_corr = px.line(
rolling_corr,
title="📈 30-Day Rolling Correlation",
labels={"index": "Date", "value": "Correlation"},
template=selected_theme
)
fig_corr.update_traces(line=dict(color='purple'))
fig_corr.update_layout(
hovermode='x unified',
height=500,
xaxis_title='Date',
yaxis_title='Correlation'
)
st.plotly_chart(fig_corr, use_container_width=True)
st.subheader("📉 Top 10 Drawdowns Comparison Between Portfolios")
col3, col4 = st.columns([1,1])
with col3:
# 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({
f"{portfolio1_name} Date": drawdowns_a_df['Date'],
f"{portfolio1_name} Drawdown (%)": drawdowns_a_df['Drawdown'],
f"{portfolio2_name} Date": drawdowns_b_df['Date'],
f"{portfolio2_name} 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=portfolio1_name,
x=drawdowns_a_df['Date'],
y=drawdowns_a_df['Drawdown'],
marker_color='cyan',
hovertemplate='%{y:.2f}% on %{x}<extra></extra>'
),
go.Bar(
name=portfolio2_name,
x=drawdowns_b_df['Date'],
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.")
def display_portfolio_vs_benchmark(results, portfolio_name):
# ... [previous code] ...
# Diversification Metrics
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.")
with col2:
# Risk Contribution Analysis with Interactive Filters
st.subheader("🛡️ Risk Contribution Analysis")
col3, col4 = st.columns([1,1])
with col3:
# Risk Contribution for Portfolio
risk_contrib = calculate_risk_contribution(
price_data_a[available_a].pct_change().dropna(),
weights_a
)
# Create DataFrame for plotting
risk_contrib_df_a = pd.DataFrame({
'Asset': available_a,
'Risk Contribution (%)': risk_contrib * 100
}).sort_values(by='Risk Contribution (%)', ascending=False)
# Interactive filter for top N assets
top_n = st.slider("Select Top N Assets for Risk Contribution", min_value=5, max_value=len(available_a), value=10)
filtered_risk_contrib_a = risk_contrib_df_a.head(top_n)
fig_risk_a = px.bar(
filtered_risk_contrib_a,
x='Asset',
y='Risk Contribution (%)',
title=f"🔍 {portfolio1_name} Risk Contribution (Top {top_n})",
labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
template=selected_theme,
color='Risk Contribution (%)',
color_continuous_scale='Blues',
hover_data=['Risk Contribution (%)']
)
fig_risk_a.update_layout(
xaxis_title='Asset',
yaxis_title='Risk Contribution (%)',
height=500
)
st.plotly_chart(fig_risk_a, 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.")