示例#1
0
        private void SetPortfolioConstruction(Language language, QCAlgorithm algorithm)
        {
            algorithm.SetPortfolioConstruction(new InsightWeightingPortfolioConstructionModel());
            if (language == Language.Python)
            {
                using (Py.GIL())
                {
                    var name     = nameof(InsightWeightingPortfolioConstructionModel);
                    var instance = Py.Import(name).GetAttr(name).Invoke();
                    var model    = new PortfolioConstructionModelPythonWrapper(instance);
                    algorithm.SetPortfolioConstruction(model);
                }
            }

            foreach (var kvp in _algorithm.Portfolio)
            {
                kvp.Value.SetHoldings(kvp.Value.Price, 0);
            }
            _algorithm.Portfolio.SetCash(_startingCash);
            SetUtcTime(new DateTime(2018, 7, 31));

            var changes = SecurityChanges.Added(_algorithm.Securities.Values.ToArray());

            algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes);
        }
示例#2
0
        private void SetPortfolioConstruction(Language language)
        {
            _algorithm.SetPortfolioConstruction(new BLOPCM(new UnconstrainedMeanVariancePortfolioOptimizer()));
            if (language == Language.Python)
            {
                try
                {
                    using (Py.GIL())
                    {
                        var name     = nameof(BLOPCM);
                        var instance = PythonEngine.ModuleFromString(name, GetPythonBLOPCM()).GetAttr(name).Invoke();
                        var model    = new PortfolioConstructionModelPythonWrapper(instance);
                        _algorithm.SetPortfolioConstruction(model);
                    }
                }
                catch (Exception e)
                {
                    Assert.Ignore(e.Message);
                }
            }

            var changes = SecurityChanges.Added(_algorithm.Securities.Values.ToList().ToArray());

            _algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes);
        }
示例#3
0
        private void SetPortfolioConstruction(Language language, QCAlgorithm algorithm, dynamic paramenter = null)
        {
            paramenter = paramenter ?? Resolution.Daily;
            algorithm.SetPortfolioConstruction(new ConfidenceWeightedPortfolioConstructionModel(paramenter));
            if (language == Language.Python)
            {
                using (Py.GIL())
                {
                    var name     = nameof(ConfidenceWeightedPortfolioConstructionModel);
                    var instance = Py.Import(name).GetAttr(name).Invoke(((object)paramenter).ToPython());
                    var model    = new PortfolioConstructionModelPythonWrapper(instance);
                    algorithm.SetPortfolioConstruction(model);
                }
            }

            foreach (var kvp in _algorithm.Portfolio)
            {
                kvp.Value.SetHoldings(kvp.Value.Price, 0);
            }
            _algorithm.Portfolio.SetCash(_startingCash);
            SetUtcTime(new DateTime(2018, 7, 31));

            var changes = SecurityChanges.Added(_algorithm.Securities.Values.ToArray());

            algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes);
        }
示例#4
0
        private void SetPortfolioConstruction(Language language, QCAlgorithm algorithm, PortfolioBias bias = PortfolioBias.LongShort)
        {
            algorithm.SetPortfolioConstruction(new AccumulativeInsightPortfolioConstructionModel((Func <DateTime, DateTime>)null, bias));
            if (language == Language.Python)
            {
                using (Py.GIL())
                {
                    var name     = nameof(AccumulativeInsightPortfolioConstructionModel);
                    var instance = Py.Import(name).GetAttr(name).Invoke(((object)null).ToPython(), ((int)bias).ToPython());
                    var model    = new PortfolioConstructionModelPythonWrapper(instance);
                    algorithm.SetPortfolioConstruction(model);
                }
            }

            foreach (var kvp in _algorithm.Portfolio)
            {
                kvp.Value.SetHoldings(kvp.Value.Price, 0);
            }
            _algorithm.Portfolio.SetCash(_startingCash);
            SetUtcTime(new DateTime(2018, 7, 31));

            var changes = SecurityChanges.Added(_algorithm.Securities.Values.ToArray());

            algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes);
        }
        private void SetPortfolioConstruction(Language language)
        {
            _algorithm.SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
            if (language == Language.Python)
            {
                try
                {
                    using (Py.GIL())
                    {
                        var name     = nameof(EqualWeightingPortfolioConstructionModel);
                        var instance = Py.Import(name).GetAttr(name).Invoke();
                        var model    = new PortfolioConstructionModelPythonWrapper(instance);
                        _algorithm.SetPortfolioConstruction(model);
                    }
                }
                catch (Exception e)
                {
                    Assert.Ignore(e.Message);
                }
            }

            var changes = SecurityChanges.Added(_algorithm.Securities.Values.ToArray());

            _algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes);
        }
示例#6
0
        /// <summary>
        /// Sets the portfolio construction model
        /// </summary>
        /// <param name="portfolioConstruction">Model defining how to build a portoflio from alphas</param>
        public void SetPortfolioConstruction(PyObject portfolioConstruction)
        {
            IPortfolioConstructionModel model;

            if (portfolioConstruction.TryConvert(out model))
            {
                SetPortfolioConstruction(model);
            }
            else
            {
                PortfolioConstruction = new PortfolioConstructionModelPythonWrapper(portfolioConstruction);
            }
        }
示例#7
0
        public void RespectsRebalancingPeriod(Language language, InsightDirection direction)
        {
            PortfolioConstructionModel model = new AccumulativeInsightPortfolioConstructionModel(Resolution.Daily);

            if (language == Language.Python)
            {
                using (Py.GIL())
                {
                    var     name     = nameof(AccumulativeInsightPortfolioConstructionModel);
                    dynamic instance = Py.Import(name).GetAttr(name);
                    model = new PortfolioConstructionModelPythonWrapper(instance(Resolution.Daily));
                }
            }

            model.RebalanceOnSecurityChanges = false;
            model.RebalanceOnInsightChanges  = false;

            SetUtcTime(new DateTime(2018, 7, 31));
            // First emit long term insight
            var insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, TimeSpan.FromDays(10)) };

            AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, insights).ToList());

            // One minute later, emits insight to add to portfolio
            SetUtcTime(_algorithm.Time.AddMinutes(1));
            insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, TimeSpan.FromMinutes(10)) };
            AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, insights));

            // the second insight should expire
            SetUtcTime(_algorithm.Time.AddMinutes(1));
            AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, insights));

            // the rebalancing period is due and the first insight is still valid
            SetUtcTime(_algorithm.Time.AddDays(1));
            var targets         = model.CreateTargets(_algorithm, new Insight[0]);
            var expectedTargets = new List <IPortfolioTarget> {
                PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * (decimal)DefaultPercent)
            };

            AssertTargets(expectedTargets, targets);

            // the rebalancing period is due and no insight is valid
            SetUtcTime(_algorithm.Time.AddDays(10));
            AssertTargets(
                new List <IPortfolioTarget> {
                PortfolioTarget.Percent(_algorithm, Symbols.SPY, 0)
            },
                model.CreateTargets(_algorithm, new Insight[0]));

            AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, new Insight[0]));
        }
        public void PythonDoesNotImplementDetermineTargetPercent()
        {
            var algorithm = new AlgorithmStub();

            using (Py.GIL())
            {
                dynamic model = PythonEngine.ModuleFromString(
                    "TestPCM",
                    @"

from clr import AddReference
AddReference(""QuantConnect.Algorithm.Framework"")

from QuantConnect.Algorithm.Framework.Portfolio import *

class PyPCM(EqualWeightingPortfolioConstructionModel):
    def __init__(self):
        self.CreateTargets_WasCalled = False
        self.OnSecuritiesChanged_WasCalled = False
        self.ShouldCreateTargetForInsight_WasCalled = False
        self.IsRebalanceDue_WasCalled = False
        self.GetTargetInsights_WasCalled = False

    def CreateTargets(self, algorithm, insights):
        self.CreateTargets_WasCalled = True
        return super().CreateTargets(algorithm, insights)

    def OnSecuritiesChanged(self, algorithm, changes):
        self.OnSecuritiesChanged_WasCalled = True
        super().OnSecuritiesChanged(algorithm, changes)

    def ShouldCreateTargetForInsight(self, insight):
        self.ShouldCreateTargetForInsight_WasCalled = True
        return super().ShouldCreateTargetForInsight(insight)

    def IsRebalanceDue(self, insights, algorithmUtc):
        self.IsRebalanceDue_WasCalled = True
        return True

    def GetTargetInsights(self):
        self.GetTargetInsights_WasCalled = True
        return super().GetTargetInsights()
"
                    ).GetAttr("PyPCM").Invoke();

                var now          = new DateTime(2020, 1, 10);
                var wrappedModel = new PortfolioConstructionModelPythonWrapper(model);
                var aapl         = algorithm.AddEquity("AAPL");
                aapl.SetMarketPrice(new Tick(now, aapl.Symbol, 10, 10));
                algorithm.SetDateTime(now);

                wrappedModel.OnSecuritiesChanged(algorithm, new SecurityChanges(SecurityChanges.Added(aapl)));
                Assert.IsTrue((bool)model.OnSecuritiesChanged_WasCalled);

                var insight = new Insight(now, aapl.Symbol, TimeSpan.FromDays(1), InsightType.Price, InsightDirection.Down, null, null);
                var result  = wrappedModel.CreateTargets(algorithm, new[] { insight }).ToList();
                Assert.AreEqual(1, result.Count);
                Assert.IsTrue((bool)model.CreateTargets_WasCalled);
                Assert.IsTrue((bool)model.GetTargetInsights_WasCalled);
                Assert.IsTrue((bool)model.IsRebalanceDue_WasCalled);
                Assert.IsTrue((bool)model.ShouldCreateTargetForInsight_WasCalled);
            }
        }