# Tooling

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

# Libraries

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

`import jsonimport requestsimport pandas as pdimport numpy as npimport 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:

# Returns

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

• We stored the average return of every asset
• We stored the cumulative return for every historic we have

# 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.

• When x = y the value is the variance of the asset
• 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.

# 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)`

## 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.

# 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:

`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("")# ...`
• Better handling of the constraints
• 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.

Written by

Written by

## Brick Pop

#### Full stack tech, thoughts and life. Personal journey is underway. The future is now. ## 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