public override IEnumerable <Insight> Update(QCAlgorithm algorithm, Slice data)
        {
            var insights = new List <Insight>();

            // Check for all Quandl Symbols in current data Slice
            if (!(data.ContainsKey(_highs) && data.ContainsKey(_lows)))
            {
                return(insights);
            }

            // Higher numbers of stocks at their 52-week low naturally correlate with recessions or
            // large stock market corrections, and the opposite can be said of large numbers of stocks
            // reaching their 52-week highs at the same time. When viewed like this, the spread between
            // the two numbers can tell us a lot about the overall direction of the US equities
            // market. If the spread between High and Low decreases and/or inverts, this is likely a
            // significant indicator of a bear market. This and other metrics can be used to generate
            // valuable Insights

            // More URC market data can be found at Quandl
            // https://www.quandl.com/data/URC-Unicorn-Research-Corporation

            // Generate Insights here!

            return(insights);
        }
        public override void OnData(Slice data)
        {
            if (!data.ContainsKey(Usdinr) || !data.ContainsKey(Nifty))
            {
                return;
            }

            _today = new CorrelationPair(data.Time);
            _today.Add(Usdinr, data[Usdinr].Price);

            try
            {
                _today.Add(Nifty, data[Nifty].Close);
                if (_today.Date == data.Time)
                {
                    Log("Date: " + data.Time + " Price: " + data[Nifty].Price);
                    _prices.Add(_today);

                    if (_prices.Count > MinimumCorrelationHistory)
                    {
                        _prices.RemoveAt(0);
                    }
                }

                if (_prices.Count < 2)
                {
                    return;
                }

                var maxAsset = string.Empty;
                var maxGain  = double.MinValue;

                foreach (var symbol in _today.Prices.Keys)
                {
                    var last  = (from pair in _prices select pair.Prices[symbol]).Last();
                    var first = (from pair in _prices select pair.Prices[symbol]).First();
                    var gain  = (last - first) / first;

                    if (!(gain > maxGain))
                    {
                        continue;
                    }

                    maxAsset = symbol;
                    maxGain  = gain;
                }

                if (!maxAsset.Equals(string.Empty))
                {
                    CustomSetHoldings(maxAsset, 1, true);
                }
            }
            catch (Exception ex)
            {
                Debug("Exception: " + ex.Message);
            }
        }
Example #3
0
        /// <summary>
        /// Event Handler for Nifty Data Events: These Nifty objects are created from our
        /// "Nifty" type below and fired into this event handler.
        /// </summary>
        /// <param name="data">One(1) Nifty Object, streamed into our algorithm synchronised in time with our other data streams</param>
        public void OnData(Slice data)
        {
            if (data.ContainsKey("USDINR"))
            {
                _today = new CorrelationPair(Time)
                {
                    CurrencyPrice = Convert.ToDouble(data["USDINR"].Close)
                };
            }

            if (!data.ContainsKey("NIFTY"))
            {
                return;
            }

            try
            {
                _today.NiftyPrice = Convert.ToDouble(data["NIFTY"].Close);
                if (_today.Date == data["NIFTY"].Time)
                {
                    _prices.Add(_today);

                    if (_prices.Count > _minimumCorrelationHistory)
                    {
                        _prices.RemoveAt(0);
                    }
                }

                //Strategy
                var quantity     = (int)(Portfolio.MarginRemaining * 0.9m / data["NIFTY"].Close);
                var highestNifty = (from pair in _prices select pair.NiftyPrice).Max();
                var lowestNifty  = (from pair in _prices select pair.NiftyPrice).Min();

                if (Time.DayOfWeek == DayOfWeek.Wednesday) //prices.Count >= minimumCorrelationHistory &&
                {
                    //List<double> niftyPrices = (from pair in prices select pair.NiftyPrice).ToList();
                    //List<double> currencyPrices = (from pair in prices select pair.CurrencyPrice).ToList();
                    //double correlation = Correlation.Pearson(niftyPrices, currencyPrices);
                    //double niftyFraction = (correlation)/2;

                    if (Convert.ToDouble(data["NIFTY"].Open) >= highestNifty)
                    {
                        var code = Order("NIFTY", quantity - Portfolio["NIFTY"].Quantity);
                        Debug("LONG " + code + " Time: " + Time.ToShortDateString() + " Quantity: " + quantity + " Portfolio:" + Portfolio["NIFTY"].Quantity + " Nifty: " + data["NIFTY"].Close + " Buying Power: " + Portfolio.TotalPortfolioValue);
                    }
                    else if (Convert.ToDouble(data["NIFTY"].Open) <= lowestNifty)
                    {
                        var code = Order("NIFTY", -quantity - Portfolio["NIFTY"].Quantity);
                        Debug("SHORT " + code + " Time: " + Time.ToShortDateString() + " Quantity: " + quantity + " Portfolio:" + Portfolio["NIFTY"].Quantity + " Nifty: " + data["NIFTY"].Close + " Buying Power: " + Portfolio.TotalPortfolioValue);
                    }
                }
            }
            catch (Exception err)
            {
                Debug("Error: " + err.Message);
            }
        }
Example #4
0
        public override void OnData(Slice slice)
        {
            if (!slice.ContainsKey(Securities[_symbol1].Symbol))
            {
                Console.WriteLine("No " + _symbol1 + " data on " + slice.Time);
                return;
            }
            if (!slice.ContainsKey(Securities[_symbol2].Symbol))
            {
                Console.WriteLine("No " + _symbol2 + " data on " + slice.Time);
                return;
            }

            if (slice.Time.DayOfYear == _dayOfYear)
                return;
            else
                _dayOfYear = slice.Time.DayOfYear;

            var price1 = slice.Bars[_symbol1].Close;
            var price2 = slice.Bars[_symbol2].Close;

            if (_initialized)
            {
                var return1 = price1 / _lastPrice1 - 1;
                var return2 = price2 / _lastPrice2 - 1;

                if (return1 > return2)
                {
                    int shortQuantity = Portfolio.Securities[_symbol1].Holdings.Quantity;
                    if (shortQuantity > 0)
                        Order(Securities[_symbol1].Symbol, -shortQuantity);

                    decimal actualCash = Portfolio.Cash - Portfolio.Securities[_symbol1].Holdings.Quantity * price1;
                    int longQuantity = Decimal.ToInt32(Math.Floor(actualCash / price2));
                    if (longQuantity > 0)
                        Order(Securities[_symbol2].Symbol, longQuantity);
                }
                else if (return2 > return1)
                {
                    int shortQuantity = Portfolio.Securities[_symbol2].Holdings.Quantity;
                    if (shortQuantity > 0)
                        Order(Securities[_symbol2].Symbol, -shortQuantity);

                    decimal actualCash = Portfolio.Cash - Portfolio.Securities[_symbol1].Holdings.Quantity * price1;
                    Console.WriteLine("2>1: " + actualCash);
                    int longQuantity = Decimal.ToInt32(Math.Floor(actualCash / price1));
                    if (longQuantity > 0)
                        Order(Securities[_symbol1].Symbol, longQuantity);
                }
            }
            else
                _initialized = true;

            _lastPrice1 = price1;
            _lastPrice2 = price2;
        }
Example #5
0
        public override void OnData(Slice slice)
        {
            if (!slice.ContainsKey(_spx))
            {
                return;
            }

            if (_addOption)
            {
                var contracts = OptionChainProvider.GetOptionContractList(_spx, Time);
                contracts = contracts.Where(x =>
                                            x.ID.OptionRight == OptionRight.Put &&
                                            x.ID.Date.Date == new DateTime(2021, 1, 15));

                var option = AddIndexOptionContract(contracts.First(), Resolution.Minute);
                _optionExpiry = option.Expiry;
                _optionSymbol = option.Symbol;


                _addOption = false;
            }

            if (slice.ContainsKey(_optionSymbol))
            {
                if (!Portfolio.Invested)
                {
                    SetHoldings(_optionSymbol, 0.25);
                }

                // Verify the order of delisting; warning then delisting
                Delisting delisting;
                if (slice.Delistings.TryGetValue(_optionSymbol, out delisting))
                {
                    switch (delisting.Type)
                    {
                    case DelistingType.Warning:
                        _receivedWarning = true;
                        break;

                    case DelistingType.Delisted:
                        if (!_receivedWarning)
                        {
                            throw new Exception("Did not receive warning before delisting");
                        }
                        break;
                    }
                }

                // Verify we aren't receiving expired option data.
                if (_optionExpiry < Time.Date)
                {
                    throw new Exception($"Received expired contract {_optionSymbol} expired: {_optionExpiry} current time: {Time}");
                }
            }
        }
Example #6
0
        public override void OnData(Slice data)
        {
            if (data.ContainsKey(_cboeVix))
            {
                var vix = data.Get <CBOE>(_cboeVix);
                Log($"VIX: {vix}");
            }

            if (data.ContainsKey(_usEnergy))
            {
                var inputIntoRefineries = data.Get <USEnergy>(_usEnergy);
                Log($"U.S. Input Into Refineries: {Time}, {inputIntoRefineries.Value}");
            }
        }
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!_equityBought && data.ContainsKey(_spy))
            {
                //Buy our Equity
                var quantity = CalculateOrderQuantity(_spy, .1m);
                _equityBuy    = MarketOrder(_spy, quantity, asynchronous: true);
                _equityBought = true;
            }

            if (!_optionBought)
            {
                // Buy our option
                OptionChain chain;
                if (data.OptionChains.TryGetValue(_optionSymbol, out chain))
                {
                    // Find the second call strike under market price expiring today
                    var contracts = (
                        from optionContract in chain.OrderByDescending(x => x.Strike)
                        where optionContract.Right == OptionRight.Call
                        where optionContract.Expiry == Time.Date
                        where optionContract.Strike < chain.Underlying.Price
                        select optionContract
                        ).Take(2);

                    if (contracts.Any())
                    {
                        var optionToBuy = contracts.FirstOrDefault();
                        _optionStrikePrice = optionToBuy.Strike;
                        _optionBuy         = MarketOrder(optionToBuy.Symbol, 1);
                        _optionBought      = true;
                    }
                }
            }
        }
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!data.ContainsKey("SPY"))
            {
                return;
            }

            // After an order is placed, it will decrease in quantity by one for each minute, being cancelled altogether
            // if not filled within 10 minutes.
            if (Transactions.GetOpenOrders().Count == 0)
            {
                var goLong = Time.Day < 9;
                _negative = goLong ? 1 : -1;
                var orderRequest = new SubmitOrderRequest(OrderType.LimitIfTouched, SecurityType.Equity, "SPY",
                                                          _negative * 10, 0,
                                                          data["SPY"].Price - (decimal)_negative, data["SPY"].Price - (decimal)0.25 * _negative, UtcTime,
                                                          $"LIT - Quantity: {_negative * 10}");
                _request = Transactions.AddOrder(orderRequest);
                return;
            }

            // Order updating if request exists
            if (_request != null)
            {
                if (_request.Quantity == 1)
                {
                    Transactions.CancelOpenOrders();
                    _request = null;
                    return;
                }

                var newQuantity = _request.Quantity - _negative;
                _request.UpdateQuantity(newQuantity, $"LIT - Quantity: {newQuantity}");
            }
        }
Example #9
0
        public void EquitiesIgnoreQuoteBars()
        {
            var quoteBar = new QuoteBar {
                Symbol = Symbols.SPY, Time = DateTime.Now
            };
            var slice = new Slice(DateTime.Now, new[] { quoteBar });

            Assert.IsFalse(slice.HasData);
            Assert.IsTrue(slice.ToList().Count == 0);
            Assert.IsFalse(slice.ContainsKey(Symbols.SPY));
            Assert.Throws <KeyNotFoundException>(() => { var data = slice[Symbols.SPY]; });
            Assert.AreEqual(0, slice.Count);

            var tickQuoteBar = new Tick {
                Symbol = Symbols.SPY, Time = DateTime.Now, TickType = TickType.Quote
            };

            slice = new Slice(DateTime.Now, new[] { tickQuoteBar });

            Assert.IsFalse(slice.HasData);
            Assert.IsTrue(slice.ToList().Count == 0);
            Assert.IsFalse(slice.ContainsKey(Symbols.SPY));
            Assert.Throws <KeyNotFoundException>(() => { var data = slice[Symbols.SPY]; });
            Assert.AreEqual(0, slice.Count);
        }
        public override void OnData(Slice data)
        {
            // Make sure we have an interest rate calendar event
            if (!data.ContainsKey(_interestRate))
            {
                return;
            }

            var announcement = data.Get <TradingEconomicsCalendar>(_interestRate);

            // Confirm it's a FED Rate Decision
            if (announcement.Event != "Fed Interest Rate Decision")
            {
                return;
            }

            // In the event of a rate increase, rebalance 50% to Bonds.
            var interestRateDecreased = announcement.Actual <= announcement.Previous;

            if (interestRateDecreased)
            {
                SetHoldings("SPY", 1);
                SetHoldings("AGG", 0);
            }
            else
            {
                SetHoldings("SPY", 0.5);
                SetHoldings("AGG", 0.5);
            }
        }
Example #11
0
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            //foreach (string symbol in Securities.Keys)
            //{
            //    if (Securities[symbol].Holdings.UnrealizedProfit > 0)
            //    {
            //        Order(symbol, -Securities[symbol].Holdings.Quantity);
            //    }
            //}

            //if (Portfolio["SPY"].UnrealizedProfit > 0)
            //{
            //}
            if (!data.ContainsKey(securityName))
            {
                return;
            }

            TradeBar bar = data.Bars[securityName];

            if (!Portfolio.Invested)
            {
                //SetHoldings(securityName, 10);
                OrderTicket ticket = Order(securityName, 100);
                WriteTicketInfo(ticket);
                Debug("Purchased Stock");
                WriteBarInfo(bar);
                WritePortfolioInfo();
            }
        }
Example #12
0
        public override void OnData(Slice data)
        {
            if (_contractSymbol != null)
            {
                return;
            }

            // Buy the underlying for our covered put
            if (data.ContainsKey(_equity) && !_purchasedUnderlying)
            {
                MarketOrder(_equity, 100 * quantity);
            }

            // Buy a contract and exercise it immediately
            if (_purchasedUnderlying && data.OptionChains.TryGetValue(_option, out OptionChain chain))
            {
                var contract = chain
                               .Where(x => x.Right == OptionRight.Put)
                               .OrderByDescending(x => x.Strike - data[_equity].Price)
                               .FirstOrDefault();

                _contractSymbol = contract.Symbol;
                MarketOrder(_contractSymbol, quantity);

                // Exercise option
                Log("Quantity before: " + Portfolio[_equity].Quantity);
                ExerciseOption(_contractSymbol, quantity);
                Log("Quantity after: " + Portfolio[_equity].Quantity);
            }
        }
Example #13
0
        /// <summary>
        /// Updates this alpha model with the latest data from the algorithm.
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="data">The new data available</param>
        /// <returns>The new insights generated</returns>
        public override IEnumerable <Insight> Update(QCAlgorithm algorithm, Slice data)
        {
            if (!data.ContainsKey(_calendar))
            {
                return(Enumerable.Empty <Insight>());
            }

            var insights = new List <Insight>();

            // Forecast Interest Rate
            var foreIR = System.Convert.ToDecimal(data[_calendar].Forecast.Replace("%", ""), CultureInfo.InvariantCulture);
            // Previous released actual Interest Rate
            var prevIR     = System.Convert.ToDecimal(data[_calendar].Previous.Replace("%", ""), CultureInfo.InvariantCulture);
            var usdValueUp = foreIR >= prevIR;

            foreach (var pair in _pairs)
            {
                var direction = pair.Value.StartsWith("USD") && usdValueUp ||
                                pair.Value.EndsWith("USD") && !usdValueUp
                    ? InsightDirection.Up
                    : InsightDirection.Down;

                insights.Add(Insight.Price(pair, _predictionInterval, direction));
            }

            return(insights);
        }
Example #14
0
        /// <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 override IEnumerable <Insight> Update(QCAlgorithmFramework algorithm, Slice data)
        {
            var insights = new List <Insight>();
            int mag      = 0;

            var symbol = _symbolDataBySymbol.Keys.First();

            if (data.ContainsKey(symbol))
            {
                for (int i = 0; i < _prices.Length; i++)
                {
                    if (_magnitudes[i] > 0)
                    {
                        if ((double)((TradeBar)data[symbol]).Price > _prices[i])
                        {
                            mag = _magnitudes[i];
                        }
                    }
                    else
                    {
                        if ((double)((TradeBar)data[symbol]).Price < _prices[i])
                        {
                            mag = _magnitudes[i];
                        }
                    }

                    if ((mag > 0 && mag > _lastMag) || (mag < 0 && mag < _lastMag))
                    {
                        _lastMag = mag;

                        insights.Add(Insight.Price(symbol, TimeSpan.FromMinutes(15), ((mag < 0 && _inverted) || (mag > 0 && !_inverted)) ? InsightDirection.Up : InsightDirection.Down, mag));
                    }
                }

                /*
                 * OptionChain chain;
                 * if (!TryGetOptionChain(algorithm, symbol, out chain))
                 * return insights;
                 *
                 * var options = chain.Where((o) => Math.Abs((o.Expiry - data.Time).TotalDays) <= _period);
                 * if (options.Count()>0)
                 * {
                 * if (!_symbolDataBySymbol[symbol])
                 * {
                 * _symbolDataBySymbol[symbol] = true; //debounce
                 * //indicate a 'short' signal for expiring options
                 * insights.Add(Insight.Price(symbol, TimeSpan.FromDays(_period + 1), _inverted ? InsightDirection.Up : InsightDirection.Down, 1));
                 * }
                 * }
                 * else if (_symbolDataBySymbol[symbol])
                 * {
                 * _symbolDataBySymbol[symbol] = false; //debounce
                 * insights.Add(Insight.Price(symbol, TimeSpan.FromDays(_period + 1), InsightDirection.Flat));
                 * }
                 */
            }

            return(insights);
        }
        public override void OnData(Slice data)
        {
            if (!data.HasData)
            {
                return;
            }

            _onDataReached = true;

            var hasOptionQuoteBars = false;

            foreach (var qb in data.QuoteBars.Values)
            {
                if (qb.Symbol.SecurityType != SecurityType.FutureOption)
                {
                    continue;
                }

                hasOptionQuoteBars = true;

                _symbolsReceived.Add(qb.Symbol);
                if (!_dataReceived.ContainsKey(qb.Symbol))
                {
                    _dataReceived[qb.Symbol] = new List <QuoteBar>();
                }

                _dataReceived[qb.Symbol].Add(qb);
            }

            if (_invested || !hasOptionQuoteBars)
            {
                return;
            }

            if (data.ContainsKey(_es20h20) && data.ContainsKey(_es19m20))
            {
                SetHoldings(_es20h20, 0.2);
                SetHoldings(_es19m20, 0.2);

                _invested = true;
            }
        }
        public override void OnData(Slice data)
        {
            if (data.ContainsKey(_cboeVix))
            {
                var vix = data.Get <CBOE>(_cboeVix);
                Log($"VIX: {vix}");
            }

            if (data.ContainsKey(_usEnergy))
            {
                var inputIntoRefineries = data.Get <USEnergy>(_usEnergy);
                Log($"U.S. Input Into Refineries: {Time}, {inputIntoRefineries.Value}");
            }

            if (data.ContainsKey(_fredPeakToTrough))
            {
                var peakToTrough = data.Get <Fred>(_fredPeakToTrough);
                Log($"OECD based Recession Indicator for the United States from the Peak through the Trough: {peakToTrough}");
            }
        }
Example #17
0
        public override void OnData(Slice data)
        {
            // if (Time > new DateTime(2018,1,18,0,0,0) && stocks.Contains("VXX.1") )
            // {
            //  stocks.Remove("VXX.1");
            //  stocks.Add("VXX");
            // }

            if (allocationTime)
            {
                Log("OnDataVarOptimised allocationTime");
                if (canAllocate && (data.ContainsKey("VXX.1") && bb1.IsReady && data["VXX.1"].Close > bb1.UpperBand ||
                                    data.ContainsKey("VXX") && bb.IsReady && data["VXX"].Close > bb.UpperBand))
                {
                    Log("VXX Burst Liquidating");
                    Liquidate("UPRO");
                    Liquidate("TMF");
                    canAllocate = false;
                }
                else if (canAllocate)
                {
                    Log($"canAllocate");
                    Allocate(data);
                }
                else
                {
                    Log($"canNOTAllocate");
                    var spreadToRecovery1 = 0.25m * (bb1.UpperBand - bb1.MiddleBand);
                    var spreadToRecovery  = 0.25m * (bb.UpperBand - bb.MiddleBand);
                    if (data.ContainsKey("VXX.1") && bb1.IsReady && data["VXX.1"].Close < bb1.UpperBand - spreadToRecovery1 ||
                        data.ContainsKey("VXX") && bb.IsReady && data["VXX"].Close < bb.UpperBand - spreadToRecovery)
                    {
                        Log($"Recovery Threashold reached: Allocating");
                        Allocate(data);
                        canAllocate = true;
                    }
                }
                Plot("CAN_ALLOCATE", "CA", (canAllocate) ? 1m : 0);
                allocationTime = false;
            }
        }
 /// <summary>
 /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
 /// </summary>
 /// <param name="data">TradeBars IDictionary object with your stock data</param>
 public override void OnData(Slice data)
 {
     if (data.ContainsKey("SPY"))
     {
         if (Time.Second == 0 && Time.Minute == 0)
         {
             var goLong   = Time < StartDate.AddDays(2);
             var negative = goLong ? 1 : -1;
             LimitOrder("SPY", negative * 10, data["SPY"].Price);
         }
     }
 }
Example #19
0
        /// <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 override IEnumerable <Insight> Update(QCAlgorithmFramework algorithm, Slice data)
        {
            var insights = new List <Insight>();

            foreach (var kvp in _symbolDataBySymbol)
            {
                if (!data.ContainsKey(kvp.Key) || data[kvp.Key] == null)
                {
                    continue;
                }

                var symbol = kvp.Key;
                kvp.Value.Update(data[kvp.Key]);

                var std = kvp.Value.STD;
                if (!std.IsReady)
                {
                    continue;
                }

                var    previousState = kvp.Value.State;
                var    previousMag   = kvp.Value.Mag;
                double mag;
                var    state = GetState(kvp.Value.Indicator.Current.Value, std, out mag);

                if ((state != previousState || mag > previousMag) && std.IsReady)
                {
                    var insightPeriod = _resolution.Multiply(_period);

                    switch (state)
                    {
                    case State.Neutral:
                        insights.Add(Insight.Price(symbol, insightPeriod, InsightDirection.Flat));
                        break;

                    case State.TrippedHigh:
                        insights.Add(Insight.Price(symbol, insightPeriod, _inverted ? InsightDirection.Up : InsightDirection.Down, mag));
                        break;

                    case State.TrippedLow:
                        insights.Add(Insight.Price(symbol, insightPeriod, _inverted ? InsightDirection.Down : InsightDirection.Up, mag));
                        break;
                    }

                    kvp.Value.State = state;
                    kvp.Value.Mag   = mag;
                }
            }

            return(insights);
        }
Example #20
0
        private IEnumerable <Insight> GetInsights(Slice slice)
        {
            try
            {
                var candidateLongs = RankSymbols(ActiveSecurities
                                                 .Where(x => x.Value.IsTradable &&
                                                        slice.ContainsKey(x.Key) &&
                                                        _longCandidates.Contains(x.Key) &&
                                                        _indicators.ContainsKey(x.Key) &&
                                                        _indicators[x.Key].IsReady &&
                                                        _indicators[x.Key].Momentum > MinLongMomentum &&
                                                        !_indicators[x.Key].ExcludedBySma &&
                                                        !_indicators[x.Key].ExcludedBySpread &&
                                                        (slice[x.Key] as BaseData).Price >= MinPrice)
                                                 .Select(x => x.Key))
                                     .ToList();

                var holdingRanks = Portfolio
                                   .Where(x => x.Value.Invested)
                                   .ToDictionary(
                    x => x.Key,
                    x => candidateLongs.FindIndex(y => y == x.Key));
                var rankThreshold = 2.5 * NumLong;
                var toSell        = holdingRanks
                                    .Where(x => x.Value <0 || x.Value> rankThreshold)
                                    .Select(x => x.Key);

                var toHold = holdingRanks.Keys.Except(toSell);
                var toBuy  = candidateLongs
                             .Where(x => !toHold.Contains(x))
                             .OrderByDescending(x => _indicators[x].Momentum)
                             .Take(NumLong - toHold.Count());

                var toOwn = toBuy
                            .Union(toHold)
                            .Select(x => new Insight(
                                        x,
                                        RebalancePeriod,
                                        InsightType.Price,
                                        InsightDirection.Up));

                return(toOwn);
            }
            catch (Exception e)
            {
                var msg = $"Exception: GetInsights: {e.Message}, {e.StackTrace}";
                Log(msg);
                SendEmailNotification(msg);
                throw;
            }
        }
Example #21
0
        public override IEnumerable <Insight> Update(QCAlgorithmFramework algorithm, Slice data)
        {
            var insights  = new List <Insight>();
            var period    = TimeSpan.FromMinutes(5);
            var magnitude = 0.0005;

            // We will create our insights when we recieve news
            if (data.ContainsKey("DFX"))
            {
                var calendar = data.Get <DailyFx>("DFX");

                // Only act if this is important news.
                if (calendar.Importance != FxDailyImportance.High)
                {
                    return(insights);
                }
                if (calendar.Meaning == FxDailyMeaning.None)
                {
                    return(insights);
                }

                // Create insights for all active currencies in our universe when country matches currency
                foreach (var kvp in algorithm.ActiveSecurities.Where(kvp => kvp.Value.Symbol.SecurityType == SecurityType.Forex))
                {
                    var symbol    = kvp.Key;
                    var pair      = (Forex)kvp.Value;
                    var direction = InsightDirection.Flat;

                    if (pair.BaseCurrencySymbol == calendar.Currency.ToUpper())
                    {
                        direction = (calendar.Meaning == FxDailyMeaning.Better) ? InsightDirection.Up : InsightDirection.Down;
                    }
                    else if (pair.QuoteCurrency.Symbol == calendar.Currency.ToUpper())
                    {
                        direction = (calendar.Meaning == FxDailyMeaning.Better) ? InsightDirection.Down : InsightDirection.Up;
                    }

                    if (direction != InsightDirection.Flat)
                    {
                        insights.Add(Insight.Price(symbol, period, direction, magnitude));
                    }
                }
            }

            return(insights);
        }
        public override void OnData(Slice data)
        {
            if (!data.ContainsKey(securityName))
            {
                return;
            }

            TradeBar bar = data.Bars[securityName];

            WriteBarInfo(bar);

            Plot("Custom chart", "Custom Series", i++);


            Plot("Plotter", securityName, bar.Price);

            Plot("Assets", securityName, bar.Price);
        }
        /// <summary>
        /// Purchase a contract when we are not invested, liquidate otherwise
        /// </summary>
        public override void OnData(Slice slice)
        {
            if (!Portfolio.Invested)
            {
                // SPX Index is not tradable, but we can trade an option
                MarketOrder(SpxOption, 1);
            }
            else
            {
                Liquidate();
            }

            // Count how many slices we receive with SPX data in it to assert later
            if (slice.ContainsKey(Spx))
            {
                BarCounter++;
            }
        }
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (data.SymbolChangedEvents.Count != 0)
            {
                foreach (var symbolChanged in data.SymbolChangedEvents.Values)
                {
                    if (symbolChanged.Symbol != _qqq)
                    {
                        throw new Exception($"Mapped symbol is not QQQ. Instead, found: {symbolChanged.Symbol}");
                    }
                    if (symbolChanged.OldSymbol != "QQQQ")
                    {
                        throw new Exception($"Old QQQ Symbol is not QQQQ. Instead, found: {symbolChanged.OldSymbol}");
                    }
                    if (symbolChanged.NewSymbol != "QQQ")
                    {
                        throw new Exception($"New QQQ Symbol is not QQQ. Instead, found: {symbolChanged.NewSymbol}");
                    }

                    _mappingEventOccurred = true;
                }
            }

            if (data.Keys.Count == 1 && data.ContainsKey(_qqq))
            {
                return;
            }

            if (!_constituentDataEncountered.ContainsKey(UtcTime.Date))
            {
                _constituentDataEncountered[UtcTime.Date] = false;
            }

            if (_constituentSymbols.Intersect(data.Keys).Any())
            {
                _constituentDataEncountered[UtcTime.Date] = true;
            }

            if (!Portfolio.Invested)
            {
                SetHoldings(_aapl, 0.5m);
            }
        }
Example #25
0
 private void UpdateIndicatorOpen(Slice slice)
 {
     Parallel.ForEach(_indicators, (indicator) =>
     {
         try
         {
             if (slice.ContainsKey(indicator.Key))
             {
                 indicator.Value.UpdateOpen(slice[indicator.Key]);
             }
         }
         catch (Exception e)
         {
             var msg = $"Exception: UpdateIndicatorOpen: {e.Message}, {e.StackTrace}";
             Log(msg);
             SendEmailNotification(msg);
         }
     });
 }
Example #26
0
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!data.ContainsKey(_spy) || !data.Bars.ContainsKey(_spy))
            {
                return;
            }

            var c = this.OptionChainProvider.GetOptionContractList(_spy, data.Bars[_spy].EndTime);

            if (c != null)
            {
                var con = new List <QuantConnect.Symbol>(c);
                Debug("OPTION COUNT:" + con.Count);
            }
            if (!Portfolio.Invested)
            {
                SetHoldings(_spy, 1);
                Debug("Purchased Stock");
            }
        }
Example #27
0
        public override void OnData(Slice data)
        {
            if (!data.ContainsKey(_yieldCurve))
            {
                return;
            }

            // Preserve null values by getting the data with `slice.Get<T>`
            // Accessing the data using `data[_yieldCurve]` results in null
            // values becoming `default(decimal)` which is equal to 0
            var rates = data.Get <USTreasuryYieldCurveRate>().Values.First();

            // Check for null before using the values
            if (!rates.TenYear.HasValue || !rates.TwoYear.HasValue)
            {
                return;
            }

            // Only advance if a year has gone by
            if (Time - _lastInversion < TimeSpan.FromDays(365))
            {
                return;
            }

            // if there is a yield curve inversion after not having one for a year, short SPY for two years
            if (!Portfolio.Invested && rates.TwoYear > rates.TenYear)
            {
                Debug($"{Time} - Yield curve inversion! Shorting the market for two years");
                SetHoldings(_spy, -0.5);

                _lastInversion = Time;

                return;
            }

            // If two years have passed, liquidate our position in SPY
            if (Time - _lastInversion >= TimeSpan.FromDays(365 * 2))
            {
                Liquidate(_spy);
            }
        }
Example #28
0
        public override IEnumerable <Insight> Update(QCAlgorithm algorithm, Slice data)
        {
            var insights = new List <Insight>();

            // Check for all Quandl Symbols in current data Slice
            if (!data.ContainsKey(_compensationDelta))
            {
                return(insights);
            }

            // Employee compensation levels and cost of living are important
            // factors in determining how much consumers will be able or want to spend on discretionary
            // items. The Consumer Price Index measures changes in the price level of a market basket of
            // consumer goods and services purchased by households. If the cost of living and/or the
            // inflation rate increases faster than compensation levels, this will likely put downward
            // pressure on consumer discretionary industries -- retail, automobile manufacturing, luxury/travel, etc.

            // Generate Insights here!

            return(insights);
        }
Example #29
0
        private void UpdateIndicatorData(Slice currentSlice)
        {
            var localHistories = History(slowSmaDays, Resolution.Daily).ToList();

            foreach (var symbol in universe)
            {
                if (!currentSlice.ContainsKey(symbol))
                {
                    continue;
                }

                histories[symbol] = localHistories
                                    .Where(x => x.ContainsKey(symbol))
                                    .Select(x => x[symbol] as BaseData)
                                    .Union(new[] { currentSlice[symbol] as BaseData })
                                    .OrderByDescending(x => x.Time)
                                    .ToList();
                macds[symbol] = MacdHistogram(symbol);

                var stoHistories = History <TradeBar>(symbol, stoLookbackPeriod, Resolution.Daily)
                                   .Union(new[] { currentSlice[symbol] as TradeBar });
                stos[symbol] = Sto(stoHistories);
            }
        }
Example #30
0
        private void HandleVixData(Slice slice)
        {
            if (!slice.ContainsKey(_cboeVix))
            {
                return;
            }

            if (_vix != null && (_vix as TradeBar).Time.Day == slice.Time.Day)
            {
                return;
            }

            _vix = slice.Get <CBOE>(_cboeVix);

            var vixHistories = History <CBOE>(_cboeVix, 35, Resolution.Daily)
                               .Cast <TradeBar>();

            if (vixHistories.Any())
            {
                var momentum = vixHistories
                               .OrderByDescending(x => x.Time)
                               .Take(5)
                               .Select(x => x.Price)
                               .Average()
                               /
                               vixHistories
                               .OrderBy(x => x.Time)
                               .Take(5)
                               .Select(x => x.Price)
                               .Average();
                _tooVolatile = momentum > 2;
                Plot("VIX-momentum", "momentum", momentum);
            }

            Plot("VIX", "price", _vix.Price);
        }
Example #31
0
        public override void OnData(Slice data)
        {
            //Confirm that the data is in the collection
            if (!data.ContainsKey(_tiingoSymbol))
            {
                return;
            }

            // Gets the first piece of data from the Slice
            var article = data.Get <TiingoNews>(_tiingoSymbol);

            // Article descriptions come in all caps. Lower and split by word
            var descriptionWords = article.Description.ToLowerInvariant().Split(' ');

            // Take the intersection of predefined words and the words in the
            // description to get a list of matching words
            var intersection = _words.Keys.Intersect(descriptionWords);

            // Get the sum of the article's sentiment, and go long or short
            // depending if it's a positive or negative description
            var sentiment = intersection.Select(x => _words[x]).Sum();

            SetHoldings(article.Symbol.Underlying, sentiment);
        }