File/Class/Method:portfolio_optimizer.py / Streamlit Layout / Run Backtest
Relevance: This segment is directly related to the problem of the "Run Backtest" button not triggering any reaction. The code checks if the button is clicked and then runs the backtest.
python
run = st.button("Run Backtest")
if run:
with st.spinner("Running backtest..."):
if comparison_type == "Portfolio vs Benchmark":
portfolio = next(p for p in st.session_state.portfolios if p['name'] == portfolio1)
result = run_portfolio_comparison("vs_benchmark", portfolio)
else:
if portfolio1 == portfolio2:
st.error("Please select two different portfolios for comparison.")
st.stop()
portfolio_a = next(p for p in st.session_state.portfolios if p['name'] == portfolio1)
portfolio_b = next(p for p in st.session_state.portfolios if p['name'] == portfolio2)
result = run_portfolio_comparison("vs_portfolio", portfolio_a, portfolio_b)
if result.get("error"):
st.error(result["error"])
else:
display_backtest_results(result["backtest_results"], comparison_type, portfolio1, portfolio2)
Relevance: This function is responsible for running the backtest. It handles the comparison between portfolios or a portfolio and a benchmark.
python
Assistant
@handle_exceptions
def run_portfolio_comparison(comparison_type, portfolio1, portfolio2=None):
"""
Generalized function to run portfolio comparisons.
Parameters:
- comparison_type (str): "vs_benchmark" or "vs_portfolio"
- portfolio1 (dict): Primary portfolio.
- portfolio2 (dict, optional): Secondary portfolio for "vs_portfolio".
Returns:
- dict: Backtest results or error.
"""
try:
if comparison_type == "vs_benchmark":
# Handle primary portfolio data
available, missing, price_data = handle_portfolio_data(portfolio1)
if not available:
return {"error": "No valid tickers with available data."}
# Adjust allocations based on available tickers
allocations = adjust_allocations([portfolio1['allocations'][portfolio1['selected'].index(t)] for t in available])
# Perform backtest for the portfolio
returns, cum_returns = backtest(
weights=np.array(allocations) / 100,
prices=price_data[available],
rebalance_freq=portfolio1['rebalance_freq'],
broker_fee=portfolio1['broker_fee']
)
if cum_returns.empty:
return {"error": "Cumulative returns are empty."}
# Download benchmark data
benchmark_data = download_data(
[portfolio1['benchmark_symbol']],
portfolio1['start_date'].strftime('%Y-%m-%d'),
portfolio1['end_date'].strftime('%Y-%m-%d')
)
if benchmark_data.empty:
return {"error": "Benchmark data could not be downloaded."}
# Process benchmark data and handle potential errors
try:
benchmark_returns, benchmark_cum_returns, benchmark_metrics = process_benchmark(benchmark_data, returns, portfolio1)
except ValueError as ve:
return {"error": str(ve)}
except Exception as e:
return {"error": f"Benchmark processing failed: {e}"}
# Calculate metrics for the portfolio without benchmark comparison
portfolio_metrics = calculate_metrics(returns, cum_returns, portfolio1['rf_rate'])
# Compile backtest results
backtest_results = {
'returns': returns,
'cum_returns': cum_returns,
'weights': allocations,
'price_data': price_data[available],
'available_selected': available,
'metrics': portfolio_metrics,
'benchmark_returns': benchmark_returns,
'benchmark_cum_returns': benchmark_cum_returns,
'benchmark_metrics': benchmark_metrics
}
return {"backtest_results": backtest_results}
elif comparison_type == "vs_portfolio":
# Determine overlapping date range between the two portfolios
overlap_start = max(portfolio1['start_date'], portfolio2['start_date'])
overlap_end = min(portfolio1['end_date'], portfolio2['end_date'])
if overlap_start >= overlap_end:
return {"error": "No overlapping date ranges."}
# Handle data for both portfolios within the overlapping date range
available_a, missing_a, price_data_a = handle_portfolio_data(portfolio1, (overlap_start, overlap_end))
available_b, missing_b, price_data_b = handle_portfolio_data(portfolio2, (overlap_start, overlap_end))
if not available_a or not available_b:
return {"error": "One of the portfolios has no valid tickers with available data."}
# Adjust allocations based on available tickers for both portfolios
allocations_a = adjust_allocations([portfolio1['allocations'][portfolio1['selected'].index(t)] for t in available_a])
allocations_b = adjust_allocations([portfolio2['allocations'][portfolio2['selected'].index(t)] for t in available_b])
# Perform backtest for both portfolios
returns_a, cum_returns_a = backtest(
weights=np.array(allocations_a) / 100,
prices=price_data_a[available_a],
rebalance_freq=portfolio1['rebalance_freq'],
broker_fee=portfolio1['broker_fee']
)
returns_b, cum_returns_b = backtest(
weights=np.array(allocations_b) / 100,
prices=price_data_b[available_b],
rebalance_freq=portfolio2['rebalance_freq'],
broker_fee=portfolio2['broker_fee']
)
if cum_returns_a.empty or cum_returns_b.empty:
return {"error": "One of the cumulative returns is empty."}
# Align two portfolios' returns
common_index = cum_returns_a.index.intersection(cum_returns_b.index)
if common_index.empty:
return {"error": "No overlapping dates after backtesting."}
returns_a = returns_a.loc[common_index]
returns_b = returns_b.loc[common_index]
cum_returns_a = cum_returns_a.loc[common_index]
cum_returns_b = cum_returns_b.loc[common_index]
# Calculate metrics for both portfolios
metrics_a = calculate_metrics(returns_a, cum_returns_a, portfolio1['rf_rate'])
metrics_b = calculate_metrics(returns_b, cum_returns_b, portfolio2['rf_rate'])
# Compile backtest results
backtest_results = {
'returns_a': returns_a,
'cum_returns_a': cum_returns_a,
'weights_a': allocations_a,
'price_data_a': price_data_a[available_a],
'metrics_a': metrics_a,
'returns_b': returns_b,
'cum_returns_b': cum_returns_b,
'weights_b': allocations_b,
'price_data_b': price_data_b[available_b],
'metrics_b': metrics_b
}
return {"backtest_results": backtest_results}
except Exception as e:
return {"error": f"An unexpected error occurred: {e}"}
Relevance: This function is responsible for displaying the results of the backtest. It checks the comparison type and calls the appropriate display function.
python
def display_backtest_results(results, comparison_type, portfolio1, portfolio2=None):
if comparison_type == "Portfolio vs Benchmark":
display_portfolio_vs_benchmark(results)
else:
# For portfolio vs portfolio comparison
display_portfolio_vs_portfolio(results, portfolio1, portfolio2)
Summary
The provided code segments are essential for handling the "Run Backtest" button click, executing the backtest, and displaying the results. If the button is not triggering any reaction, the issue might be related to the button click handling, the backtest execution, or the display of results. Ensure that all necessary conditions are met before the backtest is executed, and that the results are correctly passed to the display functions.
problem: clicked button Run Backtest when doing portfolio vs benchmark, seems like no reaction of the system
fix it and return full updated segment, dont return full code, only the full updated segement code is needed
It appears that the issue stems from the "Portfolio vs Benchmark" comparison not handling the backtest results appropriately. Specifically, after running the backtest, the code does not check for errors or display the results, unlike the "Portfolio vs Portfolio" comparison. To fix this, you'll need to add error handling and result display for the "Portfolio vs Benchmark" case.
Below is the updated Button Click Handling segment with the necessary modifications:
python
run = st.button("Run Backtest")
if run:
with st.spinner("Running backtest..."):
if comparison_type == "Portfolio vs Benchmark":
try:
portfolio = next(p for p in st.session_state.portfolios if p['name'] == portfolio1)
except StopIteration:
st.error(f"Portfolio '{portfolio1}' not found.")
st.stop()
result = run_portfolio_comparison("vs_benchmark", portfolio)
if result.get("error"):
st.error(result["error"])
else:
display_backtest_results(result["backtest_results"], comparison_type, portfolio1)
else:
if portfolio1 == portfolio2:
st.error("Please select two different portfolios for comparison.")
st.stop()
try:
portfolio_a = next(p for p in st.session_state.portfolios if p['name'] == portfolio1)
portfolio_b = next(p for p in st.session_state.portfolios if p['name'] == portfolio2)
except StopIteration as e:
st.error("One of the selected portfolios was not found.")
st.stop()
result = run_portfolio_comparison("vs_portfolio", portfolio_a, portfolio_b)
if result.get("error"):
st.error(result["error"])
else:
display_backtest_results(result["backtest_results"], comparison_type, portfolio1, portfolio2)
Changes Made:
Error Handling for Portfolio Retrieval:
Added try-except blocks when retrieving portfolios using next(...). This ensures that if the specified portfolio name does not exist in st.session_state.portfolios, an appropriate error message is displayed.
Error Handling and Result Display for "Portfolio vs Benchmark":
After running run_portfolio_comparison, the code now checks if result contains an "error" key.
If an error exists, it displays the error message using st.error(result["error"]).
If no error is present, it calls display_backtest_results to show the backtest results.
Consistent Handling for Both Comparison Types:
Ensured that both comparison types ("vs_benchmark" and "vs_portfolio") follow a similar structure for error handling and result display. This consistency helps in maintaining the code and avoiding similar issues in the future.
Additional Error Handling for "vs_portfolio":
Added a try-except block to handle cases where one of the selected portfolios might not be found, ensuring that the user is informed appropriately.
Summary
By implementing these changes, the "Run Backtest" button should now respond correctly when performing a "Portfolio vs Benchmark" comparison. It will handle scenarios where portfolios might not be found and will display either error messages or the backtest results accordingly.