if currentstep == "Optimize Portfolio": st.title("🔧 Optimize Portfolio") if not…
- User
if current_step == "Optimize Portfolio": st.title("🔧 Optimize Portfolio")
code - Assistant
if current_step == "Optimize Portfolio": st.title("🔧 Optimize Portfolio")
if not st.session_state.portfolios:
st.warning("Please add at least one portfolio to optimize.")
else:
portfolio_names = [p['name'] for p in st.session_state.portfolios]
selected_portfolio_name = st.selectbox("📁 Select Portfolio to Optimize", portfolio_names)
portfolio = next(p for p in st.session_state.portfolios if p['name'] == selected_portfolio_name)
# Download and prepare data
price_data = download_data(
portfolio['selected'],
portfolio['start_date'],
portfolio['end_date']
)
if price_data.empty:
st.error("No price data available for the selected portfolio.")
else:
available_selected = [ticker for ticker in portfolio['selected'] if ticker in price_data.columns]
missing_selected = list(set(portfolio['selected']) - set(available_selected))
if missing_selected:
st.warning(f"Excluded tickers with no data: {', '.join(missing_selected)}")
if not available_selected:
st.error("No selected tickers have available data for the chosen date range.")
else:
returns = price_data[available_selected].pct_change().dropna()
st.header("🚀 Portfolio Optimization Settings")
# Constraints Section
with st.expander("⚙️ Constraints", expanded=True):
constraints_col1, constraints_col2 = st.columns(2)
with constraints_col1:
max_weight = st.slider(
"📈 Maximum Weight per Asset (%)",
min_value=0.0,
max_value=100.0,
value=100.0,
step=0.1,
help="Set the maximum allocation percentage for any single asset."
) / 100 # Convert to decimal
with constraints_col2:
min_weight = st.slider(
"📉 Minimum Weight per Asset (%)",
min_value=0.0,
max_value=100.0,
value=0.0,
step=0.1,
help="Set the minimum allocation percentage for any single asset."
) / 100 # Convert to decimal
# Validation: Ensure min_weight does not exceed max_weight
if min_weight > max_weight:
st.error("⚠️ **Minimum weight cannot exceed Maximum weight.** Please adjust your settings.")
# Objectives Section
with st.expander("🎯 Objectives", expanded=True):
objective_options = {
"Maximize Sharpe Ratio": "sharpe",
"Minimize Variance": "min_variance",
"Maximize Return": "max_return",
"Minimize Drawdown": "min_drawdown",
"Maximize Alpha": "maximize_alpha",
"Minimize Beta": "minimize_beta"
}
selected_objectives = st.multiselect(
"Select Optimization Objectives",
options=list(objective_options.keys()),
default=["Maximize Sharpe Ratio"],
help="Choose one or more objectives to optimize your portfolio."
)
if not selected_objectives:
st.warning("⚠️ Please select at least one optimization objective.")
# Target Return Section
with st.expander("🎯 Target Return", expanded=True):
target_return = st.number_input(
"📈 Target Annual Return (%)",
min_value=0.0,
max_value=100.0,
value=10.0,
step=0.1,
help="Set the target annual return for portfolio optimization."
) / 100 # Convert to decimal
# Optimization Trigger
if st.button("✅ Run Optimization"):
if not selected_objectives:
st.error("❌ Please select at least one optimization objective.")
else:
# Map objectives to their internal codes
objective_map = {v: k for k, v in objective_options.items()}
objectives_selected = [objective_options[obj] for obj in selected_objectives]
with st.spinner("🧮 Optimizing portfolio..."):
# Fetch benchmark returns
benchmark_symbol = portfolio['benchmark_symbol']
benchmark_data = download_data([benchmark_symbol], portfolio['start_date'], portfolio['end_date'])
if benchmark_data.empty:
st.error(f"Benchmark symbol '{benchmark_symbol}' does not have available data for the chosen period.")
else:
benchmark_returns = benchmark_data[benchmark_symbol].pct_change().dropna()
benchmark_returns = benchmark_returns.reindex(returns.index, method='ffill').dropna()
# Run optimization
optimized_weights = optimize_portfolio(
returns,
benchmark_returns=benchmark_returns,
objectives=objectives_selected,
rf=portfolio['rf_rate'],
max_weight=max_weight,
min_weight=min_weight,
target_return=target_return
)
if optimized_weights is not None:
# Ensure allocations sum to 100%
total_allocation = sum(optimized_weights)
if not np.isclose(total_allocation, 1.0, atol=1e-4):
st.warning(f"🔄 Allocations sum to {total_allocation*100:.2f}%. Adjusting proportionally.")
optimized_weights = [w / total_allocation for w in optimized_weights]
# Display Optimized Weights
st.subheader("📊 Optimized Portfolio Allocation")
weights_df = pd.DataFrame({
'Ticker': available_selected,
'Allocation (%)': [f"{w*100:.2f}" for w in optimized_weights]
})
st.table(weights_df)
# Plot Allocation Pie Chart
plot_allocation_pie(
optimized_weights,
available_selected,
title="🥧 Optimized Allocation",
hover_info="percent+name"
)
# Display Performance Metrics
st.subheader("📈 Optimized Portfolio Performance Metrics")
optimized_return = np.dot(optimized_weights, returns.mean()) * 252
optimized_volatility = np.sqrt(np.dot(optimized_weights, np.dot(returns.cov() * 252, optimized_weights)))
optimized_sharpe = (optimized_return - portfolio['rf_rate']) / optimized_volatility if optimized_volatility > 0 else np.nan
optimized_metrics = {
'Expected Annual Return (%)': f"{optimized_return * 100:.2f}%",
'Annualized Volatility (%)': f"{optimized_volatility * 100:.2f}%",
'Sharpe Ratio': f"{optimized_sharpe:.2f}"
}
optimized_metrics_df = pd.DataFrame(list(optimized_metrics.items()), columns=['Metric', 'Value'])
st.table(optimized_metrics_df)
# Store optimized weights and metrics in session state
st.session_state.backtest_results.update({
'optimized_weights': optimized_weights,
'optimized_return': optimized_return,
'optimized_volatility': optimized_volatility,
'optimized_sharpe': optimized_sharpe
})
st.success("🎉 Portfolio optimization completed successfully!")
else:
st.error("❌ Optimization did not return any weights.")
else:
st.warning("Please add at least one portfolio to optimize.")
File "/content/portfolio_optimizer.py", line 3369 else: ^ SyntaxError: invalid syntax
fix it
The SyntaxError you're encountering is due to an improperly aligned else statement in your code. Specifically, there's an extra else: at the end of your script that isn't paired with a corresponding if statement, which causes Python to raise a syntax error.
Here's how you can fix it:
Identify the Redundant else:
In your provided code, after handling the case where st.session_state.portfolios does not exist (if not st.session_state.portfolios:), there's a corresponding else: to handle the case when portfolios are available. However, at the very end of your code snippet, there's another else: that isn't paired with any if statement. This is the root cause of the syntax error.
Remove the Extra else:
The extra else: at the end of your code should be removed to maintain proper indentation and logical flow.
Ensure Proper Indentation:
Python relies heavily on indentation to define code blocks. Ensure that all if, elif, and else statements are correctly indented and paired.
Complete Corrected Code:
Below is the corrected version of your code with the redundant else: removed and proper indentation maintained.
if current_step == "Optimize Portfolio":
st.title("🔧 Optimize Portfolio")
if not st.session_state.portfolios:
st.warning("Please add at least one portfolio to optimize.")
else:
portfolio_names = [p['name'] for p in st.session_state.portfolios]
selected_portfolio_name = st.selectbox("📁 Select Portfolio to Optimize", portfolio_names)
portfolio = next(p for p in st.session_state.portfolios if p['name'] == selected_portfolio_name)
# Download and prepare data
price_data = download_data(
portfolio['selected'],
portfolio['start_date'],
portfolio['end_date']
)
if price_data.empty:
st.error("No price data available for the selected portfolio.")
else:
available_selected = [ticker for ticker in portfolio['selected'] if ticker in price_data.columns]
missing_selected = list(set(portfolio['selected']) - set(available_selected))
if missing_selected:
st.warning(f"Excluded tickers with no data: {', '.join(missing_selected)}")
if not available_selected:
st.error("No selected tickers have available data for the chosen date range.")
else:
returns = price_data[available_selected].pct_change().dropna()
st.header("🚀 Portfolio Optimization Settings")
# Constraints Section
with st.expander("⚙️ Constraints", expanded=True):
constraints_col1, constraints_col2 = st.columns(2)
with constraints_col1:
max_weight = st.slider(
"📈 Maximum Weight per Asset (%)",
min_value=0.0,
max_value=100.0,
value=100.0,
step=0.1,
help="Set the maximum allocation percentage for any single asset."
) / 100 # Convert to decimal
with constraints_col2:
min_weight = st.slider(
"📉 Minimum Weight per Asset (%)",
min_value=0.0,
max_value=100.0,
value=0.0,
step=0.1,
help="Set the minimum allocation percentage for any single asset."
) / 100 # Convert to decimal
# Validation: Ensure min_weight does not exceed max_weight
if min_weight > max_weight:
st.error("⚠️ **Minimum weight cannot exceed Maximum weight.** Please adjust your settings.")
# Objectives Section
with st.expander("🎯 Objectives", expanded=True):
objective_options = {
"Maximize Sharpe Ratio": "sharpe",
"Minimize Variance": "min_variance",
"Maximize Return": "max_return",
"Minimize Drawdown": "min_drawdown",
"Maximize Alpha": "maximize_alpha",
"Minimize Beta": "minimize_beta"
}
selected_objectives = st.multiselect(
"Select Optimization Objectives",
options=list(objective_options.keys()),
default=["Maximize Sharpe Ratio"],
help="Choose one or more objectives to optimize your portfolio."
)
if not selected_objectives:
st.warning("⚠️ Please select at least one optimization objective.")
# Target Return Section
with st.expander("🎯 Target Return", expanded=True):
target_return = st.number_input(
"📈 Target Annual Return (%)",
min_value=0.0,
max_value=100.0,
value=10.0,
step=0.1,
help="Set the target annual return for portfolio optimization."
) / 100 # Convert to decimal
# Optimization Trigger
if st.button("✅ Run Optimization"):
if not selected_objectives:
st.error("❌ Please select at least one optimization objective.")
else:
# Map objectives to their internal codes
objective_map = {v: k for k, v in objective_options.items()}
objectives_selected = [objective_options[obj] for obj in selected_objectives]
with st.spinner("🧮 Optimizing portfolio..."):
# Fetch benchmark returns
benchmark_symbol = portfolio['benchmark_symbol']
benchmark_data = download_data([benchmark_symbol], portfolio['start_date'], portfolio['end_date'])
if benchmark_data.empty:
st.error(f"Benchmark symbol '{benchmark_symbol}' does not have available data for the chosen period.")
else:
benchmark_returns = benchmark_data[benchmark_symbol].pct_change().dropna()
benchmark_returns = benchmark_returns.reindex(returns.index, method='ffill').dropna()
# Run optimization
optimized_weights = optimize_portfolio(
returns,
benchmark_returns=benchmark_returns,
objectives=objectives_selected,
rf=portfolio['rf_rate'],
max_weight=max_weight,
min_weight=min_weight,
target_return=target_return
)
if optimized_weights is not None:
# Ensure allocations sum to 100%
total_allocation = sum(optimized_weights)
if not np.isclose(total_allocation, 1.0, atol=1e-4):
st.warning(f"🔄 Allocations sum to {total_allocation*100:.2f}%. Adjusting proportionally.")
optimized_weights = [w / total_allocation for w in optimized_weights]
# Display Optimized Weights
st.subheader("📊 Optimized Portfolio Allocation")
weights_df = pd.DataFrame({
'Ticker': available_selected,
'Allocation (%)': [f"{w*100:.2f}" for w in optimized_weights]
})
st.table(weights_df)
# Plot Allocation Pie Chart
plot_allocation_pie(
optimized_weights,
available_selected,
title="🥧 Optimized Allocation",
hover_info="percent+name"
)
# Display Performance Metrics
st.subheader("📈 Optimized Portfolio Performance Metrics")
optimized_return = np.dot(optimized_weights, returns.mean()) * 252
optimized_volatility = np.sqrt(np.dot(optimized_weights, np.dot(returns.cov() * 252, optimized_weights)))
optimized_sharpe = (optimized_return - portfolio['rf_rate']) / optimized_volatility if optimized_volatility > 0 else np.nan
optimized_metrics = {
'Expected Annual Return (%)': f"{optimized_return * 100:.2f}%",
'Annualized Volatility (%)': f"{optimized_volatility * 100:.2f}%",
'Sharpe Ratio': f"{optimized_sharpe:.2f}"
}
optimized_metrics_df = pd.DataFrame(list(optimized_metrics.items()), columns=['Metric', 'Value'])
st.table(optimized_metrics_df)
# Store optimized weights and metrics in session state
st.session_state.backtest_results.update({
'optimized_weights': optimized_weights,
'optimized_return': optimized_return,
'optimized_volatility': optimized_volatility,
'optimized_sharpe': optimized_sharpe
})
st.success("🎉 Portfolio optimization completed successfully!")
else:
st.error("❌ Optimization did not return any weights.")
# Removed the redundant else block below
# else:
# st.warning("Please add at least one portfolio to optimize.")
Removed Redundant else:
At the very end of your original code, there was an else: statement that wasn't paired with any if. This has been removed to prevent the SyntaxError.
Verified Proper Indentation:
Ensured that all if, elif, and else blocks are correctly indented to maintain the logical flow of the program.
No Logic Changes:
The functionality of your portfolio optimization remains unchanged. The fix solely addresses the syntax issue without altering any logic or feature.
Use an IDE or Linter:
Tools like VSCode, PyCharm, or linters like flake8 can help catch such syntax errors before running the code.
Consistent Indentation:
Ensure that you're consistently using spaces or tabs for indentation. Mixing both can lead to unexpected errors.
Code Formatting:
Properly formatting your code enhances readability and maintainability. Consider using tools like black for automatic code formatting.
By applying the above fix, your code should run without the SyntaxError. If you encounter further issues or have additional questions, feel free to ask!