/
Antonacci_DualMomentumInvesting.cs
472 lines (434 loc) · 19.4 KB
/
Antonacci_DualMomentumInvesting.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//==============================================================================
// Project: TuringTrader, algorithms from books & publications
// Name: Antonacci_DualMomentumInvesting
// Description: Strategy, as published in Gary Antonacci's book
// 'Dual Momentum Investing'.
// http://www.optimalmomentum.com/
// History: 2018xi22, FUB, created
//------------------------------------------------------------------------------
// Copyright: (c) 2011-2023, Bertram Enterprises LLC dba TuringTrader.
// https://www.turingtrader.org
// License: This file is part of TuringTrader, an open-source backtesting
// engine/ trading simulator.
// TuringTrader is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
// TuringTrader is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public
// License along with TuringTrader. If not, see
// https://www.gnu.org/licenses/agpl-3.0.
//==============================================================================
#region libraries
using System;
using System.Collections.Generic;
using System.Linq;
using TuringTrader.Algorithms.Glue;
using TuringTrader.Indicators;
using TuringTrader.Simulator;
#endregion
namespace TuringTrader.BooksAndPubs
{
// the book is not always conclusive how to really implement these strategies
// additional clarifications can be found here:
// https://www.optimalmomentum.com/faq/
public abstract class Antonacci_DualMomentumInvesting_Core : AlgorithmPlusGlue
{
public override string Name => "Antonacci's Dual Momentum";
#region inputs
protected class AssetClass
{
public double weight = 1.0;
public bool setSafeInstrument = false;
public HashSet<string> assets;
}
/// <summary>
/// hash set of asset classes
/// </summary>
protected abstract HashSet<AssetClass> ASSET_CLASSES { get; }
/// <summary>
/// benchmark to measure absolute momentum
/// </summary>
protected virtual string ABS_MOMENTUM => Assets.BIL; // BIL - 1 to 3-Months U.S. Treasury Bills
/// <summary>
/// safe instrument
/// </summary>
protected virtual string SAFE_INSTR => Assets.AGG; // AGG - Aggregate Bond Market
/// <summary>
/// charting benchmark
/// </summary>
protected virtual string BENCHMARK => Indices.PORTF_60_40; // 60/40 Portfolio
/// <summary>
/// momentum calculation
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
protected virtual double MOMENTUM(Instrument i) => i.Close[0] / i.Close[252] - 1.0;
/// <summary>
/// simulation start time
/// </summary>
protected virtual DateTime START_TIME => Globals.START_TIME;
/// <summary>
/// simulation end time
/// </summary>
protected virtual DateTime END_TIME => Globals.END_TIME;
#endregion
#region public override void Run()
public override IEnumerable<Bar> Run(DateTime? startTime, DateTime? endTime)
{
//========== initialization ==========
StartTime = START_TIME;
EndTime = END_TIME;
WarmupStartTime = StartTime - TimeSpan.FromDays(365);
Deposit(Globals.INITIAL_CAPITAL);
CommissionPerShare = Globals.COMMISSION; // it is unclear, if Antonacci considers commissions
// assets we can trade
List<string> ASSETS = ASSET_CLASSES
.SelectMany(c => c.assets)
.Distinct()
.Where(nick => nick != ABS_MOMENTUM)
.ToList();
ASSETS.Add(SAFE_INSTR);
var assets = AddDataSources(ASSETS);
var safe = AddDataSource(SAFE_INSTR); // we just need the data source
var absMom = AddDataSource(ABS_MOMENTUM);
var benchmark = AddDataSource(BENCHMARK);
double totalWeights = ASSET_CLASSES.Sum(a => a.weight);
//========== simulation loop ==========
foreach (DateTime simTime in SimTimes)
{
// skip if there are any missing instruments
if (!HasInstruments(assets) || !HasInstrument(benchmark) || !HasInstrument(absMom))
continue;
// evaluate momentum for all known instruments
Dictionary<Instrument, double> instrumentMomentum = Instruments
.ToDictionary(i => i, i => MOMENTUM(i));
// execute trades once per month
// CAUTION: do not calculate indicators within this block!
if (SimTime[0].Month != NextSimTime.Month)
{
// create empty structure for instrument weights
Dictionary<Instrument, double> instrumentWeights = Instruments
.ToDictionary(i => i, i => 0.0);
// loop through all asset classes, and find the top-ranked one
Instrument safeInstrument = safe.Instrument;
foreach (AssetClass assetClass in ASSET_CLASSES)
{
// find the instrument with the highest momentum
// in each asset class
var bestInstrument = assetClass.assets
.Select(nick => FindInstrument(nick))
.OrderByDescending(i => instrumentMomentum[i])
.Take(1)
.First();
// sum up the weights (because instrument is duplicated)
instrumentWeights[bestInstrument] += assetClass.weight / totalWeights;
if (assetClass.setSafeInstrument)
safeInstrument = bestInstrument;
}
// if momentum of any instrument drops below that of a T-Bill,
// we use the safe instrument instead
// therefore, we swap T-Bills for the safe instrument:
double pcntTbill = instrumentWeights[absMom.Instrument];
instrumentWeights[absMom.Instrument] = 0.0;
instrumentWeights[safeInstrument] += pcntTbill;
// submit orders
foreach (var ds in assets)
{
Alloc.Allocation[ds.Instrument] = instrumentWeights[ds.Instrument];
int targetShares = (int)Math.Floor(instrumentWeights[ds.Instrument] * NetAssetValue[0] / ds.Instrument.Close[0]);
int currentShares = ds.Instrument.Position;
Order newOrder = ds.Instrument.Trade(targetShares - currentShares);
if (newOrder != null)
{
if (currentShares == 0) newOrder.Comment = "open";
else if (targetShares == 0) newOrder.Comment = "close";
else newOrder.Comment = "rebalance";
}
}
}
// plotter output
if (!IsOptimizing && TradingDays > 0)
{
_plotter.AddNavAndBenchmark(this, benchmark.Instrument);
_plotter.AddStrategyHoldings(this, assets.Select(ds => ds.Instrument));
if (Alloc.LastUpdate == SimTime[0])
_plotter.AddTargetAllocationRow(Alloc);
}
var v = 10.0 * NetAssetValue[0] / Globals.INITIAL_CAPITAL;
yield return Bar.NewOHLC(
this.GetType().Name, SimTime[0],
v, v, v, v, 0);
}
//========== post processing ==========
if (!IsOptimizing)
{
_plotter.AddTargetAllocation(Alloc);
_plotter.AddOrderLog(this);
_plotter.AddPositionLog(this);
_plotter.AddPnLHoldTime(this);
_plotter.AddMfeMae(this);
//_plotter.AddParameters(this);
}
FitnessValue = this.CalcFitness();
}
#endregion
}
#region U.S. Stocks w/ Absolute Momentum
public class Antonacci_USStocksWithAbsoluteMomentum : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Antonacci's U.S. Stocks w/ Absolute Momentum";
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
new AssetClass
{
weight = 1.0,
assets = new HashSet<string> {
Assets.SPY,
ABS_MOMENTUM,
}
},
};
protected override string BENCHMARK => Indices.SPXTR;
}
#endregion
#region Global Equities Momentum
public class Antonacci_GlobalEquitiesMomentum : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Antonacci's Global Equities Momentum";
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
new AssetClass
{
weight = 1.0,
assets = new HashSet<string> {
Assets.SPY,
Assets.ACWX,
ABS_MOMENTUM,
},
},
};
protected override string BENCHMARK => Indices.PORTF_60_40;
}
public class Antonacci_GlobalEquitiesMomentum_p98 : Antonacci_GlobalEquitiesMomentum
{
// on page 98 of his book, Antonacci describes that he tests
// for S&P 500's absolute momentum first, because S&P 500
// is leading world markets.
// this contradicts the flowchart and description on page 101
// this code is the 'absolute momentum first' implementation
public override string Name => "Antonacci's Global Equities Momentum (p98 variant)";
protected override double MOMENTUM(Instrument i)
{
var m = i.Close[0] / i.Close[252] - 1.0;
var spx = FindInstrument(Assets.SPY);
var abs = FindInstrument(ABS_MOMENTUM);
if (i.Nickname == Assets.ACWX
&& MOMENTUM(spx) < MOMENTUM(abs))
{
// if S&P 500 returns are below T-Bill,
// ACWX is forced negative, so that we end
// up in bonds
return -999.9;
}
return m;
}
}
#endregion
#region Global Balanced Momentum
public class Antonacci_GlobalBalancedMomentum : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Antonacci's Global Balanced Momentum";
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
new AssetClass
{
weight = 0.7,
assets = new HashSet<string> {
Assets.SPY,
Assets.ACWX,
ABS_MOMENTUM,
},
},
new AssetClass
{
weight = 0.3,
setSafeInstrument = true, // use this group as safe instrument
assets = new HashSet<string> {
Assets.TLT,
Assets.BWX,
Assets.HYG,
ABS_MOMENTUM,
},
}
};
}
#endregion
#region Parity Portfolio w/ Absolute Momentum
public class Antonacci_ParityPortfolioWithAbsoluteMomentum : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Antonacci's Parity Portfolio w/ Absolute Momentum";
protected override string BENCHMARK => Indices.PORTF_60_40;
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
//--- equity
new AssetClass {
weight = 0.2,
assets = new HashSet<string> {
Assets.SPY,
ABS_MOMENTUM,
},
},
//--- treasury bond
new AssetClass {
weight = 0.2,
assets = new HashSet<string> {
Assets.TLT,
ABS_MOMENTUM,
},
},
//--- reit
new AssetClass {
weight = 0.2,
assets = new HashSet<string> {
Assets.VNQ,
ABS_MOMENTUM,
},
},
//--- credit bonds
new AssetClass {
weight = 0.2,
assets = new HashSet<string> {
Assets.IGIB,
ABS_MOMENTUM,
},
},
//--- gold
new AssetClass {
weight = 0.2,
assets = new HashSet<string> {
Assets.GLD,
ABS_MOMENTUM,
},
},
};
}
#endregion
#region Dual Momentum Sector Rotation
public class Antonacci_DualMomentumSectorRotation : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Antonacci's Dual Momentum Sector Rotation";
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
new AssetClass { assets = new HashSet<string> { Assets.XLB, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLC, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLE, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLF, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLI, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLK, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLP, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLRE, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLU, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLV, ABS_MOMENTUM } },
new AssetClass { assets = new HashSet<string> { Assets.XLY, ABS_MOMENTUM } },
};
protected override string BENCHMARK => Indices.SPXTR;
}
#endregion
#region Dual Momentum w/ 4 asset pairs - as seen on Scott's Investments
// see also:
// https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2042750
// https://allocatesmartly.com/antonaccis-composite-dual-momentum/
// Equities: SPY/ EFA
// Credit risk: LQD/ HYG
// Real estate: VNQ/ REM
// Economic stress: GLD/ TLT
// safe instrument: BIL
public class Antonacci_4PairsDualMomentum : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Antonacci's Dual Momentum w/ 4 Pairs";
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
//--- equity
new AssetClass {
weight = 0.25,
assets = new HashSet<string> {
Assets.SPY,
Assets.ACWX,
ABS_MOMENTUM,
},
},
//--- credit
new AssetClass {
weight = 0.25,
assets = new HashSet<string> {
Assets.HYG,
Assets.IGIB,
ABS_MOMENTUM,
},
},
//--- real estate
new AssetClass {
weight = 0.25,
assets = new HashSet<string> {
Assets.VNQ,
Assets.REM,
ABS_MOMENTUM,
},
},
//--- economic stress
new AssetClass {
weight = 0.25,
assets = new HashSet<string> {
Assets.GLD,
Assets.TLT,
ABS_MOMENTUM,
},
},
};
}
#endregion
#region Accelerating Dual Momentum - as seen on www.EngineeredPortfolio.com
// post: https://engineeredportfolio.com/2018/05/02/accelerating-dual-momentum-investing/
// code by author here: https://www.quantopian.com/posts/accelerating-dual-momentum-150-year-backtest
// simulation: https://www.portfoliovisualizer.com/test-market-timing-model?s=y&coreSatellite=false&timingModel=6&startYear=1985&endYear=2018&initialAmount=10000&symbols=VFINX+VINEX&singleAbsoluteMomentum=false&volatilityTarget=9.0&downsideVolatility=false&outOfMarketAssetType=2&outOfMarketAsset=VUSTX&movingAverageSignal=1&movingAverageType=1&multipleTimingPeriods=true&periodWeighting=2&windowSize=1&windowSizeInDays=105&movingAverageType2=1&windowSize2=10&windowSizeInDays2=105&volatilityWindowSize=0&volatilityWindowSizeInDays=0&assetsToHold=1&allocationWeights=1&riskControl=false&riskWindowSize=10&riskWindowSizeInDays=0&rebalancePeriod=1&separateSignalAsset=false&tradeExecution=0&benchmark=VFINX&timingPeriods[0]=1&timingUnits[0]=2&timingWeights[0]=33&timingPeriods[1]=3&timingUnits[1]=2&timingWeights[1]=33&timingPeriods[2]=6&timingUnits[2]=2&timingWeights[2]=34&timingUnits[3]=2&timingWeights[3]=0&timingUnits[4]=2&timingWeights[4]=0&volatilityPeriodUnit=2&volatilityPeriodWeight=0
public class EngineeredPortfolio_AcceleratingDualMomentum : Antonacci_DualMomentumInvesting_Core
{
public override string Name => "Engineered Portfolio's Accelerating Dual Momentum";
//protected override DateTime START_TIME => DateTime.Parse("01/01/1990");
protected override HashSet<AssetClass> ASSET_CLASSES => new HashSet<AssetClass>
{
new AssetClass
{
weight = 1.0,
assets = new HashSet<string> {
Assets.SPY,
Assets.VSS,
ABS_MOMENTUM,
},
},
};
// the instrument for absolute momentum is just a dummy,
// MOMENTUM() will always return zero for this
protected override string ABS_MOMENTUM => Assets.BIL;
protected override string SAFE_INSTR => Assets.VGLT;
//protected override string BENCHMARK => "yahoo:VFINX";
//protected override string BENCHMARK => "$SPXTR";
//protected override string BENCHMARK => "$SPX";
protected override double MOMENTUM(Instrument i)
{
if (i.Nickname == ABS_MOMENTUM)
return 0.0;
var m1 = i.Close[0] / i.Close[21] - 1.0;
var m3 = i.Close[0] / i.Close[63] - 1.0;
var m6 = i.Close[0] / i.Close[126] - 1.0;
return m1 + m3 + m6;
}
}
#endregion
}
//==============================================================================
// end of file