Lean  $LEAN_TAG$
MaxDrawdownReportElement.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.Collections.Generic;
18 using System.Linq;
19 using Deedle;
20 using QuantConnect.Packets;
21 
23 {
24  internal sealed class MaxDrawdownReportElement : ReportElement
25  {
26  private LiveResult _live;
27  private BacktestResult _backtest;
28 
29  /// <summary>
30  /// Estimate the max drawdown of the strategy.
31  /// </summary>
32  /// <param name="name">Name of the widget</param>
33  /// <param name="key">Location of injection</param>
34  /// <param name="backtest">Backtest result object</param>
35  /// <param name="live">Live result object</param>
36  public MaxDrawdownReportElement(string name, string key, BacktestResult backtest, LiveResult live)
37  {
38  _live = live;
39  _backtest = backtest;
40  Name = name;
41  Key = key;
42  }
43 
44  /// <summary>
45  /// The generated output string to be injected
46  /// </summary>
47  public override string Render()
48  {
49  if (_live == null)
50  {
51  var backtestDrawdown = _backtest?.TotalPerformance?.PortfolioStatistics?.Drawdown;
52  Result = backtestDrawdown;
53  return backtestDrawdown?.ToString("P1") ?? "-";
54  }
55 
56  var equityCurve = new SortedDictionary<DateTime, decimal>(DrawdownCollection.NormalizeResults(_backtest, _live)
57  .Observations
58  .ToDictionary(kvp => kvp.Key, kvp => (decimal)kvp.Value));
59 
60  var maxDrawdown = Statistics.Statistics.DrawdownPercent(equityCurve);
61  Result = maxDrawdown;
62 
63  return $"{maxDrawdown:P1}";
64  }
65  }
66 }