Exemplo n.º 1
0
        /// <summary>
        /// Will handle adding and removing securities from the algorithm based on the current portfolio of the different alphas
        /// </summary>
        private void ProcessPortfolioState(QCAlgorithm algorithm, AlphaStreamsPortfolioState portfolioState)
        {
            if (portfolioState == null)
            {
                return;
            }

            var alphaId = portfolioState.Symbol;

            if (!_symbolsPerAlpha.TryGetValue(alphaId, out var currentSymbols))
            {
                _symbolsPerAlpha[alphaId] = currentSymbols = new HashSet <Symbol>();
            }

            var newSymbols = new HashSet <Symbol>(currentSymbols.Count);

            foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions).Select(state => state.Symbol) ?? Enumerable.Empty <Symbol>())
            {
                // only add it if it's not used by any alpha (already added check)
                if (newSymbols.Add(symbol) && !UsedBySomeAlpha(symbol))
                {
                    algorithm.AddSecurity(symbol,
                                          resolution: algorithm.UniverseSettings.Resolution,
                                          extendedMarketHours: algorithm.UniverseSettings.ExtendedMarketHours);
                }
            }
            _symbolsPerAlpha[alphaId] = newSymbols;

            foreach (var symbol in currentSymbols.Where(symbol => !UsedBySomeAlpha(symbol)))
            {
                algorithm.RemoveSecurity(symbol);
            }
        }
 private void AddSecurities(QCAlgorithm algorithm, AlphaStreamsPortfolioState portfolioState)
 {
     foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions)
              .Select(state => state.Symbol) ?? Enumerable.Empty <Symbol>())
     {
         _algorithm.AddSecurity(symbol);
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AlphaResultPacket"/> class
 /// </summary>
 /// <param name="algorithmId">The algorithm's unique identifier</param>
 /// <param name="userId">The user's id</param>
 /// <param name="insights">Alphas generated by the algorithm</param>
 /// <param name="orderEvents">OrderEvents generated by the algorithm</param>
 /// <param name="orders">Orders generated or updated by the algorithm</param>
 /// <param name="portfolio">The algorithms current portfolio state</param>
 public AlphaResultPacket(string algorithmId, int userId, List <Insight> insights = null, List <OrderEvent> orderEvents = null, List <Order> orders = null, AlphaStreamsPortfolioState portfolio = null)
     : base(PacketType.AlphaResult)
 {
     UserId      = userId;
     AlgorithmId = algorithmId;
     Insights    = insights;
     OrderEvents = orderEvents;
     Orders      = orders;
     Portfolio   = portfolio;
 }
Exemplo n.º 4
0
        public void AlphaStreamsPortfolioStateRoundTrip()
        {
            var symbol = Symbol.CreateBase(typeof(AlphaStreamsPortfolioState),
                                           Symbol.Create("9fc8ef73792331b11dbd5429a", SecurityType.Base, Market.USA),
                                           Market.USA);

            var state = new AlphaStreamsPortfolioState
            {
                Id              = 1000,
                Time            = DateTime.UtcNow,
                Symbol          = symbol,
                Source          = "Live trading",
                AccountCurrency = Currencies.EUR,
                AlgorithmId     = "BasicTemplateAlgorithm",
                AlphaId         = "9fc8ef73792331b11dbd5429a",
                CashBook        = new Dictionary <string, Cash>
                {
                    { Currencies.EUR, new Cash(Currencies.EUR, 1, 1) }
                },
                UnsettledCashBook = new Dictionary <string, Cash>
                {
                    { Currencies.USD, new Cash(Currencies.USD, 1, 1.2m) }
                },
                PositionGroups = new List <PositionGroupState>
                {
                    new PositionGroupState
                    {
                        MarginUsed = 10,
                        PortfolioValuePercentage = 0.001m,
                        Positions = new List <PositionState>
                        {
                            new PositionState
                            {
                                Quantity     = 1,
                                UnitQuantity = 1,
                                Symbol       = Symbols.SPY
                            }
                        }
                    }
                },
                TotalMarginUsed     = 1000,
                TotalPortfolioValue = 100000,
            };

            var serializedState = state.ProtobufSerialize(new Guid());

            using (var stream = new MemoryStream(serializedState))
            {
                var result = (AlphaStreamsPortfolioState)Serializer.Deserialize <IEnumerable <BaseData> >(stream).First();

                AssertAreEqual(state, result);
            }
        }
        /// <summary>
        /// Determines the portfolio weight to give a specific alpha. Default implementation just returns equal weighting
        /// </summary>
        /// <param name="portfolioState">The alphas portfolio state to get the weight for</param>
        /// <param name="totalUsablePortfolioValue">This algorithms usable total portfolio value, removing the free portfolio value</param>
        /// <param name="cashBook">This algorithms cash book</param>
        /// <returns>The weight to use on this alphas positions</returns>
        private decimal GetAlphaWeight(AlphaStreamsPortfolioState portfolioState,
                                       decimal totalUsablePortfolioValue,
                                       CashBook cashBook)
        {
            var alphaPortfolioValueInOurAccountCurrency =
                cashBook.ConvertToAccountCurrency(portfolioState.TotalPortfolioValue, portfolioState.AccountCurrency);

            if (alphaPortfolioValueInOurAccountCurrency == 0)
            {
                return(0);
            }

            return(totalUsablePortfolioValue * GetAlphaWeight(portfolioState.AlphaId) / alphaPortfolioValueInOurAccountCurrency);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Determines the portfolio weight to give a specific alpha. Default implementation just returns equal weighting
        /// </summary>
        /// <param name="portfolioState">The alphas portfolio state to get the weight for</param>
        /// <param name="totalUsablePortfolioValue">This algorithms usable total portfolio value</param>
        /// <param name="cashBook">This algorithms cash book</param>
        /// <returns>The weight to use on this alphas positions</returns>
        protected virtual decimal GetAlphaWeight(AlphaStreamsPortfolioState portfolioState,
                                                 decimal totalUsablePortfolioValue,
                                                 CashBook cashBook)
        {
            var alphaPortfolioValueInOurAccountCurrency =
                cashBook.ConvertToAccountCurrency(portfolioState.TotalPortfolioValue, portfolioState.AccountCurrency);

            if (alphaPortfolioValueInOurAccountCurrency == 0)
            {
                return(0);
            }

            var equalWeightFactor = 1m / _targetsPerSymbolPerAlpha.Count;

            return(totalUsablePortfolioValue * equalWeightFactor / alphaPortfolioValueInOurAccountCurrency);
        }
Exemplo n.º 7
0
        private bool ProcessPortfolioState(AlphaStreamsPortfolioState portfolioState, QCAlgorithm algorithm)
        {
            var alphaId = portfolioState.Symbol;

            if (!_targetsPerSymbolPerAlpha.TryGetValue(alphaId, out var ourExistingTargets))
            {
                _targetsPerSymbolPerAlpha[alphaId] = ourExistingTargets = new Dictionary <Symbol, PortfolioTarget>();
            }

            var totalUsablePortfolioValue = algorithm.Portfolio.TotalPortfolioValue - algorithm.Settings.FreePortfolioValue;
            var alphaWeightFactor         = GetAlphaWeight(portfolioState, totalUsablePortfolioValue, algorithm.Portfolio.CashBook);

            // first we create all the new aggregated targets for the provided portfolio state
            var newTargets = new Dictionary <Symbol, PortfolioTarget>();

            foreach (var positionGroup in portfolioState.PositionGroups ?? Enumerable.Empty <PositionGroupState>())
            {
                foreach (var position in positionGroup.Positions)
                {
                    // let's keep the unit quantity so we can round by it
                    _unitQuantity[position.Symbol] = position.UnitQuantity;

                    newTargets.TryGetValue(position.Symbol, out var existingAggregatedTarget);
                    var quantity = position.Quantity * alphaWeightFactor + (existingAggregatedTarget?.Quantity ?? 0);
                    newTargets[position.Symbol] = new PortfolioTarget(position.Symbol, quantity.DiscretelyRoundBy(position.UnitQuantity, MidpointRounding.ToZero));
                }
            }

            var updatedTargets = false;

            // We adjust the new targets based on what we already have:
            // - We add any existing targets if any -> other alphas
            //    - But we deduct our own existing target from it if any (previous state)
            foreach (var ourNewTarget in newTargets.Values)
            {
                var symbol = ourNewTarget.Symbol;
                var newAggregatedTarget = ourNewTarget;
                if (_targetsPerSymbol.TryGetValue(symbol, out var existingAggregatedTarget))
                {
                    ourExistingTargets.TryGetValue(symbol, out var ourExistingTarget);

                    var quantity = existingAggregatedTarget.Quantity + ourNewTarget.Quantity - (ourExistingTarget?.Quantity ?? 0);
                    newAggregatedTarget = new PortfolioTarget(symbol, quantity.DiscretelyRoundBy(_unitQuantity[symbol], MidpointRounding.ToZero));
                }
                ourExistingTargets[symbol] = ourNewTarget;

                if (existingAggregatedTarget == null || existingAggregatedTarget.Quantity != newAggregatedTarget.Quantity)
                {
                    updatedTargets            = true;
                    _targetsPerSymbol[symbol] = newAggregatedTarget;
                }
            }

            List <Symbol> symbolsToRemove = null;

            // We adjust existing targets for symbols that got removed from this alpha
            foreach (var removedTarget in ourExistingTargets.Values.Where(target => !newTargets.ContainsKey(target.Symbol)))
            {
                var symbol = removedTarget.Symbol;
                var newAggregatedTarget = removedTarget;
                if (_targetsPerSymbol.TryGetValue(symbol, out var existingAggregatedTarget))
                {
                    var quantity = existingAggregatedTarget.Quantity - removedTarget.Quantity;
                    newAggregatedTarget = new PortfolioTarget(symbol, quantity.DiscretelyRoundBy(_unitQuantity[symbol], MidpointRounding.ToZero));
                }

                symbolsToRemove ??= new List <Symbol>();
                symbolsToRemove.Add(symbol);
                if (existingAggregatedTarget == null || existingAggregatedTarget.Quantity != newAggregatedTarget.Quantity)
                {
                    updatedTargets            = true;
                    _targetsPerSymbol[symbol] = newAggregatedTarget;
                }
            }

            if (symbolsToRemove != null)
            {
                for (var i = 0; i < symbolsToRemove.Count; i++)
                {
                    // we can't remove from dictionary while iterating through it
                    ourExistingTargets.Remove(symbolsToRemove[i]);
                }
            }

            return(updatedTargets);
        }