Repository navigation
Expand file tree
/
Copy pathTradeStatistics.cs
More file actions
443 lines (364 loc) · 19 KB
/
Copy pathTradeStatistics.cs
File metadata and controls
443 lines (364 loc) · 19 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
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
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using QuantConnect.Util;
namespace QuantConnect.Statistics
{
/// <summary>
/// The <see cref="TradeStatistics"/> class represents a set of statistics calculated from a list of closed trades
/// </summary>
public class TradeStatistics
{
/// <summary>
/// The entry date/time of the first trade
/// </summary>
public DateTime? StartDateTime { get; set; }
/// <summary>
/// The exit date/time of the last trade
/// </summary>
public DateTime? EndDateTime { get; set; }
/// <summary>
/// The total number of trades
/// </summary>
public int TotalNumberOfTrades { get; set; }
/// <summary>
/// The total number of winning trades
/// </summary>
public int NumberOfWinningTrades { get; set; }
/// <summary>
/// The total number of losing trades
/// </summary>
public int NumberOfLosingTrades { get; set; }
/// <summary>
/// The total profit/loss for all trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal TotalProfitLoss { get; set; }
/// <summary>
/// The total profit for all winning trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal TotalProfit { get; set; }
/// <summary>
/// The total loss for all losing trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal TotalLoss { get; set; }
/// <summary>
/// The largest profit in a single trade (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal LargestProfit { get; set; }
/// <summary>
/// The largest loss in a single trade (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal LargestLoss { get; set; }
/// <summary>
/// The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal AverageProfitLoss { get; set; }
/// <summary>
/// The average profit for all winning trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal AverageProfit { get; set; }
/// <summary>
/// The average loss for all winning trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal AverageLoss { get; set; }
/// <summary>
/// The average duration for all trades
/// </summary>
public TimeSpan AverageTradeDuration { get; set; }
/// <summary>
/// The average duration for all winning trades
/// </summary>
public TimeSpan AverageWinningTradeDuration { get; set; }
/// <summary>
/// The average duration for all losing trades
/// </summary>
public TimeSpan AverageLosingTradeDuration { get; set; }
/// <summary>
/// The median duration for all trades
/// </summary>
public TimeSpan MedianTradeDuration { get; set; }
/// <summary>
/// The median duration for all winning trades
/// </summary>
public TimeSpan MedianWinningTradeDuration { get; set; }
/// <summary>
/// The median duration for all losing trades
/// </summary>
public TimeSpan MedianLosingTradeDuration { get; set; }
/// <summary>
/// The maximum number of consecutive winning trades
/// </summary>
public int MaxConsecutiveWinningTrades { get; set; }
/// <summary>
/// The maximum number of consecutive losing trades
/// </summary>
public int MaxConsecutiveLosingTrades { get; set; }
/// <summary>
/// The ratio of the average profit per trade to the average loss per trade
/// </summary>
/// <remarks>If the average loss is zero, ProfitLossRatio is set to 0</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal ProfitLossRatio { get; set; }
/// <summary>
/// The ratio of the number of winning trades to the number of losing trades
/// </summary>
/// <remarks>If the total number of trades is zero, WinLossRatio is set to zero</remarks>
/// <remarks>If the number of losing trades is zero and the number of winning trades is nonzero, WinLossRatio is set to 10</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal WinLossRatio { get; set; }
/// <summary>
/// The ratio of the number of trades with positive profit loss to the total number of trades
/// </summary>
/// <remarks>If the total number of trades is zero, WinRate is set to zero</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal WinRate { get; set; }
/// <summary>
/// The ratio of the number of trades with zero or negative profit loss to the total number of trades
/// </summary>
/// <remarks>If the total number of trades is zero, LossRate is set to zero</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal LossRate { get; set; }
/// <summary>
/// The average Maximum Adverse Excursion for all trades
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal AverageMAE { get; set; }
/// <summary>
/// The average Maximum Favorable Excursion for all trades
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal AverageMFE { get; set; }
/// <summary>
/// The largest Maximum Adverse Excursion in a single trade (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal LargestMAE { get; set; }
/// <summary>
/// The largest Maximum Favorable Excursion in a single trade (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal LargestMFE { get; set; }
/// <summary>
/// The maximum closed-trade drawdown for all trades (as symbol currency)
/// </summary>
/// <remarks>The calculation only takes into account the profit/loss of each trade</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal MaximumClosedTradeDrawdown { get; set; }
/// <summary>
/// The maximum intra-trade drawdown for all trades (as symbol currency)
/// </summary>
/// <remarks>The calculation takes into account MAE and MFE of each trade</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal MaximumIntraTradeDrawdown { get; set; }
/// <summary>
/// The standard deviation of the profits/losses for all trades (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal ProfitLossStandardDeviation { get; set; }
/// <summary>
/// The downside deviation of the profits/losses for all trades (as symbol currency)
/// </summary>
/// <remarks>This metric only considers deviations of losing trades</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal ProfitLossDownsideDeviation { get; set; }
/// <summary>
/// The ratio of the total profit to the total loss
/// </summary>
/// <remarks>If the total profit is zero, ProfitFactor is set to zero</remarks>
/// <remarks>if the total loss is zero and the total profit is nonzero, ProfitFactor is set to 10</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal ProfitFactor { get; set; }
/// <summary>
/// The ratio of the average profit/loss to the standard deviation
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal SharpeRatio { get; set; }
/// <summary>
/// The ratio of the average profit/loss to the downside deviation
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal SortinoRatio { get; set; }
/// <summary>
/// The ratio of the total profit/loss to the maximum closed trade drawdown
/// </summary>
/// <remarks>If the total profit/loss is zero, ProfitToMaxDrawdownRatio is set to zero</remarks>
/// <remarks>if the drawdown is zero and the total profit is nonzero, ProfitToMaxDrawdownRatio is set to 10</remarks>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal ProfitToMaxDrawdownRatio { get; set; }
/// <summary>
/// The maximum amount of profit given back by a single trade before exit (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal MaximumEndTradeDrawdown { get; set; }
/// <summary>
/// The average amount of profit given back by all trades before exit (as symbol currency)
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal AverageEndTradeDrawdown { get; set; }
/// <summary>
/// The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks)
/// </summary>
public TimeSpan MaximumDrawdownDuration { get; set; }
/// <summary>
/// The sum of fees for all trades
/// </summary>
[JsonConverter(typeof(JsonRoundingConverter))]
public decimal TotalFees { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TradeStatistics"/> class
/// </summary>
/// <param name="trades">The list of closed trades</param>
public TradeStatistics(IEnumerable<Trade> trades)
{
var maxConsecutiveWinners = 0;
var maxConsecutiveLosers = 0;
var maxTotalProfitLoss = 0m;
var maxTotalProfitLossWithMfe = 0m;
var sumForVariance = 0m;
var sumForDownsideVariance = 0m;
var lastPeakTime = DateTime.MinValue;
var isInDrawdown = false;
var allTradeDurationsTicks = new List<long>();
var winningTradeDurationsTicks = new List<long>();
var losingTradeDurationsTicks = new List<long>();
var numberOfITMOptionsWinningTrades = 0;
foreach (var trade in trades)
{
if (lastPeakTime == DateTime.MinValue) lastPeakTime = trade.EntryTime;
if (StartDateTime == null || trade.EntryTime < StartDateTime)
StartDateTime = trade.EntryTime;
if (EndDateTime == null || trade.ExitTime > EndDateTime)
EndDateTime = trade.ExitTime;
TotalNumberOfTrades++;
if (TotalProfitLoss + trade.MFE > maxTotalProfitLossWithMfe)
maxTotalProfitLossWithMfe = TotalProfitLoss + trade.MFE;
if (TotalProfitLoss + trade.MAE - maxTotalProfitLossWithMfe < MaximumIntraTradeDrawdown)
MaximumIntraTradeDrawdown = TotalProfitLoss + trade.MAE - maxTotalProfitLossWithMfe;
if (trade.ProfitLoss > 0)
{
// winning trade
NumberOfWinningTrades++;
TotalProfitLoss += trade.ProfitLoss;
TotalProfit += trade.ProfitLoss;
AverageProfit += (trade.ProfitLoss - AverageProfit) / NumberOfWinningTrades;
AverageWinningTradeDuration += TimeSpan.FromSeconds((trade.Duration.TotalSeconds - AverageWinningTradeDuration.TotalSeconds) / NumberOfWinningTrades);
winningTradeDurationsTicks.Add(trade.Duration.Ticks);
if (trade.ProfitLoss > LargestProfit)
LargestProfit = trade.ProfitLoss;
maxConsecutiveWinners++;
maxConsecutiveLosers = 0;
if (maxConsecutiveWinners > MaxConsecutiveWinningTrades)
MaxConsecutiveWinningTrades = maxConsecutiveWinners;
if (TotalProfitLoss > maxTotalProfitLoss)
{
// new equity high
maxTotalProfitLoss = TotalProfitLoss;
if (isInDrawdown && trade.ExitTime - lastPeakTime > MaximumDrawdownDuration)
MaximumDrawdownDuration = trade.ExitTime - lastPeakTime;
lastPeakTime = trade.ExitTime;
isInDrawdown = false;
}
}
else
{
// losing trade
NumberOfLosingTrades++;
TotalProfitLoss += trade.ProfitLoss;
TotalLoss += trade.ProfitLoss;
var prevAverageLoss = AverageLoss;
AverageLoss += (trade.ProfitLoss - AverageLoss) / NumberOfLosingTrades;
sumForDownsideVariance += (trade.ProfitLoss - prevAverageLoss) * (trade.ProfitLoss - AverageLoss);
var downsideVariance = NumberOfLosingTrades > 1 ? sumForDownsideVariance / (NumberOfLosingTrades - 1) : 0;
ProfitLossDownsideDeviation = (decimal)Math.Sqrt((double)downsideVariance);
AverageLosingTradeDuration += TimeSpan.FromSeconds((trade.Duration.TotalSeconds - AverageLosingTradeDuration.TotalSeconds) / NumberOfLosingTrades);
losingTradeDurationsTicks.Add(trade.Duration.Ticks);
if (trade.ProfitLoss < LargestLoss)
LargestLoss = trade.ProfitLoss;
// even though losing money, an ITM option trade is a winning trade,
// so IsWin for an ITM OptionTrade will return true even if the trade was not profitable.
if (trade.IsWin)
{
numberOfITMOptionsWinningTrades++;
maxConsecutiveLosers = 0;
maxConsecutiveWinners++;
if (maxConsecutiveWinners > MaxConsecutiveWinningTrades)
MaxConsecutiveWinningTrades = maxConsecutiveWinners;
}
else
{
maxConsecutiveWinners = 0;
maxConsecutiveLosers++;
if (maxConsecutiveLosers > MaxConsecutiveLosingTrades)
MaxConsecutiveLosingTrades = maxConsecutiveLosers;
}
if (TotalProfitLoss - maxTotalProfitLoss < MaximumClosedTradeDrawdown)
MaximumClosedTradeDrawdown = TotalProfitLoss - maxTotalProfitLoss;
isInDrawdown = true;
}
var prevAverageProfitLoss = AverageProfitLoss;
AverageProfitLoss += (trade.ProfitLoss - AverageProfitLoss) / TotalNumberOfTrades;
sumForVariance += (trade.ProfitLoss - prevAverageProfitLoss) * (trade.ProfitLoss - AverageProfitLoss);
var variance = TotalNumberOfTrades > 1 ? sumForVariance / (TotalNumberOfTrades - 1) : 0;
ProfitLossStandardDeviation = (decimal)Math.Sqrt((double)variance);
AverageTradeDuration += TimeSpan.FromSeconds((trade.Duration.TotalSeconds - AverageTradeDuration.TotalSeconds) / TotalNumberOfTrades);
allTradeDurationsTicks.Add(trade.Duration.Ticks);
AverageMAE += (trade.MAE - AverageMAE) / TotalNumberOfTrades;
AverageMFE += (trade.MFE - AverageMFE) / TotalNumberOfTrades;
if (trade.MAE < LargestMAE)
LargestMAE = trade.MAE;
if (trade.MFE > LargestMFE)
LargestMFE = trade.MFE;
if (trade.EndTradeDrawdown > MaximumEndTradeDrawdown)
MaximumEndTradeDrawdown = trade.EndTradeDrawdown;
TotalFees += trade.TotalFees;
}
// Adjust number of winning and losing trades: ITM options assignment loss counts as a loss for profit and loss calculations,
// but adds a win to the wins count since this is an actual win even though premium paid is a loss.
NumberOfWinningTrades += numberOfITMOptionsWinningTrades;
NumberOfLosingTrades -= numberOfITMOptionsWinningTrades;
ProfitLossRatio = AverageLoss == 0 ? 0 : AverageProfit / Math.Abs(AverageLoss);
WinLossRatio = TotalNumberOfTrades == 0 ? 0 : (NumberOfLosingTrades > 0 ? (decimal)NumberOfWinningTrades / NumberOfLosingTrades : 10);
WinRate = TotalNumberOfTrades > 0 ? (decimal)NumberOfWinningTrades / TotalNumberOfTrades : 0;
LossRate = TotalNumberOfTrades > 0 ? 1 - WinRate : 0;
ProfitFactor = TotalProfit == 0 ? 0 : (TotalLoss < 0 ? TotalProfit / Math.Abs(TotalLoss) : 10);
SharpeRatio = ProfitLossStandardDeviation > 0 ? AverageProfitLoss / ProfitLossStandardDeviation : 0;
SortinoRatio = ProfitLossDownsideDeviation > 0 ? AverageProfitLoss / ProfitLossDownsideDeviation : 0;
ProfitToMaxDrawdownRatio = TotalProfitLoss == 0 ? 0 : (MaximumClosedTradeDrawdown < 0 ? TotalProfitLoss / Math.Abs(MaximumClosedTradeDrawdown) : 10);
AverageEndTradeDrawdown = AverageProfitLoss - AverageMFE;
if (allTradeDurationsTicks.Count > 0)
MedianTradeDuration = TimeSpan.FromTicks(allTradeDurationsTicks.Median());
if (winningTradeDurationsTicks.Count > 0)
MedianWinningTradeDuration = TimeSpan.FromTicks(winningTradeDurationsTicks.Median());
if (losingTradeDurationsTicks.Count > 0)
MedianLosingTradeDuration = TimeSpan.FromTicks(losingTradeDurationsTicks.Median());
}
/// <summary>
/// Initializes a new instance of the <see cref="TradeStatistics"/> class
/// </summary>
public TradeStatistics()
{
}
}
}