Finding top crypto portfolios with Tensorflow and Matrix calculus

Brick Pop
Brick Pop
Aug 6, 2018 · 12 min read

Tooling

If you are already not familiar with Python, do yourself a favor and follow a good tutorial to get up and running.

Image for post
Image for post
Jupyter Notebook example (from Toyplot)

Libraries

So let’s create a blank notebook and start with our optimizer. First, we need to import the following libraries:

import json
import requests
import pandas as pd
import numpy as np
import tensorflow as tf
# import matplotlib.pyplot as plt

Fetching historic data

To start working with data, we need to retrieve it from an API endpoint. In our case, we will use CryptoCompare. Copy this code in the Colab and run it. Let’s get some data and arrange it:

Image for post
Image for post

Returns

Next, we need to add a couple of columns with values derived from the current columns: the (daily) return and the excess return.

Image for post
Image for post
Image for post
Image for post
  • We stored the average return of every asset
  • We stored the cumulative return for every historic we have
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Excess Return Matrix
Image for post
Image for post
Image for post
Image for post

Risk Modeling

There are many approaches that can be used to optimize a portfolio. In the present article we will analyze the variance and covariance of individual assets in order to minimize the global risk.

Image for post
Image for post
Variance-covariance Matrix
Image for post
Image for post
Image for post
Image for post
  • When x = y the value is the variance of the asset
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
  • Correlation values range from –1 to 1
  • Values tending to 1 mean that two random variables tend to have linear relationship
  • Correlation values tending to –1 (anticorrelation) mean that two assets tend to have opposite behaviors
  • Correlation values of 0 mean that two random variables are independent

Portfolio optimization

Given the average return and the variance of our assets, now it’s time to decide how much money is allocated in each one.

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Tensorflow

This is where Tensorflow comes into play. TensorFlow is an opensource Machine Learning framework originally developed by Google.

coin_weights = tf.Variable(np.full((len(coins), 1), 1.0 / len(coins)))
weighted_std_devs = tf.multiply(coin_weights, std_deviations)
product_1 = tf.transpose(weighted_std_devs)
product_2 = tf.matmul(product_1, correlation_matrix)
portfolio_variance = tf.matmul(product_2, weighted_std_devs)
portfolio_volatility = tf.sqrt(portfolio_variance)
init = tf.global_variables_initializer()train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(portfolio_volatility)
with tf.Session() as sess:
sess.run(init)
for i in range(steps):
sess.run(train_step)
Image for post
Image for post

Constraints

In Tensorflow we can’t assign values to variables like var = val. Values can be declared via tf.constant(...) , as a tf.Variable(...) with a default value or be assigned via my_tensor.assign(...) , which creates an operation that needs to be run.

Image for post
Image for post

Sharpe ratio

The Sharpe Ratio is one of the most used metrics in the Modern Portfolio Theory. It combines both magnitudes we want into a simple formula:

Image for post
Image for post
Image for post
Image for post
Optimizer(...).minimize(tf.negative(sharpe_ratio))
coin_weights = tf.Variable(tf.random_uniform((len(coins), 1), dtype=tf.float64))
if i % 2000 == 0 : 
print("[round {:d}]".format(i))
# print("Coin weights", sess.run(coin_weights)) # if needed
print("Volatility: {:.2f} %".format(portfolio_volatility.eval() * 100))
print("Return {:.2f} %".format(sess.run(portfolio_return)*100))
print("Sharpe ratio", sess.run(sharpe_ratio))
print("")
# ...
Image for post
Image for post
  • Better handling of the constraints
  • Allowing short trades
  • Keeping track of many portfolios
  • Chart and plotting artifacts
  • Playing with train and test timeframes

Wrap up

We just wrote a Cryptocurrency Portfolio Optimizer using Python, Tensorflow and Financial Risk Modeling. Writing an equivalent tool would have involved much time of research and development in the past.

Investing in crypto involves substantial risk of loss. Past results are no indication of future performance.

Please, write the above disclaimer in a big banner and never forget to read it twice before you commit to an investment.



Stack Me Up

Full stack, Blockchain, Mobile.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store