Loading ...

Blockchain Quantitative Investment Series - Dynamic Balance Strategy

Author: mindrainbow, Created: 2019-03-26 11:52:11, Updated:

Original: FMZ Quant www.fmz.com

The “real stuff” of quantitative trading gathering place where you can truly benefit from.

NO.1

Warren Buffett’s mentor, Benjamin Graham, once mentioned in the book <<The Intelligent Investor>> a trading model in which stock and bonds are dynamically balanced. img This trading model is very simple:

50% of the funds in the hands are invested in equity funds, and the remaining 50% are invested in bond funds. That is, stocks and bonds each account for half.

An asset position rebalancing based on fixed intervals or market changes restores the ratio of stock assets to bond assets to an initial 1:1.

This is the whole logic of the entire strategy, including when to buy and sell, and how much to buy and sell. How simple and effect it is!

NO.2

In this method, the volatility of bond funds is actually very small, far below the stock volatility, so bonds are used here as “reference anchors”, that is, using bonds to measure whether the stocks are rising too much or too little.

If the stock price rises, the market value of the stock will be greater than the market value of the bond. When the market value ratio of these two exceeds the set of a threshold, the total position will be readjusted, the stock will be sold, and the bond will be bought to make the stock value to bond value ratio to restore to the initial 1:1.

Conversely, if the stock price falls, the market value of the stock will be less than the market value of the bond. When the market value ratio of the these two exceeds the set of a threshold, the total position will be readjusted, the stock will be bought, and the bond will be sold to make the market capitalization ratio of the bond value to stock value to restore to the initial 1:1. img In this way, the ratio between the dynamic balance of stocks and bonds is enough to enjoy the profit of stock growth and reduce asset volatility. As a pioneer in the value investing, Graham provided us with a wonderful idea.

Since this is a complete and mutual strategy, why don’t we use it on cryptocurrency market?

NO.3

Blockchain Assets Dynamic Balance Strategy in BTC

Strategy logic

According to the current value of BTC, the account balance is retained at $6400 cash and 1 BTC, ie the initial ratio of cash to BTC market value is 1:1.

If the price of the BTC rises to $7400, that is, the BTC market value is greater than the account balance, and the difference between them exceeds the set threshold, then (7400-6400)/7400/2 coins are sold. It means that BTC has appreciated and we need to exchange the cash back.

If the price of the BTC falls to $5400, ie the BTC market value is less than the account balance and the difference between them exceeds the set threshold, buy (6400-5400)/5400/2 coins. It means that BTC has depreciated and we need to buy BTC back.

In this way, regardless of whether the BTC is appreciated or depreciated, the account balance and the market value of the BTC are always kept dynamically equal. If the BTC is devalued, buy some, and then sell it when it raises again, just like the balance scales.

NO.4

So how do you implement it with programming code?

Let us take the FMZ quantitative trading platform as an example. Let us first look at the strategic framework:

// strategy parameter
var threshold = 0.05; // Threshold
var LoopInterval = 60; // Polling interval(seconds)
var MinStock = 0.001; // Minimum transaction volume
var XPrecision = 4; // Quantity accuracy
var ZPrecision = 8; // Price accuracy

// Withdrawal order function
function CancelPendingOrders() {

}

// Placing Order function
function onTick() {

}

// Main function
function main() {
    // Filter non-critical information
    SetErrorFilter("GetRecords:|GetOrders:|GetDepth:|GetAccount|:Buy|Sell|timeout");
    while (true) { // Polling mode
        if (onTick()) { // Execute the onTick function
            CancelPendingOrders(); // Cancel unexecuted pending orders
        }
        Sleep(LoopInterval * 1000); // Sleep
    }
}

The entire strategy framework is actually very simple, a “main” function, an “onTick” order placing function, a “CancelPendingOrders” function, and the necessary parameters.

NO.5

Order module

// Placing Order function
function onTick() {
    var acc = _C(exchange.GetAccount); // Get account information
    var ticker = _C(exchange.GetTicker); // Get Tick data
    var spread = ticker.Sell - ticker.Buy; // Get the bid-ask spread of Tick data
    // 0.5 times the difference between the account balance and the current position value
    var diffAsset = (acc.Balance - (acc.Stocks * ticker.Sell)) / 2;
    var ratio = diffAsset / acc.Balance; // diffAsset / Account Balance
    LogStatus('ratio:', ratio, _D()); // Print ratio and current time
    if (Math.abs(ratio) < threshold) { // If the absolute value of ratio is less than the specified threshold
        return false; // return false
    }
    if (ratio > 0) { // If ratio is greater than 0
        var buyPrice = _N(ticker.Sell + spread, ZPrecision); // Calculate the order price
        var buyAmount = _N(diffAsset / buyPrice, XPrecision); // Calculate the order quantity
        if (buyAmount < MinStock) { // If the order quantity is less than the minimum transaction volume
            return false; // return false
        }
        exchange.Buy(buyPrice, buyAmount, diffAsset, ratio); // Buy order
    } else {
        var sellPrice = _N(ticker.Buy - spread, ZPrecision); // Calculate the order price
        var sellAmount = _N(-diffAsset / sellPrice, XPrecision); // Calculate the order quantity
        if (sellAmount < MinStock) { // If the order quantity is less than the minimum transaction volume
            return false; // return false
        }
        exchange.Sell(sellPrice, sellAmount, diffAsset, ratio); // Sell order
    }
    return true; // return true
}

The logic of the order transaction is clear, and all the comments have been written into the code. You can click on the image to enlarge it.

The main process is as follows:

Get account information.

Get the Tick data.

Calculate the Tick data bid-ask spread.

Calculate the account balance and the BTC market value spread.

Calculate the trigger condition of trading, order price, and order quantity.

Place an order and return true.

NO.6

Cancel pending order module

// Withdrawal order function
function CancelPendingOrders() {
    Sleep(1000); // Sleep 1 second
    var ret = false;
    while (true) {
        var orders = null;
        // Continue to get an array of unexecuted orders, if an exception is returned, continue to get
        while (!(orders = exchange.GetOrders())) {
            Sleep(1000); // Sleep 1 second
        }
        if (orders.length == 0) { // If the order array is empty
            return ret; // Return to withdrawal status
        }
        for (var j = 0; j < orders.length; j++) { // Traversing the array of unexecuted orders
            exchange.CancelOrder(orders[j].Id); // Cancel unexecuted orders one by one
            ret = true;
            if (j < (orders.length - 1)) {
                Sleep(1000); // Sleep 1 second
            }
        }
    }
}

The cancel pending order module is even simpler, the steps are as follows:

Wait 1 second before withdrawing the order, because some exchange houses may have server delays.

Continue to get an array of unexecuted orders, and if an exception is returned, keep trying until it successful.

If the unexecuted order array is empty, it will return the withdrawal status immediately.

If there are unexecuted orders, the entire array is traversed and the order is withdrawn according to the order ID.

NO.7

This Strategy’s all programming source code img img On the FMZ quantitative trading platform, with just 80 lines of code, a complete blockchain BTC dynamic balancing strategy has been successfully build. But such simple strategy as this one, is there any value? Look down~

NO.8

Next, let’s test this simple dynamic balancing strategy to see if it works. The following is a backtest on the historical data of BTC, for your reference only.

Backtesting environment img Backtest performance img Back test curve img Another one, the same period BTC price chart img Is there any shock to you?

The BTC has continued its eight-month decline, and even the biggest decline has exceeded 70%, which has caused many investors to lose confidence in blockchain assets.

The cumulative revenue of this strategy is as high as 160%, and the annualized return-to-risk ratio exceeds 5. For such a simple trading strategy, this return on investment has exceeded the majority of the “All-in” types of players.

NO.9

This balancing strategy, with only one core parameter (threshold value), is a very simple investment method that pursues not excess returns but solid profits.

Contrary to the trend strategy, the dynamic balance strategy is against the trend. This strategy is to reduce the position and cool down when the market is too hot. When the market is deserted, it will be hidden in, which is similar to macroeconomic regulation.

In fact, the dynamic balance strategy is based on the idea that the price is unpredictable, while at the same time capturing the price fluctuations. The key core of the dynamic balancing strategy is to set and adjust the asset allocation ratio, as well as the trigger threshold.

In view of the length of the article, it is impossible for an article to be comprehensive about everything. As an old saying “Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime.”. The most important thing about the dynamic balance strategy is the investment idea. You can even replace the individual BTC assets in this article with a basket of blockchain asset portfolios. img Finally, let’s end this article with a paragraph in Benjamin Graham’s famous book <<The Intelligent Investor>>:

The stock market is not a “weighing gauge” that accurately measures value. On the contrary, it is a “voting machine”. The decisions made by countless people are a rational and emotional dopant. There are many times when these choices are made. It is a far cry from the value judgment of reason. The secret of investing is to invest when prices are much lower than intrinsic value, and believe that market trends will pick up.

  • Benjamin Graham

For directly copy the source code, please visit our strategy square at : https://www.fmz.com/strategy/110900

there are lot of strategies that you can study, download, rent, or purchase.

NO.10

about us

The reason for operating this website is to change the current status of the quantitative trading world where lack of the “real stuff”, where has a lot of scams and barely deep communications, and create a more pure quantitative trading learning and communication platform. For more information, please visit our website (www.fmz.com)

Your forwarding will be the driving force to support us to continue to create more “real stuff”! If you feel that this article is helpful to you, please forward it to your friend and support us. Sharing is also a kind of wisdom!

Contact us

Telegram: FMZ Quant

Email: henry@fmz.com

Website: www.fmz.com


More