Lean  $LEAN_TAG$
CAGRReportElement.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 Deedle;
18 using QuantConnect.Packets;
19 
21 {
22  internal sealed class CAGRReportElement : ReportElement
23  {
24  private LiveResult _live;
25  private BacktestResult _backtest;
26 
27  /// <summary>
28  /// Estimate the CAGR of the strategy.
29  /// </summary>
30  /// <param name="name">Name of the widget</param>
31  /// <param name="key">Location of injection</param>
32  /// <param name="backtest">Backtest result object</param>
33  /// <param name="live">Live result object</param>
34  public CAGRReportElement(string name, string key, BacktestResult backtest, LiveResult live)
35  {
36  _live = live;
37  _backtest = backtest;
38  Name = name;
39  Key = key;
40  }
41 
42  /// <summary>
43  /// The generated output string to be injected
44  /// </summary>
45  public override string Render()
46  {
47  var equityCurve = _live == null
48  ? new Series<DateTime, double>(ResultsUtil.EquityPoints(_backtest))
49  : DrawdownCollection.NormalizeResults(_backtest, _live);
50 
51  if (equityCurve.IsEmpty)
52  {
53  return "-";
54  }
55 
56  var years = (decimal)(equityCurve.LastKey() - equityCurve.FirstKey()).TotalDays / 365m;
57 
58  Result = Statistics.Statistics.CompoundingAnnualPerformance(
59  equityCurve.FirstValue().SafeDecimalCast(),
60  equityCurve.LastValue().SafeDecimalCast(),
61  years);
62 
63  return ((decimal?)Result)?.ToString("P1") ?? "-";
64  }
65  }
66 }