FAQ: Mean-Variance Portfolio Optimization - Review

This community-built FAQ covers the “Review” exercise from the lesson “Mean-Variance Portfolio Optimization”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Analyze Financial Data with Python

FAQs on the exercise Review

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hey! Just downloaded the rf.py code to contribute to my capstone project. I’m having some issues with organising and downloading the proper packages to make it work.

This is a screen shot of the problems section of my VSC.

Thanks!

Looks like you need to install NumPy. If you’re using Python 3 (recommended), enter the following command into your Terminal. If you’re using Python 2, change ‘pip3’ to ‘pip’

pip3 install numpy

return_portfolios and optimal_portfolio are custom functions made by Codecademy. They can be found in the lessons. They’re in a separate script inside the lessons. See the tabs at the top of the editor. You’ll need to copy those functions into a file in the same directory as your own script, and then import the functions as you would a normal module. I put them in a file called calc.py, so then:

from calc import return_portfolios, optimal_portfolio

As opt and blas: the Codecademy custom functions depend on a Python library called CVXOPT: Download — CVXOPT It’s not available on pip sadly. You have to download and install it separately.

I’m in a similar situation to you, wanting to use this to build my capstone project. I’m thinking of using the PyPortfolioOpt. It has some things to do with Efficient Frontiers: Efficient Frontier Optimisation — PyPortfolioOpt 1.3.1 documentation

1 Like

Hey thank ya1

I ran through it again and all seems well. The issue will be importing and massaging the data to work with the functions!

opt and blas seem like very useful tools, above my level, but still interesting.

Hi guys! Is there a way to select a certain portfolio with the risks and returns that you want and the algorithm will tell you the weights? Thanks!

2 Likes

Hi!
Actually it would be great, if the the following information were revealed:

  1. how can I see the weights of assets for a given return (or risk)?
  2. how can I add additional constraints (like weight caps, prohibition of short sales)?
  3. what is the runtime of the algorithm in terms of O()? Is it possible to run the code on 1000 shares?
  4. can I insert my own expectations of future returns?

It would be much much more useful. Thanks a lot, if you are going to reveal it.

1 Like

Where did you get the rf.py code to download?

Dunno if I’m supposed to, but it was difficult to locate the code for rf.py, so here it is:

# Code for  performing portfolio optimizations
import pandas as pd
import numpy as np
import cvxopt as opt
from cvxopt import blas, solvers

def return_portfolios(expected_returns, cov_matrix):
    port_returns = []
    port_volatility = []
    stock_weights = []

    selected = (expected_returns.axes)[0]

    num_assets = len(selected)
    num_portfolios = 5000

    for single_portfolio in range(num_portfolios):
        weights = np.random.random(num_assets)
        weights /= np.sum(weights)
        returns = np.dot(weights, expected_returns)
        volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
        port_returns.append(returns)
        port_volatility.append(volatility)
        stock_weights.append(weights)

    portfolio = {'Returns': port_returns,
                 'Volatility': port_volatility}

    for counter,symbol in enumerate(selected):
        portfolio[symbol +' Weight'] = [Weight[counter] for Weight in stock_weights]

    df = pd.DataFrame(portfolio)

    column_order = ['Returns', 'Volatility'] + [stock+' Weight' for stock in selected]

    df = df[column_order]

    return df


def optimal_portfolio(returns):
    n = returns.shape[1]
    # returns = np.transpose(returns.as_matrix())  # as_matrix() deprecated after 0.23.0
    returns = np.transpose(returns.values)

    N = 100
    mus = [10**(5.0 * t/N - 1.0) for t in range(N)]

    # Convert to cvxopt matrices
    S = opt.matrix(np.cov(returns))
    pbar = opt.matrix(np.mean(returns, axis=1))

    # Create constraint matrices
    G = -opt.matrix(np.eye(n))   # negative n x n identity matrix
    h = opt.matrix(0.0, (n ,1))
    A = opt.matrix(1.0, (1, n))
    b = opt.matrix(1.0)

    # Calculate efficient frontier weights using quadratic programming
    portfolios = [solvers.qp(mu*S, -pbar, G, h, A, b)['x']
                  for mu in mus]
    ## CALCULATE RISKS AND RETURNS FOR FRONTIER
    returns = [blas.dot(pbar, x) for x in portfolios]
    risks = [np.sqrt(blas.dot(x, S*x)) for x in portfolios]
    ## CALCULATE THE 2ND DEGREE POLYNOMIAL OF THE FRONTIER CURVE
    m1 = np.polyfit(returns, risks, 2)
    x1 = np.sqrt(m1[2] / m1[0])
    # CALCULATE THE OPTIMAL PORTFOLIO
    wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x']
    return np.asarray(wt), returns, risks

Anyone knows why if you have more than 6 stocks data, the optimal_portfolio() doesn’t work??