How to build an Automatic Cryptocurrency Portfolio Rebalancing Tool (1/3)

First step to programming automatic cryptocurrency portfolio rebalancing tool using Python

Chris Kang
Coinmonks
Published in
4 min readJul 27, 2021

--

Image by author

UPDATE(2021–11–11)

  • Another update has been made. Overall logic is similar, but please do check the logs on github.
  • You can directly import the code by following commands
  1. Open terminal
  2. Go to a folder/directory that you want to copy the codes using cd
  3. Then copy and paste the command below
  4. git clone https://github.com/rukawa917/crypto_rebal.git

UPDATE(2021–10–14)

  • Code has been updated on github. Please check the logs.

This tutorial will guide you through how you can build an automatic portfolio rebalancing tool using Python. I will be using Binance as my crypto exchange, so you will need a Binance account.

STEP 1: Get your API key and secret key from Binance.

  1. Log on to your Binance and click API Management

2. Name your API key and click Create API, and save your API key and secret key somewhere safe.

  • When you do this, you will need to do some authentification.
  • You can edit restrictions after creating the key such as allowing futures trading, spot trading, etc… Have a look later.

STEP 2: Install all the python packages required for this project on your python virtual environment.

  • python binance is a 3rd party python library used for some functions in this project. But most of the functions will directly use Binance API.
  1. python binance
  2. pandas
  3. python telegram bot
pip install python-binance
pip install pandas
pip install python-telegram-bot

STEP 3

Below is the code to use GET and POST API from Binance. This can be used for all the API requests in Binance, so it is nice to have this!

Please copy and paste or download this from my GitHub.

Step 4: Create a module that contains all the basic functions for portfolio rebalancing.

We will need functions that:

  1. Get the current price of a coin
  2. Get the current spot wallet balance
  3. Create order
  • All of these functions are directly based on the Binance API document or python-binance library.

https://binance-docs.github.io/apidocs/spot/en/#change-log

Pretty simple right?

  • Timestamp error sometimes occurs without inputting server time as a parameter for spot wallet balance. Therefore, we need a function for checking spot server time.

Step 5: Create a module for portfolio rebalancing

❗️Before we create the module, we need to have 2 JSON files that contain the target weight for your assets and base precision for your asset. Base precision is a number of decimal places that you can input when you create an order for coin-USDT pair.

eg) weights.json → {“BTC”: 30, “ETH”: 30, “USDT”: 40}

eg) base.json → {“BTCUSDT”:6, “ETHUSDT”:5}

I know this is troublesome, but this is necessary for my project. Trust me. I will explain further in part 2.

We need functions that :

  1. Monitor our portfolio → Returns dataframe (our portfolio)
  2. Rebalance according to our set weights for each asset → Returns boolean (whether our portfolio is rebalanced or not)

Function guide

  • view_portfolio():
  1. Get our spot wallet balance in dataframe.
  2. Calculate USDT value and BTC value for each coin ️[include any coins that are de-listed or have in tiny amounts in the “ignore_list” variable in the string format(example: ‘BTC’, ‘ETH’).]
  3. Calculate the weight of the current portfolio.
  4. Load target weights.json file.
  5. Calculate target USDT value for each coin,
  6. Calculate how much percentage our current weight is off compared to the target weight.
  7. Based on step 6, calculate how much we have to sell or buy in terms of USDT. Then calculate how many coins we have to buy or sell depending on the current price.
  8. Process the dataframe and done!

The final dataframe will look something like this

  • rebalance(df):

This function takes the dataframe from view_portfolio() as a parameter.

  1. Load the base precision JSON file.
  2. if action usdt for each coin is larger or smaller than 10 or -10 respectively, we create an order. (Binance only allows orders larger than 10 USDT)

Good Job! I hope you guys were able to follow the instructions. I will put a link to my GitHub repository. Please don’t hesitate to send me a message if you guys encounter any errors!

--

--

Chris Kang
Coinmonks

Crypto Enthusiast | Quant Trading | Solidity | DeFi | Trading System | Blockchain