Lean  $LEAN_TAG$
LeverageUtilizationReportElement.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 Python.Runtime;
21 using QuantConnect.Orders;
22 using QuantConnect.Packets;
23 
25 {
26  internal sealed class LeverageUtilizationReportElement : ChartReportElement
27  {
28  private LiveResult _live;
29  private BacktestResult _backtest;
30  private List<PointInTimePortfolio> _backtestPortfolios;
31  private List<PointInTimePortfolio> _livePortfolios;
32 
33  /// <summary>
34  /// Create a new plot of the leverage utilization
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="backtestPortfolios">Backtest point in time portfolios</param>
41  /// <param name="livePortfolios">Live point in time portfolios</param>
42  public LeverageUtilizationReportElement(
43  string name,
44  string key,
45  BacktestResult backtest,
46  LiveResult live,
47  List<PointInTimePortfolio> backtestPortfolios,
48  List<PointInTimePortfolio> livePortfolios)
49  {
50  _backtest = backtest;
51  _backtestPortfolios = backtestPortfolios;
52  _live = live;
53  _livePortfolios = livePortfolios;
54  Name = name;
55  Key = key;
56  }
57 
58  /// <summary>
59  /// Generate the leverage utilization plot using the python libraries.
60  /// </summary>
61  public override string Render()
62  {
63  var backtestSeries = Metrics.LeverageUtilization(_backtestPortfolios).FillMissing(Direction.Forward);
64  var liveSeries = Metrics.LeverageUtilization(_livePortfolios).FillMissing(Direction.Forward);
65 
66  var base64 = "";
67  using (Py.GIL())
68  {
69  var backtestList = new PyList();
70  var liveList = new PyList();
71 
72  backtestList.Append(backtestSeries.Keys.ToList().ToPython());
73  backtestList.Append(backtestSeries.Values.ToList().ToPython());
74 
75  liveList.Append(liveSeries.Keys.ToList().ToPython());
76  liveList.Append(liveSeries.Values.ToList().ToPython());
77 
78  base64 = Charting.GetLeverage(backtestList, liveList);
79  }
80 
81  return base64;
82  }
83  }
84 }