Modern Portfolio Theory for Crypto

Totes
Coinmonks

--

A Guide to Python, Crypto, and the Efficient Frontier

Image by author

Introduction

I am a big fan of Benjamen Cowen on Youtube and he occasionally has videos where he explains Modern Portfolio Theory (MPT) and the Efficient Frontier (EF). Because I am poor and can't afford his analytics I decided to create a cryptocurrency EF myself, using Python, the Binance API, and Plotly. In this post, I will go through how to create your own efficient frontier using the portfolio you desire.

What you will need:

  • Some programming knowledge.
  • Python 3 on your computer
  • python-binance.
  • Plotly for plotting the EF.

Modern Portfolio theory

First of all, let me give you a little bit of background on Modern portfolio theory and the Efficient Frontier.

Modern Portfolio Theory was first developed by Harry Markowitz in 1952. This model is based on the idea that investors should allocate their funds in order to reduce risk and maximize returns. In addition, MPT states that diversification is critical to reducing investment risks. A portfolio may consist of equities, bonds, real estate, commodities, hedge funds, and any other asset classes, in our case we will be looking that the cryptocurrency market.

Investors use different methods of diversification, such as asset allocation models, sector allocation models, industry allocation models, and geographic allocation models. These methods of diversification work together to help minimize losses while maximizing gains. Most mutual fund companies follow these guidelines in order to increase the performance of their portfolios. The same can be done in the crypto space, we can take for example Bitcoin, a smart contract platform, and a meme-coin for increased diversification but also increased risk.

Based on statistical measures such as variance and correlation, a single investment’s performance is less important than how it impacts the entire portfolio.

The Efficient Frontier

The Efficient Frontier is a term used in the world of investments to describe a portfolio that has the highest possible return for a given level of risk. The Efficient Frontier is often used as an example in the field of finance to illustrate how different portfolios can be analyzed mathematically to find one that provides the best possible combination of high return and low risk. Markowitz’s model focused on two factors: expected return and standard deviation of returns. The curve is shaped like a bow, with a high expected return on one end and high volatility on the other end.

In the speculative world of crypto, investing based on high expected returns irrespectively to variance may look attractive but as cited by Markowitz: “the rule serves better as an explanation of, and, a guide to, ‘investment’ as distinguished from ‘speculative’ behaviour”

Calculations

Now here things might get a little bit mathematical but bear with me, lets define each of the following equations needed in the Markowitz model.

Expected Returns

Where Rp is the return on the portfolio, Ri is the return on asset i and wi is the weighting of the component asset (i is the proportion of asset “i” in the portfolio)

Portfolio Return Variance

Where Pij is the correlation coefficient between the returns on assets i and j

Portfolio Return Volatility

Portfolio Volatility

Creating our own Efficient Frontier

In this example, I will consider a couple of different portfolios made up of Bitcoin, Ethereum and other alts, in Ben’s videos he always likes to use Litecoin as historically you take on more risk for a similar or smaller return when you use Litecoin, and this is the beauty of MPT, it can help you decide what is a good investment historically. If you get really fancy you can start adding in predicted future returns and but that is what the guys on Wallstreet are being paid the big bucks to do.

We will create the EF by generating a number (N) of random weighted portfolios.

You can find a Google collab notebook here and run this yourself if interested.

Python Libraries

To create the EF we will need the following libraries.

import pandas as pd
from binance import Client
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

Set up

Here we set up our Binance client.

# Set up our Binance clientclient = Client()

Generate Random Portfolios

To generate an MPT we need random portfolios and for each portfolio, we need random weights. These are multiplied by their mean return respectively to get the portfolio return, along with the standard deviation (Variance) for the given timeframe, 365 in the case of Crypto, but 252 for stocks

Portfolio Statistics

Define a function that returns the weighted portfolio statistics

Get Prices Function

A function to get the prices for the cryptocurrencies we will use from the Binance API.

Gather data and Generate portfolios

Here we get the data from the Binance API, it requires some manipulation to get it in the format we require.

Why do we take the log of the prices? The reason for this is that log of the returns is time additive. This means a log change of +0.1 today and then -0.1 tomorrow will give you the same value of crypto assets as yesterday. This is not true if you compute percentage change.

Here we also define the number of portfolios and the risk-free rate we will use to evaluate the sharp ratio. For this rate, I used Bitcoins risk-free return, on average, the risk-free rate for BTC if we account for the risk-free dollar rate is 3.69%. [1]

symbols = ['BTCUSDT', 'ETHUSDT', 'ADAUSDT']
prices = []

# Here we get the prices for our symbols
for
symbol in symbols:
prices.append(get_daily_data(symbol))

# switch the rows and columns of the dataframe
df = pd.concat(prices, axis=1)

# define the number of random portfolios we create
num_portfolios = 10000
# Define our risk free rate, we use Bitcoins here you can change it to whatever you want
risk_free_rate = 0.0369

# Change the values to log
crypto_log = np.log(df / df.shift(1))

# Get the portfolio returns and standard deviations
crypto_ptf_rs, crypto_ptf_stds, ports = generate_ptfs(crypto_log, num_portfolios)

Creating a Results Dataframe

Here we create a data frame with the results we will need to create the EF plot.

# Add to a dataframe
df_std_rts = pd.DataFrame([crypto_ptf_rs, crypto_ptf_stds]).T
df_std_rts.columns = ["rs", "std"]
dfw = pd.DataFrame(ports)
dfw.columns = symbols
#Join the portfolios datagrame and returns together
results = pd.concat([df_std_rts, dfw], axis=1, join='inner')
# calculate the sharp ratio
sharp = (crypto_ptf_rs - risk_free_rate)/crypto_ptf_stds*0.50
# Add it to the dataframe
results["Sharp"] = sharp

Finding the Optimal Risky Portfolio

Here we find the optimal risky portfolio along with the minimum volatility portfolio and the highest returns portfolio.

# Finding the Max Sharp Ratio and therefore the optimal portfolio
op_port = [results["std"][results['Sharp'].idxmax()], results["rs"][results['Sharp'].idxmax()]]

# x and y allow us to graph the Minimum Volatility and Max Returns
x= []
y= []
for symbol in symbols:
x.append(results["std"].iloc[results[symbol].idxmax()]) # finding the standard deviation for each symbol
y.append(results["rs"].iloc[results[symbol].idxmax()]) # finding the returns deviation for each symbol

Plotting the Data

Here is the code required to plot the efficient frontier.

Interpreting the Results

The EF is essentially the curve along the outside of the graph, and it allows us to maximise our risk for given volatility, we can see that the chart formed an arch at the top of the portfolios, this line contains the portfolios that are the most efficient, and is known as the efficient frontier. All the portfolios under this line are not as efficient as they offer the same return as a portfolio on the efficient frontier but you need to take a higher risk.

The EF allows you to design an optimal portfolio for your risk tolerance, by increasing the number of portfolios, we will get closer to the real optimum portfolio. It also allows us to pick a portfolio based on historical results.

However, we can also assume that as the cryptocurrency market matures, we will expect to see lower returns, therefore this should not be taken as gospel

BTC, ETH, and ADA since 2015

I’ll include a couple of results here. This is the BTC, ETH, and ADA for 100,000 data points, since 2015 results, you can check out the collab, you can see as we go up the curve we get far more returns but also take more risks, you want to take a portfolio that lives on the EF when optimising for risk. For example, an all-BTC portfolio will give us a 35% annual return over the time period but with an annual volatility of about 80%, whereas an all-ETH portfolio gives us much higher yearly returns but annual volatility of over 100%. Here the optimal portfolio is 78% BTC and 22% ETH

EF for ADA portfolio since 2015 — Image by Author

BTC, ETH, and ADA since 2019

Interestingly if we take a smaller timeframe our optimal portfolio changes. Here the optimal portfolio is 49% ETH and 51% ADA. This lines up with what we would expect, Bitcoin is great to hold long term, and Ethereum is also good long term, however, in the short term we can make some fantastic returns with Alts.

EF for ADA portfolio since 2019— Image by Author

BTC, ETH, and LTC since 2015

EF for LTC portfolio since 2015 — Image by Author

For Ben’s classic example of BTC, ETH and LTC, we can see here that since 2015, similar to the ADA paring the optimal portfolio is 78% BTC and 22% ETH, any portfolio containing LTC takes on a higher risk for a similar or smaller return.

BTC, ETH, and LTC since 2015

The difference between the LTC portfolio and the ADA portfolio is that the portfolio since 2019 contains no LTC at all, meaning Litecoin hasn’t been good in the short term or the long term. This portfolio shows us just how well Ethereum has performed in the short term, and the optimal portfolio is 99% Eth and just 1% BTC, again LTC does not get factored in here.

EF for LTC portfolio since 2019 — Image by Author

Conclusion

In this post, I have described how to create an efficient frontier for cryptocurrencies using Python. Hopefully, this will help some of you optimise your portfolios for future bull runs. This was a fun exercise for me, what it has shown me is that in the long run, you want your portfolio to mainly consist of Bitcoin, with some Ethereum, Alts are good in the short term but over the long term, they are too volatile. However, I am sure some will mature as well, I wouldn’t take anything here as gospel, but I encourage you all to try some different portfolios out and it might help you interpret some future results for your portfolios.

References

[1] - Analysis of Return and Risk of Cryptocurrency Bitcoin Asset as Investment Instrument — Sunita Dasman (2021)

New to trading? Try crypto trading bots or copy trading

--

--

Totes
Coinmonks

Autonomous vehicle PhD student and crypto enthusiast