top of page

Robust Feedback Control for Bitcoin Holdings

Updated: Mar 2, 2021

Cryptocurrencies have soared in price relative to the US Dollar and Euro in the past few weeks drawing additional attention from general media. Cryptocurrencies may offer the same services as fiat money does in the future, that is, mainly, storage of value and means of exchange. To properly fulfill its functions, or at least to start a transition to these functions, a certain stability is needed in the exchange value of the cryptocurrency against other (rotating) assets. The exchange value has seen wild changes lately in what basically constitutes a form of "virtual" Foreign Exchange, this time positively, gaining relative value against common fiat. Every critic of cryptocurrency is now expecting it to fall sharply and demonstrate that the world of cryptographic coinage is not ready yet, it is not fit for purpose. Without further criticizing cryptocurrencies, yes, the risk of suddenly losing a lot of value is there, it is almost a mathematical certainty. Let's take a look a the past few months for the BTC-USD exchange price to illustrate the bright side of the situation:

And to the relative traded volume, from a single exchange. Finding the real traded volume for cryptocurrencies is still a difficult task, relative daily values have to be enough for the time being to get an idea of how much is traded:


In this period the standard deviation of the daily returns is 4.25%. This means a 22% monthly volatility or 80% annualized volatility taking just this period into consideration. If we take any other one-year period the results do not differ much, yes, Bitcoin as measured in USD is highly volatile and 80% of your investment can disappear in a year, or you can generate 100% returns in a few months. Risk and reward at the extremes.


Investing is a risk and reward balancing act and there are individuals and institutions that would like to add a little bit of risk to their investment in an attempt to capture the rewards cryptocurrencies might bring. This is not dangerous by itself if we follow a quantitative approach to investing, or trading Bitcoin, and we keep our exposure accordingly high or low. Risk should be known, analyzed and positions entered with full awareness of the multiple future possibilities.


Once we have decided that we want to risk up to 80% of the value of our investment yearly for a similar gain, additional control methods can be used to minimize the risk and maximize the benefit. One such method is a linear control system that is first (that we can find) described in this publication: On Trading of Equities: A Robust Control Paradigm. This paper introduces a simple linear feedback control system that will modulate our investment in Bitcoin depending on the returns of the previous period multiplied by a certain gain value. The research paper itself contains this controller architecture image, which is relatively simple:


The code model that reflects this controlling strategy and can help us modulate exposure to risky assets starts with the required imports and the general setup required to initialize an algorithm using Quantconnect framework:

import numpy as np
import pandas as pd
class CryptoController(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2020, 12, 1)
        self.SetEndDate(datetime.today())
        self.SetCash(1000000)
        self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin)

        res = Resolution.Hour
        self.SetPortfolioConstruction(InsightWeightingPortfolioConstructionModel())
        self.Settings.RebalancePortfolioOnInsightChanges = Trueself.SetExecution(ImmediateExecutionModel())
        self.UniverseSettings.Resolution = res

        # Instruments to trade.
        crypto = ['BTCUSD']

        # K-Gain parameter, 4 as stated in referenced paper.try:
            self.K = float(self.GetParameter("K"))
        except:
            self.Debug('No K-gain parameter detected. Using default')
            self.K = float(4)

        # Create the symbols:self.crypto = [self.AddCrypto(ticker, res).Symbol for ticker in crypto]
        self.AddAlpha(CryptoControl(self.crypto, self.K))

We are setting up a "K" gain of 4 according to the paper. The last change in hourly price (our resolution is Resolution.Hour) will be multiplied times 4 ("K") to obtain the change in percentage of our invested equity. This model allows for a flexible approach to setting K so that we can check what the behavior is for different values. Further research seems to partially focus on the generation of the gain function. It seems that the feedback controller could benefit from a past volatility metric as gain control, we have been unable to find any literature in this direction.


The model will invest a calculated percentage of total equity in the BTCUSD pair, the rest will remain in cash for the shake of simplicity. The exchange we are using for our simulation is Bitfinex, as the implementation in Quantconnect of this specific venue allows for the use of a margin account and simplifies the development of this trial algorithm. We really have no exchange preferences, our mentions to specific brokers or exchanges are always for technical reasons related to the availability of an Application Programming Interface. For an evaluation of cryptocurrency exchanges www.commodity.com contains information for multiple alternatives, they also have extensive information on commodities trading in general.


We have to initialize our alpha model to set up the initial conditions and logical data storages in the form of Python dictionaries:

class CryptoControl(AlphaModel):
    def __init__(self,
                 crypto,
                 K):
        self.Name = 'Crypto Controller'self.crypto = crypto
        self.K = K
        self.total_assets = len(self.crypto)
        self.init = False# Dictionaries for data:self.changes = {}
        self.loads = {}
        self.gains = {}
        
        # Low pass filter for very low weights, positions below# epsilon (0.005%) are set to 0 to avoid insights# that would result in no trade:
        self.epsilon = 0.005
        # Subsampler cycle of insights, skipping every square root# of the gain to allow intermediate rebalancing.
        self.subsampler = int(np.sqrt(int(self.K)))
        self.sample = 0

Data will be acted upon at the same rate as it is received if we do not sub-sample the buy or sell signals. We are emitting a new portfolio target every integer part of the square root of the gain (every 2 hours in this case) to allow re-balancing of the portfolio in between generation of consecutive signals. We also add a minimum trade limit, portfolio weights for Bitcoin of less than 0.05% are considered 0 to avoid generating trades of insignificant value.


The Update method of the alpha model, the method that will be executed when a slice of data is received, contains the following code, where the gain is computed and the expected portfolio loadings and signals are generated:

 # Compute the gain g for crypto symbols:
 for symbol in self.crypto:
            self.gains[symbol] = self.changes[symbol].Current.Value*self.K
            self.loads[symbol] = min(max(self.loads[symbol] + self.gains[symbol], 0), 1)
        
        # Subsample to avoid sync with rebalance and insight periods.
        if self.sample % self.subsampler != 0: return[]
        
        # Obtain insight time delta and magnitudes.
        t_delta = timedelta(hours=self.subsampler)
        magnitude_values = np.array(list(self.gains.values()))
        magnitude = abs(np.mean(magnitude_values))*100
        for symbol in self.crypto:
            w = self.loads[symbol] 
            g = self.gains[symbol]
            if w <= self.epsilon: continue
            if abs(g) <= self.epsilon/10000: continue
            
            insights.append(Insight(symbol, t_delta,
                                    InsightType.Price,
                                    InsightDirection.Up,
                                    magnitude, int(True),
                                    self.Name, w))
                                    

        return insights

The rest of the details on the initialization and error management are in the sample back-test at the end of the publication.


In terms of results we will first take a look at what the fate of our investment had we invested 100% of our equity (1 million dollars) in Bitcoin 60 days ago to hold it using a naïve buy and hold model, conditional and hypothetical:


Not a bad result at all as we are enjoying the rally. We will check now the same period if we had used our feedback controller model to modulate the investment depending on past performance. Basically, a closed-loop momentum-technical model telling us to add or subtract the latest returns multiplied by the gain K (4 in this case) :


Comparing the feedback-controlled model to the naïve model we observe two very basic performance factors; the returns are 15% less and the fees are astronomically high in our controlled model. Apparently, we did not do anything good with this model... a more detailed look into the returns and the risk shows a difference in the probabilistic Sharpe ratio of around 4%, which does not seem good enough until we inspect the drawdown on both models. For the uncontrolled, naïve model the maximum drawdown is almost 30%, for the controlled model the drawdown is "just" 19% (this is crypto volatility at play). We are paying with raw returns and fees for a little bit of peace of mind. Instead of $1.65M we end up with $1.5M and 11% less alarming Sunday mornings. Crypto markets do not stop.


What the feedback controller is basically doing is improving the risk-reward ratio for any time series shape we may feed into it by virtue of chasing momentum at a high frequency. It will never be able to turn a bear market or a constantly dropping stock into a profitable trade, it will limit the losses. In the same manner, it will limit the wins and alter the returns and drawdown profile to a less volatile combination of both.


The worst period for Bitcoin (and for cryptocurrencies in general) was January 2018 to August 2018. In this period the disaster for the buy-and-hold model was a 43% loss:


The same period, under feedback control, brings us 30% down; a notable difference in equity at the end of the period that is in our favor:


Cryptocurrencies are risky assets, mathematically speaking, in terms of return volatility. Any attempt to engage with them and participate in the possible future benefits must be very well risk-reward calibrated. Volatility must be studied as time goes forward and cryptocurrencies find their footing, the scenario may slowly change until stability of value appears, if it ever does. The market is not currently showing signs of slowing down so that it remains a risky bet with a very uncertain fundamental pricing that, sincerely, we think cannot be accurately predicted. The best we can do is manage the risk and obtain acceptable results in whatever direction the market takes.


Information in ostirion.net does not constitute financial advice; we do not hold positions in any of the companies or assets that we mention in our posts at the time of posting. If you are in need of quantitative model development, deployment, verification, or validation do not hesitate and contact us. We will be also glad to help you with your machine learning or artificial intelligence challenges when applied to asset management, trading, or risk evaluations. The model described in this publication is found here, hitting the clone button will replicate it in your Quantconnect account:


52 views0 comments

Recent Posts

See All
bottom of page