Efficient Frontier Function (Python)

Over the last two weeks I’ve been learning and writing about possible portfolios, the risk-return boundaries, and the efficient frontiers. This won’t be the last post either. I created a python function that can accept a vector of asset returns and a covariance matrix, then produce the piece-wise parabolic function for all of the possible frontiers. It also optionally graphs them, noting the minimum possible variance.

In order to make sense of it, you need to know 1) how diversification works, and 2) how the frontiers are composed. However, the graphs can go a long way in explanation without one knowing all of the details. The function works for any three-asset portfolio. For the moment, I’m pretty proud of what I’ve made, even though it still needs improvements.

You can download the function from github:

https://github.com/zacharybartsch/frontier_segments/tree/main/frontier_segments

Below are the kinds of graphs that the function produces. I created them by swapping the returns with associated variance-covariances. Typically, people talk only about the efficient frontier, but I went ahead and graphed all of the frontiers for greater clarity. They all appear as the ought, except for a tiny blue segment that is in the bottom-left image.

The function is easy to use. Here is how I called the upper left graph:

mu_ex = np.array([0.2044, 0.1579, 0.095])
sigma_ex = np.array([
        [0.00024086, 0.00005642, 0.00008801],
        [0.00005642, 0.00011336, 0.00006400],
        [0.00008801, 0.00006400, 0.00015271]])

frontier_segments(mu_ex, sigma_ex, verbose=True, graph=True)

The function can also optionally spit out the parabola line segments that compose the frontiers. Each row represents a parabola segment. It’s lower and upper bound for which it describes the frontier, whether it’s on the efficient northwest frontier or on the lower southeast frontier. Finally, the a, b, & c refer to the typical parts of a quadratic function. Together, they are the piece-wise function for a portfolio’s frontier:

I plan to upgrade this function in the future with a more efficient quadratic programming process for portfolios with many assets, and to allow a weights vector to that can calculate several efficiency stats.

One thought on “Efficient Frontier Function (Python)

Leave a comment