Build a Diversified Portfolio With QuantAnalyzer

Jan 28, 2021

The ability to efficiently trade a diversified portfolio of strategies is one of the biggest advantages of algorithmic trading. Here we will use QuantAnalyzer’s Portfolio Master to build a portfolio consisting of high performing, uncorrelated strategies.

Unlike strategy development, information on portfolio composition seems to be relatively scarce.

As if individual strategy development wasn’t difficult enough, you now need to figure out how to combine those strategies into a portfolio. Is there an easy way to do it?

Before diving into that, let’s quickly recap why portfolio trading can be beneficial.

Why Diversified Portfolio Trading?

Building a diversified portfolio lets you enjoy higher risk-adjusted returns. By spreading your eggs across multiple baskets, you will also adapt better to changing market conditions and have shorter periods of stagnation.

The key to diversifying your portfolio is to select strategies that are uncorrelated. Uncorrelated strategies do not win/lose money at the same time.

I’ll illustrate this with a simple case study.

EURUSD + GBPUSD Portfolio

I have a simple 2-strategy portfolio, consisting of a M30 EURUSD and a M30 GBPUSD strategy. To check their correlations, I first construct a correlation matrix in QuantAnalyzer.

The correlation coefficient displayed in the matrix above indicates the level of correlation between the strategies. It ranges from -1 to +1. A value of -0.02 above means the strategies are practically uncorrelated, so let’s proceed to combine them in the portfolio.

 

The portfolio equity curve is created by combining the trading results from the individual strategies.

Looking at the metrics, the portfolio’s return/drawdown is higher, and its stagnation lower, than either of its two strategies alone. Why?

The returns from your individual strategies are additive, meaning you simply add them up to get your total portfolio return.

With a diversified portfolio, however, your strategy drawdowns are not additive. Your portfolio drawdown should be less than the sum of drawdown from your individual strategies.

The net result is that trading a diversified portfolio gives you much higher risk-adjusted returns than trading any strategy in isolation.

The reduction in stagnation for your portfolio can be a big deal, especially if you trade for income.

The GBPUSD strategy, in isolation, had a dreadful 1297-day stagnation. But thanks to the EURUSD performing well during that period, the overall portfolio stagnation dropped to only 648 days.

What’s Difficult About Building a Diversified Portfolio?

The strategies you select for your portfolio should concurrently satisfy these two conditions:

  • Have the highest performance, as measured by your favourite metric
  • Have low correlations with other strategies in the portfolio

The challenge is that portfolio performance and correlations are interrelated. Suppose you wanted to build a 5-strategy portfolio manually. The process would probably look something like this:

From your initial pool of eligible strategies, you first shortlist the 5 top-performing strategies (Strategies A-E).

You realize that strategy E is highly correlated with A and B. So you remove strategy E and replace it with a slightly lower performing strategy, F.

But now you realize the new strategy F is correlated with C and D.

If you are building a large portfolio manually, it becomes very difficult to select strategies that are both high performing and uncorrelated.

If your strategy pool contains a good mix of trend and countertrend strategies, or strategies across a range of timeframes, you will probably have fewer issues with correlations.

But what if you’re a die-hard trend trader? I know of many retail traders who only trade trend strategies on the higher timeframes, partly because such strategies typically require less monitoring. You could have serious correlation issues in that case.

Fortunately, QuantAnalyzer has solved this problem for us.

Building a Diversified Portfolio With QuantAnalyzer

QuantAnalyzer has a really handy Portfolio Master module that helps build high performing diversified portfolios.

You just need to load your pool of strategies and input your portfolio constraints, and the Portfolio Master will do the number crunching for you.

The rest of this post will show you how to use the Portfolio Master.

We’ll start with strategies from four 30-minute markets – EURUSD, GBPUSD, USDJPY and GBPJPY. There will be 10 trend following strategies for each market, giving a total of 40 strategies in the pool. These strategies were developed over 17 years, from August 2003 to December 2020.

I want the final portfolio to contain 8 strategies, with a maximum of 2 from each market.

1. Access the QuantAnalyzer Portfolio Master module

Let’s open QuantAnalyzer and select Portfolio Master on the left bar.

2. Load Your Pool of Strategies

Now we need to load all the strategies in our pool.

Select Load report at the top bar.

Here I will be loading strategies generated using StrategyQuant’s (QuantAnalyzer’s big brother) genetic builder. If you developed your strategy using MT4 instead, you can upload your MT4 backtest report.

The loaded strategies will appear under the Simple strategies tab at the bottom of the screen.

3. Select Final Portfolio Size

Before deciding whether to compute the portfolios using brute force or genetic evolution, let’s specify how many strategies the final portfolio should contain.  This will help us gauge the computation time required.

  1. Since we want to use all the 40 loaded strategies, select all of them under the Simple strategies tab.
  2. Here we specify the minimum and maximum portfolio size. For this example, I want the final portfolio to have exactly 8 strategies, so I set both the minimum and maximum to 8.
  3. The best portfolios, as determined by the ranking function to be specified later, will be stored in the databank. Here I only want the best 20 portfolios to be stored. If a better portfolio is computed after the limit of 20 is reached, it will replace one of the existing 20.

When selecting the minimum and maximum portfolio size, do note that the number of possible portfolio combinations can increase really quickly. For example, if I increase the maximum portfolio size from 8 to 12 strategies, the number of combinations increases from 76 million to 9 billion!

4. Select the Computation Method

Here we have two choices – Brute force and Genetic search.

If you select brute force, Portfolio Master will simply iterate through every possible portfolio combination. This means you will arrive at the best possible combination, but be prepared for long computation times.

Alternatively, if you are a prolific developer with a huge pool of strategies, you may wish to genetically search for portfolio solutions. Genetic algorithms mimic the evolutionary process to efficiently search for optimal solutions.

In fact, one of StrategyQuant’s cool features is its genetic algorithm that automatically generates profitable strategies.

If you’re interested, I explain how genetic algorithms work here.

Using the genetic search is recommended, or even required, if you have a huge number of possible portfolio combinations. However, since genetic algorithms operate on probabilities, it is not guaranteed that you will obtain the optimal solution.

If you select the genetic search, you will have the following options to choose from:

I recommend choosing Set recommended values. QuantAnalyzer will prefill everything for you.

  1. The Population size and Generations are key genetic evolution parameters. QuantAnalyzer will help you select appropriate values based on the number of strategies in your pool.
  2. The Out of sample (OOS) option lets you reserve some data to test for curve fitting. With the 30% OOS selected above, only 70% of the 17 years will be used by the genetic algorithm for portfolio building. The remaining 30% will be used to verify that the portfolio still performs well using previously unseen data. Later under Filtering, we will apply a profit factor filter to this 30% OOS portion.
  3. Since genetic algorithms operate on probabilities, there is a small chance that successive evolutions fail to lead to improved portfolios. The evolution will restart if this happens.
  4. If you use the recommended values, the genetic evolution will restart automatically once the number of generations is reached. This means you will need to manually stop the algorithm.

So should you select brute force or genetic search?

I’ll provide the following reference to help you decide.

With the 76 million combinations above, the brute force method took me 69 minutes (on an average desktop) to compute.

On the other hand, after running the genetic search for only 10 minutes, 6 of the 10 best portfolios obtained from the brute force method had already appeared in my databank.

This shows the amazing efficiency of the genetic algorithm, considering that we had over 76 million combinations!

In this case, either computation method will suffice, but we will use the genetic search to illustrate Portfolio Master’s full capabilities.

5. Choose Your Ranking Function

QuantAnalyzer provides a few ranking functions.

The Return/Drawdown ratio is a decent choice for a simple risk-adjusted metric, so let’s go with that.

6. Limit Your Market Exposure

Black swan events could be around the corner, and spreading our trades across different markets can offer some level of protection.

The Sectors selection option helps prevent excessive exposure to any one market, or group of markets.

If you trade futures, you can limit the number of strategies per group (energies, meats, indices etc.). For our case, we want the final portfolio to contain a maximum of 2 strategies per currency pair.

To make use of the Sectors selection option, we need to add a Note column to the strategy databank, and type in a unique identifier for each market.

In this case, the identifier is simply the market being traded. If you instead to limit exposure to each currency (not currency pair), you can use the currency itself as the identifier. For example, both GBPUSD and GBPJPY would have ‘GBP’ as the identifier.

If you don’t see the Note column, head over to the top right corner of the databank and change the view to Default with Note.

Alternatively, you can click Manage and add the Note column to your databank view.

Finally, we need to specify that we want a maximum of 2 strategies per market.

If a computed portfolio violates the above condition, you will see the More strategies from the same sector than allowed message in the log:

7. Limit Strategy Correlations

The Correlation Settings are at the core of building a diversified portfolio. Click on the Settings button to configure the settings.

  1. This is the maximum allowable correlation between any two strategies in the portfolio. I consider coefficients of 0.4 or more to indicate significant correlation, so I’ll use that. If you are building a larger portfolio, you may wish to use a slightly larger value here, since having a few moderately correlated strategies in a large portfolio is unlikely to be a problem.
  2. This is the strategy metric that will be used to measure correlations. I always use the Profit/Loss over a certain time period, since this is what ultimately determines your bottom line.
  3. This is the time period over which the profits/losses will be measured. Your trading frequency should be taken into account when selecting your time period. Since our pool consists of M30 trend following strategies, I’ll measure the profits/losses on a weekly basis. If you trade very short-term strategies, hour or day would be more appropriate.
  4. This affects only the appearance of the correlation matrix (which we will check later), so don’t worry about it. If you leave Allow negative correlation unchecked, large negative correlations will be coloured red. Generally you don’t want your correlations to be too negative since your strategies’ performance would cancel out.
  5. When you compare strategies that were developed over different historical periods, there will be periods when one or more strategies has zero trades. If you check Add empty periods, a ‘0’ correlation value will be assigned to the period with no trades. If unchecked, these empty periods will be ignored. Since all the strategies in the pool were developed over the same 17-year period, this option is not relevant, so let’s leave it unchecked.

8. Select Data Range

This option lets you limit the date range over which the portfolio is computed. This can be useful if you have strategies that start and stop trading at different times. Once again, this does not apply to our case, so I’ll select Full available.

9. Set Portfolio Filtering Conditions

This is where we set the benchmarks that the portfolios will have to meet. I usually specify performance filters when generating the individual strategies, so I’ll only add a profit factor ≥ 1.5 condition to the portfolio. Profit factor is your gross profits divided by your gross losses.

  1. From the dropdown menu, select Profit factor.
  2. Since the profit factor does not contain units, the PL Type is not relevant. But if you use another filtering condition such as drawdown, your choice here depends on whether you implemented variable position sizing in your strategy development. If your position sizing varied as a function of account equity, choose %. If you developed with fixed lots, choose $.
  3. Remember when discussing the portfolio computation method above, we allocated 30% of the data for out-of-sample testing? We will now apply the profit factor condition to that data segment, so let’s select Out Of Sample.
  4. Finally, input the < 1.5 condition for the profit factor. Note that we’re selecting which portfolios to dismiss, hence the “<” operator. Lastly, don’t forget to check the Use box!

That’s it! Click Compute portfolios and watch Portfolio Master do its thing.

Portfolio Computation Results

I let Portfolio Master run for 15 minutes. If you’re using the genetic search and selected Run continually under the genetic settings, you will need to stop the computation manually.

The top 20 portfolio results are now in the databank.

Let’s select the best portfolio and examine the results.

Portfolio Performance

Each currency pair is represented twice in the 8-strategy portfolio, so the sectors selection feature has worked well.

Portfolio stagnation is 247 days, which is not too bad over a 17-year period. I find that building a diversified portfolio is a great way to reduce overall stagnation. Trying to reduce stagnation on an individual strategy level can easily lead to overfitting.

To inspect the out-of-sample segment of the portfolio, select Portfolio only at the top left. The 30% out-of-sample segment we selected earlier is now highlighted in blue. It seems to perform as well as the in-sample segment, which gives us confidence that the portfolio was not curve fit.

If you want to look at the performance of the individual strategies in the portfolio, head over to the Overview tab and select the SQ with Portfolio template.

Portfolio Correlations

Finally, we have to run the correlation checks. Select the Portfolio correlation tab and input the same correlation settings as above. Then click Compute.

A sea of green cells is always pleasant. The highest correlation between any two strategies is only 0.31, so there’s a good chance our portfolio is well diversified.

Correlations do shift over time, however. The correlations above were computed over the entire 17-year history. Over that period, there may have been shorter periods of time when the strategies were more correlated.

During financial crises, there is usually a mass exodus towards safe haven assets, and prevailing correlations are likely to break down.

If you are concerned about how correlations may have shifted, you can recompute the matrix above using a more recent historical period.

Wrapping Up

Turns out building a diversified portfolio isn’t that difficult after all. QuantAnalyzer’s Portfolio Master will do the heavy lifting for you; specifying your ranking function and portfolio constraints is all that’s required.

Knowledge of intermarket relationships and your personal trading preferences will help you select optimal portfolio constraints.

Before trading your portfolio, you need to ensure your drawdowns are acceptable. If drawdowns are too high, you can either alter your individual strategy position sizing, or select different strategies for your portfolio. Using drawdown as a portfolio filter will be a good idea in this case.

If you like what you see above, and would like to give QuantAnalyzer a shot, you can use coupon TACT-QA to get 20% off QuantAnalyzer Pro!

If you’re still unsure, you can try out QuantAnalyzer’s FREE version. You can only build a 4-strategy portfolio in the free version, but the Portfolio Master’s capabilities are otherwise similar.

Happy portfolio building!

Powered By

Development Platform

Forex VPS

FXVM Forex VPS

Popular Posts

Laguerre RSI Trend Following Strategy

The Laguerre RSI attempts to improve the responsiveness of the regular RSI, whilst keeping whipsaw trades to a minimum. Let’s see how well it detects short-term pullbacks for a trend following strategy!

read more

What is Fixed Ratio Money Management?

Have you heard of fixed ratio money management? How does it compare to the popular fixed fractional approach? Here I’ll explain how fixed ratio works, and see how it stacks up against fixed fractional money management.

read more

What Is the QQE Indicator?

The QQE is a mysterious indicator that sometimes pops up in trading forums. Does it deserve a place alongside the more traditional momentum indicators like the RSI and CCI? Let’s add it to a trend following strategy to find out!

read more

Make your money work for you!

Get promotions, trading ideas and strategy development tips delivered to your inbox!

Comments

2 Comments

  1. Astral

    Superior article, thank you very much for it!

    My question: if we want to compute different strategies from different symbols (so more than from one pair) and these was build from different starting date (depending of possible backtest data for each) – what would be good idea to:
    – select “Add empty periods” to Correlation settings and use full available data range
    – or to not select this and instead set starting point date manually as date that was for sure possible already for every pair?

    Reply
    • Wayne

      Hi Astral, my preference would be your second option, meaning your date range will be limited to the shortest date range among all the symbols in consideration.

      I don’t think it’s wise to assume a 0 correlation for the empty periods, unless your strategies and/or markets are very different.

      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Trading Strategies

What’s the Best Time to Trade Forex?

What’s the Best Time to Trade Forex?

The forex markets are open 24/5, but not all hours are created equal. Here I dissect my broker data to determine the best time to trade forex.

Forex Weekend Gaps: Can You Exploit Them?

Forex Weekend Gaps: Can You Exploit Them?

Have you noticed that forex weekend gaps usually reverse within 3 days? Here I’ll program a mean reversion strategy to exploit gaps over the last 18 years!

Money Flow Index: An Improved RSI?

Money Flow Index: An Improved RSI?

The Money Flow Index is sometimes called the volume-weighted RSI. Can it outperform the RSI in this trend following strategy?

Automated Bollinger Bands Squeeze Forex Strategy

Automated Bollinger Bands Squeeze Forex Strategy

StrategyQuant’s BBWR indicator is the perfect tool to detect a Bollinger Bands squeeze. Here I explain how it’s calculated, and use it to program a breakout strategy for the AUDJPY!

Should You Use the Kelly Criterion for Forex Trading?

Should You Use the Kelly Criterion for Forex Trading?

The Kelly criterion is a famous mathematical formula that attempts to maximize your long-term capital growth. In this post, I’ll apply it to a EURUSD breakout strategy and explain some of its potential shortcomings when applied to forex trading.

Can a Trading Pause Improve Your Trend Following Results?

Can a Trading Pause Improve Your Trend Following Results?

A temporary trading pause can improve your win rate if you’re trend following a volatile market. Here I’ll program a trading pause into a simple breakout strategy, and test its effectiveness on the Widow Maker – the GBPJPY.

Laguerre RSI Trend Following Strategy

Laguerre RSI Trend Following Strategy

The Laguerre RSI attempts to improve the responsiveness of the regular RSI, whilst keeping whipsaw trades to a minimum. Let’s see how well it detects short-term pullbacks for a trend following strategy!

How to Use the Supertrend Indicator

How to Use the Supertrend Indicator

Despite its cool name, the Supertrend indicator often seems to slip under the radar. Here I explain how it’s calculated, and combine it with moving averages to produce a simple trend following strategy.

Strategy Development

Do You Know Your System Quality Number?

Do You Know Your System Quality Number?

The System Quality Number measures the profitability & consistency of your trading system. Here’s how to calculate your SQN and use it to improve your trading!

How to Get a Realistic Backtest Spread

How to Get a Realistic Backtest Spread

Your choice of backtest spread can certainly make or break a strategy. This post will show you how to study the intraday spread variations of your market, and suggest several ways to avoid paying ridiculous spreads.

Do You Know Your Strategy’s Optimization Profile?

Do You Know Your Strategy’s Optimization Profile?

Your strategy’s optimization profile often reveals its robustness, helping you select strategies that will remain profitable in live trading. Here I explain why an optimization profile is important, and how you can easily obtain one using StrategyQuant’s optimizer.

Which MT4 Backtest Report Metrics Should You Use?

Which MT4 Backtest Report Metrics Should You Use?

Understanding your backtest report is an essential part of being a successful strategy developer. Here I explain what the numbers mean, and how you can make use of each metric during strategy development.

Out-of-sample Testing Using Monte Carlo Simulations

Out-of-sample Testing Using Monte Carlo Simulations

Traders often use Monte Carlo simulations to estimate worst-case drawdowns, but did you know they can be used for out-of-sample testing too? This post demonstrates the use of StrategyQuant’s Monte Carlo simulator to randomize historical prices and strategy parameters, helping you select robust strategies for live trading.

How Many Trades Should Your Backtest Have?

How Many Trades Should Your Backtest Have?

We all want a large sample of trades in our backtests, but practical limitations such as data availability often get in the way. Here I’ll explain why 30 trades is insufficient, and how you can use standard error to quantify the uncertainty arising from a small sample size.

Strategy Optimization Using MT4

Strategy Optimization Using MT4

How do you improve your trading strategy in MT4? This post will show you how to optimize the entry and exit parameters for a moving average crossover strategy. Finally, an intraday time filter will be added to help avoid false breakouts.

Debugging & Backtesting Using MT4

Debugging & Backtesting Using MT4

With a fresh algorithm at your fingertips, how do you verify that it has been programmed correctly? This guide will show you how to use Metatrader 4’s visual backtester to debug and backtest your strategy.

Create Your Trading Algorithm in 15 Minutes (FREE)

Create Your Trading Algorithm in 15 Minutes (FREE)

Converting your trading idea into an algorithm is the first step towards reaping the benefits of automated trading. This guide will cover the creation of a simple moving average crossover algorithm, without any actual programming.

What Is Drawdown in Trading?

What Is Drawdown in Trading?

Are you getting a comprehensive assessment of your strategy’s downside? This post will discuss several methods to measure drawdowns, helping you build and select strategies that better suit your risk appetite.

How to Select the Best Trading Strategy Entry

How to Select the Best Trading Strategy Entry

With an abundance of technical indicators available, selecting your strategy’s entry conditions can be overwhelming. This post will illustrate a method to graphically compare the profitability of different entries.

Live Trading

What’s the Best Time to Trade Forex?

What’s the Best Time to Trade Forex?

The forex markets are open 24/5, but not all hours are created equal. Here I dissect my broker data to determine the best time to trade forex.

How to Find a Real Trading Guru

How to Find a Real Trading Guru

Every day I come across a trading guru offering educational content on the internet. Many of them speak of huge returns with minimal effort. Should these be trusted? Here’s some tips on how to separate the wheat from the chaff.

How to Enjoy Stress-Free Trading

How to Enjoy Stress-Free Trading

Trading is a great way to make some additional income, but not if you’re constantly pulling your hair out. Here I offer 7 tips to help make your trading profitable and stress-free.

How to Select the Best Forex VPS

How to Select the Best Forex VPS

A virtual private server (VPS) is a virtual computer that you can rent and access remotely. It provides a reliable platform on which to execute your forex strategies. This post will help you decide whether you need a VPS, and show you how to select an optimal VPS.

Make your money work for you!

Make your money work for you!

 

Get trading ideas and strategy development tips delivered to your inbox!

Thanks for subscribing!

Pin It on Pinterest

Share This