-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathAlvarez_EtfSectorRotation.cs
More file actions
191 lines (165 loc) · 7.63 KB
/
Copy pathAlvarez_EtfSectorRotation.cs
File metadata and controls
191 lines (165 loc) · 7.63 KB
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
//==============================================================================
// Project: TuringTrader, algorithms from books & publications
// Name: Alvarez_EtfSectorRotation
// Description: Strategy, as published on Cesar Alvarez' blog
// https://alvarezquanttrading.com/blog/etf-sector-rotation/
// History: 2019iii18, EFB, created
//------------------------------------------------------------------------------
// Copyright: (c) 2011-2025, 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.
//==============================================================================
using System;
using System.Linq;
using TuringTrader.Algorithms.Glue;
using TuringTrader.Indicators;
using TuringTrader.Simulator;
namespace TuringTrader.BooksAndPubs
{
public class Alvarez_EtfSectorRotation : Algorithm
{
public override string Name => "ETF Sector Rotation";
private static readonly string[] UNIVERSE =
{
Assets.XLY,
Assets.XLP,
Assets.XLE,
Assets.XLF,
Assets.XLV,
Assets.XLI,
Assets.XLB,
Assets.XLK,
Assets.XLU,
//Assets.STOCKS_US_SECT_COMMUNICATION, // Communication Services
//Assets.STOCKS_US_SECT_REAL_ESTATE, // Real Estate
};
private static readonly string SAFE_INSTRUMENT = Assets.TLT;
private static readonly string BENCHMARK = Indices.SPXTR;
private static readonly int RANK1_DAYS = 252;
private static readonly int RANK2_DAYS = 126;
private Plotter _plotter = new Plotter();
public override void Run()
{
//========== initialization ==========
StartTime = Globals.START_TIME;
EndTime = Globals.END_TIME;
var universe = AddDataSources(UNIVERSE);
var safeInstrument = AddDataSource(SAFE_INSTRUMENT);
var benchmark = AddDataSource(BENCHMARK);
Deposit(Globals.INITIAL_CAPITAL);
CommissionPerShare = Globals.COMMISSION;
//========== simulation loop ==========
foreach (var s in SimTimes)
{
//----- skip until all required instruments are valid
if (!HasInstruments(universe)
|| !HasInstrument(safeInstrument)
|| !HasInstrument(benchmark))
continue;
//----- memorize our momentum
// its good practice to do this, to make sure
// indicators are only evaluated once
var momentum1 = universe
.ToDictionary(
ds => ds.Instrument,
ds => ds.Instrument.Close.Momentum(RANK1_DAYS)[0]);
var momentum2 = universe
.ToDictionary(
ds => ds.Instrument,
ds => ds.Instrument.Close.Momentum(RANK2_DAYS)[0]);
//----- rank universe by momentum
var rank1 = universe
.OrderByDescending(ds => momentum1[ds.Instrument])
.Select((ds, n) => new { instr = ds.Instrument, rank = n, mom = momentum1[ds.Instrument] })
.ToDictionary(
i => i.instr,
i => i);
var rank2 = universe
.OrderByDescending(ds => momentum2[ds.Instrument])
.Select((ds, n) => new { instr = ds.Instrument, rank = n, mom = momentum2[ds.Instrument] })
.ToDictionary(
i => i.instr,
i => i);
var rank3 = universe
.OrderBy(ds => 1.001 * rank1[ds.Instrument].rank + rank2[ds.Instrument].rank) // use rank1 as tie break
.Select((ds, n) => new { instr = ds.Instrument, rank = n, sum = 1.001 * rank1[ds.Instrument].rank + rank2[ds.Instrument].rank })
.ToDictionary(
i => i.instr,
i => i);
//----- select our 2 top ranking instruments
#if true
// this is what Cesar Alvarez seems to be describing
// in his blog post. however, the results are nowhere close
// to what he published.
var top2 = rank3
.OrderBy(i => i.Value.rank)
.Take(2)
.ToDictionary(
i => i.Key,
i => i.Value);
#else
// this is probably what Cesar Alvarez has simulated,
// as the results seem to match those published
// on the blog closely.
// this is chosing the 2 _worst_ ranked sectors,
// making this a mean-reversion strategy
var top2 = rank3
.OrderByDescending(i => i.Value.rank)
.Take(2)
.ToDictionary(
i => i.Key,
i => i.Value);
#endif
//----- assign weights
var weights = universe
.ToDictionary(
ds => ds.Instrument,
ds => top2.ContainsKey(ds.Instrument)
? (ds.Instrument.Close[0] > ds.Instrument.Close[252] ? 0.5 : 0.0)
: 0.0);
weights[safeInstrument.Instrument] = 1.0 - weights.Sum(i => i.Value);
//----- trade instruments
if (SimTime[0].Month != SimTime[1].Month)
{
foreach (var i in weights.Keys)
{
var targetShares = (int)Math.Floor(weights[i] * NetAssetValue[0] / i.Close[0]);
i.Trade(targetShares - i.Position);
}
}
//---- plot output
_plotter.AddNavAndBenchmark(this, benchmark.Instrument);
_plotter.AddStrategyHoldings(this, universe.Select(ds => ds.Instrument));
}
//========== 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();
}
public override void Report()
{
_plotter.OpenWith("SimpleReport");
}
}
}
//==============================================================================
// end of file