-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathClenow_StocksOnTheMove.cs
More file actions
327 lines (279 loc) · 13.5 KB
/
Copy pathClenow_StocksOnTheMove.cs
File metadata and controls
327 lines (279 loc) · 13.5 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
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
//==============================================================================
// Project: TuringTrader, algorithms from books & publications
// Name: Clenow_StocksOnTheMove
// Description: Strategy, as published in Andreas F. Clenow's book
// 'Stocks on the Move'.
// http://www.followingthetrend.com/
// History: 2018xii14, 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.
//==============================================================================
// USE_CLENOWS_RANGE
// defined: match simulation range to Clenow's book
// undefined: simulate from 2007 to last week
//#define USE_CLENOWS_RANGE
#region libraries
using System;
using System.Collections.Generic;
using System.Linq;
using TuringTrader.Algorithms.Glue;
using TuringTrader.Indicators;
using TuringTrader.Optimizer;
using TuringTrader.Simulator;
#endregion
namespace TuringTrader.BooksAndPubs
{
public class Clenow_StocksOnTheMove : AlgorithmPlusGlue
{
public override string Name => "Clenow's Stocks on the Move";
#region inputs
/// <summary>
/// length of momentum calculation (in days)
/// </summary>
[OptimizerParam(63, 252, 21)]
public virtual int MOM_PERIOD { get; set; } = 90;
/// <summary>
/// maximum daily move (in percent)
/// </summary>
[OptimizerParam(10, 25, 5)]
public virtual int MAX_MOVE { get; set; } = 15;
/// <summary>
/// length of SMA for instrument trend filter (in days)
/// </summary>
[OptimizerParam(63, 252, 21)]
public virtual int INSTR_TREND { get; set; } = 100;
/// <summary>
/// length of ATR calculation (in days)
/// </summary>
[OptimizerParam(5, 25, 5)]
public virtual int ATR_PERIOD { get; set; } = 20;
/// <summary>
/// length of SMA for index trend filter (in days)
/// </summary>
[OptimizerParam(63, 252, 21)]
public virtual int INDEX_TREND { get; set; } = 200;
/// <summary>
/// length of SMA for index trend filter (in days)
/// </summary>
[OptimizerParam(5, 20, 5)]
public virtual int INDEX_FLT { get; set; } = 10;
/// <summary>
/// percentage of instruments from the top (in %)
/// </summary>
[OptimizerParam(5, 50, 5)]
public virtual int TOP_PCNT { get; set; } = 20;
/// <summary>
/// target risk per stock (in basis points)
/// </summary>
[OptimizerParam(5, 50, 5)]
public virtual int RISK_PER_STOCK { get; set; } = 10;
/// <summary>
/// target risk for portfolio (in basis points)
/// </summary>
public virtual int RISK_TOTAL { get; set; } = 10000;
/// <summary>
/// maximum weight per stock (in percent)
/// </summary>
public virtual int MAX_PER_STOCK { get; set; } = 100;
/// <summary>
/// traded stock universe
/// </summary>
protected virtual Universe UNIVERSE { get; set; } = Universes.STOCKS_US_LG_CAP;
/// <summary>
/// day of weekly rebalancing
/// </summary>
protected virtual bool IsTradingDay
=> SimTime[0].DayOfWeek <= DayOfWeek.Wednesday && NextSimTime.DayOfWeek > DayOfWeek.Wednesday;
/// <summary>
/// supplemental money-management code
/// </summary>
/// <param name="w"></param>
protected virtual void ManageWeights(Dictionary<Instrument, double> w) { }
/// <summary>
/// allow new entries: this covers both new positions, and increasing of existing positions.
/// </summary>
/// <param name="sp500">S&P 500 instrument</param>
/// <returns>true, if new entries are allowed</returns>
protected virtual bool AllowNewEntries(Instrument sp500)
=> sp500.Close.SMA(INDEX_FLT)[0] > sp500.Close.SMA(INDEX_TREND)[0];
#endregion
#region private data
protected virtual string BENCHMARK { get; set; } = Indices.SPXTR;
private readonly string SP500 = "$SPX";
#endregion
#region public override void Run()
public override IEnumerable<Bar> Run(DateTime? startTime, DateTime? endTime)
{
//========== initialization ==========
#if USE_CLENOWS_RANGE
// matching Clenow's charts
StartTime = DateTime.Parse("01/01/1999", CultureInfo.InvariantCulture);
WarmupStartTime = StartTime - TimeSpan.FromDays(180);
EndTime = DateTime.Parse("12/31/2014", CultureInfo.InvariantCulture);
#else
WarmupStartTime = Globals.WARMUP_START_TIME;
StartTime = Globals.START_TIME;
EndTime = Globals.END_TIME;
#endif
Deposit(Globals.INITIAL_CAPITAL);
CommissionPerShare = Globals.COMMISSION; // Clenow is not considering commissions
var all = AddDataSources(UNIVERSE.Constituents);
var sp500 = AddDataSource(SP500);
var benchmark = AddDataSource(BENCHMARK);
//========== simulation loop ==========
double? sp500Initial = null;
// loop through all bars
foreach (DateTime simTime in SimTimes)
{
if (!HasInstrument(benchmark))
continue;
sp500Initial = sp500Initial ?? sp500.Instrument.Open[0];
// calculate indicators exactly once per bar
// we are doing this on all available instruments,
// as we don't know when they will become S&P500 constituents
var indicators = Instruments
.ToDictionary(
i => i,
i => new
{
regression = i.Close.LogRegression(MOM_PERIOD),
maxMove = i.Close.SimpleMomentum(1).AbsValue().Highest(MOM_PERIOD),
avg100 = i.Close.SMA(INSTR_TREND),
atr20 = i.AverageTrueRange(ATR_PERIOD),
}); ;
// index filter: only buy any shares, while S&P-500 is trading above its 200-day moving average
// NOTE: the 10-day SMA on the benchmark is _not_ mentioned in
// the book. We added it here, to compensate for the
// simplified re-balancing schedule.
bool allowNewEntries = AllowNewEntries(sp500.Instrument);
// determine current S&P 500 constituents
var constituents = Instruments
.Where(i => i.IsConstituent(UNIVERSE))
.ToList();
// trade once per week
// this is a slight simplification from Clenow's suggestion to adjust positions
// every week, and adjust position sizes only every other week
if (IsTradingDay)
{
// rank by volatility-adjusted momentum and pick top 20% (top-100)
var topRankedInstruments = constituents
// FIXME: how exactly are we multiplying the regression slope with R2?
.OrderByDescending(i => (Math.Exp(252.0 * indicators[i].regression.Slope[0]) - 1.0) * indicators[i].regression.R2[0])
//.OrderByDescending(i => indicators[i].regression.Slope[0] * indicators[i].regression.R2[0])
.Take((int)Math.Round(TOP_PCNT / 100.0 * constituents.Count))
.ToList();
// disqualify
// - trading below 100-day moving average
// - maximum move > 15%
// FIXME: is maxMove > 1.0???
var availableInstruments = topRankedInstruments
.Where(i => i.Close[0] > indicators[i].avg100[0]
&& indicators[i].maxMove[0] < MAX_MOVE / 100.0)
.ToList();
// allocate capital until we run out of cash
var weights = Instruments
.ToDictionary(
i => i,
i => 0.0);
double availableCapital = 1.0;
int portfolioRisk = 0;
foreach (var i in availableInstruments)
{
// Clenow does not limit the total portfolio risk
if (portfolioRisk > RISK_TOTAL)
continue;
var currentWeight = NetAssetValue[0] > 0
? i.Position * i.Close[0] / NetAssetValue[0]
: 0.0;
var newWeight = Math.Min(Math.Min(availableCapital, MAX_PER_STOCK / 100.0),
RISK_PER_STOCK * 0.0001 / indicators[i].atr20[0] * i.Close[0]);
var w = allowNewEntries
? newWeight
: Math.Min(currentWeight, newWeight);
weights[i] = w;
availableCapital -= w;
portfolioRisk += RISK_PER_STOCK;
}
// perform customized money-management
ManageWeights(weights);
// submit trades
Alloc.Allocation.Clear();
foreach (var i in Instruments)
{
if (weights[i] > 0.005)
Alloc.Allocation[i] = weights[i];
var targetShares = (int)Math.Round(NetAssetValue[0] * weights[i] / i.Close[0]);
i.Trade(targetShares - i.Position, OrderType.openNextBar);
}
#if false
if (!IsOptimizing && (EndTime - SimTime[0]).TotalDays < 30)
{
string message = constituents
.Where(i => weights[i] != 0.0)
.Aggregate(string.Format("{0:MM/dd/yyyy}: ", SimTime[0]),
(prev, i) => prev + string.Format("{0}={1:P2} ", i.Symbol, weights[i]));
Output.WriteLine(message);
}
#endif
}
// create charts
if (!IsOptimizing && TradingDays > 0)
{
_plotter.AddNavAndBenchmark(this, benchmark.Instrument);
_plotter.AddStrategyHoldings(this, constituents);
// plot strategy exposure
_plotter.SelectChart("Strategy Exposure", "Date");
_plotter.SetX(SimTime[0]);
_plotter.Plot("Stock Exposure", constituents.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]);
_plotter.Plot("Number of Stocks", constituents.Where(i => i.Position != 0).Count());
if (Alloc.LastUpdate == SimTime[0])
_plotter.AddTargetAllocationRow(Alloc);
#if true
_plotter.SelectChart("Clenow-style Chart", "Date");
_plotter.SetX(SimTime[0]);
_plotter.Plot(Name, NetAssetValue[0] / Globals.INITIAL_CAPITAL);
_plotter.Plot(sp500.Instrument.Name, sp500.Instrument.Close[0] / sp500Initial);
_plotter.Plot(sp500.Instrument.Name + " 200-day moving average", sp500.Instrument.Close.SMA(200)[0] / sp500Initial);
_plotter.Plot("Cash", Cash / NetAssetValue[0]);
#endif
}
if (IsDataSource)
{
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.AddAverageHoldings(this);
_plotter.AddTargetAllocation(Alloc);
_plotter.AddOrderLog(this);
_plotter.AddPositionLog(this);
_plotter.AddPnLHoldTime(this);
_plotter.AddMfeMae(this);
_plotter.AddParameters(this);
}
FitnessValue = this.CalcFitness();
}
#endregion
}
}
//==============================================================================
// end of file