Algorithmic Trading Strategies
  • Cryptocurrency Algorithmic Trading Strategies
    • Building Blocks Of Creating an Algo Trading Strategy
    • How To Apply The Strategies In This Library
    • Strategy 1: Candlestick Trading Pattern (Hammer and Hanging Man candles)
    • Strategy 2: Stochastic Oscillator and Bollinger Bands
    • Strategy 3: Diversified Crypto Portfolio Investing with Stochastics & Bollinger Bands
Powered by GitBook
On this page
  1. Cryptocurrency Algorithmic Trading Strategies

Strategy 3: Diversified Crypto Portfolio Investing with Stochastics & Bollinger Bands

This strategy is similar to Strategy 2, however strategy 2 is only made to handle 1 Crypto asset. This strategy will create and trade a portfolio of Crypto assets based on parameters that we set.

The Algorithim:

Initialization: In this section, you're setting up the parameters for the algorithm.

self.SetStartDate(2016, 6, 18) and self.SetEndDate(2023, 7, 23) set the time frame for the backtest from mid-June 2016 to mid-June 2023.

self.SetCash(self._cash) sets the initial cash amount to $100,000.

AddUniverse piece of code allows us to add all the Cryptocurrencies from Binance that will meet the parameters that we set later on.


class RetrospectiveYellowGreenAlligator(QCAlgorithm):

    def Initialize(self):
        # INITIALIZE
        self.SetStartDate(2023, 1, 18)
        self.SetEndDate(2023, 7, 23)
        self._cash = 100000
        self.SetCash(self._cash)

        self.UniverseSettings.Resolution = Resolution.Daily
        self.AddUniverse(CryptoCoarseFundamentalUniverse(Market.Binance, self.UniverseSettings, self.universe_filter))

In the code below, we have defined the universe to only consist of Cryptocurrencies that have more than $60m of daily trading volume. This ensures that the portfolio only consists of high quality coins.

    def universe_filter(self, crypto_coarse: List[CryptoCoarseFundamental]) -> List[Symbol]:
        return [cf.Symbol for cf in crypto_coarse if cf.VolumeInUsd is not None and cf.VolumeInUsd > 60000000]

Setting the technical Indicators:

This sets up both our Stochastics and Bollinger Bands strategy.

# SET TECHNICAL INDICATORS
        self.Bolband = {}
        self.sto = {}

Risk Management: This section adds risk management to the algorithm.

TrailingStopRiskManagementModel(0.03) will sell the asset if its price drops by 3%. This is effectively a stop-loss.

OnData: This is the core logic of the algorithm. It runs every time new data comes in (in this case, daily).

self.Bolband[symbol] = self.BB(symbol, 10, 0.45, MovingAverageType.Simple, Resolution.Daily) sets up a Bollinger Bands indicator with a period of 10 days and a standard deviation of 0.45.

self.sto[symbol] = self.STO(symbol, 8, 5, 5, Resolution.Daily) sets up a Stochastic Oscillator with a period of 8 days, smoothing period K of 5, and smoothing period D of 5.

The code follows this logic:

1) The Algo will buy and hold crypto unless the conditions for a short position are met. Therefore this a bullish Investing strategy more suited for those that want to hold their crypto assets for the long-term and do not mind short-term price fluctuations. The algo Invests equally in all of the assets that meet the $60m trading volume criteria and rebalances daily.

2) If the price of the crypto asset is above the upper Bollinger band & the Stochastics value is greater than 80 then it will trigger a short position using 100% of the portfolio.The algo Invests equally in all of the assets that meet the $60m trading volume criteria and rebalances daily.

If the unrealized profit from the current holdings is above 10%, the algorithm will take profit from the trade and close it (self.Liquidate(self.ticker)).

def OnData(self, data):
        for symbol in data.Keys:
            if symbol not in self.reference_ticker:
                self.reference_ticker[symbol] = self.History(symbol, 10, Resolution.Daily)['close']
                self._initialValue_ticker[symbol] = self.reference_ticker[symbol].iloc[0]
                self.Bolband[symbol] = self.BB(symbol, 10, 0.45, MovingAverageType.Simple, Resolution.Daily)
                self.sto[symbol] = self.STO(symbol, 8, 5, 5, Resolution.Daily)

            price = data[symbol].Close
            sto_value = self.sto[symbol].Current.Value

            if price > self.Bolband[symbol].UpperBand.Current.Value and sto_value > 80:
                self.SetHoldings(symbol, -1)
                self.Debug(f"Short position triggered for {symbol}")
            
            elif self.Portfolio[symbol].UnrealizedProfitPercent > 0.1:
                self.Liquidate(symbol)
                self.Debug(f"Take profit triggered for {symbol}")
            else:
                self.SetHoldings(symbol, 1)

Plotting: The algorithm plots three charts: "Strategy Equity", "Bollinger", and "Stochastic".

The "Strategy Equity" chart shows the growth of the portfolio value.

The "Bollinger" chart shows the three Bollinger Bands (upper, middle, lower) and the closing price .

The "Stochastic" chart shows the three lines of the Stochastic Oscillator: fast stochastic, stochastic %K, and stochastic %D.

            self.Plot("Strategy Equity", str(symbol), self._cash * self.Securities[symbol].Close / self._initialValue_ticker[symbol])
            self.Plot("Strategy Equity", 'Portfolio Value', self.Portfolio.TotalPortfolioValue)
            self.Plot("Bollinger", 'BB Lower', self.Bolband[symbol].LowerBand.Current.Value)
            self.Plot("Bollinger", 'BB Upper', self.Bolband[symbol].UpperBand.Current.Value)
            self.Plot("Bollinger", 'BB Middle', self.Bolband[symbol].MiddleBand.Current.Value)
            self.Plot("Bollinger", str(symbol), price)
            self.Plot("Stochastic", "faststoch", self.sto[symbol].FastStoch.Current.Value)
            self.Plot("Stochastic", "stochk", self.sto[symbol].StochK.Current.Value)
            self.Plot("Stochastic", "stochd", self.sto[symbol].StochD.Current.Value)

Backtesting the performance of the Algorithm:

Here is the portfolio of crypto assets that the algorithim selected based of the criteria we set earlier:

Please refer to the Algorithmic Trading Strategies main page to see how to start using this algorithm.

PreviousStrategy 2: Stochastic Oscillator and Bollinger Bands

Last updated 1 year ago

Link to view the backtest yourself:

https://www.quantconnect.com/terminal/processCache?request=embedded_backtest_dc5ce276507bee4c529be723012f0235.html
Page cover image
Backtesting results
Backtesting metrics