# 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
main_tab, metrics_tab, risk_tab, analysis_tab = st.tabs([
"📈 Main Charts", "📊 Performance Metrics", "🎯 Risk Analysis", "🔍 Deep Analysis"
])
with main_tab:
st.header("🔹 Portfolio vs Benchmark Overview")
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("Portfolio Composition")
fig_composition = px.pie(
values=weights,
names=price_data.columns,
title="Current Portfolio Allocation",
template=selected_theme,
hole=0.4
)
fig_composition.update_traces(textinfo='percent+label')
st.plotly_chart(fig_composition, use_container_width=True)
with col2:
st.subheader("Key Performance Indicators")
metrics_display = {
"Total Return": f"{(cum_returns.iloc[-1] - 1) * 100:.2f}%",
"Annualized Return": metrics.get('Annualized Return (CAGR)', 'N/A'),
"Sharpe Ratio": metrics.get('Sharpe Ratio', 'N/A'),
"Max Drawdown": metrics.get('Maximum Drawdown', 'N/A')
}
for metric, value in metrics_display.items():
st.metric(metric, value)
# Enhanced Cumulative Returns Plot with Interactive Features
st.subheader("Cumulative Returns Comparison")
fig_returns = go.Figure()
fig_returns.add_trace(go.Scatter(
x=cum_returns.index,
y=cum_returns,
name="Portfolio",
line=dict(color='cyan', width=2),
hovertemplate='%{y:.2f}'
))
fig_returns.add_trace(go.Scatter(
x=benchmark_cum_returns.index,
y=benchmark_cum_returns,
name="Benchmark",
line=dict(color='orange', width=2, dash='dash'),
hovertemplate='%{y:.2f}'
))
fig_returns.update_layout(
template=selected_theme,
hovermode='x unified',
height=500,
xaxis_title='Date',
yaxis_title='Cumulative Returns',
legend=dict(x=0.01, y=0.99)
)
st.plotly_chart(fig_returns, use_container_width=True)
# Interactive Summary Recommendations
create_summary_recommendations('overview', metrics=metrics)
with metrics_tab:
st.header("📊 Detailed Performance Metrics")
st.subheader("Performance Comparison Table")
# Create comparison metrics table assuming both metrics and benchmark_metrics have same keys
portfolio_metrics_df = pd.DataFrame(metrics.items(), columns=['Metric', 'Portfolio'])
benchmark_metrics_df = pd.DataFrame(benchmark_metrics.items(), columns=['Metric', 'Benchmark'])
metrics_comparison = pd.merge(portfolio_metrics_df, benchmark_metrics_df, on='Metric', how='outer')
# Define a custom formatter to handle numeric and non-numeric values
def custom_formatter(x):
try:
# Attempt to convert to float after stripping possible symbols
value = float(str(x).strip('%').strip('$').replace(',', ''))
return f"{value:.2f}%"
except (ValueError, TypeError):
return x # Return the original value if conversion fails
# Style the metrics table
def highlight_better(row):
styles = [''] * len(row)
portfolio_val = row["Portfolio"]
benchmark_val = row["Benchmark"]
# Skip if either is N/A
if portfolio_val == "N/A" or benchmark_val == "N/A":
return styles
# Convert to float if possible
try:
portfolio_num = float(str(portfolio_val).strip('%').strip('$').replace(',', ''))
benchmark_num = float(str(benchmark_val).strip('%').strip('$').replace(',', ''))
except:
return styles
# Determine if higher is better or lower is better based on metric name
if any(keyword in row['Metric'] for keyword in ['Drawdown', 'Deviation']):
better = portfolio_num < benchmark_num
else:
better = portfolio_num > benchmark_num
styles[1] = 'background-color: #d4f7d4' if better else 'background-color: #f7d4d4'
return styles
styled_metrics = metrics_comparison.style.apply(highlight_better, axis=1)
# Apply the custom formatter only to numeric cells
styled_metrics = styled_metrics.format(
custom_formatter,
subset=pd.IndexSlice[:, ['Portfolio', 'Benchmark']]
)
st.dataframe(styled_metrics, height=400)
# Interactive Summary Recommendations
create_summary_recommendations('comparison', metrics=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)
with col2:
# Rolling Beta with Interactive Thresholds
st.subheader("Rolling Beta (30-Day)")
# Rolling correlation is used to compute beta
rolling_cov = returns.rolling(window=30).cov(benchmark_returns)
rolling_var = benchmark_returns.rolling(window=30).var()
rolling_beta = rolling_cov / rolling_var
fig_beta = px.line(
rolling_beta,
title="30-Day Rolling Beta",
labels={"index": "Date", "value": "Beta"},
template=selected_theme
)
fig_beta.update_traces(line=dict(color='green'))
fig_beta.update_layout(
hovermode='x unified',
height=400,
xaxis_title='Date',
yaxis_title='Beta'
)
st.plotly_chart(fig_beta, use_container_width=True)
# 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)
# Interactive Summary Recommendations
create_summary_recommendations('risk', metrics=metrics)
with analysis_tab:
st.header("🔍 Deep Analysis")
col1, col2 = st.columns([1,1])
with col1:
# Monthly Returns Heatmap with Enhanced Color Scale
st.subheader("Monthly Returns Heatmap")
monthly_returns = returns.resample('M').agg(lambda x: (1 + x).prod() - 1)
monthly_returns_matrix = monthly_returns.groupby([monthly_returns.index.year, monthly_returns.index.month]).first().unstack()
fig_heatmap = px.imshow(
monthly_returns_matrix,
labels=dict(x="Month", y="Year", color="Returns"),
color_continuous_scale="RdYlGn",
title="Monthly Returns Heatmap",
template=selected_theme
)
fig_heatmap.update_layout(
xaxis_title='Month',
yaxis_title='Year',
height=500
)
st.plotly_chart(fig_heatmap, use_container_width=True)
with col2:
# Rolling Correlation with Benchmark
st.subheader("Rolling Correlation with Benchmark (30-Day)")
rolling_corr = returns.rolling(window=30).corr(benchmark_returns)
fig_corr = px.line(
rolling_corr,
title="30-Day Rolling Correlation with Benchmark",
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)
# Risk Contribution Detailed Analysis
st.subheader("Detailed Risk Contribution Analysis")
risk_contrib = calculate_risk_contribution(price_data[available_selected].pct_change().dropna(), weights)
fig_risk_detailed = px.scatter(
x=price_data.columns,
y=risk_contrib * 100,
size=(risk_contrib * 100),
color=price_data.columns,
hover_name=price_data.columns,
title="Risk Contribution by Asset",
labels={'x': 'Asset', 'y': 'Risk Contribution (%)'},
template=selected_theme
)
fig_risk_detailed.update_layout(
xaxis_title='Asset',
yaxis_title='Risk Contribution (%)',
height=600
)
st.plotly_chart(fig_risk_detailed, use_container_width=True)
# Interactive Summary Recommendations
create_summary_recommendations('deep', metrics=metrics)
def calculate_metrics(
returns: pd.Series,
cum_returns: pd.Series,
rf: float = 0.02,
benchmark_returns: pd.Series = None
) -> dict:
metrics = {}
metrics['Start Balance'] = "10,000.00"
if not cum_returns.empty and not returns.empty:
end_balance = 10000 * cum_returns.iloc[-1]
years = (cum_returns.index[-1] - cum_returns.index[0]).days / 365.25
try:
cagr = (end_balance / 10000) ** (1 / years) - 1 if years > 0 else np.nan
except:
cagr = np.nan
metrics.update({
'End Balance': f"{end_balance:,.2f}",
'Annualized Return (CAGR)': f"{cagr * 100:.2f}%" if not np.isnan(cagr) else "N/A",
'Best Year': f"{returns.resample('Y').apply(lambda x: (1 + x).prod() - 1).max() * 100:.2f}%" if not returns.empty else "N/A",
'Worst Year': f"{returns.resample('Y').apply(lambda x: (1 + x).prod() - 1).min() * 100:.2f}%" if not returns.empty else "N/A",
'Arithmetic Mean (Monthly)': f"{returns.mean() * 100:.2f}%",
'Arithmetic Mean (Annualized)': f"{returns.mean() * 252 * 100:.2f}%",
'Geometric Mean (Monthly)': f"{(np.exp(np.log1p(returns).mean()) - 1) * 100:.2f}%" if not returns.empty else "N/A",
'Geometric Mean (Annualized)': f"{(np.exp(np.log1p(returns).mean() * 252) - 1) * 100:.2f}%" if not returns.empty else "N/A",
'Standard Deviation (Monthly)': f"{returns.std() * 100:.2f}%",
'Standard Deviation (Annualized)': f"{returns.std() * np.sqrt(252) * 100:.2f}%",
'Downside Deviation (Monthly)': f"{returns[returns < 0].std() * 100:.2f}%" if not returns.empty else "N/A",
'Maximum Drawdown': f"{drawdown(cum_returns) * 100:.2f}%" if not cum_returns.empty else "N/A",
'Sharpe Ratio': f"{calculate_sharpe_ratio(returns, rf):.2f}" if not cum_returns.empty else "N/A",
'Sortino Ratio': f"{calculate_sortino_ratio(returns, rf):.2f}" if not cum_returns.empty else "N/A",
'Gain/Loss Ratio': f"{calculate_gain_loss_ratio(returns):.2f}" if not cum_returns.empty else "N/A",
'Skewness': f"{skew(returns):.2f}" if not returns.empty else "N/A",
'Excess Kurtosis': f"{kurtosis(returns):.2f}" if not returns.empty else "N/A",
'Safe Withdrawal Rate': f"{calculate_safe_withdrawal_rate(returns):.6f}%" if not returns.empty else "N/A",
'Perpetual Withdrawal Rate': f"{calculate_perpetual_withdrawal_rate(returns):.6f}%" if not returns.empty else "N/A",
'Positive Periods': calculate_positive_periods(returns) if not returns.empty else "N/A"
})
else:
# Assign "N/A" to all metrics if cum_returns or returns are empty
metrics.update({
'End Balance': "N/A",
'Annualized Return (CAGR)': "N/A",
'Best Year': "N/A",
'Worst Year': "N/A",
'Arithmetic Mean (Monthly)': "N/A",
'Arithmetic Mean (Annualized)': "N/A",
'Geometric Mean (Monthly)': "N/A",
'Geometric Mean (Annualized)': "N/A",
'Standard Deviation (Monthly)': "N/A",
'Standard Deviation (Annualized)': "N/A",
'Downside Deviation (Monthly)': "N/A",
'Maximum Drawdown': "N/A",
'Sharpe Ratio': "N/A",
'Sortino Ratio': "N/A",
'Gain/Loss Ratio': "N/A",
'Skewness': "N/A",
'Excess Kurtosis': "N/A",
'Safe Withdrawal Rate': "N/A",
'Perpetual Withdrawal Rate': "N/A",
'Positive Periods': "N/A"
})
def calculate_metrics(
returns: pd.Series,
cum_returns: pd.Series,
rf: float = 0.02,
benchmark_returns: pd.Series = None
) -> dict:
metrics = {}
metrics['Start Balance'] = "$10,000.00"
if not cum_returns.empty and not returns.empty:
end_balance = 10000 * cum_returns.iloc[-1]
years = (cum_returns.index[-1] - cum_returns.index[0]).days / 365.25
try:
cagr = (end_balance / 10000) ** (1 / years) - 1 if years > 0 else np.nan
except:
cagr = np.nan
metrics.update({
'End Balance': end_balance,
'Total Return': (cum_returns.iloc[-1] - 1) * 100,
'Annualized Return (CAGR)': cagr * 100 if not np.isnan(cagr) else "N/A",
'Best Year': returns.resample('Y').apply(lambda x: (1 + x).prod() - 1).max() * 100 if not returns.empty else "N/A",
'Worst Year': returns.resample('Y').apply(lambda x: (1 + x).prod() - 1).min() * 100 if not returns.empty else "N/A",
'Arithmetic Mean (Monthly)': returns.mean() * 100,
'Arithmetic Mean (Annualized)': returns.mean() * 252 * 100,
'Geometric Mean (Monthly)': (np.exp(np.log1p(returns).mean()) - 1) * 100 if not returns.empty else "N/A",
'Geometric Mean (Annualized)': (np.exp(np.log1p(returns).mean() * 252) - 1) * 100 if not returns.empty else "N/A",
'Standard Deviation (Monthly)': returns.std() * 100,
'Standard Deviation (Annualized)': returns.std() * np.sqrt(252) * 100,
'Downside Deviation (Monthly)': returns[returns < 0].std() * 100 if not returns.empty else "N/A",
'Maximum Drawdown': drawdown(cum_returns) * 100 if not cum_returns.empty else "N/A",
'Sharpe Ratio': calculate_sharpe_ratio(returns, rf) if not cum_returns.empty else "N/A",
'Sortino Ratio': calculate_sortino_ratio(returns, rf) if not cum_returns.empty else "N/A",
'Gain/Loss Ratio': calculate_gain_loss_ratio(returns) if not cum_returns.empty else "N/A",
'Skewness': skew(returns) if not returns.empty else "N/A",
'Excess Kurtosis': kurtosis(returns) if not returns.empty else "N/A",
'Safe Withdrawal Rate': calculate_safe_withdrawal_rate(returns) * 100 if not returns.empty else "N/A",
'Perpetual Withdrawal Rate': calculate_perpetual_withdrawal_rate(returns) * 100 if not returns.empty else "N/A",
'Positive Periods': calculate_positive_periods(returns) if not returns.empty else "N/A"
})
else:
# Assign "N/A" to all metrics if cum_returns or returns are empty
metrics.update({
'End Balance': "N/A",
'Total Return': "N/A",
'Annualized Return (CAGR)': "N/A",
'Best Year': "N/A",
'Worst Year': "N/A",
'Arithmetic Mean (Monthly)': "N/A",
'Arithmetic Mean (Annualized)': "N/A",
'Geometric Mean (Monthly)': "N/A",
'Geometric Mean (Annualized)': "N/A",
'Standard Deviation (Monthly)': "N/A",
'Standard Deviation (Annualized)': "N/A",
'Downside Deviation (Monthly)': "N/A",
'Maximum Drawdown': "N/A",
'Sharpe Ratio': "N/A",
'Sortino Ratio': "N/A",
'Gain/Loss Ratio': "N/A",
'Skewness': "N/A",
'Excess Kurtosis': "N/A",
'Safe Withdrawal Rate': "N/A",
'Perpetual Withdrawal Rate': "N/A",
'Positive Periods': "N/A"
})
if benchmark_returns is not None and not benchmark_returns.empty:
# Calculate benchmark-relative metrics
correlation = returns.corr(benchmark_returns)
beta = calculate_beta(returns, benchmark_returns)
alpha = calculate_alpha(returns, benchmark_returns, rf)
r2 = calculate_r_squared(returns, benchmark_returns)
treynor = calculate_treynor_ratio(returns, benchmark_returns, rf)
calmar = calculate_calmar_ratio(returns, cum_returns)
m2 = calculate_modigliani_miller(returns, benchmark_returns, rf)
info_ratio = calculate_information_ratio(returns, benchmark_returns)
tracking_error = calculate_tracking_error(returns, benchmark_returns)
active_return = calculate_active_return(returns, benchmark_returns)
upside_capture = calculate_capture_ratio(returns, benchmark_returns, upside=True)
downside_capture = calculate_capture_ratio(returns, benchmark_returns, upside=False)
metrics.update({
'Benchmark Correlation': correlation if not np.isnan(correlation) else "N/A",
'Beta': beta if not np.isnan(beta) else "N/A",
'Alpha (annualized)': alpha * 100 if not np.isnan(alpha) else "N/A",
'R2': r2 * 100 if not np.isnan(r2) else "N/A",
'Treynor Ratio': treynor if not np.isnan(treynor) else "N/A",
'Calmar Ratio': calmar if not np.isnan(calmar) else "N/A",
'Modigliani–Modigliani Measure': m2 * 100 if not np.isnan(m2) else "N/A",
'Information Ratio': info_ratio if not np.isnan(info_ratio) else "N/A",
'Tracking Error': tracking_error * 100 if not np.isnan(tracking_error) else "N/A",
'Active Return': active_return * 100 if not np.isnan(active_return) else "N/A",
'Upside Capture Ratio': upside_capture * 100 if not np.isnan(upside_capture) else "N/A",
'Downside Capture Ratio': downside_capture * 100 if not np.isnan(downside_capture) else "N/A"
})
else:
# Assign "N/A" to all benchmark metrics
metrics.update({
'Benchmark Correlation': "N/A",
'Beta': "N/A",
'Alpha (annualized)': "N/A",
'R2': "N/A",
'Treynor Ratio': "N/A",
'Calmar Ratio': "N/A",
'Modigliani–Modigliani Measure': "N/A",
'Information Ratio': "N/A",
'Tracking Error': "N/A",
'Active Return': "N/A",
'Upside Capture Ratio': "N/A",
'Downside Capture Ratio': "N/A"
})
return metrics