/// <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);
        }
Beispiel #2
0
        public override void Initialize()
        {
            SetStartDate(2001, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(10000);

            mean  = SMA(symbol, n, Resolution.Daily);
            sigma = STD(symbol, n, Resolution.Daily);

            var history = History(symbol, TimeSpan.FromDays(150), Resolution.Daily);

            foreach (var tb in history)
            {
                mean.Update(tb.EndTime, tb.Close);
                sigma.Update(tb.EndTime, tb.Close);
            }

            Schedule.On(DateRules.EveryDay(), TimeRules.At(11, 0), () =>
            {
                var z      = (Securities[symbol].Price - mean) / sigma;
                var target = 2.0 / (1 + Math.Exp((double)(-1.2m * z)));

                if (z >= -4 && z <= 4)
                {
                    SetHoldings(symbol, target);
                    SetHoldings("TLT", 2 - target);
                }
                else
                {
                    SetHoldings(symbol, 0);
                    SetHoldings("TLT", 1);
                }
            });
        }
Beispiel #3
0
 protected override void Initialize()
 {
     _StdDev   = Indicators.StandardDeviation(MarketSeries.Close, Period, MovingAverageType.Simple);
     _LinReg   = Indicators.LinearRegressionForecast(MarketSeries.Close, Period);
     _Range    = CreateDataSeries();
     _Baseline = Indicators.SimpleMovingAverage(_Range, Period);
 }
        public void RegressionChannelComputesCorrectly()
        {
            var period    = 20;
            var indicator = new RegressionChannel(period, 2);
            var stdDev    = new StandardDeviation(period);
            var time      = DateTime.Now;

            var prices   = LeastSquaresMovingAverageTest.prices;
            var expected = LeastSquaresMovingAverageTest.expected;

            var actual = new decimal[prices.Length];

            for (int i = 0; i < prices.Length; i++)
            {
                indicator.Update(time, prices[i]);
                stdDev.Update(time, prices[i]);
                actual[i] = Math.Round(indicator.Current.Value, 4);
                time      = time.AddMinutes(1);
            }
            Assert.AreEqual(expected, actual);

            var expectedUpper = indicator.Current + stdDev.Current * 2;

            Assert.AreEqual(expectedUpper, indicator.UpperChannel);
            var expectedLower = indicator.Current - stdDev.Current * 2;

            Assert.AreEqual(expectedLower, indicator.LowerChannel);
        }
Beispiel #5
0
 protected override void Initialize()
 {
     _StdDev = Indicators.StandardDeviation(MarketSeries.Close, Period, MovingAverageType.Simple);
     _LinReg = Indicators.LinearRegressionForecast(MarketSeries.Close, Period);
     _Range = CreateDataSeries();
     _Baseline = Indicators.SimpleMovingAverage(_Range, Period);
 }
        /// <summary>
        /// Determines whether the specified <see cref="ChannelStatistics"/> is equal to the current <see cref="ChannelStatistics"/>.
        /// </summary>
        /// <param name="other">The channel statistics to compare this <see cref="ChannelStatistics"/> with.</param>
        /// <returns>True when the specified <see cref="ChannelStatistics"/> is equal to the current <see cref="ChannelStatistics"/>.</returns>
        public bool Equals(ChannelStatistics other)
        {
            if (ReferenceEquals(other, null))
            {
                return(false);
            }

            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                (Depth.Equals(other.Depth) &&
                 Entropy.Equals(other.Entropy) &&
                 Kurtosis.Equals(other.Kurtosis) &&
                 Maximum.Equals(other.Maximum) &&
                 Mean.Equals(other.Mean) &&
                 Minimum.Equals(other.Minimum) &&
                 Skewness.Equals(other.Skewness) &&
                 StandardDeviation.Equals(other.StandardDeviation) &&
                 Sum.Equals(other.Sum) &&
                 SumCubed.Equals(other.SumCubed) &&
                 SumFourthPower.Equals(other.SumFourthPower) &&
                 SumSquared.Equals(other.SumSquared) &&
                 Variance.Equals(other.Variance));
        }
		/// <summary>
		/// Создать <see cref="Correlation"/>.
		/// </summary>
		public Correlation()
		{
			_source = new StandardDeviation();
			_other = new StandardDeviation();

			Length = 20;
		}
Beispiel #8
0
            public SymbolData(QCAlgorithmFramework algorithm, Symbol symbol, int period, bool indicatorIsPercent)
            {
                Symbol = symbol;
                _indicatorIsPercent = indicatorIsPercent;
                IndicatorSeries     = new Series(typeof(T).Name, SeriesType.Line);
                IndicatorSeriesSTD  = new Series(typeof(T).Name + " STD", SeriesType.Line);
                //TODO: make this magical auto-detecting better
                List <object> parameterValues = new List <object>();
                var           ctor            = typeof(T).GetConstructors()[0];

                foreach (var p in ctor.GetParameters())
                {
                    var value = p.DefaultValue;
                    if (p.Name.ToLower() == "period")
                    {
                        value = period;
                    }
                    parameterValues.Add(value);
                }

                Indicator = (T)ctor.Invoke(parameterValues.ToArray());
                Mag       = 0;
                STD       = new StandardDeviation(period);

                State = State.Neutral;
            }
Beispiel #9
0
        public override void GetAll(IIndicatorValues Ind)
        {
            int period = (int)this.IndicatorParameters.List[0];

            if (!Ind.SD(period).IsPopulated)
            {
                int oldCurrentBar = Ind.Bar.CurrentBar;
                for (int i = 1; i <= Ind.Bar.MaxBar; i++)
                {
                    Ind.Bar.CurrentBar = i;

                    object prototype = null;
                    if (i == 1)
                    {
                        prototype = new StandardDeviation();
                    }
                    else
                    {
                        prototype = (StandardDeviation)Ind.SD(period)[1].Clone();
                    }

                    Get(ref prototype, Ind);

                    Ind.SD(period)[0] = (StandardDeviation)prototype;

                    Ind.SD(period).IsPopulated = true;                     // set here so instance is guaranteed to exits
                }

                Ind.Bar.CurrentBar = oldCurrentBar;
            }
        }
Beispiel #10
0
 /// <summary>
 ///      Resets this indicator and all sub-indicators (StandardDeviation, LowerBand, MiddleBand, UpperBand)
 /// </summary>
 public override void Reset()
 {
     StandardDeviation.Reset();
     MiddleBand.Reset();
     UpperBand.Reset();
     LowerBand.Reset();
     base.Reset();
 }
Beispiel #11
0
        /// <summary>
        /// Creates a new StandardDeviation indicator. This will return the population standard deviation of samples over the specified period.
        /// </summary>
        /// <param name="symbol">The symbol whose STD we want</param>
        /// <param name="period">The period over which to compute the STD</param>
        /// <param name="resolution">The resolution</param>
        /// <returns>The StandardDeviation indicator for the requested symbol over the speified period</returns>
        public StandardDeviation STD(string symbol, int period, Resolution?resolution = null)
        {
            var name = CreateIndicatorName(symbol, "STD" + period, resolution);
            var std  = new StandardDeviation(name, period);

            RegisterIndicator(symbol, std, resolution, x => x.Value);
            return(std);
        }
Beispiel #12
0
        /// <summary>
        /// Computes the next value of the following sub-indicators from the given state:
        /// StandardDeviation, MiddleBand, UpperBand, LowerBand, BandWidth, %B
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>The input is returned unmodified.</returns>
        protected override decimal ComputeNextValue(IndicatorDataPoint input)
        {
            StandardDeviation.Update(input);
            MiddleBand.Update(input);
            Price.Update(input);

            return(input.Value);
        }
        /// <summary>
        /// Creates a new StandardDeviation indicator. This will return the population standard deviation of samples over the specified period.
        /// </summary>
        /// <param name="symbol">The symbol whose STD we want</param>
        /// <param name="period">The period over which to compute the STD</param>
        /// <param name="resolution">The resolution</param>
        /// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
        /// <returns>The StandardDeviation indicator for the requested symbol over the speified period</returns>
        public StandardDeviation STD(string symbol, int period, Resolution?resolution = null, Func <BaseData, decimal> selector = null)
        {
            var name = CreateIndicatorName(symbol, "STD" + period, resolution);
            var std  = new StandardDeviation(name, period);

            RegisterIndicator(symbol, std, resolution, selector);
            return(std);
        }
Beispiel #14
0
        public override int GetHashCode()
        {
            var hashCode = 1081252967;

            hashCode = hashCode * -1521134295 + Mean.GetHashCode();
            hashCode = hashCode * -1521134295 + StandardDeviation.GetHashCode();
            return(hashCode);
        }
Beispiel #15
0
 public override string ToString()
 {
     return("\nStrategy Results for " + Name + "\n\n" +
            Count + " trades. " + ProfitLoss + " total profit.\n" +
            Average.ToString("N2") + " average. " +
            StandardDeviation.ToString("N2") + " std dev. " +
            ModifiedSharpe.ToString("N2") + " mod Sharpe.\n");
 }
            public SymbolData(Symbol symbol, int period)
            {
                Symbol = symbol;
                STD    = new StandardDeviation(period);
                State  = State.Neutral;

                IVSkewSeries = new Series("IV Skew STD", SeriesType.Line);
            }
            public SymbolData(Symbol symbol, int period)
            {
                Symbol = symbol;
                STD    = new StandardDeviation(period);
                State  = State.Neutral;

                MaxPainSeries       = new Series("Max Pain Strike", SeriesType.Line);
                MaxPainRelSTDSeries = new Series("Relative STD", SeriesType.Line);
            }
Beispiel #18
0
        public async Task TestSdAsync()
        {
            var equity = await ImportEquityAsync();

            var indicator = new StandardDeviation(equity, 10);
            var result    = indicator.ComputeByIndex(equity.Count - 1);

            Assert.IsTrue(0.93m.IsApproximatelyEquals(result.Sd.Value));
        }
Beispiel #19
0
        private void InitIndicators()
        {
            _lookBack = 1440;

            _rollingSpread = new RollingWindow <decimal>(_lookBack);
            _spreadStd     = new StandardDeviation(_lookBack);
            _priceSpread   = new PriceSpread();
            _halfLife      = new HalfLife();
        }
 protected override void Initialize()
 {
     bb       = Indicators.BollingerBands(source, bandsPeriod, deviations, bandsMAType);
     pctB     = CreateDataSeries();
     bandsGap = CreateDataSeries();
     // zscore = Indicators.GetIndicator<ZScore>(bandsGap, lookBack);
     ma = Indicators.MovingAverage(bandsGap, lookBack, MovingAverageType.Simple);
     sd = Indicators.StandardDeviation(bandsGap, lookBack, MovingAverageType.Simple);
 }
Beispiel #21
0
        public async Task TestSdAsync()
        {
            var candles = await ImportCandlesAsync();

            var indicator = new StandardDeviation(candles, 10);
            var result    = indicator[candles.Count - 1];

            Assert.IsTrue(0.93m.IsApproximatelyEquals(result.Value));
        }
Beispiel #22
0
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(10000);

            AddSecurity(SecurityType.Equity, symbol, Resolution.Daily);

            _stdDev = STD(symbol, 30, Resolution.Minute);
        }
            public SymbolData(Symbol symbol, int period)
            {
                Symbol = symbol;
                STD    = new StandardDeviation(period);
                State  = State.Neutral;

                FrontIVSeries = new Series("Front IV", SeriesType.Line);
                BackIVSeries  = new Series("Back IV", SeriesType.Line);
                STDSeries     = new Series("Std Dev Contango", SeriesType.Line);
            }
Beispiel #24
0
 /// <summary>
 ///      Initializes a new instance of the BollingerBands class
 /// </summary>
 /// <param name="name">The name of this indicator</param>
 /// <param name="period">The period of the standard deviation and moving average (middle band)</param>
 /// <param name="k">The number of standard deviations specifying the distance between the middle band and upper or lower bands</param>
 /// <param name="movingAverageType">The type of moving average to be used</param>
 public BollingerBands(string name, int period, double k, MovingAverageType movingAverageType = MovingAverageType.Simple)
     : base(name)
 {
     WarmUpPeriod      = period;
     MovingAverageType = movingAverageType;
     StandardDeviation = new StandardDeviation(name + "_StandardDeviation", period);
     MiddleBand        = movingAverageType.AsIndicator(name + "_MiddleBand", period);
     LowerBand         = MiddleBand.Minus(StandardDeviation.Times(k), name + "_LowerBand");
     UpperBand         = MiddleBand.Plus(StandardDeviation.Times(k), name + "_UpperBand");
 }
Beispiel #25
0
        static public decimal Interval(int percent, int[] nums)
        {
            int     df         = nums.Length - 1;
            decimal mean       = Mean.findMean(nums);
            decimal sd         = StandardDeviation.findSD(nums);
            decimal confidence = Multiplication.Product(percent, .01m);
            decimal ans        = Division.Quotient((1 - confidence), 2);

            return(Tscore(df, ans));
        }
Beispiel #26
0
 protected override void Initialize()
 {
     llrrss = Indicators.LinearRegressionSlope(source, linRegSlpPeriods).Result;
     //lrs = Indicators.LinearRegressionSlope(source, linRegSlpPeriods);
     bb       = Indicators.BollingerBands(llrrss, /*lrs.Result*/ bandsPeriod, deviations, bandsMAType);
     pctB     = CreateDataSeries();
     bandsGap = CreateDataSeries();
     ma       = Indicators.MovingAverage(bandsGap, lookBack, MovingAverageType.Simple);
     sd       = Indicators.StandardDeviation(bandsGap, lookBack, MovingAverageType.Simple);
 }
Beispiel #27
0
 /// <summary>
 /// Resets this indicator and all sub-indicators (StandardDeviation, LowerBand, MiddleBand, UpperBand, BandWidth, %B)
 /// </summary>
 public override void Reset()
 {
     StandardDeviation.Reset();
     MiddleBand.Reset();
     UpperBand.Reset();
     LowerBand.Reset();
     BandWidth.Reset();
     PercentB.Reset();
     base.Reset();
 }
        public void ConvertInputStringToListOfDoubles(StandardDeviation model)
        {
            string[] doubles = model.InputString.Split(',');

            foreach (var item in doubles)
            {
                model.InputNumbers.Add(Double.Parse(item));
                _logger.LogInformation($"{item}");
            }
            _logger.LogInformation("All the numbers entered by the user:");
        }
Beispiel #29
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BollingerBand"/>.
		/// </summary>
		/// <param name="ma">Moving Average.</param>
		/// <param name="dev">Standard deviation.</param>
		public BollingerBand(LengthIndicator<decimal> ma, StandardDeviation dev)
		{
			if (ma == null)
				throw new ArgumentNullException(nameof(ma));

			if (dev == null)
				throw new ArgumentNullException(nameof(dev));

			_ma = ma;
			_dev = dev;
		}
Beispiel #30
0
        protected override void Initialize()
        {
            lrf = Indicators.LinearRegressionForecast(Source, LRFperiod);
            ma  = Indicators.SimpleMovingAverage(lrf.Result, MAperiod);

            psar = Indicators.ParabolicSAR(minAF, maxAF);

            diff     = CreateDataSeries();
            zsma     = Indicators.TimeSeriesMovingAverage(diff, ZSperiod);
            zsstddev = Indicators.StandardDeviation(diff, ZSperiod, MovingAverageType.Simple);
        }
            public SymbolData(Symbol symbol, IEnumerable <BaseData> history)
            {
                Symbol = symbol;
                SMA    = new SimpleMovingAverage(365).Of(ROC);
                STD    = new StandardDeviation(365).Of(ROC);

                foreach (var data in history)
                {
                    Update(data);
                }
            }
Beispiel #32
0
        public void Calculate_RandomSample_ShouldCalculateStandDeviation()
        {
            // I'd usually mock this but in the interest of time just do an integration test.
            var unitUnderTest = new StandardDeviation(new ArithmeticMean());

            var numbers = new[] { 4d, 9d, 11d, 12d, 17d, 5d, 8d, 12d, 14d };

            var result = unitUnderTest.Calculate(numbers);

            // irrational number round to nearest 2dp.
            Assert.AreEqual(3.94, Math.Round(result, 2));
        }
        public void ResetsProperlyStandardDeviation()
        {
            var std = new StandardDeviation(3);

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

            std.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(std);
        }