Sub algorithms in Quantconnect LEAN

So it would be nice if LEAN supported multiple algorithms out of the box with a sort of portfolio manager but it doesn’t. So I made my own which works to my purpose.

The idea is to make a SubAlgorithm class:

  public SubAlgorithm(PortfolioAlgorithm mainalgorithm,decimal portfolioPct)
  {
      _mainAlgorithm = mainalgorithm;
      PortfolioPct = portfolioPct;
  }
  public virtual void Initialize()
  {
             
  }
  public virtual void OnData(TradeBars data)
  {
             
  }

You can then make a new sub algorithm deriving from this class, say a ETF rotation algorithm:

  public class ETFRotation_SubAlgorithm: SubAlgorithm
     { 
 
         public ETFRotation_SubAlgorithm(PortfolioAlgorithm mainalgorithm,decimal portfolioPct): base(mainalgorithm,portfolioPct)
         {
 
 
         }
             
 
         public override void Initialize ()
         {
             foreach (var symbol in GrowthSymbols.Union(SafetySymbols))
             {
                 var res = _mainAlgorithm.LiveMode ? Resolution.Minute : Resolution.Daily;
                 if (!_mainAlgorithm.Securities.ContainsKey(symbol))
                     _mainAlgorithm.AddSecurity(SecurityType.Equity, symbol, res);
                 var oneMonthPerformance = _mainAlgorithm.MOM(symbol, 30, Resolution.Daily);
                 var threeMonthPerformance = _mainAlgorithm.MOM(symbol, 90, Resolution.Daily);
                 var sd = new MeanRevertSymbolData {
                     Symbol = symbol,
                     OneMonthPerformance = oneMonthPerformance,
                     ThreeMonthPerformance = threeMonthPerformance,
                     _tradeReturns = AlgoHelper.LoadSymbolReturns (symbol),
                     _lastBuyTime = AlgoHelper.LoadSymbolBuyTime (symbol),
                 };
                 SymbolData.Add(sd);
                 var history = _mainAlgorithm.History(symbol, 90,Resolution.Daily);
                 foreach (var bar in history) {
                     oneMonthPerformance.Update (bar.Time,bar.Close);
                     threeMonthPerformance.Update (bar.Time,bar.Close);
                 }    
                 
             }
         }
         

Our PortfolioAlgorithm is a normal algorithm but contains a list of our sub algorithms

 public class PortfolioAlgorithm: QCAlgorithm
 {
         private readonly List<SubAlgorithm> _subAlgorithms = new List<SubAlgorithm> ();
         public PortfolioAlgorithm ()
         {
             Test1_SubAlgorithm sub = new Test1_SubAlgorithm (this, 0.15m);
             Test2_SubAlgorithm sub2 = new Test2_SubAlgorithm (this, 0.10m);
             Test3_SubAlgorithm sub3 = new Test3_SubAlgorithm (this, 0.30m);
             Test4_SubAlgorithm sub4 = new Test4_SubAlgorithm (this, 0.15m);
             Test5_SubAlgorithm sub5 = new Test5_SubAlgorithm (this, 0.15m);
             Test6_SubAlgorithm sub6 = new Test6_SubAlgorithm (this, 0.10m);
 
             _subAlgorithms.Add (sub);
             _subAlgorithms.Add (sub2);
             _subAlgorithms.Add (sub3);
             _subAlgorithms.Add (sub4);
             _subAlgorithms.Add (sub5);
             _subAlgorithms.Add (sub6);
         }
         public override void Initialize ()
         {
             SetStartDate(2015, 01, 15);  //Set Start Date
             SetEndDate(2015,06, 01);    //Set End Date
             SetCash(100000);             //Set Strategy Cash
 
 
             foreach (var sub in _subAlgorithms) {
                 sub.Initialize ();
             }
          }
         public void OnData(TradeBars data)
         {
             foreach (var sub in _subAlgorithms) {
                 sub.OnData (data);
             }
         } 

 }    

Voila! Now we can add all the sub algorithms we want and it does work both in backtesting and live.

How to optimize the portfolio percentage of each sub algorithm is a good question. Making it dynamic is probably the best.

Currently I am testing this with a mean reversion algorithm, three ETF rotation algorithms, a xiv/vxx algorithm and a buy-and-hold hedge algorithm.

Genetic optimization of trading algorithm

I just commited some code to show how one can optimize a parameter of a trading algorithm to increase the sharpe ratio. The code works with the open source LEAN engine.

https://github.com/chrisdk2015/LeanOptimization

Currently there’s a 40 second delay from running each iteration meaning it can take a long time to run say 10,000 iterations 🙂

But hopefully this can be fixed either in the engine or with some further hacks.

Quantconnect LEAN open source trading engine

I recently found a cool open source project http://lean.quantconnect.com which I started using for a trading algorithm I am making now based on mean reversion – buy low sell high.

For testing purposes I made a rough GTK# client in Mono on Linux and it works really well. Monodevelop has really come a long way since I started using it years ago. Very good debugger.

quantconnect

Anyway, the LEAN engine is very nice and fast. Of course the algorithm you have to make on your own. Profits do not come easily in this game it seems 🙂

Right now I am paper trading live with Interactive Brokers and I find new bugs every day. There are a lot of small things you need to consider, like partial fills, updating non-filled orders, correlations between symbols, market regimes, risk management and position sizing.

However, it is very exciting and I get new ideas on what to build into the program continously.

Market status

Total put-call ratio is 1.04 while EMA120 is 0.98 – which means market is bearish. Historically when total put/call ratio EMA120 was 1.0 corrections of 10-20% or more happened.

http://m.nasdaq.com/article/this-indicator-helped-me-avoid-the-2008-stock-market-crash-cm401724

The momentum in ZIV is going a bit down meaning more volatility. I will probably reduce my holding in ZIV and go for HACK instead.

Both SPY and QQQ are ranging and the action is happening in the sectors instead.

Approx 19% per year with simple buy and hold portfolio

Fred Piard at seekingalpha has written about his thoughts on having a buy-and-hold part of his portfolio even though he considers himself a dynamic investor.

Now for his ALFA-FXG-FXH-PJP part I have created a backtest from 31, May, 2012 using quantopian with yearly rebalancing.

Benchmark (SPY) gives total 69.19% return while the above gives 119.6% return which is approximately 19% per year. Not bad but then again this is in the bullmarket.

Biotech and healthcare have given excellent returns in the last few years and probably will outperform SPY in the future.

This is an easy way to beat SPY with no doing on your part.

Please note that currently as of today the co-direction values of ALFA-FXH, ALFA-PJP are 0.69 and 0.67 respectively meaning we are roughly investing in the same moves up and down. This could however change if the holdings of the ETFs change.

Personally I try to minimize the co-direction values in order to diversify my portfolio.