コード例 #1
0
 public override void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
 {
 }
コード例 #2
0
 /// <summary>
 /// Manages the algorithm's risk at each time step
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 /// <param name="targets">The current portfolio targets to be assessed for risk</param>
 public virtual IEnumerable <IPortfolioTarget> ManageRisk(QCAlgorithmFramework algorithm, IPortfolioTarget[] targets)
 {
     return(Enumerable.Empty <IPortfolioTarget>());
 }
コード例 #3
0
 /// <summary>
 /// Manages the algorithm's risk at each time step
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 public void ManageRisk(QCAlgorithmFramework algorithm)
 {
 }
コード例 #4
0
ファイル: AlphaModel.cs プロジェクト: jasonhillier/Lean
 /// <summary>
 /// Updates this alpha model with the latest data from the algorithm.
 /// This is called each time the algorithm receives data for subscribed securities
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 /// <param name="data">The new data available</param>
 /// <returns>The new insights generated</returns>
 public virtual IEnumerable <Insight> Update(QCAlgorithmFramework algorithm, Slice data)
 {
     throw new System.NotImplementedException("Types deriving from 'AlphaModel' must implement the 'IEnumerable<Insight> Update(QCAlgorithmFramework, Slice) method.");
 }
 /// <inheritdoc />
 public override IEnumerable <Symbol> SelectCoarse(QCAlgorithmFramework algorithm, IEnumerable <CoarseFundamental> coarse)
 {
     return(_coarseSelector(coarse));
 }
コード例 #6
0
 protected virtual List <IPortfolioTarget> IncrementOptionPositions(QCAlgorithmFramework algorithm, Symbol baseSymbol, IEnumerable <OptionHolding> holdings, Insight insight)
 {
     return(null);
 }
コード例 #7
0
 /// <summary>
 /// Creates the universes for this algorithm. Called once after <see cref="IAlgorithm.Initialize"/>
 /// </summary>
 /// <param name="algorithm">The algorithm instance to create universes for</param>
 /// <returns>The universes to be used by the algorithm</returns>
 public virtual IEnumerable <Universe> CreateUniverses(QCAlgorithmFramework algorithm)
 {
     throw new System.NotImplementedException("Types deriving from 'UniverseSelectionModel' must implement the 'IEnumerable<Universe> CreateUniverses(QCAlgorithmFramework) method.");
 }
コード例 #8
0
 /// <summary>
 /// Defines the fine fundamental selection function.
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 /// <param name="fine">The fine fundamental data used to perform filtering</param>
 /// <returns>An enumerable of symbols passing the filter</returns>
 public virtual IEnumerable <Symbol> SelectFine(QCAlgorithmFramework algorithm, IEnumerable <FineFundamental> fine)
 {
     // default impl performs no filtering of fine data
     return(fine.Select(f => f.Symbol));
 }
コード例 #9
0
 /// <summary>
 /// Manages the algorithm's risk at each time step
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 /// <param name="targets">The current portfolio targets to be assessed for risk</param>
 public virtual IEnumerable <IPortfolioTarget> ManageRisk(QCAlgorithmFramework algorithm, IPortfolioTarget[] targets)
 {
     throw new System.NotImplementedException("Types deriving from 'RiskManagementModel' must implement the 'IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithmFramework, IPortfolioTarget[]) method.");
 }
コード例 #10
0
 /// <summary>
 /// Manages the algorithm's risk at each time step
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 public IEnumerable <IPortfolioTarget> ManageRisk(QCAlgorithmFramework algorithm)
 {
     return(Enumerable.Empty <IPortfolioTarget>());
 }
コード例 #11
0
 public abstract List <IPortfolioTarget> OpenTargetsFromInsight(QCAlgorithmFramework algorithm, Symbol symbol, Insight insight);
コード例 #12
0
 public virtual List <IPortfolioTarget> CloseTargetsFromInsight(QCAlgorithmFramework algorithm, Symbol symbol, Insight insight)
 {
     //by default, does nothing, position sizing/closing/etc can all be done from OpenTargetsFromInsight.
     return(null);
 }
コード例 #13
0
 public virtual IEnumerable <IPortfolioTarget> CreateTargets(QCAlgorithmFramework algorithm, Insight[] insights)
 {
     return(Enumerable.Empty <IPortfolioTarget>());
 }
コード例 #14
0
 public override IEnumerable <IPortfolioTarget> CreateTargets(QCAlgorithmFramework algorithm, Insight[] insights)
 {
     Insights = insights;
     return(insights.Select(insight => PortfolioTarget.Percent(algorithm, insight.Symbol, 0.01m)));
 }
コード例 #15
0
        public void OrdersAreSubmittedWhenRequiredForTargetsToExecute(
            Language language,
            double[] historicalPrices,
            int expectedOrdersSubmitted,
            decimal expectedTotalQuantity)
        {
            var actualOrdersSubmitted = new List <SubmitOrderRequest>();

            var time            = new DateTime(2018, 8, 2, 16, 0, 0);
            var historyProvider = new Mock <IHistoryProvider>();

            historyProvider.Setup(m => m.GetHistory(It.IsAny <IEnumerable <HistoryRequest> >(), It.IsAny <DateTimeZone>()))
            .Returns(historicalPrices.Select((x, i) =>
                                             new Slice(time.AddMinutes(i),
                                                       new List <BaseData>
            {
                new TradeBar
                {
                    Time   = time.AddMinutes(i),
                    Symbol = Symbols.AAPL,
                    Open   = Convert.ToDecimal(x),
                    High   = Convert.ToDecimal(x),
                    Low    = Convert.ToDecimal(x),
                    Close  = Convert.ToDecimal(x),
                    Volume = 100m
                }
            })));

            var algorithm = new QCAlgorithmFramework();

            algorithm.SetPandasConverter();
            algorithm.SetHistoryProvider(historyProvider.Object);
            algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
            algorithm.SetDateTime(time.AddMinutes(5));

            var security = algorithm.AddEquity(Symbols.AAPL.Value);

            security.SetMarketPrice(new TradeBar {
                Value = 250
            });

            algorithm.SetFinishedWarmingUp();

            var orderProcessor = new Mock <IOrderProcessor>();

            orderProcessor.Setup(m => m.Process(It.IsAny <SubmitOrderRequest>()))
            .Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request))
            .Callback((SubmitOrderRequest request) => actualOrdersSubmitted.Add(request));
            orderProcessor.Setup(m => m.GetOpenOrders(It.IsAny <Func <Order, bool> >()))
            .Returns(new List <Order>());
            algorithm.Transactions.SetOrderProcessor(orderProcessor.Object);

            var model = GetExecutionModel(language);

            algorithm.SetExecution(model);

            var changes = new SecurityChanges(new[] { security }, Enumerable.Empty <Security>());

            model.OnSecuritiesChanged(algorithm, changes);

            var targets = new IPortfolioTarget[] { new PortfolioTarget(Symbols.AAPL, 10) };

            model.Execute(algorithm, targets);

            Assert.AreEqual(expectedOrdersSubmitted, actualOrdersSubmitted.Count);
            Assert.AreEqual(expectedTotalQuantity, actualOrdersSubmitted.Sum(x => x.Quantity));

            if (actualOrdersSubmitted.Count == 1)
            {
                var request = actualOrdersSubmitted[0];
                Assert.AreEqual(expectedTotalQuantity, request.Quantity);
                Assert.AreEqual(algorithm.UtcTime, request.Time);
            }
        }
コード例 #16
0
 /// <summary>
 /// Defines the coarse fundamental selection function.
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 /// <param name="coarse">The coarse fundamental data used to perform filtering</param>
 /// <returns>An enumerable of symbols passing the filter</returns>
 public abstract IEnumerable <Symbol> SelectCoarse(QCAlgorithmFramework algorithm, IEnumerable <CoarseFundamental> coarse);
コード例 #17
0
 public IEnumerable <IPortfolioTarget> CreateTargets(QCAlgorithmFramework algorithm, List <Insight> insights)
 {
     return(Enumerable.Empty <IPortfolioTarget>());
 }
コード例 #18
0
        /// <summary>
        /// Create portfolio targets from the specified insights
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="insights">The insights to create portoflio targets from</param>
        /// <returns>An enumerable of portoflio targets to be sent to the execution model</returns>
        public override IEnumerable <IPortfolioTarget> CreateTargets(QCAlgorithmFramework algorithm, Insight[] insights)
        {
            var targets = new List <IPortfolioTarget>();

            if (algorithm.UtcTime <= _nextExpiryTime &&
                algorithm.UtcTime <= _rebalancingTime &&
                insights.Length == 0 &&
                _removedSymbols == null)
            {
                return(targets);
            }

            _insightCollection.AddRange(insights);

            // Create flatten target for each security that was removed from the universe
            if (_removedSymbols != null)
            {
                var universeDeselectionTargets = _removedSymbols.Select(symbol => new PortfolioTarget(symbol, 0));
                targets.AddRange(universeDeselectionTargets);
                _removedSymbols = null;
            }

            // Get insight that haven't expired of each symbol that is still in the universe
            var activeInsights = _insightCollection.GetActiveInsights(algorithm.UtcTime);

            // Get the last generated active insight for each symbol
            var lastActiveInsights = (from insight in activeInsights
                                      group insight by new { insight.Symbol, insight.SourceModel } into g
                                      select g.OrderBy(x => x.GeneratedTimeUtc).Last())
                                     .OrderBy(x => x.Symbol).ToArray();

            double[,] P;
            double[] Q;
            if (TryGetViews(lastActiveInsights, out P, out Q))
            {
                // Updates the ReturnsSymbolData with insights
                foreach (var insight in lastActiveInsights)
                {
                    ReturnsSymbolData symbolData;
                    if (_symbolDataDict.TryGetValue(insight.Symbol, out symbolData))
                    {
                        if (insight.Magnitude == null)
                        {
                            algorithm.SetRunTimeError(new ArgumentNullException("BlackLittermanOptimizationPortfolioConstructionModel does not accept \'null\' as Insight.Magnitude. Please make sure your Alpha Model is generating Insights with the Magnitude property set."));
                        }
                        symbolData.Add(algorithm.Time, (decimal)insight.Magnitude);
                    }
                }
                // Get symbols' returns
                var symbols = lastActiveInsights.Select(x => x.Symbol).Distinct().ToList();
                var returns = _symbolDataDict.FormReturnsMatrix(symbols);

                // Calculate posterior estimate of the mean and uncertainty in the mean
                double[,] Σ;
                var Π = GetEquilibriumReturns(returns, out Σ);

                ApplyBlackLittermanMasterFormula(ref Π, ref Σ, P, Q);

                // Create portfolio targets from the specified insights
                var W    = _optimizer.Optimize(returns, Π, Σ);
                var sidx = 0;
                foreach (var symbol in symbols)
                {
                    var weight = (decimal)W[sidx];
                    targets.Add(PortfolioTarget.Percent(algorithm, symbol, weight));
                    sidx++;
                }
            }
            // Get expired insights and create flatten targets for each symbol
            var expiredInsights = _insightCollection.RemoveExpiredInsights(algorithm.UtcTime);

            var expiredTargets = from insight in expiredInsights
                                 group insight.Symbol by insight.Symbol into g
                                 where !_insightCollection.HasActiveInsights(g.Key, algorithm.UtcTime)
                                 select new PortfolioTarget(g.Key, 0);

            targets.AddRange(expiredTargets);

            _nextExpiryTime  = _insightCollection.GetNextExpiryTime();
            _rebalancingTime = algorithm.UtcTime.Add(_rebalancingPeriod);

            return(targets);
        }
コード例 #19
0
ファイル: MacdAlphaModel.cs プロジェクト: scotb/Lean
 /// <summary>
 /// Cleans up the indicator and consolidator
 /// </summary>
 /// <param name="algorithm">The algorithm instance</param>
 public void CleanUp(QCAlgorithmFramework algorithm)
 {
     Consolidator.DataConsolidated -= OnDataConsolidated;
     algorithm.SubscriptionManager.RemoveConsolidator(Security.Symbol, Consolidator);
 }
 /// <inheritdoc />
 public override IEnumerable <Symbol> SelectFine(QCAlgorithmFramework algorithm, IEnumerable <FineFundamental> fine)
 {
     return(_fineSelector(fine));
 }
コード例 #21
0
 /// <summary>
 /// Provides derived types a chance to initialize anything special they require
 /// </summary>
 protected virtual void InitializeAlgorithm(QCAlgorithmFramework algorithm)
 {
     _algorithm.SetStartDate(2018, 1, 4);
     _algorithm.AddEquity(Symbols.SPY.Value, Resolution.Daily);
 }
コード例 #22
0
 /// <summary>
 /// Establish one leg of an iron condor according to the insight.
 /// </summary>
 public override List <IPortfolioTarget> FindPotentialOptions(QCAlgorithmFramework algorithm, Symbol symbol, Insight insight)
 {
     return(FindPotentialOptions(algorithm, symbol, insight.Direction));
 }
コード例 #23
0
 /// <summary>
 /// Event fired each time the we add/remove securities from the data feed
 /// </summary>
 /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
 /// <param name="changes">The security additions and removals from the algorithm</param>
 public override void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
 {
     // Get removed symbol and invalidate them in the insight collection
     _removedSymbols = changes.RemovedSecurities.Select(x => x.Symbol).ToList();
     _insightCollection.Clear(_removedSymbols.ToArray());
 }
コード例 #24
0
 /// <summary>
 /// Determines if it's safe to remove the associated symbol data
 /// </summary>
 protected virtual bool IsSafeToRemove(QCAlgorithmFramework algorithm, Symbol symbol)
 {
     // confirm the security isn't currently a member of any universe
     return(!algorithm.UniverseManager.Any(kvp => kvp.Value.ContainsMember(symbol)));
 }
コード例 #25
0
        /// <summary>
        /// Create portfolio targets from the specified insights
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="insights">The insights to create portoflio targets from</param>
        /// <returns>An enumerable of portoflio targets to be sent to the execution model</returns>
        public override IEnumerable <IPortfolioTarget> CreateTargets(QCAlgorithmFramework algorithm, Insight[] insights)
        {
            var targets = new List <IPortfolioTarget>();

            if (algorithm.UtcTime <= _nextExpiryTime &&
                algorithm.UtcTime <= _rebalancingTime &&
                insights.Length == 0 &&
                _removedSymbols == null)
            {
                return(targets);
            }

            _insightCollection.AddRange(insights);

            // Create flatten target for each security that was removed from the universe
            if (_removedSymbols != null)
            {
                var universeDeselectionTargets = _removedSymbols.Select(symbol => new PortfolioTarget(symbol, 0));
                targets.AddRange(universeDeselectionTargets);
                _removedSymbols = null;
            }

            // Get insight that haven't expired of each symbol that is still in the universe
            var activeInsights = _insightCollection.GetActiveInsights(algorithm.UtcTime);

            // Get the last generated active insight for each symbol
            var lastActiveInsights = from insight in activeInsights
                                     group insight by insight.Symbol into g
                                     select g.OrderBy(x => x.GeneratedTimeUtc).Last();

            // give equal weighting to each security
            var count   = lastActiveInsights.Count(x => x.Direction != InsightDirection.Flat);
            var percent = count == 0 ? 0 : 1m / count;

            var errorSymbols = new HashSet <Symbol>();

            foreach (var insight in lastActiveInsights)
            {
                var target = PortfolioTarget.Percent(algorithm, insight.Symbol, (int)insight.Direction * percent);
                if (target != null)
                {
                    targets.Add(target);
                }
                else
                {
                    errorSymbols.Add(insight.Symbol);
                }
            }

            // Get expired insights and create flatten targets for each symbol
            var expiredInsights = _insightCollection.RemoveExpiredInsights(algorithm.UtcTime);

            var expiredTargets = from insight in expiredInsights
                                 group insight.Symbol by insight.Symbol into g
                                 where !_insightCollection.HasActiveInsights(g.Key, algorithm.UtcTime) && !errorSymbols.Contains(g.Key)
                                 select new PortfolioTarget(g.Key, 0);

            targets.AddRange(expiredTargets);

            _nextExpiryTime  = _insightCollection.GetNextExpiryTime();
            _rebalancingTime = algorithm.UtcTime.Add(_rebalancingPeriod);

            return(targets);
        }
コード例 #26
0
ファイル: AlphaModel.cs プロジェクト: jasonhillier/Lean
 /// <summary>
 /// Event fired each time the we add/remove securities from the data feed
 /// </summary>
 /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
 /// <param name="changes">The security additions and removals from the algorithm</param>
 public virtual void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
 {
 }
コード例 #27
0
 public override IEnumerable <Insight> Update(QCAlgorithmFramework algorithm, Slice data)
 {
     yield return(Insight.Price(Symbols.SPY, TimeSpan.FromDays(1), InsightDirection.Up, .5, .75));
 }
コード例 #28
0
 protected override void InitializeAlgorithm(QCAlgorithmFramework algorithm)
 {
     algorithm.AddEquity("BAC");
     algorithm.AddEquity("AIG");
 }
コード例 #29
0
 /// <summary>
 /// Check whether the assets pass a pairs trading test
 /// </summary>
 /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
 /// <param name="asset1">The first asset's symbol in the pair</param>
 /// <param name="asset2">The second asset's symbol in the pair</param>
 /// <returns>True if the statistical test for the pair is successful</returns>
 public override bool HasPassedTest(QCAlgorithmFramework algorithm, Symbol asset1, Symbol asset2)
 {
     return(_bestPair != null && asset1 == _bestPair.Item1 && asset2 == _bestPair.Item2);
 }