/*
* 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 System;
namespace QuantConnect.Python
{
///
/// Dynamic data class for Python algorithms.
/// Stores properties of python instances in DynamicData dictionary
///
public class PythonData : DynamicData
{
private readonly dynamic _pythonData;
///
/// Constructor for initialising the PythonData class
///
public PythonData()
{
//Empty constructor required for fast-reflection initialization
}
///
/// Constructor for initialising the PythonData class with wrapped PyObject
///
///
public PythonData(PyObject pythonData)
{
_pythonData = pythonData;
}
///
/// Source Locator for algorithm written in Python.
///
/// Subscription configuration object
/// Date of the data file we're looking for
/// true if we're in live mode, false for backtesting mode
/// STRING API Url.
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
using (Py.GIL())
{
var source = _pythonData.GetSource(config, date, isLiveMode);
return GetTypeAndDispose(source);
}
}
///
/// Generic Reader Implementation for Python Custom Data.
///
/// Subscription configuration
/// CSV line of data from the souce
/// Date of the requested line
/// true if we're in live mode, false for backtesting mode
///
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
using (Py.GIL())
{
var data = _pythonData.Reader(config, line, date, isLiveMode);
return GetTypeAndDispose(data);
}
}
///
/// Indexes into this PythonData, where index is key to the dynamic property
///
/// the index
/// Dynamic property of a given index
public object this[string index]
{
get
{
return GetProperty(index);
}
set
{
SetProperty(index, value is double ? Convert.ToDecimal(value) : value);
}
}
private T GetTypeAndDispose(dynamic instance)
{
if (instance == null)
{
return default(T);
}
var pyInstance = instance as PyObject;
if (pyInstance != null)
{
var returnInstance = pyInstance.As();
pyInstance.Dispose();
return returnInstance;
}
throw new ArgumentException($"Unexpected type: {instance.GetType()}." +
$" Was expecting {nameof(PyObject)}");
}
}
}