/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Python.Runtime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Python
{
///
/// Collection of methods that converts lists of objects in pandas.DataFrame
///
public class PandasConverter
{
private static dynamic _pandas;
private static PyObject _concat;
///
/// Initializes the class
///
static PandasConverter()
{
using (Py.GIL())
{
var pandas = Py.Import("pandas");
_pandas = pandas;
// keep it so we don't need to ask for it each time
_concat = pandas.GetAttr("concat");
}
}
///
/// Converts an enumerable of in a pandas.DataFrame
///
/// Enumerable of
/// Optional type of bars to add to the data frame
/// containing a pandas.DataFrame
public PyObject GetDataFrame(IEnumerable data, Type dataType = null)
{
var maxLevels = 0;
var sliceDataDict = new Dictionary();
// if no data type is requested we check all
var requestedTick = dataType == null || dataType == typeof(Tick) || dataType == typeof(OpenInterest);
var requestedTradeBar = dataType == null || dataType == typeof(TradeBar);
var requestedQuoteBar = dataType == null || dataType == typeof(QuoteBar);
foreach (var slice in data)
{
AddSliceDataTypeDataToDict(slice, requestedTick, requestedTradeBar, requestedQuoteBar, sliceDataDict, ref maxLevels, dataType);
}
return CreateDataFrame(sliceDataDict, maxLevels);
}
///
/// Converts an enumerable of in a pandas.DataFrame
///
/// Enumerable of
/// Whether to make the index only the symbol, without time or any other index levels
/// containing a pandas.DataFrame
/// Helper method for testing
public PyObject GetDataFrame(IEnumerable data, bool symbolOnlyIndex = false)
where T : ISymbolProvider
{
var pandasDataBySymbol = new Dictionary();
var maxLevels = 0;
foreach (var datum in data)
{
var pandasData = GetPandasDataValue(pandasDataBySymbol, datum.Symbol, datum, ref maxLevels);
pandasData.Add(datum);
}
if (symbolOnlyIndex)
{
return PandasData.ToPandasDataFrame(pandasDataBySymbol.Values);
}
return CreateDataFrame(pandasDataBySymbol,
// Use 2 instead of maxLevels for backwards compatibility
maxLevels: symbolOnlyIndex ? 1 : 2,
sort: false,
// Multiple data frames (one for each symbol) will be concatenated,
// so make sure rows with missing values only are not filtered out before concatenation
filterMissingValueColumns: pandasDataBySymbol.Count <= 1);
}
///
/// Converts a dictionary with a list of in a pandas.DataFrame
///
/// Dictionary with a list of
/// containing a pandas.DataFrame
public PyObject GetIndicatorDataFrame(IEnumerable>> data)
{
using (Py.GIL())
{
var pyDict = new PyDict();
foreach (var kvp in data)
{
AddSeriesToPyDict(kvp.Key, kvp.Value, pyDict);
}
return MakeIndicatorDataFrame(pyDict);
}
}
///
/// Converts a dictionary with a list of in a pandas.DataFrame
///
/// that should be a dictionary (convertible to PyDict) of string to list of
/// containing a pandas.DataFrame
public PyObject GetIndicatorDataFrame(PyObject data)
{
using (Py.GIL())
{
using var inputPythonType = data.GetPythonType();
var inputTypeStr = inputPythonType.ToString();
var targetTypeStr = nameof(PyDict);
PyObject currentKvp = null;
try
{
using var pyDictData = new PyDict(data);
using var seriesPyDict = new PyDict();
targetTypeStr = $"{nameof(String)}: {nameof(List)}";
foreach (var kvp in pyDictData.Items())
{
currentKvp = kvp;
AddSeriesToPyDict(kvp[0].As(), kvp[1].As>(), seriesPyDict);
}
return MakeIndicatorDataFrame(seriesPyDict);
}
catch (Exception e)
{
if (currentKvp != null)
{
inputTypeStr = $"{currentKvp[0].GetPythonType()}: {currentKvp[1].GetPythonType()}";
}
throw new ArgumentException(Messages.PandasConverter.ConvertToDictionaryFailed(inputTypeStr, targetTypeStr, e.Message), e);
}
}
}
///
/// Returns a string that represent the current object
///
///
public override string ToString()
{
if (_pandas == null)
{
return Messages.PandasConverter.PandasModuleNotImported;
}
using (Py.GIL())
{
return _pandas.Repr();
}
}
///
/// Create a data frame by concatenated the resulting data frames from the given data
///
private static PyObject CreateDataFrame(Dictionary dataBySymbol, int maxLevels = 2, bool sort = true,
bool filterMissingValueColumns = true)
{
using (Py.GIL())
{
if (dataBySymbol.Count == 0)
{
return _pandas.DataFrame();
}
var dataFrames = dataBySymbol.Select(x => x.Value.ToPandasDataFrame(maxLevels, filterMissingValueColumns));
var result = ConcatDataFrames(dataFrames, sort: sort, dropna: true);
foreach (var df in dataFrames)
{
df.Dispose();
}
return result;
}
}
///
/// Concatenates multiple data frames
///
/// The data frames to concatenate
///
/// Optional new keys for a new multi-index level that would be added
/// to index each individual data frame in the resulting one
///
/// The optional names of the new index level (and the existing ones if they need to be changed)
/// Whether to sort the resulting data frame
/// Whether to drop columns containing NA values only (Nan, None, etc)
/// A new data frame result from concatenating the input
public static PyObject ConcatDataFrames(IEnumerable dataFrames, IEnumerable