Overall Statistics
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuantConnect;
using QuantConnect.Data.Market;
using QuantConnect.Algorithm;
using Python.Runtime;
using QuantConnect.Data;
using System.Net;

namespace Quantability.Algorithm.CSharp.PythonTest
{
    public class PythonTest : QCAlgorithm
    {
    	// Url of dynamically loaded Python code
        static string moduleUrl = "https://www.dropbox.com/s/n5ju2n6tt1leorf/TestModule.py?dl=1";
        // Python module name
        static string moduleName = "TestModule";
        // Symbol of Equity
        static string ticker = "SPY";
        // Reference to dynamically loaded Python module
        static dynamic moduleRef;

        public override void Initialize()
        {
            SetStartDate(2007, 10, 7);
            SetEndDate(2007, 10, 15);
            AddSecurity(SecurityType.Equity, ticker, Resolution.Daily);

            // Run initialize method in Python function
            Debug("Loading Python Module");
            PythonEngine.Initialize();
            PythonEngine.BeginAllowThreads();
            using (Py.GIL())
            {
                moduleRef = PythonEngine.ModuleFromString(moduleName, PythonModuleCode(moduleUrl));
                moduleRef.InvokeMethod("initialize_model");
                PythonEngine.RunSimpleString("print('Python Module Execution Successful')");
            }
        }

        private static string _pythonModuleCode = "";
        // Only retrieve file via Http once.
        public static string PythonModuleCode(string url)
        {
            if (_pythonModuleCode.Length == 0)
            {
                using (var client = new WebClient())
                {
                    _pythonModuleCode = client.DownloadString(url);
                }
            }
            return _pythonModuleCode;
        }

        public void OnData(Slice data)
        {
            if (data.ContainsKey(ticker))
            {
                //decimal allocation = GetAllocation(data[ticker]);
                SetHoldings(ticker, GetAllocation(data[ticker]));
            }
        }

		// Pass current price bar into Python module for entry/exit decisions.
        public decimal GetAllocation(TradeBar bar)
        {
            decimal ret = 0m;
            using (Py.GIL())
            {
                ret = moduleRef.scan_entry(bar.Close);
            }
            Debug("Return value: " + ret);
            return ret;
        }

    }
}