Lean  $LEAN_TAG$
PSRReportElement.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.Linq;
18 using Deedle;
19 using QuantConnect.Packets;
20 
22 {
23  internal sealed class PSRReportElement : ReportElement
24  {
25  private LiveResult _live;
26  private BacktestResult _backtest;
27 
28  /// <summary>
29  /// The number of trading days per year to get better result of statistics
30  /// </summary>
31  private int _tradingDaysPerYear;
32 
33  /// <summary>
34  /// Estimate the PSR of the strategy.
35  /// </summary>
36  /// <param name="name">Name of the widget</param>
37  /// <param name="key">Location of injection</param>
38  /// <param name="backtest">Backtest result object</param>
39  /// <param name="live">Live result object</param>
40  /// <param name="tradingDaysPerYear">The number of trading days per year to get better result of statistics</param>
41  public PSRReportElement(string name, string key, BacktestResult backtest, LiveResult live, int tradingDaysPerYear)
42  {
43  _live = live;
44  _backtest = backtest;
45  Name = name;
46  Key = key;
47  _tradingDaysPerYear = tradingDaysPerYear;
48  }
49 
50  /// <summary>
51  /// The generated output string to be injected
52  /// </summary>
53  public override string Render()
54  {
55  decimal? psr;
56  if (_live == null)
57  {
58  psr = _backtest?.TotalPerformance?.PortfolioStatistics?.ProbabilisticSharpeRatio;
59  Result = psr;
60  if (psr == null)
61  {
62  return "-";
63  }
64 
65  return $"{psr:P0}";
66  }
67 
68  var equityCurvePerformance = DrawdownCollection.NormalizeResults(_backtest, _live)
69  .ResampleEquivalence(date => date.Date, s => s.LastValue())
70  .PercentChange();
71 
72  if (equityCurvePerformance.IsEmpty || equityCurvePerformance.KeyCount < 180)
73  {
74  return "-";
75  }
76 
77  var sixMonthsBefore = equityCurvePerformance.LastKey() - TimeSpan.FromDays(180);
78 
79  var benchmarkSharpeRatio = 1.0d / Math.Sqrt(_tradingDaysPerYear);
80  psr = Statistics.Statistics.ProbabilisticSharpeRatio(
81  equityCurvePerformance
82  .Where(kvp => kvp.Key >= sixMonthsBefore)
83  .Values
84  .ToList(),
85  benchmarkSharpeRatio)
86  .SafeDecimalCast();
87 
88  Result = psr;
89  return $"{psr:P0}";
90  }
91  }
92 }