Lean  $LEAN_TAG$
DailyReturnsReportElement.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 Python.Runtime;
20 using QuantConnect.Packets;
21 
23 {
24  internal sealed class DailyReturnsReportElement : ChartReportElement
25  {
26  private LiveResult _live;
27  private BacktestResult _backtest;
28 
29  /// <summary>
30  /// Create a new plot of the daily returns in bar chart format
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 DailyReturnsReportElement(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  /// Generate the daily returns plot using the python libraries.
46  /// </summary>
47  public override string Render()
48  {
49  var backtestReturns = ResultsUtil.EquityPoints(_backtest);
50  var liveReturns = ResultsUtil.EquityPoints(_live);
51 
52  var backtestSeries = new Series<DateTime, double>(backtestReturns.Keys, backtestReturns.Values);
53  var liveSeries = new Series<DateTime, double>(liveReturns.Keys, liveReturns.Values);
54 
55  // The following two operations are equivalent to the Pandas `DataFrame.resample(...)` method
56  var backtestResampled = backtestSeries.ResampleEquivalence(date => date.Date, s => s.LastValue()).PercentChange().DropMissing() * 100;
57  var liveResampled = liveSeries.ResampleEquivalence(date => date.Date, s => s.LastValue()).PercentChange().DropMissing() * 100;
58 
59  var base64 = "";
60  using (Py.GIL())
61  {
62  var backtestList = new PyList();
63  backtestList.Append(backtestResampled.Keys.ToList().ToPython());
64  backtestList.Append(backtestResampled.Values.ToList().ToPython());
65 
66  var liveList = new PyList();
67  liveList.Append(liveResampled.Keys.ToList().ToPython());
68  liveList.Append(liveResampled.Values.ToList().ToPython());
69 
70  base64 = Charting.GetDailyReturns(backtestList, liveList);
71 
72  backtestList.Dispose();
73  liveList.Dispose();
74  }
75 
76  return base64;
77  }
78  }
79 }