public void PipesDataUsingOfFromFirstToSecond()
        {
            var first = new SimpleMovingAverage(2);
            var second = new Delay(1);
            
            // this is a configuration step, but returns the reference to the second for method chaining
            second.Of(first);

            var data1 = new IndicatorDataPoint(DateTime.UtcNow, 1m);
            var data2 = new IndicatorDataPoint(DateTime.UtcNow, 2m);
            var data3 = new IndicatorDataPoint(DateTime.UtcNow, 3m);
            var data4 = new IndicatorDataPoint(DateTime.UtcNow, 4m);

            // sma has one item
            first.Update(data1);
            Assert.IsFalse(first.IsReady);
            Assert.AreEqual(0m, second.Current.Value);

            // sma is ready, delay will repeat this value
            first.Update(data2);
            Assert.IsTrue(first.IsReady);
            Assert.IsFalse(second.IsReady);
            Assert.AreEqual(1.5m, second.Current.Value);

            // delay is ready, and repeats its first input
            first.Update(data3);
            Assert.IsTrue(second.IsReady);
            Assert.AreEqual(1.5m, second.Current.Value);

            // now getting the delayed data
            first.Update(data4);
            Assert.AreEqual(2.5m, second.Current.Value);
        }
        public void IsReadyAfterPeriodUpdates()
        {
            var sma = new SimpleMovingAverage(3);

            sma.Update(DateTime.UtcNow, 1m);
            sma.Update(DateTime.UtcNow, 1m);
            Assert.IsFalse(sma.IsReady);
            sma.Update(DateTime.UtcNow, 1m);
            Assert.IsTrue(sma.IsReady);
        }
        public void ResetsProperly()
        {
            var sma = new SimpleMovingAverage(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                sma.Update(data);
            }
            Assert.IsTrue(sma.IsReady);
            
            sma.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(sma);
            TestHelper.AssertIndicatorIsInDefaultState(sma.RollingSum);
            sma.Update(DateTime.UtcNow, 2.0m);
            Assert.AreEqual(sma.Current.Value, 2.0m);
        }
        public override void ResetsProperly()
        {
            var sma = new SimpleMovingAverage(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                sma.Update(data);
            }

            Assert.IsTrue(sma.IsReady);

            sma.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(sma);
            TestHelper.AssertIndicatorIsInDefaultState(sma.RollingSum);
            sma.Update(DateTime.UtcNow, 2.0d);
            Assert.AreEqual(sma.Current.Value, 2.0d);
        }
 private void UpdateBar(SimpleMovingAverage sma, BaseData tradeBar, int position)
 {
     if (!(tradeBar is TradeBar))
     {
         throw new Exception("Expected a TradeBar");
     }
     _consolidationCount[position]++;
     sma.Update(tradeBar.EndTime, tradeBar.Value);
 }
Beispiel #6
0
 private void WarmUpIndicators(QCAlgorithm algorithm)
 {
     // Make a history call and update the indicators
     algorithm.History(new[] { _mortgageRate }, _indicatorPeriod, _resolution).PushThrough(bar =>
     {
         _mortgageRateSma.Update(bar.EndTime, bar.Value);
         _mortgageRateStd.Update(bar.EndTime, bar.Value);
     });
 }
Beispiel #7
0
        protected override decimal ComputeNextValue(IndicatorDataPoint input)
        {
            _fastSma.Update(input);
            _slowSma.Update(input);
            _sma200.Update(input);
            _sma100.Update(input);
            _sma20.Update(input);

            return(0);
        }
            /// <summary>
            /// Updates indicators and other class state
            /// </summary>
            /// <param name="data">The data used to updated</param>
            public void Update(TradeBar data)
            {
                // verify the input data matches our symbol - sanity check
                if (!string.Equals(data.Symbol, Symbol, StringComparison.CurrentCultureIgnoreCase))
                {
                    throw new ArgumentException("Expected trade bar data for " + Symbol + " but received " + data.Symbol.ToUpper());
                }

                Bars.Add(data);
                SMA.Update(data.Time, data.Close);
            }
        public void SMAComputesCorrectly()
        {
            var sma = new SimpleMovingAverage(4);
            var data = new[] {1m, 10m, 100m, 1000m, 10000m, 1234m, 56789m};

            var seen = new List<decimal>();
            for (int i = 0; i < data.Length; i++)
            {
                var datum = data[i];
                seen.Add(datum);
                sma.Update(new IndicatorDataPoint(DateTime.Now.AddSeconds(i), datum));
                Assert.AreEqual(Enumerable.Reverse(seen).Take(sma.Period).Average(), sma.Current.Value);
            }
        }
        public void ResetsProperly()
        {
            var sma = new SimpleMovingAverage(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                sma.Update(data);
            }
            Assert.IsTrue(sma.IsReady);

            sma.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(sma);
        }
Beispiel #11
0
        public void ResetsProperly()
        {
            var sma = new SimpleMovingAverage(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                sma.Update(data);
            }
            Assert.IsTrue(sma.IsReady);

            sma.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(sma);
        }
        public void NewDataPushesToDerivedIndicators()
        {
            var identity = new Identity("identity");
            var sma      = new SimpleMovingAverage(3);

            identity.Updated += (time, consolidated) => { sma.Update(time, consolidated); };

            identity.Update(DateTime.UtcNow, 1d);
            identity.Update(DateTime.UtcNow, 2d);
            Assert.IsFalse(sma.IsReady);

            identity.Update(DateTime.UtcNow, 3d);
            Assert.IsTrue(sma.IsReady);
            Assert.AreEqual(2d, sma.Current.Value);
        }
        public void SmaComputesCorrectly()
        {
            var sma  = new SimpleMovingAverage(4);
            var data = new[] { 1m, 10m, 100m, 1000m, 10000m, 1234m, 56789m };

            var seen = new List <decimal>();

            for (int i = 0; i < data.Length; i++)
            {
                var datum = data[i];
                seen.Add(datum);
                sma.Update(new IndicatorDataPoint(DateTime.Now.AddSeconds(i), datum));
                Assert.AreEqual(Enumerable.Reverse(seen).Take(sma.Period).Average(), sma.Current.Value);
            }
        }
        public void MovingAverage_Test()
        {
            var sma       = new SimpleMovingAverage(PeriodType.Day, 1, 10);
            var ema       = new ExponentialMovingAverage(PeriodType.Day, 1, 10);
            var periods   = DataGenerator.GetSamplePeriodsWithCloseValue();
            var sma_value = 0.0;
            var ema_value = 0.0;

            foreach (var p in periods)
            {
                sma_value = sma.Update(p).First();
                ema_value = ema.Update(p).First();
            }

            Assert.AreEqual(sma_value, 22.209);
            Assert.AreEqual(Math.Round(ema_value, 2), 22.22);
        }
Beispiel #15
0
            public SymbolData(QCAlgorithmFramework algorithm, Security security, int period, Resolution resolution)
            {
                Security     = security;
                Consolidator = algorithm.ResolveConsolidator(security.Symbol, resolution);
                var smaName = algorithm.CreateIndicatorName(security.Symbol, "SMA" + period, resolution);

                SMA = new SimpleMovingAverage(smaName, period);
                var stdName = algorithm.CreateIndicatorName(security.Symbol, "STD" + period, resolution);

                STD = new StandardDeviation(stdName, period);

                algorithm.SubscriptionManager.AddConsolidator(security.Symbol, Consolidator);
                Consolidator.DataConsolidated += (sender, consolidated) =>
                {
                    SMA.Update(consolidated.EndTime, consolidated.Value);
                    STD.Update(consolidated.EndTime, consolidated.Value);
                };
            }
Beispiel #16
0
        public void NewDataPushesToDerivedIndicators()
        {
            var identity = new Identity("identity");
            var sma = new SimpleMovingAverage(3);

            identity.Updated += (sender, consolidated) =>
            {
                sma.Update(consolidated);
            };

            identity.Update(DateTime.UtcNow, 1m);
            identity.Update(DateTime.UtcNow, 2m);
            Assert.IsFalse(sma.IsReady);

            identity.Update(DateTime.UtcNow, 3m);
            Assert.IsTrue(sma.IsReady);
            Assert.AreEqual(2m, sma);
        }
        public void NewDataPushesToDerivedIndicators()
        {
            var identity = new Identity("identity");
            var sma      = new SimpleMovingAverage(3);

            identity.Updated += (sender, consolidated) =>
            {
                sma.Update(consolidated);
            };

            identity.Update(DateTime.UtcNow, TimeZone.Utc, 1m);
            identity.Update(DateTime.UtcNow, TimeZone.Utc, 2m);
            Assert.False(sma.IsReady);

            identity.Update(DateTime.UtcNow, TimeZone.Utc, 3m);
            Assert.True(sma.IsReady);
            Assert.Equal(2m, sma);
        }
        public void ResetsProperly()
        {
            var inner = new SimpleMovingAverage(2);
            var func  = new FunctionalIndicator("f", (time, data) => {
                inner.Update(time, data);
                return(inner.Current.Value * 2);
            },
                                                @this => inner.IsReady,
                                                () => inner.Reset()
                                                );

            func.Update(DateTime.Today, 1d);
            func.Update(DateTime.Today.AddSeconds(1), 2d);
            Assert.IsTrue(func.IsReady);

            func.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(inner);
            TestHelper.AssertIndicatorIsInDefaultState(func);
        }
        public void ComputesCorrectly()
        {
            var fast   = new SimpleMovingAverage(3);
            var slow   = new SimpleMovingAverage(5);
            var signal = new SimpleMovingAverage(3);
            var macd   = new MovingAverageConvergenceDivergence("macd", 3, 5, 3, MovingAverageType.Simple);

            foreach (var data in TestHelper.GetDataStream(7))
            {
                fast.Update(data);
                slow.Update(data);
                macd.Update(data);
                Assert.Equal(fast - slow, macd);
                if (fast.IsReady && slow.IsReady)
                {
                    signal.Update(new IndicatorDataPoint(data.Occured, TimeZone.Utc, macd));
                    Assert.Equal(signal.Current.Price, macd.Current.Price);
                }
            }
        }
Beispiel #20
0
        public void ResetsProperly()
        {
            var inner = new SimpleMovingAverage(2);
            var func  = new FunctionalIndicator <IndicatorDataPoint>("f", data =>
            {
                inner.Update(data);
                return(inner.Current.Price * 2);
            },
                                                                     @this => inner.IsReady,
                                                                     () => inner.Reset()
                                                                     );

            func.Update(DateTime.Today, TimeZone.Utc, 1m);
            func.Update(DateTime.Today.AddSeconds(1), TimeZone.Utc, 2m);
            Assert.True(func.IsReady);

            func.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(inner);
            TestHelper.AssertIndicatorIsInDefaultState(func);
        }
        public void ComputesCorrectly()
        {
            var fast = new SimpleMovingAverage(3);
            var slow = new SimpleMovingAverage(5);
            var signal = new SimpleMovingAverage(3);
            var macd = new MovingAverageConvergenceDivergence("macd", 3, 5, 3, MovingAverageType.Simple);

            foreach (var data in TestHelper.GetDataStream(7))
            {
                fast.Update(data);
                slow.Update(data);
                macd.Update(data);
                Assert.AreEqual(fast - slow, macd);
                if (fast.IsReady && slow.IsReady)
                {
                    signal.Update(new IndicatorDataPoint(data.Time, macd));
                    Assert.AreEqual(signal.Current.Value, macd.Current.Value);
                }
            }
        }
Beispiel #22
0
        public void ResetsProperly()
        {
            var inner = new SimpleMovingAverage(2);
            var func = new FunctionalIndicator<IndicatorDataPoint>("f", data =>
            {
                inner.Update(data);
                return inner.Current.Value*2;
            },
            @this => inner.IsReady,
            () => inner.Reset()
            );

            func.Update(DateTime.Today, 1m);
            func.Update(DateTime.Today.AddSeconds(1), 2m);
            Assert.IsTrue(func.IsReady);

            func.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(inner);
            TestHelper.AssertIndicatorIsInDefaultState(func);
        }
Beispiel #23
0
            public SymbolData(QCAlgorithm algorithm, Security security, int period, Resolution resolution)
            {
                Security     = security;
                Consolidator = algorithm.ResolveConsolidator(security.Symbol, resolution);

                var smaName = algorithm.CreateIndicatorName(security.Symbol, "SMA" + period, resolution);

                SMA = new SimpleMovingAverage(smaName, period);
                algorithm.RegisterIndicator(security.Symbol, SMA, Consolidator);

                var stdName = algorithm.CreateIndicatorName(security.Symbol, "STD" + period, resolution);

                STD = new StandardDeviation(stdName, period);
                algorithm.RegisterIndicator(security.Symbol, STD, Consolidator);

                // warmup our indicators by pushing history through the indicators
                foreach (var bar in algorithm.History(Security.Symbol, period, resolution))
                {
                    SMA.Update(bar.EndTime, bar.Value);
                    STD.Update(bar.EndTime, bar.Value);
                }
            }
        public void ComputesCorrectly()
        {
            var delay = new Delay(3);
            var sma = new SimpleMovingAverage(3);
            var momp = new MomentumPercent(3);
            foreach (var data in TestHelper.GetDataStream(4))
            {
                delay.Update(data);
                sma.Update(data);
                momp.Update(data);

                if (sma == 0m)
                {
                    Assert.AreEqual(0m, momp.Current.Value);
                }
                else
                {
                    decimal abs = data - delay;
                    decimal perc = abs / sma;
                    Assert.AreEqual(perc, momp.Current.Value);
                }
            }
        }
Beispiel #25
0
        public void ComputesCorrectly()
        {
            var delay = new Delay(3);
            var sma   = new SimpleMovingAverage(3);
            var momp  = new MomentumPercent(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                delay.Update(data);
                sma.Update(data);
                momp.Update(data);

                if (sma == 0m)
                {
                    Assert.AreEqual(0m, momp.Current.Value);
                }
                else
                {
                    decimal abs  = data - delay;
                    decimal perc = abs / sma;
                    Assert.AreEqual(perc, momp.Current.Value);
                }
            }
        }
Beispiel #26
0
 public void OnWeek5(object sender, TradeBar consolidated)
 {
     ma.Update(new IndicatorDataPoint(consolidated.EndTime, consolidated.Close));
     Log($"{Time} OnWeek5 ma ready {ma.IsReady}");
     if (ma.IsReady && !IsWarmingUp)
     {
         //SetHoldings(SYM,1);
         if (consolidated.Close > ma && prevCondition && !prevPrevCondition)
         {
             var ratio    = 0.4m / 0.7m;
             var eq_ratio = 2m;
             SetAllWeatherHoldings(ratio, eq_ratio);
             fullOn = true;
         }
         else if (consolidated.Close < ma && prevCondition || !Portfolio.Invested)
         {
             var ratio = 1m;                    //0.6;
             SetAllWeatherHoldings(ratio);
             fullOn = false;
         }
         prevPrevCondition = prevCondition;
         prevCondition     = consolidated.Close > ma;
     }
 }
Beispiel #27
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(100000);             //Set Strategy Cash

            // Find more symbols here: http://quantconnect.com/data
            AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily);
            AddData<Quandl>("YAHOO/INDEX_SPY", Resolution.Daily);
            // specifying the exchange will allow the history methods that accept a number of bars to return to work properly
            Securities["YAHOO/INDEX_SPY"].Exchange = new EquityExchange();

            // we can get history in initialize to set up indicators and such
            spyDailySma = new SimpleMovingAverage(14);

            // get the last calendar year's worth of SPY data at the configured resolution (daily)
            var tradeBarHistory = History("SPY", TimeSpan.FromDays(365));
            
            // get the last calendar day's worth of SPY data at the specified resolution
            tradeBarHistory = History("SPY", TimeSpan.FromDays(1), Resolution.Minute);
            
            // get the last 14 bars of SPY at the configured resolution (daily)
            tradeBarHistory = History("SPY", 14).ToList();

            // get the last 14 minute bars of SPY
            tradeBarHistory = History("SPY", 14, Resolution.Minute);

            // we can loop over the return value from these functions and we get TradeBars
            // we can use these TradeBars to initialize indicators or perform other math
            foreach (TradeBar tradeBar in tradeBarHistory)
            {
                spyDailySma.Update(tradeBar.EndTime, tradeBar.Close);
            }

            // get the last calendar year's worth of quandl data at the configured resolution (daily)
            var quandlHistory = History<Quandl>("YAHOO/INDEX_SPY", TimeSpan.FromDays(365));

            // get the last 14 bars of SPY at the configured resolution (daily)
            quandlHistory = History<Quandl>("YAHOO/INDEX_SPY", 14);

            // get the last 14 minute bars of SPY

            // we can loop over the return values from these functions and we'll get Quandl data
            // this can be used in much the same way as the tradeBarHistory above
            foreach (Quandl quandl in quandlHistory)
            {
                spyDailySma.Update(quandl.EndTime, quandl.Value);
            }

            // get the last year's worth of all configured Quandl data at the configured resolution (daily)
            var allQuandlData = History<Quandl>(TimeSpan.FromDays(365));

            // get the last 14 bars worth of Quandl data for the specified symbols at the configured resolution (daily)
            allQuandlData = History<Quandl>(Securities.Keys, 14);
            
            // NOTE: using different resolutions require that they are properly implemented in your data type, since
            //  Quandl doesn't support minute data, this won't actually work, but if your custom data source has
            //  different resolutions, it would need to be implemented in the GetSource and Reader methods properly
            //quandlHistory = History<Quandl>("YAHOO/INDEX_SPY", TimeSpan.FromDays(7), Resolution.Minute);
            //quandlHistory = History<Quandl>("YAHOO/INDEX_SPY", 14, Resolution.Minute);
            //allQuandlData = History<Quandl>(TimeSpan.FromDays(365), Resolution.Minute);
            //allQuandlData = History<Quandl>(Securities.Keys, 14, Resolution.Minute);
            //allQuandlData = History<Quandl>(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);
            //allQuandlData = History<Quandl>(Securities.Keys, 14, Resolution.Minute);

            // get the last calendar year's worth of all quandl data
            allQuandlData = History<Quandl>(Securities.Keys, TimeSpan.FromDays(365));

            // the return is a series of dictionaries containing all quandl data at each time
            // we can loop over it to get the individual dictionaries
            foreach (DataDictionary<Quandl> quandlsDataDictionary in allQuandlData)
            {
                // we can access the dictionary to get the quandl data we want
                var quandl = quandlsDataDictionary["YAHOO/INDEX_SPY"];
            }

            // we can also access the return value from the multiple symbol functions to request a single
            // symbol and then loop over it
            var singleSymbolQuandl = allQuandlData.Get("YAHOO/INDEX_SPY");
            foreach (Quandl quandl in singleSymbolQuandl)
            {
                // do something with 'YAHOO/INDEX_SPY' quandl data
            }

            // we can also access individual properties on our data, this will
            // get the 'YAHOO/INDEX_SPY' quandls like above, but then only return the Low properties
            var quandlSpyLows = allQuandlData.Get("YAHOO/INDEX_SPY", "Low");
            foreach (decimal low in quandlSpyLows)
            {
                // do something we each low value
            }

            // sometimes it's necessary to get the history for many configured symbols

            // request the last year's worth of history for all configured symbols at their configured resolutions
            var allHistory = History(TimeSpan.FromDays(365));

            // request the last days's worth of history at the minute resolution
            allHistory = History(TimeSpan.FromDays(1), Resolution.Minute);

            // request the last 100 bars for the specified securities at the configured resolution
            allHistory = History(Securities.Keys, 100);
            
            // request the last 100 minute bars for the specified securities
            allHistory = History(Securities.Keys, 100, Resolution.Minute);
            
            // request the last calendar years worth of history for the specified securities
            allHistory = History(Securities.Keys, TimeSpan.FromDays(365));
            // we can also specify the resolutin
            allHistory = History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);

            // if we loop over this allHistory, we get Slice objects
            foreach (Slice slice in allHistory)
            {
                // do something with each slice, these will come in time order
                // and will NOT have auxilliary data, just price data and your custom data
                // if those symbols were specified
            }

            // we can access the history for individual symbols from the all history by specifying the symbol
            // the type must be a trade bar!
            tradeBarHistory = allHistory.Get("SPY");

            // we can access all the closing prices in chronological order using this get function
            var closeHistory = allHistory.Get("SPY", Field.Close);
            foreach (decimal close in closeHistory)
            {
                // do something with each closing value in order
            }

            // we can convert the close history into your normal double array (double[]) using the ToDoubleArray method
            double[] doubleArray = closeHistory.ToDoubleArray();
        }
Beispiel #28
0
        public override void OnEndOfDay()
        {
            //Transactions.CancelOpenOrders();
            //_pfeStrategy.Update(new TradeBar(Time, symbols.FirstOrDefault(), Portfolio.TotalPortfolioValue, Portfolio.TotalPortfolioValue, Portfolio.TotalPortfolioValue, Portfolio.TotalPortfolioValue, Portfolio.TotalPortfolioValue));_pfeStrategy
            _pfeStrategy.Update(new IndicatorDataPoint(Time, Portfolio.TotalPortfolioValue));
            Plot("PFE", "Strategy", _pfeStrategy.Current.Value);

            if (jitter < 1000)
            {
                Plot("Jitter", "Jitter", (decimal)jitter);
                jitterSma.Update(Time, jitter);
                jitterSmaL.Update(Time, jitter);
                Plot("Jitter", "JitterSMA", jitterSma.Current.Value);
                Plot("Jitter", "JitterLong", jitterSmaL.Current.Value);
            }
            jitter = 0;

            var perf  = new Dictionary <string, decimal>();
            var perfS = new Dictionary <string, decimal>();
            var bull1 = 0;
            var bull2 = 0;
            var bull3 = 0;

            foreach (var s in symbols)
            {
                // if (riskProtectSymbols.Contains(s))
                // {
                //  UpdateReference(s);
                //  _pfeReference[s].Update(new TradeBar(Time, s, reference[s], reference[s], reference[s], reference[s], reference[s]));
                // }

                if (eit[s] > 0)
                {
                    bull1++;
                }
                if (pfe[s] > 0)
                {
                    bull2++;
                }
                if (pfe[s] > ppfe[s] && pfe[s] > -50)
                {
                    bull3++;
                }
                Plot("BULLISH", "EIT", (decimal)bull1);
                Plot("BULLISH", "PFE", (decimal)bull2);
                Plot("BULLISH", "PFE+", (decimal)bull2);
                perf[s]  = TradeMonitor.GetAveragePerfForDays(s, Time, stockPickingPeriod);
                perfS[s] = TradeMonitor.GetAveragePerfForDays(s, Time, longPeriod);

                ppfe[s] = pfe[s];
            }


            tradableSymbols.Clear();
            if (!IsWarmingUp)
            {
                var l1 = (from entry in perf where perf[entry.Key] > 0  orderby perf[entry.Key] descending select entry.Key).Take(MAX_POS * 2);
                var l2 = (from entry in l1 where perfS[entry] > 0  orderby perfS[entry] descending select entry).Take(MAX_POS * 2);
                var lr = l2;        //l1.Intersect(l2);
                foreach (var s in lr)
                {
                    tradableSymbols.Add(s);
                }
                //tradableSymbols.Add("QQQ");
                // tradableSymbols.Add("VXX");
                // tradableSymbols.Add("VXX.1");
            }
        }
 public bool Update(DateTime time, decimal value)
 {
     return(_meanOfPriceChange.Update(time, value) &
            _priceChange.Update(time, value));
 }
Beispiel #30
0
 /// <summary>
 ///      Computes the next value of this indicator from the given state
 /// </summary>
 /// <param name="time"></param>
 /// <param name="input">The input given to the indicator</param>
 /// <returns>
 ///      A new value for this indicator
 /// </returns>
 protected override DoubleArray Forward(long time, DoubleArray input)
 {
     _priceLag.Update(time, input);
     _sma.Update(time, input);
     return(_priceLag - _sma);
 }
Beispiel #31
0
 public bool Update(DateTime time, decimal value)
 {
     return(SMA5.Update(time, value) && SMA100.Update(time, value));
 }
Beispiel #32
0
        public void OnHour(object sender, TradeBar data)
        {
            if (!_rsi.IsReady)
            {
                return;
            }
            if (!_sd.IsReady)
            {
                return;
            }

            _windowH.Add(data);
            if (!_windowH.IsReady)
            {
                return;
            }

            var _mH = Math.Max(Math.Max(_windowH[0].High - _windowH[1].Close, _windowH[0].High - _windowH[0].Low), Math.Max(_windowH[0].Low - _windowH[1].Close, 0));

            _mHW.Add(_m);
            if (!_mHW.IsReady)
            {
                return;
            }

            _mHL = LSMA(_mW, _volSmooth);

            if (_prevamaHour != 0)
            {
                _vamaHour = _prevamaHour + _mL * _fast * (_windowH[0].Close - _prevamaHour);
            }
            else
            {
                _vamaHour = _windowH[0].Close;
            }

            _vamaHW.Add(_vamaHour);
            if (!_vamaHW.IsReady)
            {
                return;
            }

            _residualH = _windowH[0].Close - LSMA(_vamaHW, 40);

            _residHW.Add(_residualH);
            if (!_residHW.IsReady)
            {
                return;
            }

            _residualHSm = LSMA(_residHW, 40);

            _sma.Update(data.Time, _sd);
            if (!_sma.IsReady)
            {
                return;
            }

            _prevamaHour = _vamaHour;
            _prersi      = _rsi;
        }
 private void UpdateQuoteBar(SimpleMovingAverage sma, QuoteBar quoteBar, int position)
 {
     _consolidationCount[position]++;
     sma.Update(quoteBar.EndTime, quoteBar.High);
 }
 private void UpdateTradeBar(SimpleMovingAverage sma, TradeBar tradeBar, int position)
 {
     _consolidationCount[position]++;
     sma.Update(tradeBar.EndTime, tradeBar.High);
 }
        /// <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 void OnData(TradeBars data)
        {
            decimal close = data[symbol].Close;

            barcount++;
            tradingDate = this.Time;
            var time = this.Time;

            Price.Add(idp(time, close));
            trend.Update(idp(time, close));
            trendHistory.Add(idp(time, close));
            ema10.Update(trend.Current);
            sma10.Update(trend.Current);
            emaHistory.Add(ema10.Current);
            smaHistory.Add(sma10.Current);
            var madiff1 = ema10.Current.Value - sma10.Current.Value;

            madiff.Add(idp(time, madiff1));
            stddev.Update(idp(time, madiff1));
            if (this.Time.Hour == 9 && this.Time.Minute == 31)
            {
                barcount  = 1;
                tradesize = (int)(Portfolio.Cash / Convert.ToInt32(Price[0].Value + 1));
                openprice = Price[0].Value;
            }

            if (barcount > 2)
            {
                factor = 1.5m - (.5m * ((decimal)barcount / (decimal)360));
                Strategy(data);

                string logmsg =
                    string.Format(
                        "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27}",
                        this.Time,
                        barcount,
                        data[symbol].Open,
                        data[symbol].High,
                        data[symbol].Low,
                        data[symbol].Close,
                        Price[0].Value,
                        trend.Current.Value,
                        ema10.Current.Value,
                        sma10.Current.Value,
                        madiff[0].Value,
                        stddev.Current.Value * factor,
                        stddev.Current.Value * -factor,
                        ema10.Current.Value - sma10.Current.Value,
                        trend.Current.Value - ema10.Current.Value,
                        Price[0].Value - trend.Current.Value,
                        ema10.Current.Value > sma10.Current.Value && trend.Current.Value > ema10.Current.Value && Price[0].Value > trend.Current.Value,
                        trend.Current.Value < sma10.Current.Value && trend.Current.Value < ema10.Current.Value && Price[0].Value < trend.Current.Value,
                        trend.Current.Value <ema10.Current.Value,
                                             trend.Current.Value> ema10.Current.Value,
                        orderId,
                        Portfolio.TotalUnrealisedProfit,
                        sharesOwned,
                        tradeprofit,
                        profit,
                        fees,
                        dayprofit,
                        dayfees,
                        daynet,
                        Portfolio.TotalPortfolioValue);
                mylog.Debug(logmsg);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 08);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(100000);             //Set Strategy Cash

            // Find more symbols here: http://quantconnect.com/data
            var SPY     = AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily).Symbol;
            var CME_SP1 = AddData <QuandlFuture>("CHRIS/CME_SP1", Resolution.Daily).Symbol;

            // specifying the exchange will allow the history methods that accept a number of bars to return to work properly
            Securities["CHRIS/CME_SP1"].Exchange = new EquityExchange();

            // we can get history in initialize to set up indicators and such
            _spyDailySma = new SimpleMovingAverage(14);

            // get the last calendar year's worth of SPY data at the configured resolution (daily)
            var tradeBarHistory = History <TradeBar>("SPY", TimeSpan.FromDays(365));

            AssertHistoryCount("History<TradeBar>(\"SPY\", TimeSpan.FromDays(365))", tradeBarHistory, 250, SPY);

            // get the last calendar day's worth of SPY data at the specified resolution
            tradeBarHistory = History <TradeBar>("SPY", TimeSpan.FromDays(1), Resolution.Minute);
            AssertHistoryCount("History<TradeBar>(\"SPY\", TimeSpan.FromDays(1), Resolution.Minute)", tradeBarHistory, 390, SPY);

            // get the last 14 bars of SPY at the configured resolution (daily)
            tradeBarHistory = History <TradeBar>("SPY", 14).ToList();
            AssertHistoryCount("History<TradeBar>(\"SPY\", 14)", tradeBarHistory, 14, SPY);

            // get the last 14 minute bars of SPY
            tradeBarHistory = History <TradeBar>("SPY", 14, Resolution.Minute);
            AssertHistoryCount("History<TradeBar>(\"SPY\", 14, Resolution.Minute)", tradeBarHistory, 14, SPY);

            // we can loop over the return value from these functions and we get TradeBars
            // we can use these TradeBars to initialize indicators or perform other math
            foreach (TradeBar tradeBar in tradeBarHistory)
            {
                _spyDailySma.Update(tradeBar.EndTime, tradeBar.Close);
            }

            // get the last calendar year's worth of quandl data at the configured resolution (daily)
            var quandlHistory = History <QuandlFuture>("CHRIS/CME_SP1", TimeSpan.FromDays(365));

            AssertHistoryCount("History<Quandl>(\"CHRIS/CME_SP1\", TimeSpan.FromDays(365))", quandlHistory, 250, CME_SP1);

            // get the last 14 bars of SPY at the configured resolution (daily)
            quandlHistory = History <QuandlFuture>("CHRIS/CME_SP1", 14);
            AssertHistoryCount("History<Quandl>(\"CHRIS/CME_SP1\", 14)", quandlHistory, 14, CME_SP1);

            // get the last 14 minute bars of SPY

            // we can loop over the return values from these functions and we'll get Quandl data
            // this can be used in much the same way as the tradeBarHistory above
            _spyDailySma.Reset();
            foreach (QuandlFuture quandl in quandlHistory)
            {
                _spyDailySma.Update(quandl.EndTime, quandl.Value);
            }

            // get the last year's worth of all configured Quandl data at the configured resolution (daily)
            var allQuandlData = History <QuandlFuture>(TimeSpan.FromDays(365));

            AssertHistoryCount("History<QuandlFuture>(TimeSpan.FromDays(365))", allQuandlData, 250, CME_SP1);

            // get the last 14 bars worth of Quandl data for the specified symbols at the configured resolution (daily)
            allQuandlData = History <QuandlFuture>(Securities.Keys, 14);
            AssertHistoryCount("History<QuandlFuture>(Securities.Keys, 14)", allQuandlData, 14, CME_SP1);

            // NOTE: using different resolutions require that they are properly implemented in your data type, since
            //  Quandl doesn't support minute data, this won't actually work, but if your custom data source has
            //  different resolutions, it would need to be implemented in the GetSource and Reader methods properly
            //quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", TimeSpan.FromDays(7), Resolution.Minute);
            //quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", 14, Resolution.Minute);
            //allQuandlData = History<QuandlFuture>(TimeSpan.FromDays(365), Resolution.Minute);
            //allQuandlData = History<QuandlFuture>(Securities.Keys, 14, Resolution.Minute);
            //allQuandlData = History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);
            //allQuandlData = History<QuandlFuture>(Securities.Keys, 14, Resolution.Minute);

            // get the last calendar year's worth of all quandl data
            allQuandlData = History <QuandlFuture>(Securities.Keys, TimeSpan.FromDays(365));
            AssertHistoryCount("History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(365))", allQuandlData, 250, CME_SP1);

            // the return is a series of dictionaries containing all quandl data at each time
            // we can loop over it to get the individual dictionaries
            foreach (DataDictionary <QuandlFuture> quandlsDataDictionary in allQuandlData)
            {
                // we can access the dictionary to get the quandl data we want
                var quandl = quandlsDataDictionary["CHRIS/CME_SP1"];
            }

            // we can also access the return value from the multiple symbol functions to request a single
            // symbol and then loop over it
            var singleSymbolQuandl = allQuandlData.Get("CHRIS/CME_SP1");

            AssertHistoryCount("allQuandlData.Get(\"CHRIS/CME_SP1\")", singleSymbolQuandl, 250, CME_SP1);
            foreach (QuandlFuture quandl in singleSymbolQuandl)
            {
                // do something with 'CHRIS/CME_SP1' quandl data
            }

            // we can also access individual properties on our data, this will
            // get the 'CHRIS/CME_SP1' quandls like above, but then only return the Low properties
            var quandlSpyLows = allQuandlData.Get("CHRIS/CME_SP1", "Low");

            AssertHistoryCount("allQuandlData.Get(\"CHRIS/CME_SP1\", \"Low\")", quandlSpyLows, 250);
            foreach (decimal low in quandlSpyLows)
            {
                // do something with each low value
            }

            // sometimes it's necessary to get the history for many configured symbols

            // request the last year's worth of history for all configured symbols at their configured resolutions
            var allHistory = History(TimeSpan.FromDays(365));

            AssertHistoryCount("History(TimeSpan.FromDays(365))", allHistory, 250, SPY, CME_SP1);

            // request the last days's worth of history at the minute resolution
            allHistory = History(TimeSpan.FromDays(1), Resolution.Minute);
            AssertHistoryCount("History(TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 391, SPY, CME_SP1);

            // request the last 100 bars for the specified securities at the configured resolution
            allHistory = History(Securities.Keys, 100);
            AssertHistoryCount("History(Securities.Keys, 100)", allHistory, 100, SPY, CME_SP1);

            // request the last 100 minute bars for the specified securities
            allHistory = History(Securities.Keys, 100, Resolution.Minute);
            AssertHistoryCount("History(Securities.Keys, 100, Resolution.Minute)", allHistory, 101, SPY, CME_SP1);

            // request the last calendar years worth of history for the specified securities
            allHistory = History(Securities.Keys, TimeSpan.FromDays(365));
            AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(365))", allHistory, 250, SPY, CME_SP1);
            // we can also specify the resolution
            allHistory = History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);
            AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 391, SPY, CME_SP1);

            // if we loop over this allHistory, we get Slice objects
            foreach (Slice slice in allHistory)
            {
                // do something with each slice, these will come in time order
                // and will NOT have auxilliary data, just price data and your custom data
                // if those symbols were specified
            }

            // we can access the history for individual symbols from the all history by specifying the symbol
            // the type must be a trade bar!
            tradeBarHistory = allHistory.Get <TradeBar>("SPY");
            AssertHistoryCount("allHistory.Get(\"SPY\")", tradeBarHistory, 390, SPY);

            // we can access all the closing prices in chronological order using this get function
            var closeHistory = allHistory.Get("SPY", Field.Close);

            AssertHistoryCount("allHistory.Get(\"SPY\", Field.Close)", closeHistory, 390);
            foreach (decimal close in closeHistory)
            {
                // do something with each closing value in order
            }

            // we can convert the close history into your normal double array (double[]) using the ToDoubleArray method
            double[] doubleArray = closeHistory.ToDoubleArray();

            // for the purposes of regression testing, we're explicitly requesting history
            // using the universe symbols. Requests for universe symbols are filtered out
            // and never sent to the history provider.
            var universeSecurityHistory = History(UniverseManager.Keys, TimeSpan.FromDays(10)).ToList();

            if (universeSecurityHistory.Count != 0)
            {
                throw new Exception("History request for universe symbols incorrectly returned data. "
                                    + "These requests are intended to be filtered out and never sent to the history provider.");
            }
        }
Beispiel #37
0
 /// <summary>
 /// Computes the next value of this indicator from the given state
 /// </summary>
 /// <param name="input">The input given to the indicator</param>
 /// <returns>
 /// A new value for this indicator
 /// </returns>
 protected override decimal ComputeNextValue(IndicatorDataPoint input)
 {
     _priceLag.Update(input);
     _sma.Update(input);
     return(_priceLag - _sma);
 }