Lean  $LEAN_TAG$
BaseChains.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 Python.Runtime;
17 using QuantConnect.Python;
19 using System;
20 using System.Collections.Generic;
21 using System.Linq;
22 
24 {
25  /// <summary>
26  /// Collection of <see cref="BaseChain{T, TContractsCollection}"/> keyed by canonical option symbol
27  /// </summary>
28  public class BaseChains<T, TContract, TContractsCollection> : DataDictionary<T>
29  where T : BaseChain<TContract, TContractsCollection>
30  where TContract : BaseContract
31  where TContractsCollection : DataDictionary<TContract>, new()
32  {
33  private static readonly IEnumerable<string> _flattenedDfIndexNames = new[] { "canonical", "symbol" };
34 
35  private readonly Lazy<PyObject> _dataframe;
36  private readonly bool _flatten;
37 
38  /// <summary>
39  /// The data frame representation of the option chains
40  /// </summary>
41  public PyObject DataFrame => _dataframe.Value;
42 
43  /// <summary>
44  /// Creates a new instance of the <see cref="BaseChains{T, TContract, TContractsCollection}"/> dictionary
45  /// </summary>
46  protected BaseChains()
47  : this(default, true)
48  {
49  }
50 
51  /// <summary>
52  /// Creates a new instance of the <see cref="BaseChains{T, TContract, TContractsCollection}"/> dictionary
53  /// </summary>
54  protected BaseChains(bool flatten)
55  : this(default, flatten)
56  {
57  }
58 
59  /// <summary>
60  /// Creates a new instance of the <see cref="BaseChains{T, TContract, TContractsCollection}"/> dictionary
61  /// </summary>
62  protected BaseChains(DateTime time, bool flatten)
63  : base(time)
64  {
65  _flatten = flatten;
66  _dataframe = new Lazy<PyObject>(InitializeDataFrame, isThreadSafe: false);
67  }
68 
69  private PyObject InitializeDataFrame()
70  {
71  if (!PythonEngine.IsInitialized)
72  {
73  return null;
74  }
75 
76  var dataFrames = this.Select(kvp => kvp.Value.DataFrame).ToList();
77 
78  if (_flatten)
79  {
80  var canonicalSymbols = this.Select(kvp => kvp.Key);
81  return PandasConverter.ConcatDataFrames(dataFrames, keys: canonicalSymbols, names: _flattenedDfIndexNames, sort: false);
82  }
83 
84  return PandasConverter.ConcatDataFrames(dataFrames, sort: false);
85  }
86  }
87 }