Exemplo n.º 1
0
        public void UpdateCallsDisposeOnDisposableInstances()
        {
            var disposable = new Disposable(Symbols.SPY);
            var dictionary = new Dictionary <Symbol, Disposable>
            {
                [Symbols.SPY] = disposable
            };

            var SPY = new Equity(
                Symbols.SPY,
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                new Cash("USD", 1m, 1m),
                SymbolProperties.GetDefault("USD"),
                ErrorCurrencyConverter.Instance,
                new RegisteredSecurityDataTypesProvider(),
                new SecurityCache()
                );
            var changes = SecurityChanges.Removed(SPY);

            NotifiedSecurityChanges.UpdateDictionary(dictionary, changes,
                                                     security => security.Symbol,
                                                     security => new Disposable(security.Symbol)
                                                     );

            Assert.IsTrue(disposable.Disposed);
        }
        public override void DelistedSecurityEmitsFlatTargetWithNewInsights(Language language, InsightDirection direction)
        {
            SetPortfolioConstruction(language);

            var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, Algorithm.UtcTime) };
            var targets  = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList();

            Assert.AreEqual(1, targets.Count);

            // Removing SPY should clear the key in the insight collection
            var changes = SecurityChanges.Removed(Algorithm.Securities[Symbols.SPY]);

            Algorithm.PortfolioConstruction.OnSecuritiesChanged(Algorithm, changes);

            // Equity will be divided by all securities minus 1, since SPY is already invested and we want to remove it
            var amount = Algorithm.Portfolio.TotalPortfolioValue / (decimal)(1 / Weight - 1) *
                         (1 - Algorithm.Settings.FreePortfolioValuePercentage);

            var expectedTargets = Algorithm.Securities.Select(x =>
            {
                // Expected target quantity for SPY is zero, since it will be removed
                var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price);
                return(new PortfolioTarget(x.Key, quantity));
            });

            // Do no include SPY in the insights
            insights = Algorithm.Securities.Keys.Where(x => x.Value != "SPY")
                       .Select(x => GetInsight(x, direction, Algorithm.UtcTime)).ToArray();

            // Create target from an empty insights array
            var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights);

            AssertTargets(expectedTargets, actualTargets);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="configuration">The configuration of the subscription to remove</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        public bool RemoveSubscription(SubscriptionDataConfig configuration)
        {
            // remove the subscription from our collection
            Subscription subscription;

            if (!_subscriptions.TryGetValue(configuration, out subscription))
            {
                Log.Error($"LiveTradingDataFeed.RemoveSubscription(): Unable to locate: {configuration}");
            }

            // don't remove universe subscriptions immediately, instead mark them as disposed
            // so we can turn the crank one more time to ensure we emit security changes properly
            if (subscription.IsUniverseSelectionSubscription && subscription.Universe.DisposeRequested)
            {
                // subscription syncer will dispose the universe AFTER we've run selection a final time
                // and then will invoke SubscriptionFinished which will remove the universe subscription
                return(false);
            }

            if (!_subscriptions.TryRemove(configuration, out subscription))
            {
                Log.Error($"LiveTradingDataFeed.RemoveSubscription(): Unable to remove: {configuration}");
                return(false);
            }

            var security = subscription.Security;

            // remove the subscriptions
            if (subscription.Configuration.IsCustomData)
            {
                _customExchange.RemoveEnumerator(security.Symbol);
                _customExchange.RemoveDataHandler(security.Symbol);
            }
            else
            {
                _dataQueueHandler.Unsubscribe(_job, new[] { security.Symbol });
                _exchange.RemoveDataHandler(security.Symbol);
            }

            // if the security is no longer a member of the universe, then mark the subscription properly
            if (subscription.Universe != null && !subscription.Universe.Members.ContainsKey(configuration.Symbol))
            {
                subscription.MarkAsRemovedFromUniverse();
            }
            subscription.Dispose();

            // keep track of security changes, we emit these to the algorithm
            // as notications, used in universe selection
            if (!subscription.IsUniverseSelectionSubscription)
            {
                _changes += SecurityChanges.Removed(security);
            }

            Log.Trace("LiveTradingDataFeed.RemoveSubscription(): Removed " + configuration);
            UpdateFillForwardResolution();

            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="subscription">The subscription to be removed</param>
        public bool RemoveSubscription(Subscription subscription)
        {
            Subscription sub;

            if (!_subscriptions.TryRemove(subscription.Security.Symbol, out sub))
            {
                Log.Error("FileSystemDataFeed.RemoveSubscription(): Unable to remove: " + subscription.Security.Symbol.ToString());
                return(false);
            }

            Log.Debug("FileSystemDataFeed.RemoveSubscription(): Removed " + subscription.Security.Symbol.ToString());

            _changes += SecurityChanges.Removed(sub.Security);

            _fillForwardResolution.Value = ResolveFillForwardResolution(_algorithm);
            return(true);
        }
        public override void DelistedSecurityEmitsFlatTargetWithNewInsights(Language language, InsightDirection direction)
        {
            SetPortfolioConstruction(language);

            var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, Algorithm.UtcTime) };
            var targets  = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList();

            Assert.AreEqual(1, targets.Count);

            // Removing SPY should clear the key in the insight collection
            var changes = SecurityChanges.Removed(Algorithm.Securities[Symbols.SPY]);

            Algorithm.PortfolioConstruction.OnSecuritiesChanged(Algorithm, changes);

            // Since we have 3 B, 2 T and 1 X, each security in each sector will get
            // B => .166%, T => .25, X => 0% (removed)
            var sectorCount     = 2;
            var groupedBySector = Algorithm.Securities
                                  .Where(pair => pair.Value.Fundamentals?.CompanyReference?.IndustryTemplateCode != null)
                                  .GroupBy(pair => pair.Value.Fundamentals.CompanyReference.IndustryTemplateCode);

            var expectedTargets = new List <PortfolioTarget>();

            foreach (var securities in groupedBySector)
            {
                var list   = securities.ToList();
                var amount = Algorithm.Portfolio.TotalPortfolioValue / list.Count / sectorCount *
                             (1 - Algorithm.Settings.FreePortfolioValuePercentage);

                expectedTargets.AddRange(list
                                         .Select(x => new PortfolioTarget(x.Key, x.Key.Value == "SPY" ? 0
                        : (int)direction * Math.Floor(amount / x.Value.Price))));
            }

            // Do no include SPY in the insights
            insights = Algorithm.Securities.Keys.Where(x => x.Value != "SPY")
                       .Select(x => GetInsight(x, direction, Algorithm.UtcTime)).ToArray();

            // Create target from an empty insights array
            var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights);

            Assert.Greater(Algorithm.Securities.Count, expectedTargets.Count);
            AssertTargets(expectedTargets, actualTargets);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="configuration">The configuration of the subscription to remove</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        public bool RemoveSubscription(SubscriptionDataConfig configuration)
        {
            // remove the subscription from our collection
            Subscription subscription;

            if (!_subscriptions.TryRemove(configuration, out subscription))
            {
                Log.Error("LiveTradingDataFeed.RemoveSubscription(): Unable to remove: " + configuration.ToString());
                return(false);
            }

            var security = subscription.Security;

            // remove the subscriptions
            if (subscription.Configuration.IsCustomData)
            {
                _customExchange.RemoveEnumerator(security.Symbol);
                _customExchange.RemoveDataHandler(security.Symbol);
            }
            else
            {
                _dataQueueHandler.Unsubscribe(_job, new[] { security.Symbol });
                _exchange.RemoveDataHandler(security.Symbol);
            }

            // if the security is no longer a member of the universe, then mark the subscription properly
            if (subscription.Universe != null && !subscription.Universe.Members.ContainsKey(configuration.Symbol))
            {
                subscription.MarkAsRemovedFromUniverse();
            }
            subscription.Dispose();

            // keep track of security changes, we emit these to the algorithm
            // as notications, used in universe selection
            if (!subscription.IsUniverseSelectionSubscription)
            {
                _changes += SecurityChanges.Removed(security);
            }

            Log.Trace("LiveTradingDataFeed.RemoveSubscription(): Removed " + configuration);
            UpdateFillForwardResolution();

            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="subscription">The subscription to be removed</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        public bool RemoveSubscription(Subscription subscription)
        {
            var security = subscription.Security;

            _exchange.RemoveHandler(security.Symbol);

            // request to unsubscribe from the subscription
            if (!security.SubscriptionDataConfig.IsCustomData)
            {
                _dataQueueHandler.Unsubscribe(_job, new Dictionary <SecurityType, List <string> >
                {
                    { security.Type, new List <string> {
                          security.Symbol
                      } }
                });
            }

            // remove the subscription from our collection
            Subscription sub;

            if (_subscriptions.TryRemove(new SymbolSecurityType(security), out sub))
            {
                sub.Dispose();
            }
            else
            {
                return(false);
            }

            Log.Trace("LiveTradingDataFeed.RemoveSubscription(): Removed " + security.Symbol);

            // keep track of security changes, we emit these to the algorithm
            // as notications, used in universe selection
            _changes += SecurityChanges.Removed(security);

            // update our fill forward resolution setting
            _fillForwardResolution.Value = ResolveFillForwardResolution(_algorithm);

            return(true);
        }
Exemplo n.º 8
0
        public void DelistedSecurityEmitsFlatTargetWithoutNewInsights(Language language)
        {
            SetPortfolioConstruction(language, _algorithm);

            var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, _algorithm.UtcTime) };
            var targets  = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList();

            Assert.AreEqual(1, targets.Count);

            var changes = SecurityChanges.Removed(_algorithm.Securities[Symbols.SPY]);

            _algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes);

            var expectedTargets = new List <IPortfolioTarget> {
                new PortfolioTarget(Symbols.SPY, 0)
            };

            // Create target from an empty insights array
            var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, new Insight[0]);

            AssertTargets(expectedTargets, actualTargets);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="symbol">The symbol of the subscription to be removed</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        public bool RemoveSubscription(Symbol symbol)
        {
            List <Subscription> subscriptions;

            if (!_subscriptions.TryRemove(symbol, out subscriptions))
            {
                Log.Error("FileSystemDataFeed.RemoveSubscription(): Unable to remove: " + symbol.ToString());
                return(false);
            }

            foreach (var subscription in subscriptions)
            {
                subscription.Dispose();
            }

            Log.Debug("FileSystemDataFeed.RemoveSubscription(): Removed " + symbol.ToString());

            _changes += SecurityChanges.Removed(subscriptions.Select(x => x.Security).ToArray());

            UpdateFillForwardResolution();
            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="subscription">The subscription to be removed</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        public bool RemoveSubscription(Subscription subscription)
        {
            var security = subscription.Security;

            // remove the subscriptions
            if (subscription.Configuration.IsCustomData)
            {
                _customExchange.RemoveEnumerator(security.Symbol);
                _customExchange.RemoveDataHandler(security.Symbol);
            }
            else
            {
                _dataQueueHandler.Unsubscribe(_job, new[] { security.Symbol });
                _exchange.RemoveDataHandler(security.Symbol);
            }

            // remove the subscription from our collection
            Subscription sub;

            if (_subscriptions.TryRemove(subscription.Security.Symbol, out sub))
            {
                sub.Dispose();
            }
            else
            {
                return(false);
            }

            Log.Trace("LiveTradingDataFeed.RemoveSubscription(): Removed " + security.Symbol.ToString());

            // keep track of security changes, we emit these to the algorithm
            // as notications, used in universe selection
            _changes += SecurityChanges.Removed(security);

            // update our fill forward resolution setting
            _fillForwardResolution.Value = ResolveFillForwardResolution(_algorithm);

            return(true);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="symbol">The symbol of the subscription to be removed</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        public bool RemoveSubscription(Symbol symbol)
        {
            // remove the subscription from our collection
            List <Subscription> subscriptions;

            if (!_subscriptions.TryRemove(symbol, out subscriptions))
            {
                return(false);
            }

            foreach (var subscription in subscriptions)
            {
                var security = subscription.Security;

                // remove the subscriptions
                if (subscription.Configuration.IsCustomData)
                {
                    _customExchange.RemoveEnumerator(security.Symbol);
                    _customExchange.RemoveDataHandler(security.Symbol);
                }
                else
                {
                    _dataQueueHandler.Unsubscribe(_job, new[] { security.Symbol });
                    _exchange.RemoveDataHandler(security.Symbol);
                }

                subscription.Dispose();

                // keep track of security changes, we emit these to the algorithm
                // as notications, used in universe selection
                _changes += SecurityChanges.Removed(security);
            }

            Log.Trace("LiveTradingDataFeed.RemoveSubscription(): Removed " + symbol.ToString());
            UpdateFillForwardResolution();

            return(true);
        }