def display_portfolio_vs_benchmark(results):
"""
Enhanced display function for Portfolio vs Benchmark comparison with improved visualizations and UX.
"""
# 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['benchmark_metrics']
benchmark_returns = results['benchmark_returns']
benchmark_cum_returns = results['benchmark_cum_returns']
code
Assistant
# 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')
# 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(portfolio_val.strip('%').strip('$').replace(',', ''))
benchmark_num = float(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 format only to numeric columns
styled_metrics = styled_metrics.format("{:.2f}%", 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)
ValueError: Unknown format code 'f' for object of type 'str'
Traceback:
File "/usr/local/lib/python3.10/dist-packages/streamlit/runtime/scriptrunner/exec_code.py", line 88, in exec_func_with_error_handling
result = func()
File "/usr/local/lib/python3.10/dist-packages/streamlit/runtime/scriptrunner/script_runner.py", line 579, in code_to_exec
exec(code, module.dict)
File "/content/portfolio_optimizer.py", line 4181, in
display_backtest_results(result["backtest_results"], comparison_type, portfolio1)
File "/content/portfolio_optimizer.py", line 558, in display_backtest_results
display_portfolio_vs_benchmark(results)
File "/content/portfolio_optimizer.py", line 680, in display_portfolio_vs_benchmark
st.dataframe(styled_metrics, height=400)
File "/usr/local/lib/python3.10/dist-packages/streamlit/runtime/metrics_util.py", line 410, in wrapped_func
result = non_optional_func(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/streamlit/elements/arrow.py", line 547, in dataframe
marshall_styler(proto, data, default_uuid)
File "/usr/local/lib/python3.10/dist-packages/streamlit/elements/lib/pandas_styler_utils.py", line 63, in marshall_styler
pandas_styles = styler._translate(False, False)
File "/usr/local/lib/python3.10/dist-packages/pandas/io/formats/style_render.py", line 335, in _translate
body: list = self._translate_body(idx_lengths, max_rows, max_cols)
File "/usr/local/lib/python3.10/dist-packages/pandas/io/formats/style_render.py", line 629, in _translate_body
body_row = self._generate_body_row(
File "/usr/local/lib/python3.10/dist-packages/pandas/io/formats/style_render.py", line 826, in _generate_body_row
display_value=self._display_funcs(r, c),
File "/usr/local/lib/python3.10/dist-packages/pandas/io/formats/style_render.py", line 1829, in
func_0 = lambda x: formatter.format(x)
The error you're encountering:
code
ValueError: Unknown format code 'f' for object of type 'str'
indicates that the formatting operation is attempting to apply a floating-point format ("{:.2f}%") to a string value ("N/A"), which is not permissible in Python. This issue arises in your display_portfolio_vs_benchmark function, specifically in the formats section where you're formatting the Portfolio and Benchmark columns of your metrics comparison table.
Root Cause
In your metrics_display dictionary, some metrics may have the value "N/A". When you create the metrics_comparison DataFrame and subsequently apply the format method to format these values, the formatter attempts to apply "{:.2f}%" to all entries in the Portfolio and Benchmark columns. Since "N/A" is a string, this leads to the ValueError.
Solution
To resolve this issue, you need to ensure that the formatter only applies to numeric values and gracefully handles non-numeric entries like "N/A". Here's how you can achieve this:
Use a Custom Formatter Function:
Define a custom formatter function that attempts to format numeric values and leaves non-numeric values unchanged.
Apply the Formatter Function:
Use this custom function in the .format method of the pandas Styler object, ensuring that only applicable cells are formatted.
Step-by-Step Implementation
Here's the updated display_portfolio_vs_benchmark function with the necessary changes:
python
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
# Assuming these helper functions are defined elsewhere:
# - create_summary_recommendations
# - calculate_risk_contribution
# - calculate_diversification_index
def display_portfolio_vs_benchmark(results):
"""
Enhanced display function for Portfolio vs Benchmark comparison with improved visualizations and UX.
"""
# 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['benchmark_metrics']
benchmark_returns = results['benchmark_returns']
benchmark_cum_returns = results['benchmark_cum_returns']
# 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)
Explanation of Changes
Custom Formatter Function (custom_formatter):
python
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
Purpose: This function attempts to format a value as a percentage with two decimal places. If the value is not numeric (e.g., "N/A"), it simply returns the original value without formatting.
Implementation:
Conversion: It first converts the input x to a string, removes any percentage signs (%), dollar signs ($), and commas (,) to ensure that strings like "1,234.56%" can be converted to float.
Formatting: If the conversion is successful, it formats the number as "{:.2f}%".
Error Handling: If the conversion fails (raising a ValueError or TypeError), it returns the original value ("N/A" or any other string).
Purpose: This ensures that only the Portfolio and Benchmark columns are formatted using the custom_formatter function.
Benefit: It prevents the formatter from attempting to format non-numeric values, thereby avoiding the ValueError.
Enhanced highlight_better Function:
Modification: Added str() around portfolio_val and to ensure that if they are not strings already, they are converted before applying methods.
Additional Recommendations
Data Preprocessing:
Consider preprocessing your metrics and benchmark_metrics dictionaries to ensure that all numeric values are indeed numeric types (e.g., float) and not strings. This can simplify formatting and styling.
Consistent Data Types:
Ensure that the metrics and benchmark_metrics only contain strings where necessary. For numeric metrics, store them as numbers (int or float) and use None or np.nan for missing values instead of "N/A". This approach leverages pandas' capabilities in handling missing data more gracefully.
Styling Enhancements:
You might want to add more styling rules to highlight the better performance more distinctly or to handle different types of metrics differently.
Final Thoughts
By implementing a custom formatter that safely handles both numeric and non-numeric values, you can avoid the ValueError and ensure that your metrics comparison table displays correctly in Streamlit. This approach provides a more robust and user-friendly interface for your portfolio versus benchmark analysis.
If you have further questions or need additional assistance, feel free to ask!