/// <summary>
 /// Initializes a new instance of the <see cref="AccumulationDistributionOscillator"/> class using the specified parameters
 /// </summary> 
 /// <param name="name">The name of this indicator</param>
 /// <param name="fastPeriod">The fast moving average period</param>
 /// <param name="slowPeriod">The slow moving average period</param>
 public AccumulationDistributionOscillator(string name, int fastPeriod, int slowPeriod)
     : base(name)
 {
     _period = Math.Max(fastPeriod, slowPeriod);
     _ad = new AccumulationDistribution(name + "_AD");
     _emaFast = new ExponentialMovingAverage(name + "_Fast", fastPeriod);
     _emaSlow = new ExponentialMovingAverage(name + "_Slow", slowPeriod);
 }
        /// <summary>Creates a new ExponentialMovingAverage indicator with the specified period and smoothingFactor from the left indicator
        /// </summary>
        /// <param name="left">The ExponentialMovingAverage indicator will be created using the data from left</param>
        /// <param name="period">The period of the ExponentialMovingAverage indicators</param>
        /// <param name="smoothingFactor">The percentage of data from the previous value to be carried into the next value</param>
        /// <param name="waitForFirstToReady">True to only send updates to the second if left.IsReady returns true, false to alway send updates</param>
        /// <returns>A reference to the ExponentialMovingAverage indicator to allow for method chaining</returns>
        public static ExponentialMovingAverage EMA <T>(this IndicatorBase <T> left, int period, decimal?smoothingFactor = null, bool waitForFirstToReady = true)
            where T : IBaseData
        {
            decimal k = smoothingFactor.HasValue ? k = smoothingFactor.Value : ExponentialMovingAverage.SmoothingFactorDefault(period);
            ExponentialMovingAverage emaOfLeft = new ExponentialMovingAverage(string.Format("EMA{0}_Of_{1}", period, left.Name), period, k).Of(left, waitForFirstToReady);

            return(emaOfLeft);
        }
 public PolarisedFractalEfficiency(string name, Source source, int lookback, int period)
     : base(name, 1)
 {
     _source      = source;
     xEma         = new ExponentialMovingAverage(period);
     Src          = new RollingWindow <decimal>(lookback + 1);
     C2C          = new RollingWindow <double>(lookback);
     WarmUpPeriod = period + lookback;
 }
Exemple #4
0
        public ZeroLagExponentialMovingAverage(string name, int period) : base(name)
        {
            _period = period;
            _k      = 2m / (_period + 1);
            _lag    = (int)Math.Round((_period - 1) / 2m);

            _ema          = new ExponentialMovingAverage(name + "_EMA", period);
            _delayedEMA   = new Delay(name + "_DelayedEMA", _lag);
            _delayedZLEMA = new Delay(name + "_DelayedZLEMA", 1);
        }
Exemple #5
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(2000, 07, 01);  //Set Start Date
     SetEndDate(2015,10, 05);    //Set End Date
     SetCash(5200);             //Set Strategy Cash
     // Find more symbols here: http://quantconnect.com/data
     AddSecurity(SecurityType.Equity, Symbol, Resolution.Daily);
     //AddSecurity(SecurityType.Equity, Symbol2, Resolution.Daily);
     ema = EMA (Symbol, 10, Resolution.Daily);
     SetBrokerageModel (QuantConnect.Brokerages.BrokerageName.InteractiveBrokersBrokerage);
 }
Exemple #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TrueStrengthIndex"/> class using the specified name, the short and long term smoothing periods, and the signal period and type.
 /// </summary>
 /// <param name="name">The name of the indicator</param>
 /// <param name="shortTermPeriod">Period used for the first price change smoothing</param>
 /// <param name="longTermPeriod">Period used for the second (double) price change smoothing</param>
 /// <param name="signalPeriod">The signal period</param>
 /// <param name="signalType">The type of moving average to use for the signal</param>
 public TrueStrengthIndex(string name, int longTermPeriod = 25, int shortTermPeriod = 13, int signalPeriod = 7, MovingAverageType signalType = MovingAverageType.Exponential)
     : base(name)
 {
     _priceChangeEma       = new ExponentialMovingAverage(name + "_PC_EMA", longTermPeriod);
     _absPriceChangeEma    = new ExponentialMovingAverage(name + "_APC_EMA", longTermPeriod);
     _priceChangeEmaEma    = new ExponentialMovingAverage(name + "_PC_EMA_EMA", shortTermPeriod).Of(_priceChangeEma, true);
     _absPriceChangeEmaEma = new ExponentialMovingAverage(name + "_APC_EMA_EMA", shortTermPeriod).Of(_absPriceChangeEma, true);
     _tsi         = _priceChangeEmaEma.Over(_absPriceChangeEmaEma).Times(100m);
     Signal       = signalType.AsIndicator(name + "_Signal", signalPeriod).Of(_tsi, true);
     WarmUpPeriod = longTermPeriod + shortTermPeriod;
 }
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);
            SetCash(100*1000);

            AddSecurity(SecurityType.Equity, "SPY");

            Fast = EMA("SPY", FastPeriod);
            Slow = EMA("SPY", SlowPeriod);
        }
Exemple #8
0
        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
            AddSecurity(SecurityType.Equity, Symbol, Resolution.Second);

            fast = EMA(Symbol, FastPeriod);
            slow = EMA(Symbol, SlowPeriod);

            SetWarmup(SlowPeriod);
        }
Exemple #9
0
 //Initialize the data and resolution you require for your strategy:
 public override void Initialize()
 {
     SetStartDate(2014, 07, 11);
     SetEndDate(2015,10,1);
     SetCash(25000);
     AddSecurity(SecurityType.Equity, symbol, Resolution.Daily);
     var shortval = Config.GetInt ("EMA_VAR1",10);
     emaShort = EMA(symbol, shortval, Resolution.Daily);
     emaLong = EMA(symbol, 50, Resolution.Daily);
     for (int i = 0; i < MAXRETURNS; i++) {
         _tradeReturns.Add(0);
     }
 }
        public TripleMovingAverageStrategy(Symbol sym, Indicator priceIdentity, MeanReversionAlgorithm algorithm, decimal minBarSize, decimal barDifferenceTolerance)
        {
            Algorithm = algorithm;
            symbol = sym;

            trend = new InstantaneousTrend(10).Of(_price);
            ema10 = new ExponentialMovingAverage(10).Of(_price);
            sma10 = new SimpleMovingAverage(10).Of(_price);

            Position = StockState.noInvested;
            EntryPrice = null;
            ActualSignal = OrderSignal.doNothing;
        }
Exemple #11
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, 01, 01);  //Set Start Date
            SetEndDate(2014, 01, 01);    //Set End Date
            SetCash(100000);             //Set Strategy Cash

            // Find more symbols here: http://quantconnect.com/data
            AddSecurity(SecurityType.Equity, "IBM", Resolution.Hour);
            AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily);

            macd = MACD("SPY", 12, 26, 9, MovingAverageType.Wilders, Resolution.Daily, Field.Close);
            ema = EMA("IBM", 15*6, Resolution.Hour, Field.SevenBar);

            Securities["IBM"].SetLeverage(1.0m);
        }
        public void ResetsProperly()
        {
            // ema reset is just setting the value and samples back to 0
            var ema = new ExponentialMovingAverage(3);

            foreach (var data in TestHelper.GetDataStream(5))
            {
                ema.Update(data);
            }
            Assert.IsTrue(ema.IsReady);
            Assert.AreNotEqual(0m, ema.Current.Value);
            Assert.AreNotEqual(0, ema.Samples);

            ema.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(ema);
        }
        public override void Initialize()
        {
            // set up our analysis span
            SetStartDate(2009, 01, 01);
            SetEndDate(2015, 01, 01);

            // request SPY data with minute resolution
            AddSecurity(SecurityType.Equity, Symbol, Resolution.Minute);

            // create a 15 day exponential moving average
            fast = EMA(Symbol, 15, Resolution.Daily);

            // create a 30 day exponential moving average
            slow = EMA(Symbol, 30, Resolution.Daily);

            int ribbonCount = 8;
            int ribbonInterval = 15;
            ribbon = Enumerable.Range(0, ribbonCount).Select(x => SMA(Symbol, (x + 1)*ribbonInterval, Resolution.Daily)).ToArray();
        }
Exemple #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="period"></param>
        public CyclePeriod(string name, int period = 3)
            : base(name, period)
        {
            // Initialize the differents window needed
            _smooth     = new RollingWindow <decimal>(3);
            _cycle      = new RollingWindow <decimal>(6);
            _quadrature = new RollingWindow <decimal>(2);
            _deltaPhase = new RollingWindow <decimal>(5);

            // Initialize the EMA needed
            _instPeriod = new ExponentialMovingAverage(2, new decimal(0.33));
            _period     = new ExponentialMovingAverage(10, new decimal(0.15)); // weight = 80%

            _A = (decimal)Math.Pow(1 - (double)_alpha / 2, 2);
            _B = 1 - _alpha;

            _quadCoeffA = new decimal(0.0962);
            _quadCoeffB = new decimal(0.5769);
        }
Exemple #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CrossEMAStrategy"/> class.
        /// </summary>
        /// <param name="Price">The injected price indicator.</param>
        /// <param name="SlowEMAPeriod">The slow EMA period.</param>
        /// <param name="FastEMAPeriod">The fast EMA period.</param>
        public CrossEMAStrategy(Indicator Price, int SlowEMAPeriod = 10, int FastEMAPeriod = 50)
        {
            // Initialize fields.
            _price = Price;
            fastEMA = new ExponentialMovingAverage(FastEMAPeriod).Of(_price);
            slowEMA = new ExponentialMovingAverage(SlowEMAPeriod).Of(_price);

            ActualSignal = OrderSignal.doNothing;
            Position = StockState.noInvested;
            EntryPrice = null;

            // Fill the EMA difference rolling windows at every new slowEMA observation. Once the
            // rolling windows is ready, at every indicator update the CheckSignal method will be called.
            slowEMA.Updated += (object sender, IndicatorDataPoint updated) =>
                    {
                        if (slowEMA.IsReady) EMADiffRW.Add(fastEMA - slowEMA);
                        if (EMADiffRW.IsReady) CheckSignal();
                    };
        }
Exemple #16
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.Forex, "EURUSD", Resolution.Second);

            fast = EMA("EURUSD", 60);
            slow = EMA("EURUSD", 3600);

            // 3601 because rolling window waits for one to fall off the back to be considered ready
            var history = History("EURUSD", 3601);
            foreach (var bar in history)
            {
                fast.Update(bar.EndTime, bar.Close);
                slow.Update(bar.EndTime, bar.Close);
            }

            Log(string.Format("FAST IS {0} READY. Samples: {1}", fast.IsReady ? "" : "NOT", fast.Samples));
            Log(string.Format("SLOW IS {0} READY. Samples: {1}", slow.IsReady ? "" : "NOT", slow.Samples));
        }
        public void EMAComputesCorrectly()
        {
            const int period = 4;
            decimal[] values = {1m, 10m, 100m, 1000m};
            const decimal expFactor = 2m/(1m + period);
            
            var ema4 = new ExponentialMovingAverage(period);

            decimal current = 0m;
            for (int i = 0; i < values.Length; i++)
            {
                ema4.Update(new IndicatorDataPoint(DateTime.UtcNow.AddSeconds(i), values[i]));
                if (i == 0)
                {
                    current = values[i];
                }
                else
                {
                    current = values[i]*expFactor + (1 - expFactor)*current;
                }
                Assert.AreEqual(current, ema4.Current.Value);
            }
        }
 public void ComparesAgainstExternalData()
 {
     var ema = new ExponentialMovingAverage(14);
     TestHelper.TestIndicator(ema, "spy_with_indicators.txt", "EMA14", TestHelper.AssertDeltaDecreases(2.5e-2));
 }
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            //mylog.Debug(transheader);
            mylog.Debug("Mean Reversion Algorithm");
            mylog.Debug(ondataheader);
            dailylog.Debug("Mean Reversion Algorithm");
            dailylog.Debug(dailyheader);

            //Initialize dates
            SetStartDate(_startDate);
            SetEndDate(_endDate);
            SetCash(22000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
            Price = new RollingWindow<IndicatorDataPoint>(14);
            trendHistory = new RollingWindow<IndicatorDataPoint>(14);
            trend = new InstantaneousTrend(10);
            ema10 = new ExponentialMovingAverage(10);
            sma10 = new SimpleMovingAverage(10);
            madiff = new RollingWindow<IndicatorDataPoint>(390);
            stddev = new StandardDeviation(390);
            emaHistory = new RollingWindow<IndicatorDataPoint>(10);
            smaHistory = new RollingWindow<IndicatorDataPoint>(10);
        }
        /// <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()
        {
            // initialize algorithm level parameters
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);
            //SetStartDate(2014, 01, 01);
            //SetEndDate(2014, 06, 01);
            SetCash(100000);

            // leverage tradier $1 traders
            SetBrokerageModel(BrokerageName.TradierBrokerage);

            // request high resolution equity data
            AddSecurity(SecurityType.Equity, Symbol, Resolution.Second);

            // save off our security so we can reference it quickly later
            Security = Securities[Symbol];

            // Set our max leverage
            Security.SetLeverage(MaximumLeverage);

            // define our longer term indicators
            ADX14 = ADX(Symbol, 28, Resolution.Hour);
            STD14 = STD(Symbol, 14, Resolution.Daily);
            ATR14 = ATR(Symbol, 14, resolution: Resolution.Daily);
            PSARMin = new ParabolicStopAndReverse(Symbol, afStart: 0.0001m, afIncrement: 0.0001m);

            // smooth our ATR over a week, we'll use this to determine if recent volatilty warrants entrance
            var oneWeekInMarketHours = (int)(5*6.5);
            SmoothedATR14 = new ExponentialMovingAverage("Smoothed_" + ATR14.Name, oneWeekInMarketHours).Of(ATR14);
            // smooth our STD over a week as well
            SmoothedSTD14 = new ExponentialMovingAverage("Smoothed_"+STD14.Name, oneWeekInMarketHours).Of(STD14);

            // initialize our charts
            var chart = new Chart(Symbol);
            chart.AddSeries(new Series(ADX14.Name));
            chart.AddSeries(new Series("Enter", SeriesType.Scatter));
            chart.AddSeries(new Series("Exit", SeriesType.Scatter));
            chart.AddSeries(new Series(PSARMin.Name, SeriesType.Scatter));
            AddChart(chart);

            var history = History(Symbol, 20, Resolution.Daily);
            foreach (var bar in history)
            {
                ADX14.Update(bar);
                ATR14.Update(bar);
                STD14.Update(bar.EndTime, bar.Close);
            }

            // schedule an event to run every day at five minutes after our Symbol's market open
            Schedule.Event("MarketOpenSpan")
                .EveryDay(Symbol)
                .AfterMarketOpen(Symbol, minutesAfterOpen: OpeningSpanInMinutes)
                .Run(MarketOpeningSpanHandler);

            Schedule.Event("MarketOpen")
                .EveryDay(Symbol)
                .AfterMarketOpen(Symbol, minutesAfterOpen: -1)
                .Run(() => PSARMin.Reset());
        }
            public SymbolData(Symbol symbol, QCAlgorithm algorithm)
            {
                Symbol = symbol;
                Security = algorithm.Securities[symbol];

                Close = algorithm.Identity(symbol);
                ADX = algorithm.ADX(symbol, 14);
                EMA = algorithm.EMA(symbol, 14);
                MACD = algorithm.MACD(symbol, 12, 26, 9);

                // if we're receiving daily 

                _algorithm = algorithm;
            }
 public SelectionData()
 {
     Fast = new ExponentialMovingAverage(100);
     Slow = new ExponentialMovingAverage(300);
 }
 public SelectionData()
 {
     EMA50 = new ExponentialMovingAverage(50);
     EMA100 = new ExponentialMovingAverage(100);
 }