Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,10 +9,16 @@ from scipy.optimize import minimize
|
|
| 9 |
from scipy.cluster.hierarchy import dendrogram
|
| 10 |
import matplotlib.pyplot as plt
|
| 11 |
|
| 12 |
-
|
| 13 |
# Helper functions
|
| 14 |
def fetch_stock_data(tickers, start_date, end_date):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def plot_efficient_frontier(mean_returns, cov_matrix, title):
|
| 18 |
ef = EfficientFrontier(mean_returns, cov_matrix)
|
|
@@ -206,7 +212,6 @@ st.title('Portfolio Optimization Methods')
|
|
| 206 |
|
| 207 |
st.markdown("""
|
| 208 |
This tool allows you to optimize a portfolio of stocks using different optimization methods. You can choose between optimization methods simply by selecting the method, enterING the stock tickers, and setting the parameters. Click the "Run" button to see the results.
|
| 209 |
-
|
| 210 |
""")
|
| 211 |
|
| 212 |
with st.sidebar.expander("How to Use", expanded=False):
|
|
@@ -224,17 +229,13 @@ st.sidebar.markdown("""
|
|
| 224 |
## Input Parameters:
|
| 225 |
""")
|
| 226 |
|
| 227 |
-
|
| 228 |
# Expander for Asset Symbols and Dates
|
| 229 |
with st.sidebar.expander("Asset Symbols and Dates", expanded=True):
|
| 230 |
tickers_input = st.text_input('Enter Stock Tickers (comma-separated)', 'AAPL, MSFT, GOOGL, AMZN, ASML, META, JPM, V',
|
| 231 |
help="Input stock tickers separated by commas. Example: 'AAPL, MSFT, GOOGL'")
|
| 232 |
-
|
| 233 |
tickers = [ticker.strip() for ticker in tickers_input.split(',')]
|
| 234 |
-
|
| 235 |
start_date = st.date_input('Start Date', pd.to_datetime('2015-01-01'),
|
| 236 |
help="Select the start date for the analysis.")
|
| 237 |
-
|
| 238 |
end_date = st.date_input('End Date', pd.to_datetime(pd.Timestamp.now().date() + pd.Timedelta(days=1)),
|
| 239 |
help="Select the end date for the analysis.")
|
| 240 |
|
|
@@ -246,12 +247,10 @@ with st.sidebar.expander("Optimization Method", expanded=True):
|
|
| 246 |
if selected == "Multi-Objective Optimization":
|
| 247 |
st.markdown("""
|
| 248 |
### Multi-Objective Optimization
|
| 249 |
-
|
| 250 |
Multi-Objective Optimization in portfolio management allows investors to consider multiple objectives simultaneously.
|
| 251 |
This method aims to find the best portfolio by balancing various goals such as maximizing returns, minimizing risk, maximizing the Sharpe ratio, enhancing diversification, and more.
|
| 252 |
""")
|
| 253 |
|
| 254 |
-
# Expander for Methodology and Formulas
|
| 255 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 256 |
st.markdown("""
|
| 257 |
#### Formulas:
|
|
@@ -338,42 +337,47 @@ if selected == "Multi-Objective Optimization":
|
|
| 338 |
maximize_dividend_yield = st.sidebar.checkbox('Maximize Dividend Yield', value=True)
|
| 339 |
|
| 340 |
if st.sidebar.button('Run Analysis'):
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
dividend_yield
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
| 365 |
|
| 366 |
if 'multi_objective_result' in st.session_state:
|
| 367 |
cleaned_weights = st.session_state.multi_objective_result['cleaned_weights']
|
| 368 |
returns = st.session_state.multi_objective_result['returns']
|
| 369 |
optimal_weights = st.session_state.multi_objective_result['optimal_weights']
|
| 370 |
-
|
| 371 |
fig_weights = plot_portfolio_weights(list(cleaned_weights.values()), list(cleaned_weights.keys()), 'Multi-Objective Optimization Portfolio Weights')
|
| 372 |
st.plotly_chart(fig_weights)
|
| 373 |
|
| 374 |
portfolio_returns = returns.dot(optimal_weights)
|
| 375 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 376 |
-
|
|
|
|
|
|
|
| 377 |
equal_weighted_returns = returns.mean(axis=1)
|
| 378 |
|
| 379 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -389,23 +393,17 @@ if selected == "Multi-Objective Optimization":
|
|
| 389 |
elif selected == "Robust Optimization":
|
| 390 |
st.markdown("""
|
| 391 |
### Robust Optimization
|
| 392 |
-
|
| 393 |
Robust Optimization aims to create more stable portfolios by incorporating regularization techniques.
|
| 394 |
This method adjusts the covariance matrix to reduce the impact of estimation errors, noisy or uncertain data.
|
| 395 |
""")
|
| 396 |
|
| 397 |
-
# Expander for Detailed Methodology and Formulas
|
| 398 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 399 |
st.markdown("""
|
| 400 |
#### Concept:
|
| 401 |
-
|
| 402 |
The covariance matrix can be unstable due to limited data or market volatility.
|
| 403 |
Robust Optimization addresses this by applying techniques such as covariance shrinkage to produce a more stable covariance matrix.
|
| 404 |
-
|
| 405 |
#### Regularization Technique:
|
| 406 |
-
|
| 407 |
One common approach in Robust Optimization is the Ledoit-Wolf shrinkage method, which adjusts the sample covariance matrix towards a more structured target, such as the identity matrix.
|
| 408 |
-
|
| 409 |
**Covariance Shrinkage**:
|
| 410 |
""")
|
| 411 |
st.latex(r"""
|
|
@@ -418,16 +416,11 @@ elif selected == "Robust Optimization":
|
|
| 418 |
- \( λ \) is the shrinkage intensity (a value between 0 and 1).
|
| 419 |
- \( T \) is the target covariance matrix (e.g., identity matrix).
|
| 420 |
- \( S \) is the sample covariance matrix.
|
| 421 |
-
|
| 422 |
#### Shrinkage Intensity:
|
| 423 |
-
|
| 424 |
The shrinkage intensity \( λ \) determines the balance between the sample covariance matrix and the target.
|
| 425 |
A higher \( λ \) places more weight on the target matrix, while a lower \( λ \) places more weight on the sample covariance matrix.
|
| 426 |
-
|
| 427 |
#### Mathematical Optimization Process:
|
| 428 |
-
|
| 429 |
The optimization problem can be expressed as:
|
| 430 |
-
|
| 431 |
**Objective Function**:
|
| 432 |
""")
|
| 433 |
st.latex(r"""
|
|
@@ -462,22 +455,25 @@ elif selected == "Robust Optimization":
|
|
| 462 |
gamma = st.sidebar.slider('L2 Regularization (Gamma)', min_value=0.0, max_value=1.0, value=0.1, step=0.01)
|
| 463 |
|
| 464 |
if st.sidebar.button('Run Analysis'):
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
|
|
|
|
|
|
|
|
|
| 481 |
|
| 482 |
if 'robust_result' in st.session_state:
|
| 483 |
cleaned_weights_robust = st.session_state.robust_result['cleaned_weights']
|
|
@@ -488,8 +484,10 @@ elif selected == "Robust Optimization":
|
|
| 488 |
st.plotly_chart(fig_weights)
|
| 489 |
|
| 490 |
portfolio_returns_robust = returns.dot(np.array(list(cleaned_weights_robust.values())))
|
| 491 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 492 |
-
|
|
|
|
|
|
|
| 493 |
equal_weighted_returns = returns.mean(axis=1)
|
| 494 |
|
| 495 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_robust, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -505,20 +503,15 @@ elif selected == "Robust Optimization":
|
|
| 505 |
elif selected == "Mean-Variance Optimization":
|
| 506 |
st.markdown("""
|
| 507 |
### Mean-Variance Optimization
|
| 508 |
-
|
| 509 |
Mean-Variance Optimization, introduced by Harry Markowitz aims to balance return and risk by maximizing the Sharpe ratio, thereby finding the portfolio with the best risk-adjusted returns.
|
| 510 |
""")
|
| 511 |
|
| 512 |
-
# Expander for Detailed Methodology and Formulas
|
| 513 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 514 |
st.markdown("""
|
| 515 |
#### Concept:
|
| 516 |
-
|
| 517 |
The Mean-Variance Optimization approach is based on the idea of creating a portfolio that provides the maximum expected return for a given level of risk or, equivalently, the minimum risk for a given level of expected return.
|
| 518 |
This is achieved by selecting the proportions of various assets in the portfolio.
|
| 519 |
-
|
| 520 |
#### Sharpe Ratio:
|
| 521 |
-
|
| 522 |
The Sharpe ratio is a measure of the risk-adjusted return of a portfolio. It is calculated as:
|
| 523 |
""")
|
| 524 |
st.latex(r"""
|
|
@@ -530,11 +523,8 @@ elif selected == "Mean-Variance Optimization":
|
|
| 530 |
- \( E[Rp] \) is the expected return of the portfolio.
|
| 531 |
- \( Rf \) is the risk-free rate.
|
| 532 |
- \( σp \) is the standard deviation of the portfolio returns.
|
| 533 |
-
|
| 534 |
#### Mathematical Optimization Process:
|
| 535 |
-
|
| 536 |
The optimization problem can be formulated as follows:
|
| 537 |
-
|
| 538 |
**Objective Function**:
|
| 539 |
""")
|
| 540 |
st.latex(r"""
|
|
@@ -546,7 +536,6 @@ elif selected == "Mean-Variance Optimization":
|
|
| 546 |
- \( w \) is the vector of portfolio weights.
|
| 547 |
- \( μ \) is the vector of expected asset returns.
|
| 548 |
- \( ∑ \) is the covariance matrix of asset returns.
|
| 549 |
-
|
| 550 |
**Constraints**:
|
| 551 |
1. The sum of the portfolio weights must equal 1 (fully invested portfolio):
|
| 552 |
""")
|
|
@@ -573,23 +562,26 @@ elif selected == "Mean-Variance Optimization":
|
|
| 573 |
st.sidebar.header("Optimization Parameters")
|
| 574 |
|
| 575 |
if st.sidebar.button('Run Analysis'):
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
if 'mean_variance_result' in st.session_state:
|
| 595 |
cleaned_weights = st.session_state.mean_variance_result['cleaned_weights']
|
|
@@ -602,8 +594,10 @@ elif selected == "Mean-Variance Optimization":
|
|
| 602 |
st.plotly_chart(fig_weights)
|
| 603 |
|
| 604 |
portfolio_returns = returns.dot(optimal_weights)
|
| 605 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 606 |
-
|
|
|
|
|
|
|
| 607 |
equal_weighted_returns = returns.mean(axis=1)
|
| 608 |
|
| 609 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -622,19 +616,14 @@ elif selected == "Mean-Variance Optimization":
|
|
| 622 |
elif selected == "Black-Litterman Model":
|
| 623 |
st.markdown("""
|
| 624 |
### Black-Litterman Model
|
| 625 |
-
|
| 626 |
The Black-Litterman Model combines market equilibrium with investor views to adjust the expected returns and then applies mean-variance optimization. This approach is particularly useful for incorporating subjective views into a theoretically sound framework.
|
| 627 |
""")
|
| 628 |
|
| 629 |
-
# Expander for Detailed Methodology and Formulas
|
| 630 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 631 |
st.markdown("""
|
| 632 |
#### Concept:
|
| 633 |
-
|
| 634 |
The Black-Litterman Model starts with the market equilibrium returns, which are implied by market capitalizations and a given risk aversion coefficient. Investors can then specify their own views on expected returns for certain assets or combinations of assets.
|
| 635 |
-
|
| 636 |
#### Market Equilibrium Returns:
|
| 637 |
-
|
| 638 |
The market equilibrium returns, \( \Pi \), are given by:
|
| 639 |
""")
|
| 640 |
st.latex(r"""
|
|
@@ -646,9 +635,7 @@ elif selected == "Black-Litterman Model":
|
|
| 646 |
- \( δ \) is the risk aversion coefficient.
|
| 647 |
- \( Σ \) is the covariance matrix of asset returns.
|
| 648 |
- \( wmkt \) is the vector of market capitalization weights.
|
| 649 |
-
|
| 650 |
#### Investor Views:
|
| 651 |
-
|
| 652 |
Investor views are expressed in the form of a matrix \( P \) and a vector \( Q \):
|
| 653 |
""")
|
| 654 |
st.latex(r"""
|
|
@@ -660,9 +647,7 @@ elif selected == "Black-Litterman Model":
|
|
| 660 |
- \( P \) is the matrix that identifies the assets involved in each view.
|
| 661 |
- \( μ \) is the vector of expected returns.
|
| 662 |
- \( Q \) is the vector of view returns.
|
| 663 |
-
|
| 664 |
#### Adjusted Expected Returns:
|
| 665 |
-
|
| 666 |
The adjusted expected returns, \( μ \), are then calculated as:
|
| 667 |
""")
|
| 668 |
st.latex(r"""
|
|
@@ -673,11 +658,8 @@ elif selected == "Black-Litterman Model":
|
|
| 673 |
Where:
|
| 674 |
- \( τ \) is a scalar representing the uncertainty in the prior estimates.
|
| 675 |
- \( Ω \) is the diagonal covariance matrix of the error terms in the views.
|
| 676 |
-
|
| 677 |
#### Optimization:
|
| 678 |
-
|
| 679 |
Once the adjusted expected returns, \( \mu \), are obtained, we can apply mean-variance optimization to find the optimal portfolio weights.
|
| 680 |
-
|
| 681 |
**Objective Function**:
|
| 682 |
""")
|
| 683 |
st.latex(r"""
|
|
@@ -712,47 +694,46 @@ elif selected == "Black-Litterman Model":
|
|
| 712 |
st.sidebar.header("Optimization Parameters")
|
| 713 |
|
| 714 |
if st.sidebar.button('Run Analysis'):
|
| 715 |
-
|
| 716 |
-
|
|
|
|
| 717 |
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
|
| 723 |
-
|
| 724 |
-
|
|
|
|
|
|
|
| 725 |
|
| 726 |
-
|
| 727 |
-
delta = black_litterman.market_implied_risk_aversion(market_data)
|
| 728 |
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
market_caps[ticker] = stock.info['marketCap']
|
| 734 |
|
| 735 |
-
|
| 736 |
|
| 737 |
-
|
| 738 |
-
prior = black_litterman.market_implied_prior_returns(market_caps_series, delta, cov_matrix)
|
| 739 |
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
Q = np.zeros(len(tickers))
|
| 743 |
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
bl_return = bl.bl_returns()
|
| 747 |
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
cleaned_weights_bl = ef.clean_weights()
|
| 752 |
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
|
|
|
|
|
|
| 756 |
|
| 757 |
if 'black_litterman_result' in st.session_state:
|
| 758 |
cleaned_weights_bl = st.session_state.black_litterman_result['cleaned_weights']
|
|
@@ -763,8 +744,10 @@ elif selected == "Black-Litterman Model":
|
|
| 763 |
st.plotly_chart(fig_weights)
|
| 764 |
|
| 765 |
portfolio_returns_bl = returns.dot(optimal_weights_bl)
|
| 766 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 767 |
-
|
|
|
|
|
|
|
| 768 |
equal_weighted_returns = returns.mean(axis=1)
|
| 769 |
|
| 770 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_bl, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -780,29 +763,21 @@ elif selected == "Black-Litterman Model":
|
|
| 780 |
elif selected == "Hierarchical Risk Parity":
|
| 781 |
st.markdown("""
|
| 782 |
### Hierarchical Risk Parity (HRP)
|
| 783 |
-
|
| 784 |
Hierarchical Risk Parity (HRP) is a method that groups assets into clusters based on their correlations and then allocates risk evenly among these clusters.
|
| 785 |
This approach aims to improve diversification and reduce risk concentration in the portfolio.
|
| 786 |
""")
|
| 787 |
|
| 788 |
-
# Expander for Detailed Methodology and Formulas
|
| 789 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 790 |
st.markdown("""
|
| 791 |
#### Concept:
|
| 792 |
-
|
| 793 |
HRP involves the following key steps:
|
| 794 |
-
|
| 795 |
1. **Tree Clustering**:
|
| 796 |
Assets are grouped into clusters using hierarchical clustering methods. This step forms a tree structure that helps identify similar assets based on their correlations.
|
| 797 |
-
|
| 798 |
2. **Quasi-Diagonalization**:
|
| 799 |
The covariance matrix is rearranged into a block-diagonal form. This reordering ensures that the most correlated assets are placed next to each other, facilitating more effective risk allocation.
|
| 800 |
-
|
| 801 |
3. **Recursive Bisection**:
|
| 802 |
Risk is allocated recursively from the top of the tree down to the individual assets. At each level, risk is split evenly between the clusters, ensuring that each cluster receives an equal share of the portfolio risk.
|
| 803 |
-
|
| 804 |
#### Hierarchical Clustering:
|
| 805 |
-
|
| 806 |
Hierarchical clustering is performed using the correlation matrix of asset returns. The distance between assets \( i \) and \( j \) is given by:
|
| 807 |
""")
|
| 808 |
st.latex(r"""
|
|
@@ -812,15 +787,10 @@ elif selected == "Hierarchical Risk Parity":
|
|
| 812 |
st.markdown("""
|
| 813 |
Where:
|
| 814 |
- \( ρ_{i,j} \) is the correlation coefficient between assets \( i \) and \( j \).
|
| 815 |
-
|
| 816 |
#### Quasi-Diagonalization:
|
| 817 |
-
|
| 818 |
The covariance matrix \( \Sigma \) is reordered to a block-diagonal form using the clustering information. This step ensures that the assets with higher correlations are grouped together.
|
| 819 |
-
|
| 820 |
#### Recursive Bisection:
|
| 821 |
-
|
| 822 |
Risk is allocated recursively using the following steps:
|
| 823 |
-
|
| 824 |
1. **Top-Level Allocation**:
|
| 825 |
The portfolio risk is split equally between the top-level clusters.
|
| 826 |
""")
|
|
@@ -831,7 +801,6 @@ elif selected == "Hierarchical Risk Parity":
|
|
| 831 |
st.markdown("""
|
| 832 |
2. **Sub-Level Allocation**:
|
| 833 |
The risk within each cluster is further split recursively until the individual assets are reached.
|
| 834 |
-
|
| 835 |
This recursive process ensures that risk is allocated evenly across all clusters and individual assets.
|
| 836 |
""")
|
| 837 |
|
|
@@ -847,22 +816,25 @@ elif selected == "Hierarchical Risk Parity":
|
|
| 847 |
st.sidebar.header("Optimization Parameters")
|
| 848 |
|
| 849 |
if st.sidebar.button('Run Analysis'):
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
|
|
|
|
|
|
|
|
|
| 866 |
|
| 867 |
if 'hrp_result' in st.session_state:
|
| 868 |
cleaned_weights_hrp = st.session_state.hrp_result['cleaned_weights']
|
|
@@ -874,8 +846,10 @@ elif selected == "Hierarchical Risk Parity":
|
|
| 874 |
st.plotly_chart(fig_weights)
|
| 875 |
|
| 876 |
portfolio_returns_hrp = returns.dot(optimal_weights_hrp)
|
| 877 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 878 |
-
|
|
|
|
|
|
|
| 879 |
equal_weighted_returns = returns.mean(axis=1)
|
| 880 |
|
| 881 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_hrp, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -891,18 +865,15 @@ elif selected == "Hierarchical Risk Parity":
|
|
| 891 |
st.write("### Dendrogram of Asset Clusters")
|
| 892 |
plot_dendrogram(hrp, tickers, 'Dendrogram of Asset Clusters')
|
| 893 |
|
| 894 |
-
elif selected == "Maximum Diversification
|
| 895 |
st.markdown("""
|
| 896 |
### Maximum Diversification Portfolio
|
| 897 |
-
|
| 898 |
The Maximum Diversification Portfolio method aims to create a portfolio that maximizes the diversification ratio. This approach allocates weights to assets to maximize the ratio of the weighted average volatility of individual assets to the overall portfolio volatility.
|
| 899 |
""")
|
| 900 |
|
| 901 |
-
# Expander for Detailed Methodology and Formulas
|
| 902 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 903 |
st.markdown("""
|
| 904 |
#### Concept:
|
| 905 |
-
|
| 906 |
The diversification ratio (DR) is defined as:
|
| 907 |
""")
|
| 908 |
st.latex(r"""
|
|
@@ -914,13 +885,9 @@ elif selected == "Maximum Diversification Portfolio":
|
|
| 914 |
- \( \sigma_i \) is the volatility of asset \( i \).
|
| 915 |
- \( \Sigma \) is the covariance matrix of asset returns.
|
| 916 |
- \( w \) is the weight vector of the portfolio.
|
| 917 |
-
|
| 918 |
#### Objective:
|
| 919 |
-
|
| 920 |
The objective of the Maximum Diversification Portfolio is to maximize this diversification ratio. By doing so, the portfolio aims to achieve the highest possible diversification benefit, reducing the overall portfolio risk.
|
| 921 |
-
|
| 922 |
#### Mathematical Formulation:
|
| 923 |
-
|
| 924 |
The optimization problem can be formulated as:
|
| 925 |
""")
|
| 926 |
st.latex(r"""
|
|
@@ -930,9 +897,7 @@ elif selected == "Maximum Diversification Portfolio":
|
|
| 930 |
|
| 931 |
st.markdown("""
|
| 932 |
This ensures that the sum of the weights is equal to 1 (fully invested portfolio) and that all weights are non-negative (long-only portfolio).
|
| 933 |
-
|
| 934 |
#### Steps Involved:
|
| 935 |
-
|
| 936 |
1. **Calculate Individual Volatilities**:
|
| 937 |
Compute the volatility (\( \sigma_i \)) for each asset in the portfolio.
|
| 938 |
|
|
@@ -953,21 +918,24 @@ elif selected == "Maximum Diversification Portfolio":
|
|
| 953 |
st.sidebar.header("Optimization Parameters")
|
| 954 |
|
| 955 |
if st.sidebar.button('Run Analysis'):
|
| 956 |
-
|
| 957 |
-
|
|
|
|
| 958 |
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
|
| 965 |
-
|
| 966 |
-
|
| 967 |
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
|
|
|
|
|
|
| 971 |
|
| 972 |
if 'mdp_result' in st.session_state:
|
| 973 |
cleaned_weights_mdp = st.session_state.mdp_result['cleaned_weights']
|
|
@@ -978,8 +946,10 @@ elif selected == "Maximum Diversification Portfolio":
|
|
| 978 |
st.plotly_chart(fig_weights)
|
| 979 |
|
| 980 |
portfolio_returns_mdp = returns.dot(optimal_weights_mdp)
|
| 981 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 982 |
-
|
|
|
|
|
|
|
| 983 |
equal_weighted_returns = returns.mean(axis=1)
|
| 984 |
|
| 985 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_mdp, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -992,18 +962,15 @@ elif selected == "Maximum Diversification Portfolio":
|
|
| 992 |
fig_drawdown = plot_max_drawdown(portfolio_returns_mdp, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 993 |
st.plotly_chart(fig_drawdown)
|
| 994 |
|
| 995 |
-
elif selected == "Maximum Sharpe Ratio
|
| 996 |
st.markdown("""
|
| 997 |
### Maximum Sharpe Ratio Portfolio
|
| 998 |
-
|
| 999 |
The Maximum Sharpe Ratio Portfolio method aims to create a portfolio that maximizes the Sharpe ratio. The Sharpe ratio is the measure of the portfolio's excess return per unit of risk, providing a risk-adjusted return metric.
|
| 1000 |
""")
|
| 1001 |
|
| 1002 |
-
# Expander for Detailed Methodology and Formulas
|
| 1003 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1004 |
st.markdown("""
|
| 1005 |
#### Concept:
|
| 1006 |
-
|
| 1007 |
The Sharpe ratio (\( S \)) is defined as:
|
| 1008 |
""")
|
| 1009 |
st.latex(r"""
|
|
@@ -1014,13 +981,9 @@ elif selected == "Maximum Sharpe Ratio Portfolio":
|
|
| 1014 |
- \( R_p \) is the expected portfolio return.
|
| 1015 |
- \( R_f \) is the risk-free rate.
|
| 1016 |
- \( \sigma_p \) is the portfolio's standard deviation (volatility).
|
| 1017 |
-
|
| 1018 |
#### Objective:
|
| 1019 |
-
|
| 1020 |
The objective of the Maximum Sharpe Ratio Portfolio is to find the portfolio weights that maximize the Sharpe ratio. This ensures the highest possible return for a given level of risk.
|
| 1021 |
-
|
| 1022 |
#### Mathematical Formulation:
|
| 1023 |
-
|
| 1024 |
The optimization problem can be formulated as:
|
| 1025 |
""")
|
| 1026 |
st.latex(r"""
|
|
@@ -1033,9 +996,7 @@ elif selected == "Maximum Sharpe Ratio Portfolio":
|
|
| 1033 |
- \( w \) is the weight vector of the portfolio.
|
| 1034 |
- \( \mu \) is the vector of expected returns for the assets.
|
| 1035 |
- \( \Sigma \) is the covariance matrix of asset returns.
|
| 1036 |
-
|
| 1037 |
#### Steps Involved:
|
| 1038 |
-
|
| 1039 |
1. **Estimate Expected Returns**:
|
| 1040 |
Compute the expected returns (\( \mu \)) for each asset in the portfolio.
|
| 1041 |
|
|
@@ -1046,30 +1007,33 @@ elif selected == "Maximum Sharpe Ratio Portfolio":
|
|
| 1046 |
Use optimization techniques to find the weight vector (\( w \)) that maximizes the Sharpe ratio, subject to the constraints.
|
| 1047 |
""")
|
| 1048 |
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
|
| 1056 |
st.sidebar.header("Optimization Parameters")
|
| 1057 |
|
| 1058 |
if st.sidebar.button('Run Analysis'):
|
| 1059 |
-
|
| 1060 |
-
|
|
|
|
| 1061 |
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
|
|
|
|
|
|
|
| 1073 |
|
| 1074 |
if 'msr_result' in st.session_state:
|
| 1075 |
cleaned_weights_msr = st.session_state.msr_result['cleaned_weights']
|
|
@@ -1080,8 +1044,10 @@ elif selected == "Maximum Sharpe Ratio Portfolio":
|
|
| 1080 |
st.plotly_chart(fig_weights)
|
| 1081 |
|
| 1082 |
portfolio_returns_msr = returns.dot(np.array(list(optimal_weights_msr.values())))
|
| 1083 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 1084 |
-
|
|
|
|
|
|
|
| 1085 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1086 |
|
| 1087 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_msr, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -1094,22 +1060,17 @@ elif selected == "Maximum Sharpe Ratio Portfolio":
|
|
| 1094 |
fig_drawdown = plot_max_drawdown(portfolio_returns_msr, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1095 |
st.plotly_chart(fig_drawdown)
|
| 1096 |
|
| 1097 |
-
elif selected == "Equal Risk Contribution
|
| 1098 |
st.markdown("""
|
| 1099 |
### Equal Risk Contribution Portfolio
|
| 1100 |
-
|
| 1101 |
The Equal Risk Contribution (ERC) Portfolio method aims to allocate risk equally among all assets in the portfolio. This approach ensures that each asset contributes the same amount of risk, leading to a well-balanced portfolio.
|
| 1102 |
""")
|
| 1103 |
|
| 1104 |
-
# Expander for Detailed Methodology and Formulas
|
| 1105 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1106 |
st.markdown("""
|
| 1107 |
#### Concept:
|
| 1108 |
-
|
| 1109 |
The key idea is to balance the contribution of each asset to the total portfolio risk, such that the risk contribution from each asset is equal.
|
| 1110 |
-
|
| 1111 |
#### Objective:
|
| 1112 |
-
|
| 1113 |
The objective of the ERC Portfolio is to find the weights of the assets that equalize their risk contributions. The risk contribution of an asset \( i \) to the total portfolio risk is given by:
|
| 1114 |
""")
|
| 1115 |
st.latex(r"""
|
|
@@ -1120,9 +1081,7 @@ elif selected == "Equal Risk Contribution Portfolio":
|
|
| 1120 |
- \( RC_i \) is the risk contribution of asset \( i \).
|
| 1121 |
- \( w_i \) is the weight of asset \( i \).
|
| 1122 |
- \( \sigma_p \) is the portfolio's standard deviation (volatility).
|
| 1123 |
-
|
| 1124 |
#### Mathematical Formulation:
|
| 1125 |
-
|
| 1126 |
The optimization problem can be formulated as:
|
| 1127 |
""")
|
| 1128 |
st.latex(r"""
|
|
@@ -1133,15 +1092,11 @@ elif selected == "Equal Risk Contribution Portfolio":
|
|
| 1133 |
Where:
|
| 1134 |
- \( n \) is the number of assets.
|
| 1135 |
- The goal is to minimize the sum of squared deviations of each asset's risk contribution from the average risk contribution \( \frac{\sigma_p}{n} \).
|
| 1136 |
-
|
| 1137 |
#### Steps Involved:
|
| 1138 |
-
|
| 1139 |
1. **Estimate Expected Returns and Covariance Matrix**:
|
| 1140 |
Compute the expected returns (\( \mu \)) and the covariance matrix (\( \Sigma \)) for the assets.
|
| 1141 |
-
|
| 1142 |
2. **Calculate Marginal Risk Contributions**:
|
| 1143 |
Determine the partial derivatives of the portfolio volatility with respect to each asset's weight.
|
| 1144 |
-
|
| 1145 |
3. **Optimize the Risk Contributions**:
|
| 1146 |
Use optimization techniques to find the weight vector (\( w \)) that equalizes the risk contributions, subject to the constraints.
|
| 1147 |
""")
|
|
@@ -1157,20 +1112,23 @@ elif selected == "Equal Risk Contribution Portfolio":
|
|
| 1157 |
st.sidebar.header("Optimization Parameters")
|
| 1158 |
|
| 1159 |
if st.sidebar.button('Run Analysis'):
|
| 1160 |
-
|
| 1161 |
-
|
|
|
|
| 1162 |
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
|
| 1166 |
-
|
| 1167 |
|
| 1168 |
-
|
| 1169 |
-
|
| 1170 |
|
| 1171 |
-
|
| 1172 |
-
|
| 1173 |
-
|
|
|
|
|
|
|
| 1174 |
|
| 1175 |
if 'erc_result' in st.session_state:
|
| 1176 |
cleaned_weights_erc = st.session_state.erc_result['cleaned_weights']
|
|
@@ -1181,8 +1139,10 @@ elif selected == "Equal Risk Contribution Portfolio":
|
|
| 1181 |
st.plotly_chart(fig_weights)
|
| 1182 |
|
| 1183 |
portfolio_returns_erc = returns.dot(np.array(list(optimal_weights_erc.values())))
|
| 1184 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 1185 |
-
|
|
|
|
|
|
|
| 1186 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1187 |
|
| 1188 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_erc, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -1195,26 +1155,19 @@ elif selected == "Equal Risk Contribution Portfolio":
|
|
| 1195 |
fig_drawdown = plot_max_drawdown(portfolio_returns_erc, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1196 |
st.plotly_chart(fig_drawdown)
|
| 1197 |
|
| 1198 |
-
elif selected == "CVaR Minimization
|
| 1199 |
st.markdown("""
|
| 1200 |
### CVaR Minimization Portfolio
|
| 1201 |
-
|
| 1202 |
The CVaR Minimization Portfolio method focuses on minimizing Conditional Value at Risk (CVaR), which measures the expected loss of the portfolio in the worst-case scenarios. This method is particularly useful for investors who want to limit their downside risk.
|
| 1203 |
""")
|
| 1204 |
|
| 1205 |
-
# Expander for Detailed Methodology and Formulas
|
| 1206 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1207 |
st.markdown("""
|
| 1208 |
#### Concept:
|
| 1209 |
-
|
| 1210 |
Conditional Value at Risk (CVaR) is a risk assessment measure that quantifies the expected loss in the worst-case scenarios beyond a certain confidence level. It provides a more comprehensive risk measure compared to Value at Risk (VaR).
|
| 1211 |
-
|
| 1212 |
#### Objective:
|
| 1213 |
-
|
| 1214 |
The objective of the CVaR Minimization Portfolio is to find the weights of the assets that minimize the CVaR at a given confidence level.
|
| 1215 |
-
|
| 1216 |
#### Mathematical Formulation:
|
| 1217 |
-
|
| 1218 |
The optimization problem can be formulated as:
|
| 1219 |
""")
|
| 1220 |
st.latex(r"""
|
|
@@ -1228,46 +1181,42 @@ elif selected == "CVaR Minimization Portfolio":
|
|
| 1228 |
- \( \alpha \) is the confidence level (e.g., 95%).
|
| 1229 |
- \( T \) is the number of observations.
|
| 1230 |
- \( L_t(w) \) is the loss of the portfolio at time \( t \).
|
| 1231 |
-
|
| 1232 |
#### Steps Involved:
|
| 1233 |
-
|
| 1234 |
1. **Estimate Expected Returns and Covariance Matrix**:
|
| 1235 |
-
Compute the expected returns (\( \mu \)) and the covariance matrix (\
|
| 1236 |
-
|
| 1237 |
2. **Calculate Portfolio Losses**:
|
| 1238 |
Determine the losses of the portfolio for each observation period.
|
| 1239 |
-
|
| 1240 |
3. **Optimize CVaR**:
|
| 1241 |
Use optimization techniques to find the weight vector (\( w \)) that minimizes the CVaR, subject to the constraints.
|
| 1242 |
""")
|
| 1243 |
|
| 1244 |
-
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
|
| 1249 |
-
|
| 1250 |
-
|
| 1251 |
-
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
|
| 1255 |
st.sidebar.header("Optimization Parameters")
|
| 1256 |
|
| 1257 |
if st.sidebar.button('Run Analysis'):
|
| 1258 |
-
|
| 1259 |
-
|
|
|
|
| 1260 |
|
| 1261 |
-
|
| 1262 |
-
|
| 1263 |
-
|
| 1264 |
|
| 1265 |
-
|
| 1266 |
-
|
| 1267 |
|
| 1268 |
-
|
| 1269 |
-
|
| 1270 |
-
|
|
|
|
|
|
|
| 1271 |
|
| 1272 |
if 'cvar_result' in st.session_state:
|
| 1273 |
cleaned_weights_cvar = st.session_state.cvar_result['cleaned_weights']
|
|
@@ -1278,8 +1227,10 @@ elif selected == "CVaR Minimization Portfolio":
|
|
| 1278 |
st.plotly_chart(fig_weights)
|
| 1279 |
|
| 1280 |
portfolio_returns_cvar = returns.dot(np.array(list(optimal_weights_cvar.values())))
|
| 1281 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 1282 |
-
|
|
|
|
|
|
|
| 1283 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1284 |
|
| 1285 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_cvar, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -1292,27 +1243,20 @@ elif selected == "CVaR Minimization Portfolio":
|
|
| 1292 |
fig_drawdown = plot_max_drawdown(portfolio_returns_cvar, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1293 |
st.plotly_chart(fig_drawdown)
|
| 1294 |
|
| 1295 |
-
elif selected == "Maximum Return
|
| 1296 |
|
| 1297 |
st.markdown("""
|
| 1298 |
### Maximum Return Portfolio
|
| 1299 |
-
|
| 1300 |
The Maximum Return Portfolio method focuses solely on maximizing the expected return of the portfolio, without considering risk. This method allocates the highest weights to the assets with the highest expected returns.
|
| 1301 |
""")
|
| 1302 |
|
| 1303 |
-
# Expander for Detailed Methodology and Formulas
|
| 1304 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1305 |
st.markdown("""
|
| 1306 |
#### Concept:
|
| 1307 |
-
|
| 1308 |
The Maximum Return Portfolio aims to achieve the highest possible return by investing in assets that have the highest expected returns. This approach does not take into account the risk or volatility associated with the assets.
|
| 1309 |
-
|
| 1310 |
#### Objective:
|
| 1311 |
-
|
| 1312 |
The objective of the Maximum Return Portfolio is to find the weights of the assets that maximize the expected return.
|
| 1313 |
-
|
| 1314 |
#### Mathematical Formulation:
|
| 1315 |
-
|
| 1316 |
The optimization problem can be formulated as:
|
| 1317 |
""")
|
| 1318 |
st.latex(r"""
|
|
@@ -1324,12 +1268,9 @@ elif selected == "Maximum Return Portfolio":
|
|
| 1324 |
- \( w \) is the weight vector of the assets.
|
| 1325 |
- \( \mu \) is the expected return vector of the assets.
|
| 1326 |
- \( n \) is the number of assets.
|
| 1327 |
-
|
| 1328 |
#### Steps Involved:
|
| 1329 |
-
|
| 1330 |
1. **Estimate Expected Returns**:
|
| 1331 |
Compute the expected returns (\( \mu \)) for the assets.
|
| 1332 |
-
|
| 1333 |
2. **Optimize Expected Return**:
|
| 1334 |
Use optimization techniques to find the weight vector (\( w \)) that maximizes the expected return, subject to the constraints.
|
| 1335 |
""")
|
|
@@ -1350,20 +1291,23 @@ elif selected == "Maximum Return Portfolio":
|
|
| 1350 |
st.sidebar.header("Optimization Parameters")
|
| 1351 |
|
| 1352 |
if st.sidebar.button('Run Analysis'):
|
| 1353 |
-
|
| 1354 |
-
|
|
|
|
| 1355 |
|
| 1356 |
-
|
| 1357 |
-
|
| 1358 |
-
|
| 1359 |
-
|
| 1360 |
|
| 1361 |
-
|
| 1362 |
-
|
| 1363 |
|
| 1364 |
-
|
| 1365 |
-
|
| 1366 |
-
|
|
|
|
|
|
|
| 1367 |
|
| 1368 |
if 'max_return_result' in st.session_state:
|
| 1369 |
cleaned_weights_max_return = st.session_state.max_return_result['cleaned_weights']
|
|
@@ -1374,8 +1318,10 @@ elif selected == "Maximum Return Portfolio":
|
|
| 1374 |
st.plotly_chart(fig_weights)
|
| 1375 |
|
| 1376 |
portfolio_returns_max_return = returns.dot(np.array(list(optimal_weights_max_return.values())))
|
| 1377 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 1378 |
-
|
|
|
|
|
|
|
| 1379 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1380 |
|
| 1381 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_max_return, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -1388,22 +1334,17 @@ elif selected == "Maximum Return Portfolio":
|
|
| 1388 |
fig_drawdown = plot_max_drawdown(portfolio_returns_max_return, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1389 |
st.plotly_chart(fig_drawdown)
|
| 1390 |
|
| 1391 |
-
elif selected == "Maximum Quadratic Utility
|
| 1392 |
st.markdown("""
|
| 1393 |
### Maximum Quadratic Utility Portfolio
|
| 1394 |
-
|
| 1395 |
The Maximum Quadratic Utility Portfolio method maximizes the quadratic utility function, which balances the trade-off between expected return and risk. It incorporates a risk aversion coefficient to adjust the level of risk tolerance.
|
| 1396 |
""")
|
| 1397 |
|
| 1398 |
-
# Expander for Detailed Methodology and Formulas
|
| 1399 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1400 |
st.markdown("""
|
| 1401 |
#### Concept:
|
| 1402 |
-
|
| 1403 |
The Maximum Quadratic Utility Portfolio aims to find the optimal portfolio that maximizes an investor's utility, which is a measure of satisfaction or preference. This approach takes into account both the expected return and the risk of the portfolio, weighted by a risk aversion coefficient.
|
| 1404 |
-
|
| 1405 |
#### Objective:
|
| 1406 |
-
|
| 1407 |
The objective of the Maximum Quadratic Utility Portfolio is to maximize the utility function, which is defined as:
|
| 1408 |
""")
|
| 1409 |
st.latex(r"""
|
|
@@ -1416,15 +1357,11 @@ elif selected == "Maximum Quadratic Utility Portfolio":
|
|
| 1416 |
- \( \mu \) is the expected return vector of the assets.
|
| 1417 |
- \( \Sigma \) is the covariance matrix of the asset returns.
|
| 1418 |
- \( \lambda \) is the risk aversion coefficient.
|
| 1419 |
-
|
| 1420 |
#### Steps Involved:
|
| 1421 |
-
|
| 1422 |
1. **Estimate Expected Returns and Covariance Matrix**:
|
| 1423 |
Compute the expected returns (\( \mu \)) and the covariance matrix (\( \Sigma \)) for the assets.
|
| 1424 |
-
|
| 1425 |
2. **Set Risk Aversion Coefficient**:
|
| 1426 |
Define the risk aversion coefficient (\( \lambda \)) based on the investor's risk tolerance.
|
| 1427 |
-
|
| 1428 |
3. **Optimize Utility Function**:
|
| 1429 |
Use optimization techniques to find the weight vector (\( w \)) that maximizes the utility function.
|
| 1430 |
""")
|
|
@@ -1446,20 +1383,23 @@ elif selected == "Maximum Quadratic Utility Portfolio":
|
|
| 1446 |
risk_aversion = st.sidebar.slider('Risk Aversion Coefficient', min_value=0.0, max_value=10.0, value=1.0, step=0.1)
|
| 1447 |
|
| 1448 |
if st.sidebar.button('Run Analysis'):
|
| 1449 |
-
|
| 1450 |
-
|
|
|
|
| 1451 |
|
| 1452 |
-
|
| 1453 |
-
|
| 1454 |
-
|
| 1455 |
-
|
| 1456 |
|
| 1457 |
-
|
| 1458 |
-
|
| 1459 |
|
| 1460 |
-
|
| 1461 |
-
|
| 1462 |
-
|
|
|
|
|
|
|
| 1463 |
|
| 1464 |
if 'mqu_result' in st.session_state:
|
| 1465 |
cleaned_weights_mqu = st.session_state.mqu_result['cleaned_weights']
|
|
@@ -1470,8 +1410,10 @@ elif selected == "Maximum Quadratic Utility Portfolio":
|
|
| 1470 |
st.plotly_chart(fig_weights)
|
| 1471 |
|
| 1472 |
portfolio_returns_mqu = returns.dot(np.array(list(optimal_weights_mqu.values())))
|
| 1473 |
-
sp500 = yf.download('^GSPC', start=start_date, end=end_date
|
| 1474 |
-
|
|
|
|
|
|
|
| 1475 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1476 |
|
| 1477 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_mqu, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
@@ -1484,8 +1426,6 @@ elif selected == "Maximum Quadratic Utility Portfolio":
|
|
| 1484 |
fig_drawdown = plot_max_drawdown(portfolio_returns_mqu, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1485 |
st.plotly_chart(fig_drawdown)
|
| 1486 |
|
| 1487 |
-
|
| 1488 |
-
|
| 1489 |
st.markdown(
|
| 1490 |
"""
|
| 1491 |
<style>
|
|
@@ -1498,13 +1438,10 @@ st.markdown(
|
|
| 1498 |
unsafe_allow_html=True
|
| 1499 |
)
|
| 1500 |
|
| 1501 |
-
|
| 1502 |
-
|
| 1503 |
hide_streamlit_style = """
|
| 1504 |
<style>
|
| 1505 |
#MainMenu {visibility: hidden;}
|
| 1506 |
footer {visibility: hidden;}
|
| 1507 |
</style>
|
| 1508 |
"""
|
| 1509 |
-
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
| 1510 |
-
|
|
|
|
| 9 |
from scipy.cluster.hierarchy import dendrogram
|
| 10 |
import matplotlib.pyplot as plt
|
| 11 |
|
|
|
|
| 12 |
# Helper functions
|
| 13 |
def fetch_stock_data(tickers, start_date, end_date):
|
| 14 |
+
data = yf.download(tickers, start=start_date, end=end_date, auto_adjust=False) # Unadjusted prices
|
| 15 |
+
if isinstance(data.columns, pd.MultiIndex): # Flatten multi-index
|
| 16 |
+
data.columns = data.columns.get_level_values(0)
|
| 17 |
+
if data.empty:
|
| 18 |
+
raise ValueError(f"No data found for tickers {tickers} from {start_date} to {end_date}")
|
| 19 |
+
if len(data) < 2:
|
| 20 |
+
raise ValueError(f"Insufficient data points for tickers {tickers}")
|
| 21 |
+
return data['Adj Close']
|
| 22 |
|
| 23 |
def plot_efficient_frontier(mean_returns, cov_matrix, title):
|
| 24 |
ef = EfficientFrontier(mean_returns, cov_matrix)
|
|
|
|
| 212 |
|
| 213 |
st.markdown("""
|
| 214 |
This tool allows you to optimize a portfolio of stocks using different optimization methods. You can choose between optimization methods simply by selecting the method, enterING the stock tickers, and setting the parameters. Click the "Run" button to see the results.
|
|
|
|
| 215 |
""")
|
| 216 |
|
| 217 |
with st.sidebar.expander("How to Use", expanded=False):
|
|
|
|
| 229 |
## Input Parameters:
|
| 230 |
""")
|
| 231 |
|
|
|
|
| 232 |
# Expander for Asset Symbols and Dates
|
| 233 |
with st.sidebar.expander("Asset Symbols and Dates", expanded=True):
|
| 234 |
tickers_input = st.text_input('Enter Stock Tickers (comma-separated)', 'AAPL, MSFT, GOOGL, AMZN, ASML, META, JPM, V',
|
| 235 |
help="Input stock tickers separated by commas. Example: 'AAPL, MSFT, GOOGL'")
|
|
|
|
| 236 |
tickers = [ticker.strip() for ticker in tickers_input.split(',')]
|
|
|
|
| 237 |
start_date = st.date_input('Start Date', pd.to_datetime('2015-01-01'),
|
| 238 |
help="Select the start date for the analysis.")
|
|
|
|
| 239 |
end_date = st.date_input('End Date', pd.to_datetime(pd.Timestamp.now().date() + pd.Timedelta(days=1)),
|
| 240 |
help="Select the end date for the analysis.")
|
| 241 |
|
|
|
|
| 247 |
if selected == "Multi-Objective Optimization":
|
| 248 |
st.markdown("""
|
| 249 |
### Multi-Objective Optimization
|
|
|
|
| 250 |
Multi-Objective Optimization in portfolio management allows investors to consider multiple objectives simultaneously.
|
| 251 |
This method aims to find the best portfolio by balancing various goals such as maximizing returns, minimizing risk, maximizing the Sharpe ratio, enhancing diversification, and more.
|
| 252 |
""")
|
| 253 |
|
|
|
|
| 254 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 255 |
st.markdown("""
|
| 256 |
#### Formulas:
|
|
|
|
| 337 |
maximize_dividend_yield = st.sidebar.checkbox('Maximize Dividend Yield', value=True)
|
| 338 |
|
| 339 |
if st.sidebar.button('Run Analysis'):
|
| 340 |
+
try:
|
| 341 |
+
if 'multi_objective_result' not in st.session_state:
|
| 342 |
+
st.session_state.multi_objective_result = {}
|
| 343 |
+
|
| 344 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 345 |
+
returns = data.pct_change().dropna()
|
| 346 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 347 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 348 |
+
|
| 349 |
+
dividend_yields = {}
|
| 350 |
+
for ticker in tickers:
|
| 351 |
+
stock = yf.Ticker(ticker)
|
| 352 |
+
info = stock.info
|
| 353 |
+
dividend_yield = info.get('dividendYield') or info.get('trailingAnnualDividendYield', 0)
|
| 354 |
+
if dividend_yield is None:
|
| 355 |
+
dividend_yield = 0
|
| 356 |
+
dividend_yields[ticker] = dividend_yield
|
| 357 |
+
|
| 358 |
+
dividend_yields = pd.Series(dividend_yields)
|
| 359 |
+
|
| 360 |
+
optimal_weights = optimize_portfolio(tickers, mean_returns, cov_matrix, dividend_yields, maximize_return, minimize_risk, maximize_sharpe, maximize_diversification, minimize_cvar, minimize_transaction_costs, maximize_dividend_yield)
|
| 361 |
+
cleaned_weights = dict(zip(tickers, optimal_weights))
|
| 362 |
+
st.session_state.multi_objective_result['cleaned_weights'] = cleaned_weights
|
| 363 |
+
st.session_state.multi_objective_result['returns'] = returns
|
| 364 |
+
st.session_state.multi_objective_result['optimal_weights'] = optimal_weights
|
| 365 |
+
except Exception as e:
|
| 366 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 367 |
|
| 368 |
if 'multi_objective_result' in st.session_state:
|
| 369 |
cleaned_weights = st.session_state.multi_objective_result['cleaned_weights']
|
| 370 |
returns = st.session_state.multi_objective_result['returns']
|
| 371 |
optimal_weights = st.session_state.multi_objective_result['optimal_weights']
|
| 372 |
+
|
| 373 |
fig_weights = plot_portfolio_weights(list(cleaned_weights.values()), list(cleaned_weights.keys()), 'Multi-Objective Optimization Portfolio Weights')
|
| 374 |
st.plotly_chart(fig_weights)
|
| 375 |
|
| 376 |
portfolio_returns = returns.dot(optimal_weights)
|
| 377 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 378 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 379 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 380 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 381 |
equal_weighted_returns = returns.mean(axis=1)
|
| 382 |
|
| 383 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 393 |
elif selected == "Robust Optimization":
|
| 394 |
st.markdown("""
|
| 395 |
### Robust Optimization
|
|
|
|
| 396 |
Robust Optimization aims to create more stable portfolios by incorporating regularization techniques.
|
| 397 |
This method adjusts the covariance matrix to reduce the impact of estimation errors, noisy or uncertain data.
|
| 398 |
""")
|
| 399 |
|
|
|
|
| 400 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 401 |
st.markdown("""
|
| 402 |
#### Concept:
|
|
|
|
| 403 |
The covariance matrix can be unstable due to limited data or market volatility.
|
| 404 |
Robust Optimization addresses this by applying techniques such as covariance shrinkage to produce a more stable covariance matrix.
|
|
|
|
| 405 |
#### Regularization Technique:
|
|
|
|
| 406 |
One common approach in Robust Optimization is the Ledoit-Wolf shrinkage method, which adjusts the sample covariance matrix towards a more structured target, such as the identity matrix.
|
|
|
|
| 407 |
**Covariance Shrinkage**:
|
| 408 |
""")
|
| 409 |
st.latex(r"""
|
|
|
|
| 416 |
- \( λ \) is the shrinkage intensity (a value between 0 and 1).
|
| 417 |
- \( T \) is the target covariance matrix (e.g., identity matrix).
|
| 418 |
- \( S \) is the sample covariance matrix.
|
|
|
|
| 419 |
#### Shrinkage Intensity:
|
|
|
|
| 420 |
The shrinkage intensity \( λ \) determines the balance between the sample covariance matrix and the target.
|
| 421 |
A higher \( λ \) places more weight on the target matrix, while a lower \( λ \) places more weight on the sample covariance matrix.
|
|
|
|
| 422 |
#### Mathematical Optimization Process:
|
|
|
|
| 423 |
The optimization problem can be expressed as:
|
|
|
|
| 424 |
**Objective Function**:
|
| 425 |
""")
|
| 426 |
st.latex(r"""
|
|
|
|
| 455 |
gamma = st.sidebar.slider('L2 Regularization (Gamma)', min_value=0.0, max_value=1.0, value=0.1, step=0.01)
|
| 456 |
|
| 457 |
if st.sidebar.button('Run Analysis'):
|
| 458 |
+
try:
|
| 459 |
+
if 'robust_result' not in st.session_state:
|
| 460 |
+
st.session_state.robust_result = {}
|
| 461 |
+
|
| 462 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 463 |
+
returns = data.pct_change().dropna()
|
| 464 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 465 |
+
cov_matrix_shrinked = CovarianceShrinkage(data).ledoit_wolf()
|
| 466 |
+
|
| 467 |
+
ef = EfficientFrontier(mean_returns, cov_matrix_shrinked)
|
| 468 |
+
ef.add_objective(objective_functions.L2_reg, gamma=gamma)
|
| 469 |
+
optimal_weights_robust = ef.max_sharpe()
|
| 470 |
+
cleaned_weights_robust = ef.clean_weights()
|
| 471 |
+
|
| 472 |
+
st.session_state.robust_result['cleaned_weights'] = cleaned_weights_robust
|
| 473 |
+
st.session_state.robust_result['returns'] = returns
|
| 474 |
+
st.session_state.robust_result['optimal_weights'] = optimal_weights_robust
|
| 475 |
+
except Exception as e:
|
| 476 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 477 |
|
| 478 |
if 'robust_result' in st.session_state:
|
| 479 |
cleaned_weights_robust = st.session_state.robust_result['cleaned_weights']
|
|
|
|
| 484 |
st.plotly_chart(fig_weights)
|
| 485 |
|
| 486 |
portfolio_returns_robust = returns.dot(np.array(list(cleaned_weights_robust.values())))
|
| 487 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 488 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 489 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 490 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 491 |
equal_weighted_returns = returns.mean(axis=1)
|
| 492 |
|
| 493 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_robust, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 503 |
elif selected == "Mean-Variance Optimization":
|
| 504 |
st.markdown("""
|
| 505 |
### Mean-Variance Optimization
|
|
|
|
| 506 |
Mean-Variance Optimization, introduced by Harry Markowitz aims to balance return and risk by maximizing the Sharpe ratio, thereby finding the portfolio with the best risk-adjusted returns.
|
| 507 |
""")
|
| 508 |
|
|
|
|
| 509 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 510 |
st.markdown("""
|
| 511 |
#### Concept:
|
|
|
|
| 512 |
The Mean-Variance Optimization approach is based on the idea of creating a portfolio that provides the maximum expected return for a given level of risk or, equivalently, the minimum risk for a given level of expected return.
|
| 513 |
This is achieved by selecting the proportions of various assets in the portfolio.
|
|
|
|
| 514 |
#### Sharpe Ratio:
|
|
|
|
| 515 |
The Sharpe ratio is a measure of the risk-adjusted return of a portfolio. It is calculated as:
|
| 516 |
""")
|
| 517 |
st.latex(r"""
|
|
|
|
| 523 |
- \( E[Rp] \) is the expected return of the portfolio.
|
| 524 |
- \( Rf \) is the risk-free rate.
|
| 525 |
- \( σp \) is the standard deviation of the portfolio returns.
|
|
|
|
| 526 |
#### Mathematical Optimization Process:
|
|
|
|
| 527 |
The optimization problem can be formulated as follows:
|
|
|
|
| 528 |
**Objective Function**:
|
| 529 |
""")
|
| 530 |
st.latex(r"""
|
|
|
|
| 536 |
- \( w \) is the vector of portfolio weights.
|
| 537 |
- \( μ \) is the vector of expected asset returns.
|
| 538 |
- \( ∑ \) is the covariance matrix of asset returns.
|
|
|
|
| 539 |
**Constraints**:
|
| 540 |
1. The sum of the portfolio weights must equal 1 (fully invested portfolio):
|
| 541 |
""")
|
|
|
|
| 562 |
st.sidebar.header("Optimization Parameters")
|
| 563 |
|
| 564 |
if st.sidebar.button('Run Analysis'):
|
| 565 |
+
try:
|
| 566 |
+
if 'mean_variance_result' not in st.session_state:
|
| 567 |
+
st.session_state.mean_variance_result = {}
|
| 568 |
+
|
| 569 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 570 |
+
returns = data.pct_change().dropna()
|
| 571 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 572 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 573 |
+
|
| 574 |
+
ef = EfficientFrontier(mean_returns, cov_matrix)
|
| 575 |
+
optimal_weights = ef.max_sharpe()
|
| 576 |
+
cleaned_weights = ef.clean_weights()
|
| 577 |
+
|
| 578 |
+
st.session_state.mean_variance_result['cleaned_weights'] = cleaned_weights
|
| 579 |
+
st.session_state.mean_variance_result['returns'] = returns
|
| 580 |
+
st.session_state.mean_variance_result['optimal_weights'] = optimal_weights
|
| 581 |
+
st.session_state.mean_variance_result['mean_returns'] = mean_returns # Store mean returns
|
| 582 |
+
st.session_state.mean_variance_result['cov_matrix'] = cov_matrix # Store covariance matrix
|
| 583 |
+
except Exception as e:
|
| 584 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 585 |
|
| 586 |
if 'mean_variance_result' in st.session_state:
|
| 587 |
cleaned_weights = st.session_state.mean_variance_result['cleaned_weights']
|
|
|
|
| 594 |
st.plotly_chart(fig_weights)
|
| 595 |
|
| 596 |
portfolio_returns = returns.dot(optimal_weights)
|
| 597 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 598 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 599 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 600 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 601 |
equal_weighted_returns = returns.mean(axis=1)
|
| 602 |
|
| 603 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 616 |
elif selected == "Black-Litterman Model":
|
| 617 |
st.markdown("""
|
| 618 |
### Black-Litterman Model
|
|
|
|
| 619 |
The Black-Litterman Model combines market equilibrium with investor views to adjust the expected returns and then applies mean-variance optimization. This approach is particularly useful for incorporating subjective views into a theoretically sound framework.
|
| 620 |
""")
|
| 621 |
|
|
|
|
| 622 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 623 |
st.markdown("""
|
| 624 |
#### Concept:
|
|
|
|
| 625 |
The Black-Litterman Model starts with the market equilibrium returns, which are implied by market capitalizations and a given risk aversion coefficient. Investors can then specify their own views on expected returns for certain assets or combinations of assets.
|
|
|
|
| 626 |
#### Market Equilibrium Returns:
|
|
|
|
| 627 |
The market equilibrium returns, \( \Pi \), are given by:
|
| 628 |
""")
|
| 629 |
st.latex(r"""
|
|
|
|
| 635 |
- \( δ \) is the risk aversion coefficient.
|
| 636 |
- \( Σ \) is the covariance matrix of asset returns.
|
| 637 |
- \( wmkt \) is the vector of market capitalization weights.
|
|
|
|
| 638 |
#### Investor Views:
|
|
|
|
| 639 |
Investor views are expressed in the form of a matrix \( P \) and a vector \( Q \):
|
| 640 |
""")
|
| 641 |
st.latex(r"""
|
|
|
|
| 647 |
- \( P \) is the matrix that identifies the assets involved in each view.
|
| 648 |
- \( μ \) is the vector of expected returns.
|
| 649 |
- \( Q \) is the vector of view returns.
|
|
|
|
| 650 |
#### Adjusted Expected Returns:
|
|
|
|
| 651 |
The adjusted expected returns, \( μ \), are then calculated as:
|
| 652 |
""")
|
| 653 |
st.latex(r"""
|
|
|
|
| 658 |
Where:
|
| 659 |
- \( τ \) is a scalar representing the uncertainty in the prior estimates.
|
| 660 |
- \( Ω \) is the diagonal covariance matrix of the error terms in the views.
|
|
|
|
| 661 |
#### Optimization:
|
|
|
|
| 662 |
Once the adjusted expected returns, \( \mu \), are obtained, we can apply mean-variance optimization to find the optimal portfolio weights.
|
|
|
|
| 663 |
**Objective Function**:
|
| 664 |
""")
|
| 665 |
st.latex(r"""
|
|
|
|
| 694 |
st.sidebar.header("Optimization Parameters")
|
| 695 |
|
| 696 |
if st.sidebar.button('Run Analysis'):
|
| 697 |
+
try:
|
| 698 |
+
if 'black_litterman_result' not in st.session_state:
|
| 699 |
+
st.session_state.black_litterman_result = {}
|
| 700 |
|
| 701 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 702 |
+
returns = data.pct_change().dropna()
|
| 703 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 704 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 705 |
|
| 706 |
+
market_data = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 707 |
+
if isinstance(market_data.columns, pd.MultiIndex):
|
| 708 |
+
market_data.columns = market_data.columns.get_level_values(0)
|
| 709 |
+
market_data = market_data['Adj Close']
|
| 710 |
|
| 711 |
+
delta = black_litterman.market_implied_risk_aversion(market_data)
|
|
|
|
| 712 |
|
| 713 |
+
market_caps = {}
|
| 714 |
+
for ticker in tickers:
|
| 715 |
+
stock = yf.Ticker(ticker)
|
| 716 |
+
market_caps[ticker] = stock.info.get('marketCap', 0)
|
|
|
|
| 717 |
|
| 718 |
+
market_caps_series = pd.Series(market_caps)
|
| 719 |
|
| 720 |
+
prior = black_litterman.market_implied_prior_returns(market_caps_series, delta, cov_matrix)
|
|
|
|
| 721 |
|
| 722 |
+
P = np.identity(len(tickers))
|
| 723 |
+
Q = np.zeros(len(tickers))
|
|
|
|
| 724 |
|
| 725 |
+
bl = black_litterman.BlackLittermanModel(cov_matrix, pi=prior, P=P, Q=Q)
|
| 726 |
+
bl_return = bl.bl_returns()
|
|
|
|
| 727 |
|
| 728 |
+
ef = EfficientFrontier(bl_return, cov_matrix)
|
| 729 |
+
optimal_weights_bl = ef.max_sharpe()
|
| 730 |
+
cleaned_weights_bl = ef.clean_weights()
|
|
|
|
| 731 |
|
| 732 |
+
st.session_state.black_litterman_result['cleaned_weights'] = cleaned_weights_bl
|
| 733 |
+
st.session_state.black_litterman_result['returns'] = returns
|
| 734 |
+
st.session_state.black_litterman_result['optimal_weights'] = optimal_weights_bl
|
| 735 |
+
except Exception as e:
|
| 736 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 737 |
|
| 738 |
if 'black_litterman_result' in st.session_state:
|
| 739 |
cleaned_weights_bl = st.session_state.black_litterman_result['cleaned_weights']
|
|
|
|
| 744 |
st.plotly_chart(fig_weights)
|
| 745 |
|
| 746 |
portfolio_returns_bl = returns.dot(optimal_weights_bl)
|
| 747 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 748 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 749 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 750 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 751 |
equal_weighted_returns = returns.mean(axis=1)
|
| 752 |
|
| 753 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_bl, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 763 |
elif selected == "Hierarchical Risk Parity":
|
| 764 |
st.markdown("""
|
| 765 |
### Hierarchical Risk Parity (HRP)
|
|
|
|
| 766 |
Hierarchical Risk Parity (HRP) is a method that groups assets into clusters based on their correlations and then allocates risk evenly among these clusters.
|
| 767 |
This approach aims to improve diversification and reduce risk concentration in the portfolio.
|
| 768 |
""")
|
| 769 |
|
|
|
|
| 770 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 771 |
st.markdown("""
|
| 772 |
#### Concept:
|
|
|
|
| 773 |
HRP involves the following key steps:
|
|
|
|
| 774 |
1. **Tree Clustering**:
|
| 775 |
Assets are grouped into clusters using hierarchical clustering methods. This step forms a tree structure that helps identify similar assets based on their correlations.
|
|
|
|
| 776 |
2. **Quasi-Diagonalization**:
|
| 777 |
The covariance matrix is rearranged into a block-diagonal form. This reordering ensures that the most correlated assets are placed next to each other, facilitating more effective risk allocation.
|
|
|
|
| 778 |
3. **Recursive Bisection**:
|
| 779 |
Risk is allocated recursively from the top of the tree down to the individual assets. At each level, risk is split evenly between the clusters, ensuring that each cluster receives an equal share of the portfolio risk.
|
|
|
|
| 780 |
#### Hierarchical Clustering:
|
|
|
|
| 781 |
Hierarchical clustering is performed using the correlation matrix of asset returns. The distance between assets \( i \) and \( j \) is given by:
|
| 782 |
""")
|
| 783 |
st.latex(r"""
|
|
|
|
| 787 |
st.markdown("""
|
| 788 |
Where:
|
| 789 |
- \( ρ_{i,j} \) is the correlation coefficient between assets \( i \) and \( j \).
|
|
|
|
| 790 |
#### Quasi-Diagonalization:
|
|
|
|
| 791 |
The covariance matrix \( \Sigma \) is reordered to a block-diagonal form using the clustering information. This step ensures that the assets with higher correlations are grouped together.
|
|
|
|
| 792 |
#### Recursive Bisection:
|
|
|
|
| 793 |
Risk is allocated recursively using the following steps:
|
|
|
|
| 794 |
1. **Top-Level Allocation**:
|
| 795 |
The portfolio risk is split equally between the top-level clusters.
|
| 796 |
""")
|
|
|
|
| 801 |
st.markdown("""
|
| 802 |
2. **Sub-Level Allocation**:
|
| 803 |
The risk within each cluster is further split recursively until the individual assets are reached.
|
|
|
|
| 804 |
This recursive process ensures that risk is allocated evenly across all clusters and individual assets.
|
| 805 |
""")
|
| 806 |
|
|
|
|
| 816 |
st.sidebar.header("Optimization Parameters")
|
| 817 |
|
| 818 |
if st.sidebar.button('Run Analysis'):
|
| 819 |
+
try:
|
| 820 |
+
if 'hrp_result' not in st.session_state:
|
| 821 |
+
st.session_state.hrp_result = {}
|
| 822 |
+
|
| 823 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 824 |
+
returns = data.pct_change().dropna()
|
| 825 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 826 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 827 |
+
|
| 828 |
+
hrp = HRPOpt(returns)
|
| 829 |
+
hrp_weights = hrp.optimize()
|
| 830 |
+
cleaned_weights_hrp = hrp.clean_weights()
|
| 831 |
+
|
| 832 |
+
st.session_state.hrp_result['cleaned_weights'] = cleaned_weights_hrp
|
| 833 |
+
st.session_state.hrp_result['returns'] = returns
|
| 834 |
+
st.session_state.hrp_result['optimal_weights'] = hrp_weights
|
| 835 |
+
st.session_state.hrp_result['hrp'] = hrp # Store HRP model
|
| 836 |
+
except Exception as e:
|
| 837 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 838 |
|
| 839 |
if 'hrp_result' in st.session_state:
|
| 840 |
cleaned_weights_hrp = st.session_state.hrp_result['cleaned_weights']
|
|
|
|
| 846 |
st.plotly_chart(fig_weights)
|
| 847 |
|
| 848 |
portfolio_returns_hrp = returns.dot(optimal_weights_hrp)
|
| 849 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 850 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 851 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 852 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 853 |
equal_weighted_returns = returns.mean(axis=1)
|
| 854 |
|
| 855 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_hrp, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 865 |
st.write("### Dendrogram of Asset Clusters")
|
| 866 |
plot_dendrogram(hrp, tickers, 'Dendrogram of Asset Clusters')
|
| 867 |
|
| 868 |
+
elif selected == "Maximum Diversification":
|
| 869 |
st.markdown("""
|
| 870 |
### Maximum Diversification Portfolio
|
|
|
|
| 871 |
The Maximum Diversification Portfolio method aims to create a portfolio that maximizes the diversification ratio. This approach allocates weights to assets to maximize the ratio of the weighted average volatility of individual assets to the overall portfolio volatility.
|
| 872 |
""")
|
| 873 |
|
|
|
|
| 874 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 875 |
st.markdown("""
|
| 876 |
#### Concept:
|
|
|
|
| 877 |
The diversification ratio (DR) is defined as:
|
| 878 |
""")
|
| 879 |
st.latex(r"""
|
|
|
|
| 885 |
- \( \sigma_i \) is the volatility of asset \( i \).
|
| 886 |
- \( \Sigma \) is the covariance matrix of asset returns.
|
| 887 |
- \( w \) is the weight vector of the portfolio.
|
|
|
|
| 888 |
#### Objective:
|
|
|
|
| 889 |
The objective of the Maximum Diversification Portfolio is to maximize this diversification ratio. By doing so, the portfolio aims to achieve the highest possible diversification benefit, reducing the overall portfolio risk.
|
|
|
|
| 890 |
#### Mathematical Formulation:
|
|
|
|
| 891 |
The optimization problem can be formulated as:
|
| 892 |
""")
|
| 893 |
st.latex(r"""
|
|
|
|
| 897 |
|
| 898 |
st.markdown("""
|
| 899 |
This ensures that the sum of the weights is equal to 1 (fully invested portfolio) and that all weights are non-negative (long-only portfolio).
|
|
|
|
| 900 |
#### Steps Involved:
|
|
|
|
| 901 |
1. **Calculate Individual Volatilities**:
|
| 902 |
Compute the volatility (\( \sigma_i \)) for each asset in the portfolio.
|
| 903 |
|
|
|
|
| 918 |
st.sidebar.header("Optimization Parameters")
|
| 919 |
|
| 920 |
if st.sidebar.button('Run Analysis'):
|
| 921 |
+
try:
|
| 922 |
+
if 'mdp_result' not in st.session_state:
|
| 923 |
+
st.session_state.mdp_result = {}
|
| 924 |
|
| 925 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 926 |
+
returns = data.pct_change().dropna()
|
| 927 |
+
mean_returns = returns.mean()
|
| 928 |
+
cov_matrix = returns.cov()
|
| 929 |
+
volatilities = returns.std()
|
| 930 |
|
| 931 |
+
optimal_weights_mdp = optimize_maximum_diversification(tickers, returns, mean_returns, cov_matrix, volatilities)
|
| 932 |
+
cleaned_weights_mdp = dict(zip(tickers, optimal_weights_mdp))
|
| 933 |
|
| 934 |
+
st.session_state.mdp_result['cleaned_weights'] = cleaned_weights_mdp
|
| 935 |
+
st.session_state.mdp_result['returns'] = returns
|
| 936 |
+
st.session_state.mdp_result['optimal_weights'] = optimal_weights_mdp
|
| 937 |
+
except Exception as e:
|
| 938 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 939 |
|
| 940 |
if 'mdp_result' in st.session_state:
|
| 941 |
cleaned_weights_mdp = st.session_state.mdp_result['cleaned_weights']
|
|
|
|
| 946 |
st.plotly_chart(fig_weights)
|
| 947 |
|
| 948 |
portfolio_returns_mdp = returns.dot(optimal_weights_mdp)
|
| 949 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 950 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 951 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 952 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 953 |
equal_weighted_returns = returns.mean(axis=1)
|
| 954 |
|
| 955 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_mdp, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 962 |
fig_drawdown = plot_max_drawdown(portfolio_returns_mdp, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 963 |
st.plotly_chart(fig_drawdown)
|
| 964 |
|
| 965 |
+
elif selected == "Maximum Sharpe Ratio":
|
| 966 |
st.markdown("""
|
| 967 |
### Maximum Sharpe Ratio Portfolio
|
|
|
|
| 968 |
The Maximum Sharpe Ratio Portfolio method aims to create a portfolio that maximizes the Sharpe ratio. The Sharpe ratio is the measure of the portfolio's excess return per unit of risk, providing a risk-adjusted return metric.
|
| 969 |
""")
|
| 970 |
|
|
|
|
| 971 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 972 |
st.markdown("""
|
| 973 |
#### Concept:
|
|
|
|
| 974 |
The Sharpe ratio (\( S \)) is defined as:
|
| 975 |
""")
|
| 976 |
st.latex(r"""
|
|
|
|
| 981 |
- \( R_p \) is the expected portfolio return.
|
| 982 |
- \( R_f \) is the risk-free rate.
|
| 983 |
- \( \sigma_p \) is the portfolio's standard deviation (volatility).
|
|
|
|
| 984 |
#### Objective:
|
|
|
|
| 985 |
The objective of the Maximum Sharpe Ratio Portfolio is to find the portfolio weights that maximize the Sharpe ratio. This ensures the highest possible return for a given level of risk.
|
|
|
|
| 986 |
#### Mathematical Formulation:
|
|
|
|
| 987 |
The optimization problem can be formulated as:
|
| 988 |
""")
|
| 989 |
st.latex(r"""
|
|
|
|
| 996 |
- \( w \) is the weight vector of the portfolio.
|
| 997 |
- \( \mu \) is the vector of expected returns for the assets.
|
| 998 |
- \( \Sigma \) is the covariance matrix of asset returns.
|
|
|
|
| 999 |
#### Steps Involved:
|
|
|
|
| 1000 |
1. **Estimate Expected Returns**:
|
| 1001 |
Compute the expected returns (\( \mu \)) for each asset in the portfolio.
|
| 1002 |
|
|
|
|
| 1007 |
Use optimization techniques to find the weight vector (\( w \)) that maximizes the Sharpe ratio, subject to the constraints.
|
| 1008 |
""")
|
| 1009 |
|
| 1010 |
+
st.markdown("""
|
| 1011 |
+
#### Benefits:
|
| 1012 |
+
|
| 1013 |
+
- **Risk-Adjusted Returns**: By maximizing the Sharpe ratio, this method ensures that the portfolio achieves the highest possible return per unit of risk.
|
| 1014 |
+
- **Efficiency**: The resulting portfolio is efficient in terms of return and risk, providing a balanced investment strategy.
|
| 1015 |
+
""")
|
| 1016 |
|
| 1017 |
st.sidebar.header("Optimization Parameters")
|
| 1018 |
|
| 1019 |
if st.sidebar.button('Run Analysis'):
|
| 1020 |
+
try:
|
| 1021 |
+
if 'msr_result' not in st.session_state:
|
| 1022 |
+
st.session_state.msr_result = {}
|
| 1023 |
|
| 1024 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 1025 |
+
returns = data.pct_change().dropna()
|
| 1026 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 1027 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 1028 |
|
| 1029 |
+
optimal_weights_msr = optimize_maximum_sharpe(mean_returns, cov_matrix)
|
| 1030 |
+
cleaned_weights_msr = dict(zip(tickers, optimal_weights_msr.values()))
|
| 1031 |
|
| 1032 |
+
st.session_state.msr_result['cleaned_weights'] = cleaned_weights_msr
|
| 1033 |
+
st.session_state.msr_result['returns'] = returns
|
| 1034 |
+
st.session_state.msr_result['optimal_weights'] = optimal_weights_msr
|
| 1035 |
+
except Exception as e:
|
| 1036 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 1037 |
|
| 1038 |
if 'msr_result' in st.session_state:
|
| 1039 |
cleaned_weights_msr = st.session_state.msr_result['cleaned_weights']
|
|
|
|
| 1044 |
st.plotly_chart(fig_weights)
|
| 1045 |
|
| 1046 |
portfolio_returns_msr = returns.dot(np.array(list(optimal_weights_msr.values())))
|
| 1047 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 1048 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 1049 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 1050 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 1051 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1052 |
|
| 1053 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_msr, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 1060 |
fig_drawdown = plot_max_drawdown(portfolio_returns_msr, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1061 |
st.plotly_chart(fig_drawdown)
|
| 1062 |
|
| 1063 |
+
elif selected == "Equal Risk Contribution":
|
| 1064 |
st.markdown("""
|
| 1065 |
### Equal Risk Contribution Portfolio
|
|
|
|
| 1066 |
The Equal Risk Contribution (ERC) Portfolio method aims to allocate risk equally among all assets in the portfolio. This approach ensures that each asset contributes the same amount of risk, leading to a well-balanced portfolio.
|
| 1067 |
""")
|
| 1068 |
|
|
|
|
| 1069 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1070 |
st.markdown("""
|
| 1071 |
#### Concept:
|
|
|
|
| 1072 |
The key idea is to balance the contribution of each asset to the total portfolio risk, such that the risk contribution from each asset is equal.
|
|
|
|
| 1073 |
#### Objective:
|
|
|
|
| 1074 |
The objective of the ERC Portfolio is to find the weights of the assets that equalize their risk contributions. The risk contribution of an asset \( i \) to the total portfolio risk is given by:
|
| 1075 |
""")
|
| 1076 |
st.latex(r"""
|
|
|
|
| 1081 |
- \( RC_i \) is the risk contribution of asset \( i \).
|
| 1082 |
- \( w_i \) is the weight of asset \( i \).
|
| 1083 |
- \( \sigma_p \) is the portfolio's standard deviation (volatility).
|
|
|
|
| 1084 |
#### Mathematical Formulation:
|
|
|
|
| 1085 |
The optimization problem can be formulated as:
|
| 1086 |
""")
|
| 1087 |
st.latex(r"""
|
|
|
|
| 1092 |
Where:
|
| 1093 |
- \( n \) is the number of assets.
|
| 1094 |
- The goal is to minimize the sum of squared deviations of each asset's risk contribution from the average risk contribution \( \frac{\sigma_p}{n} \).
|
|
|
|
| 1095 |
#### Steps Involved:
|
|
|
|
| 1096 |
1. **Estimate Expected Returns and Covariance Matrix**:
|
| 1097 |
Compute the expected returns (\( \mu \)) and the covariance matrix (\( \Sigma \)) for the assets.
|
|
|
|
| 1098 |
2. **Calculate Marginal Risk Contributions**:
|
| 1099 |
Determine the partial derivatives of the portfolio volatility with respect to each asset's weight.
|
|
|
|
| 1100 |
3. **Optimize the Risk Contributions**:
|
| 1101 |
Use optimization techniques to find the weight vector (\( w \)) that equalizes the risk contributions, subject to the constraints.
|
| 1102 |
""")
|
|
|
|
| 1112 |
st.sidebar.header("Optimization Parameters")
|
| 1113 |
|
| 1114 |
if st.sidebar.button('Run Analysis'):
|
| 1115 |
+
try:
|
| 1116 |
+
if 'erc_result' not in st.session_state:
|
| 1117 |
+
st.session_state.erc_result = {}
|
| 1118 |
|
| 1119 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 1120 |
+
returns = data.pct_change().dropna()
|
| 1121 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 1122 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 1123 |
|
| 1124 |
+
optimal_weights_erc = optimize_equal_risk_contribution(mean_returns, cov_matrix)
|
| 1125 |
+
cleaned_weights_erc = dict(zip(tickers, optimal_weights_erc.values()))
|
| 1126 |
|
| 1127 |
+
st.session_state.erc_result['cleaned_weights'] = cleaned_weights_erc
|
| 1128 |
+
st.session_state.erc_result['returns'] = returns
|
| 1129 |
+
st.session_state.erc_result['optimal_weights'] = optimal_weights_erc
|
| 1130 |
+
except Exception as e:
|
| 1131 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 1132 |
|
| 1133 |
if 'erc_result' in st.session_state:
|
| 1134 |
cleaned_weights_erc = st.session_state.erc_result['cleaned_weights']
|
|
|
|
| 1139 |
st.plotly_chart(fig_weights)
|
| 1140 |
|
| 1141 |
portfolio_returns_erc = returns.dot(np.array(list(optimal_weights_erc.values())))
|
| 1142 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 1143 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 1144 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 1145 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 1146 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1147 |
|
| 1148 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_erc, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 1155 |
fig_drawdown = plot_max_drawdown(portfolio_returns_erc, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1156 |
st.plotly_chart(fig_drawdown)
|
| 1157 |
|
| 1158 |
+
elif selected == "CVaR Minimization":
|
| 1159 |
st.markdown("""
|
| 1160 |
### CVaR Minimization Portfolio
|
|
|
|
| 1161 |
The CVaR Minimization Portfolio method focuses on minimizing Conditional Value at Risk (CVaR), which measures the expected loss of the portfolio in the worst-case scenarios. This method is particularly useful for investors who want to limit their downside risk.
|
| 1162 |
""")
|
| 1163 |
|
|
|
|
| 1164 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1165 |
st.markdown("""
|
| 1166 |
#### Concept:
|
|
|
|
| 1167 |
Conditional Value at Risk (CVaR) is a risk assessment measure that quantifies the expected loss in the worst-case scenarios beyond a certain confidence level. It provides a more comprehensive risk measure compared to Value at Risk (VaR).
|
|
|
|
| 1168 |
#### Objective:
|
|
|
|
| 1169 |
The objective of the CVaR Minimization Portfolio is to find the weights of the assets that minimize the CVaR at a given confidence level.
|
|
|
|
| 1170 |
#### Mathematical Formulation:
|
|
|
|
| 1171 |
The optimization problem can be formulated as:
|
| 1172 |
""")
|
| 1173 |
st.latex(r"""
|
|
|
|
| 1181 |
- \( \alpha \) is the confidence level (e.g., 95%).
|
| 1182 |
- \( T \) is the number of observations.
|
| 1183 |
- \( L_t(w) \) is the loss of the portfolio at time \( t \).
|
|
|
|
| 1184 |
#### Steps Involved:
|
|
|
|
| 1185 |
1. **Estimate Expected Returns and Covariance Matrix**:
|
| 1186 |
+
Compute the expected returns (\( \mu \)) and the covariance matrix (\$ \Sigma \) for the assets.
|
|
|
|
| 1187 |
2. **Calculate Portfolio Losses**:
|
| 1188 |
Determine the losses of the portfolio for each observation period.
|
|
|
|
| 1189 |
3. **Optimize CVaR**:
|
| 1190 |
Use optimization techniques to find the weight vector (\( w \)) that minimizes the CVaR, subject to the constraints.
|
| 1191 |
""")
|
| 1192 |
|
| 1193 |
+
st.markdown("""
|
| 1194 |
+
#### Benefits:
|
| 1195 |
+
|
| 1196 |
+
- **Downside Risk Management**: Helps in managing the downside risk by focusing on the worst-case scenarios.
|
| 1197 |
+
- **Risk-Averse Investors**: Suitable for investors with low risk tolerance who want to limit their potential losses.
|
| 1198 |
+
- **Comprehensive Risk Measure**: Provides a more comprehensive risk measure compared to VaR by considering the tail-end losses.
|
| 1199 |
+
""")
|
|
|
|
|
|
|
|
|
|
| 1200 |
|
| 1201 |
st.sidebar.header("Optimization Parameters")
|
| 1202 |
|
| 1203 |
if st.sidebar.button('Run Analysis'):
|
| 1204 |
+
try:
|
| 1205 |
+
if 'cvar_result' not in st.session_state:
|
| 1206 |
+
st.session_state.cvar_result = {}
|
| 1207 |
|
| 1208 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 1209 |
+
returns = data.pct_change().dropna()
|
| 1210 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 1211 |
|
| 1212 |
+
optimal_weights_cvar = optimize_cvar_minimization(mean_returns, returns)
|
| 1213 |
+
cleaned_weights_cvar = dict(zip(tickers, optimal_weights_cvar.values()))
|
| 1214 |
|
| 1215 |
+
st.session_state.cvar_result['cleaned_weights'] = cleaned_weights_cvar
|
| 1216 |
+
st.session_state.cvar_result['returns'] = returns
|
| 1217 |
+
st.session_state.cvar_result['optimal_weights'] = optimal_weights_cvar
|
| 1218 |
+
except Exception as e:
|
| 1219 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 1220 |
|
| 1221 |
if 'cvar_result' in st.session_state:
|
| 1222 |
cleaned_weights_cvar = st.session_state.cvar_result['cleaned_weights']
|
|
|
|
| 1227 |
st.plotly_chart(fig_weights)
|
| 1228 |
|
| 1229 |
portfolio_returns_cvar = returns.dot(np.array(list(optimal_weights_cvar.values())))
|
| 1230 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 1231 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 1232 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 1233 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 1234 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1235 |
|
| 1236 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_cvar, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 1243 |
fig_drawdown = plot_max_drawdown(portfolio_returns_cvar, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1244 |
st.plotly_chart(fig_drawdown)
|
| 1245 |
|
| 1246 |
+
elif selected == "Maximum Return":
|
| 1247 |
|
| 1248 |
st.markdown("""
|
| 1249 |
### Maximum Return Portfolio
|
|
|
|
| 1250 |
The Maximum Return Portfolio method focuses solely on maximizing the expected return of the portfolio, without considering risk. This method allocates the highest weights to the assets with the highest expected returns.
|
| 1251 |
""")
|
| 1252 |
|
|
|
|
| 1253 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1254 |
st.markdown("""
|
| 1255 |
#### Concept:
|
|
|
|
| 1256 |
The Maximum Return Portfolio aims to achieve the highest possible return by investing in assets that have the highest expected returns. This approach does not take into account the risk or volatility associated with the assets.
|
|
|
|
| 1257 |
#### Objective:
|
|
|
|
| 1258 |
The objective of the Maximum Return Portfolio is to find the weights of the assets that maximize the expected return.
|
|
|
|
| 1259 |
#### Mathematical Formulation:
|
|
|
|
| 1260 |
The optimization problem can be formulated as:
|
| 1261 |
""")
|
| 1262 |
st.latex(r"""
|
|
|
|
| 1268 |
- \( w \) is the weight vector of the assets.
|
| 1269 |
- \( \mu \) is the expected return vector of the assets.
|
| 1270 |
- \( n \) is the number of assets.
|
|
|
|
| 1271 |
#### Steps Involved:
|
|
|
|
| 1272 |
1. **Estimate Expected Returns**:
|
| 1273 |
Compute the expected returns (\( \mu \)) for the assets.
|
|
|
|
| 1274 |
2. **Optimize Expected Return**:
|
| 1275 |
Use optimization techniques to find the weight vector (\( w \)) that maximizes the expected return, subject to the constraints.
|
| 1276 |
""")
|
|
|
|
| 1291 |
st.sidebar.header("Optimization Parameters")
|
| 1292 |
|
| 1293 |
if st.sidebar.button('Run Analysis'):
|
| 1294 |
+
try:
|
| 1295 |
+
if 'max_return_result' not in st.session_state:
|
| 1296 |
+
st.session_state.max_return_result = {}
|
| 1297 |
|
| 1298 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 1299 |
+
returns = data.pct_change().dropna()
|
| 1300 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 1301 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 1302 |
|
| 1303 |
+
optimal_weights_max_return = optimize_max_return(mean_returns, cov_matrix)
|
| 1304 |
+
cleaned_weights_max_return = dict(zip(tickers, optimal_weights_max_return.values()))
|
| 1305 |
|
| 1306 |
+
st.session_state.max_return_result['cleaned_weights'] = cleaned_weights_max_return
|
| 1307 |
+
st.session_state.max_return_result['returns'] = returns
|
| 1308 |
+
st.session_state.max_return_result['optimal_weights'] = optimal_weights_max_return
|
| 1309 |
+
except Exception as e:
|
| 1310 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 1311 |
|
| 1312 |
if 'max_return_result' in st.session_state:
|
| 1313 |
cleaned_weights_max_return = st.session_state.max_return_result['cleaned_weights']
|
|
|
|
| 1318 |
st.plotly_chart(fig_weights)
|
| 1319 |
|
| 1320 |
portfolio_returns_max_return = returns.dot(np.array(list(optimal_weights_max_return.values())))
|
| 1321 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 1322 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 1323 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 1324 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 1325 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1326 |
|
| 1327 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_max_return, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 1334 |
fig_drawdown = plot_max_drawdown(portfolio_returns_max_return, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1335 |
st.plotly_chart(fig_drawdown)
|
| 1336 |
|
| 1337 |
+
elif selected == "Maximum Quadratic Utility":
|
| 1338 |
st.markdown("""
|
| 1339 |
### Maximum Quadratic Utility Portfolio
|
|
|
|
| 1340 |
The Maximum Quadratic Utility Portfolio method maximizes the quadratic utility function, which balances the trade-off between expected return and risk. It incorporates a risk aversion coefficient to adjust the level of risk tolerance.
|
| 1341 |
""")
|
| 1342 |
|
|
|
|
| 1343 |
with st.expander("Methodology and Formulas", expanded=False):
|
| 1344 |
st.markdown("""
|
| 1345 |
#### Concept:
|
|
|
|
| 1346 |
The Maximum Quadratic Utility Portfolio aims to find the optimal portfolio that maximizes an investor's utility, which is a measure of satisfaction or preference. This approach takes into account both the expected return and the risk of the portfolio, weighted by a risk aversion coefficient.
|
|
|
|
| 1347 |
#### Objective:
|
|
|
|
| 1348 |
The objective of the Maximum Quadratic Utility Portfolio is to maximize the utility function, which is defined as:
|
| 1349 |
""")
|
| 1350 |
st.latex(r"""
|
|
|
|
| 1357 |
- \( \mu \) is the expected return vector of the assets.
|
| 1358 |
- \( \Sigma \) is the covariance matrix of the asset returns.
|
| 1359 |
- \( \lambda \) is the risk aversion coefficient.
|
|
|
|
| 1360 |
#### Steps Involved:
|
|
|
|
| 1361 |
1. **Estimate Expected Returns and Covariance Matrix**:
|
| 1362 |
Compute the expected returns (\( \mu \)) and the covariance matrix (\( \Sigma \)) for the assets.
|
|
|
|
| 1363 |
2. **Set Risk Aversion Coefficient**:
|
| 1364 |
Define the risk aversion coefficient (\( \lambda \)) based on the investor's risk tolerance.
|
|
|
|
| 1365 |
3. **Optimize Utility Function**:
|
| 1366 |
Use optimization techniques to find the weight vector (\( w \)) that maximizes the utility function.
|
| 1367 |
""")
|
|
|
|
| 1383 |
risk_aversion = st.sidebar.slider('Risk Aversion Coefficient', min_value=0.0, max_value=10.0, value=1.0, step=0.1)
|
| 1384 |
|
| 1385 |
if st.sidebar.button('Run Analysis'):
|
| 1386 |
+
try:
|
| 1387 |
+
if 'mqu_result' not in st.session_state:
|
| 1388 |
+
st.session_state.mqu_result = {}
|
| 1389 |
|
| 1390 |
+
data = fetch_stock_data(tickers, start_date, end_date)
|
| 1391 |
+
returns = data.pct_change().dropna()
|
| 1392 |
+
mean_returns = expected_returns.mean_historical_return(data)
|
| 1393 |
+
cov_matrix = risk_models.sample_cov(data)
|
| 1394 |
|
| 1395 |
+
optimal_weights_mqu = optimize_max_quadratic_utility(mean_returns, cov_matrix, risk_aversion)
|
| 1396 |
+
cleaned_weights_mqu = dict(zip(tickers, optimal_weights_mqu.values()))
|
| 1397 |
|
| 1398 |
+
st.session_state.mqu_result['cleaned_weights'] = cleaned_weights_mqu
|
| 1399 |
+
st.session_state.mqu_result['returns'] = returns
|
| 1400 |
+
st.session_state.mqu_result['optimal_weights'] = optimal_weights_mqu
|
| 1401 |
+
except Exception as e:
|
| 1402 |
+
st.error(f"Error: {str(e)}. Check ticker symbols or date range.")
|
| 1403 |
|
| 1404 |
if 'mqu_result' in st.session_state:
|
| 1405 |
cleaned_weights_mqu = st.session_state.mqu_result['cleaned_weights']
|
|
|
|
| 1410 |
st.plotly_chart(fig_weights)
|
| 1411 |
|
| 1412 |
portfolio_returns_mqu = returns.dot(np.array(list(optimal_weights_mqu.values())))
|
| 1413 |
+
sp500 = yf.download('^GSPC', start=start_date, end=end_date, auto_adjust=False)
|
| 1414 |
+
if isinstance(sp500.columns, pd.MultiIndex):
|
| 1415 |
+
sp500.columns = sp500.columns.get_level_values(0)
|
| 1416 |
+
sp500_returns = sp500['Adj Close'].pct_change().dropna()
|
| 1417 |
equal_weighted_returns = returns.mean(axis=1)
|
| 1418 |
|
| 1419 |
fig_cumulative_returns = plot_cumulative_returns(portfolio_returns_mqu, sp500_returns, equal_weighted_returns, 'Cumulative Returns Over Time')
|
|
|
|
| 1426 |
fig_drawdown = plot_max_drawdown(portfolio_returns_mqu, sp500_returns, equal_weighted_returns, 'Maximum Drawdown')
|
| 1427 |
st.plotly_chart(fig_drawdown)
|
| 1428 |
|
|
|
|
|
|
|
| 1429 |
st.markdown(
|
| 1430 |
"""
|
| 1431 |
<style>
|
|
|
|
| 1438 |
unsafe_allow_html=True
|
| 1439 |
)
|
| 1440 |
|
|
|
|
|
|
|
| 1441 |
hide_streamlit_style = """
|
| 1442 |
<style>
|
| 1443 |
#MainMenu {visibility: hidden;}
|
| 1444 |
footer {visibility: hidden;}
|
| 1445 |
</style>
|
| 1446 |
"""
|
| 1447 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
|
|