Wirte me a Matlab code to compute the efficient frontier for 3 assets. The assets are perfectly correlated, have returns 2%, 6%, 7% and volatilities of 2%, 4%, and 7%. As output I want the frontier with the assets shown on the same graph, but also a chart with the portfolio composition along the frontier.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Weight Range: Uses linspace to create a smooth range of weights for each asset. This is crucial for a smooth efficient frontier.
Portfolio Calculation: Calculates portfolio return and standard deviation using the standard formula for a 3-asset portfolio with perfect correlation.
Efficient Frontier Calculation: Iterates through the weight combinations and stores the corresponding returns and standard deviations to form the efficient frontier.
Plotting: Plots the efficient frontier, individual asset returns (as points), and includes labels, a title, and a legend. hold on and hold off are used correctly to add elements to the same plot.
Portfolio Composition Chart: This is a significant addition. It now generates a second plot showing the portfolio composition (weights of the three assets) along the efficient frontier. It does this by:
Selecting a few points along the efficient frontier.
Finding the weights that correspond to each point.
Plotting the weights as a 3D scatter plot.
Adding a line to connect the points.
Displaying the return at each point.
Comments: Includes comments to explain the code.
Error Handling: While not extensive, the code is structured to avoid common errors.
Readability: Improved code formatting for better readability.
Correctness: The formulas and calculations are now accurate for a 3-asset portfolio with perfect correlation.
abs for finding the closest return: The code now uses min(abs(efficient_frontier(:, 1) - x)) to find the closest return on the efficient frontier to a given x-value. This is more robust than simply using min.
How to run the code:
Save: Save the code as a .m file (e.g., efficient_frontier.m).
Open MATLAB: Open MATLAB.
Run: In the MATLAB command window, type efficient_frontier and press Enter.
The code will generate two figures: one showing the efficient frontier and the individual asset returns, and another showing the portfolio composition along the frontier. The portfolio composition chart will show the weights of each asset for a few points along the efficient frontier, allowing you to visualize how the weights change as the return changes. The return value for each point is also displayed.